@grantjs/cli 1.0.0 → 1.1.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 +1 -1
- package/dist/index.mjs +4160 -4140
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -13
- package/dist/{api → src/api}/client.d.ts +0 -0
- package/dist/{commands → src/commands}/config-cmd.d.ts +0 -0
- package/dist/{commands → src/commands}/generate-types-impl.d.ts +0 -0
- package/dist/{commands → src/commands}/generate-types.d.ts +0 -0
- package/dist/{commands → src/commands}/start.d.ts +0 -0
- package/dist/{commands → src/commands}/version.d.ts +0 -0
- package/dist/{config → src/config}/index.d.ts +2 -2
- /package/dist/{config → src/config}/resolve-token.d.ts +0 -0
- /package/dist/{config → src/config}/storage.d.ts +0 -0
- /package/dist/{index.d.ts → src/index.d.ts} +0 -0
- /package/dist/{types → src/types}/config.d.ts +0 -0
- /package/dist/{utils → src/utils}/package.d.ts +0 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js","../../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs","../src/config/storage.ts","../src/api/client.ts","../src/config/resolve-token.ts","../src/commands/config-cmd.ts","../src/commands/generate-types-impl.ts","../src/commands/generate-types.ts","../src/commands/start.ts","../src/utils/package.ts","../src/commands/version.ts","../src/index.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nimport type { GrantConfig, GrantConfigFile } from '../types/config.js';\n\nconst CONFIG_DIR_NAME = 'grant';\nconst CONFIG_FILE_NAME = 'config.json';\nconst DEFAULT_PROFILE_NAME = 'default';\n\n/**\n * Returns the platform-specific config directory for Grant CLI.\n * - Windows: %APPDATA%\\grant\n * - Linux/macOS: $XDG_CONFIG_HOME/grant or ~/.config/grant\n */\nexport function getConfigDir(): string {\n if (platform() === 'win32') {\n const appData = process.env.APPDATA;\n if (!appData) {\n return join(homedir(), 'AppData', 'Roaming', CONFIG_DIR_NAME);\n }\n return join(appData, CONFIG_DIR_NAME);\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg) {\n return join(xdg, CONFIG_DIR_NAME);\n }\n return join(homedir(), '.config', CONFIG_DIR_NAME);\n}\n\n/**\n * Returns the path to the config file (config dir + config.json).\n */\nexport function getConfigPath(): string {\n return join(getConfigDir(), CONFIG_FILE_NAME);\n}\n\n/** Detect legacy single-profile config (apiUrl at top level, no profiles). */\nfunction isLegacyConfig(data: unknown): data is GrantConfig {\n if (!data || typeof data !== 'object') return false;\n const o = data as Record<string, unknown>;\n return typeof o.apiUrl === 'string' && !('profiles' in o);\n}\n\n/**\n * Load config file from disk. Migrates legacy single-config to profiles shape.\n * Returns null if file does not exist or is invalid.\n */\nexport async function loadConfigFile(): Promise<GrantConfigFile | null> {\n const path = getConfigPath();\n try {\n const raw = await readFile(path, 'utf-8');\n const data = JSON.parse(raw) as unknown;\n if (!data || typeof data !== 'object') return null;\n\n if (isLegacyConfig(data)) {\n const file: GrantConfigFile = {\n defaultProfile: DEFAULT_PROFILE_NAME,\n profiles: { [DEFAULT_PROFILE_NAME]: data },\n };\n await saveConfigFile(file);\n return file;\n }\n\n const file = data as GrantConfigFile;\n if (\n typeof file.defaultProfile !== 'string' ||\n !file.profiles ||\n typeof file.profiles !== 'object'\n ) {\n return null;\n }\n return file;\n } catch {\n return null;\n }\n}\n\n/**\n * Save config file to disk. Creates config dir if needed. Sets file mode to 0o600 (owner read/write only).\n */\nexport async function saveConfigFile(file: GrantConfigFile): Promise<void> {\n const dir = getConfigDir();\n const path = getConfigPath();\n await mkdir(dir, { recursive: true, mode: 0o700 });\n await writeFile(path, JSON.stringify(file, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n flag: 'w',\n });\n}\n\n/**\n * Resolve which profile name to use: explicit name, or file's default, or \"default\".\n */\nexport function resolveProfileName(file: GrantConfigFile, profileFlag: string | undefined): string {\n if (profileFlag?.trim()) return profileFlag.trim();\n return file.defaultProfile || DEFAULT_PROFILE_NAME;\n}\n\n/**\n * Get config for a profile. Returns null if profile does not exist.\n */\nexport function getProfileConfig(file: GrantConfigFile, profileName: string): GrantConfig | null {\n return file.profiles[profileName] ?? null;\n}\n\n/**\n * List profile names. Returns empty array if no file.\n */\nexport function listProfileNames(file: GrantConfigFile | null): string[] {\n if (!file?.profiles) return [];\n return Object.keys(file.profiles);\n}\n\n/** Default profile name constant for use in prompts/help. */\nexport { DEFAULT_PROFILE_NAME };\n\n/**\n * Load config file and return the default profile's config.\n * Convenience for callers that only need one profile (default). Returns null if no file or default profile missing.\n */\nexport async function loadConfig(): Promise<GrantConfig | null> {\n const file = await loadConfigFile();\n if (!file) return null;\n const name = resolveProfileName(file, undefined);\n return getProfileConfig(file, name) ?? null;\n}\n\n/**\n * Load config file and return the resolved profile's config plus file and name.\n * Use when you need to read and then update (save) the file. Returns null if no file or profile does not exist.\n */\nexport async function loadProfile(profileFlag?: string): Promise<{\n file: GrantConfigFile;\n config: GrantConfig;\n profileName: string;\n} | null> {\n const file = await loadConfigFile();\n if (!file) return null;\n const profileName = resolveProfileName(file, profileFlag);\n const config = getProfileConfig(file, profileName);\n if (!config) return null;\n return { file, config, profileName };\n}\n","/**\n * Minimal REST client for Grant API.\n * Used by start (token exchange) and generate-types (resources/permissions).\n */\n\nexport interface TokenExchangeScope {\n id: string;\n tenant: string;\n}\n\nexport interface TokenExchangeRequest {\n clientId: string;\n clientSecret: string;\n scope: TokenExchangeScope;\n}\n\nexport interface TokenExchangeResponse {\n accessToken: string;\n expiresIn: number;\n}\n\nexport interface ApiErrorBody {\n success?: false;\n error?: { code?: string; message?: string };\n reason?: string;\n code?: string;\n}\n\n/** Set GRANT_CLI_DEBUG=1 for extra verbosity (e.g. request headers). */\nconst _DEBUG = process.env.GRANT_CLI_DEBUG === '1' || process.env.GRANT_CLI_DEBUG === 'true';\n\n/** Log request URL, status, and response body when an API call fails (always on failure). */\nfunction logFailedRequest(\n label: string,\n url: string,\n status: number,\n bodyText: string,\n extra?: Record<string, unknown>\n): void {\n console.error(`[Grant CLI] ${label} failed`);\n console.error(`[Grant CLI] URL: ${url}`);\n console.error(`[Grant CLI] Status: ${status}`);\n if (bodyText) {\n try {\n const parsed = JSON.parse(bodyText) as Record<string, unknown>;\n console.error(`[Grant CLI] Response: ${JSON.stringify(parsed, null, 2)}`);\n } catch {\n console.error(`[Grant CLI] Response (raw): ${bodyText.slice(0, 500)}`);\n }\n }\n if (extra && Object.keys(extra).length > 0) {\n console.error(`[Grant CLI] Extra: ${JSON.stringify(extra)}`);\n }\n}\n\nexport interface LoginAccount {\n id: string;\n type: string;\n ownerId: string | null;\n [key: string]: unknown;\n}\n\nexport interface LoginResult {\n /** Primary account (personal or first). */\n account: LoginAccount;\n /** All user accounts from login (personal + organization). Use for account selector. */\n accounts: LoginAccount[];\n accessToken: string;\n refreshToken: string;\n}\n\nexport interface OrganizationItem {\n id: string;\n name: string;\n [key: string]: unknown;\n}\n\nexport interface ProjectItem {\n id: string;\n name: string;\n slug: string;\n [key: string]: unknown;\n}\n\n/**\n * Build a detailed message when a request fails before or during fetch (e.g. connection refused, DNS, SSL).\n */\nfunction detailFetchError(url: string, err: unknown): string {\n const attempted = `Request URL: ${url}`;\n const msg = err instanceof Error ? err.message : String(err);\n const cause =\n err instanceof Error && err.cause instanceof Error\n ? err.cause.message\n : err instanceof Error && typeof (err as NodeJS.ErrnoException).code === 'string'\n ? (err as NodeJS.ErrnoException).code\n : null;\n if (cause && cause !== msg) {\n return `Token exchange failed: ${msg}. Cause: ${cause}. ${attempted}`;\n }\n return `Token exchange failed: ${msg}. ${attempted}`;\n}\n\n/**\n * Exchange API key (clientId + clientSecret) for an access token.\n * POST {baseUrl}/api/auth/token\n */\nexport async function exchangeApiKey(\n baseUrl: string,\n body: TokenExchangeRequest\n): Promise<TokenExchangeResponse> {\n const url = new URL('/api/auth/token', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err));\n }\n\n if (!res.ok) {\n const text = await res.text();\n let message = `Token exchange failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const data = (await res.json()) as { data?: TokenExchangeResponse };\n if (!data?.data?.accessToken) {\n throw new Error('Invalid token response: missing accessToken');\n }\n return data.data;\n}\n\n/**\n * Login with email and password. POST {baseUrl}/api/auth/login\n * Returns access token, refresh token, and primary account (personal).\n */\nexport async function loginWithEmail(\n baseUrl: string,\n email: string,\n password: string\n): Promise<LoginResult> {\n const url = new URL('/api/auth/login', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n provider: 'email',\n providerId: email.trim(),\n providerData: { password },\n }),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err));\n }\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Login', url, res.status, text);\n let message = `Login failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const json = (await res.json()) as {\n data?: {\n accounts?: Array<LoginAccount>;\n accessToken?: string;\n refreshToken?: string;\n };\n };\n const data = json.data;\n if (\n !data?.accessToken ||\n !data?.refreshToken ||\n !Array.isArray(data.accounts) ||\n data.accounts.length === 0\n ) {\n throw new Error('Invalid login response: missing accessToken, refreshToken, or accounts');\n }\n const primary = data.accounts.find((a) => a.type === 'personal') ?? data.accounts[0];\n return {\n account: primary,\n accounts: data.accounts,\n accessToken: data.accessToken,\n refreshToken: data.refreshToken,\n };\n}\n\n/**\n * Exchange one-time CLI OAuth code for session. POST {baseUrl}/api/auth/cli-callback\n * Used after browser redirect from GitHub OAuth when redirect_uri was localhost.\n */\nexport async function exchangeCliCallback(baseUrl: string, code: string): Promise<LoginResult> {\n const url = new URL('/api/auth/cli-callback', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err));\n }\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('CLI callback exchange', url, res.status, text);\n let message = `Code exchange failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const json = (await res.json()) as {\n data?: {\n accessToken?: string;\n refreshToken?: string;\n accounts?: Array<LoginAccount>;\n };\n };\n const data = json.data;\n if (\n !data?.accessToken ||\n !data?.refreshToken ||\n !Array.isArray(data.accounts) ||\n data.accounts.length === 0\n ) {\n throw new Error(\n 'Invalid CLI callback response: missing accessToken, refreshToken, or accounts'\n );\n }\n const primary = data.accounts.find((a) => a.type === 'personal') ?? data.accounts[0];\n return {\n account: primary,\n accounts: data.accounts,\n accessToken: data.accessToken,\n refreshToken: data.refreshToken,\n };\n}\n\n/**\n * Fetch organizations (paginated). Requires Bearer token. GET /api/organizations?scopeId=&tenant=\n * Scope is the account context (user's personal account id, tenant 'account').\n */\nexport async function fetchOrganizations(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<OrganizationItem[]> {\n const items: OrganizationItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/organizations', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Organizations request', url.href, res.status, text, {\n scopeId: scope.id,\n tenant: scope.tenant,\n });\n let msg = `Organizations request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n if (data?.reason) msg += ` — ${data.reason}`;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { items?: OrganizationItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid organizations response: missing data');\n\n const list = data.items ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\n/**\n * Fetch projects for a scope (account or organization). Paginated. Requires Bearer token.\n * GET /api/projects?scopeId=&tenant=\n */\nexport async function fetchProjects(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<ProjectItem[]> {\n const items: ProjectItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/projects', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Projects request', url.href, res.status, text, {\n scopeId: scope.id,\n tenant: scope.tenant,\n });\n let msg = `Projects request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n if (data?.reason) msg += ` — ${data.reason}`;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { projects?: ProjectItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid projects response: missing data');\n\n const list = data.projects ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\nexport interface ApiScope {\n id: string;\n tenant: string;\n}\n\nexport interface ResourceItem {\n id: string;\n slug: string;\n name: string;\n actions: string[];\n [key: string]: unknown;\n}\n\nexport interface PermissionItem {\n id: string;\n action: string;\n name: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_PAGE_SIZE = 50;\n\n/**\n * Fetch all resources for a scope (paginated). Requires Bearer token.\n */\nexport async function fetchResources(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<ResourceItem[]> {\n const items: ResourceItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/resources', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n let msg = `Resources request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { resources?: ResourceItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid resources response: missing data');\n\n const list = data.resources ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\n/**\n * Fetch all permissions for a scope (paginated). Requires Bearer token.\n */\nexport async function fetchPermissions(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<PermissionItem[]> {\n const items: PermissionItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/permissions', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n let msg = `Permissions request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { permissions?: PermissionItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid permissions response: missing data');\n\n const list = data.permissions ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n","import { exchangeApiKey } from '../api/client.js';\n\nimport type { GrantConfig } from '../types/config.js';\n\n/**\n * Resolve a valid access token from stored config.\n * Only tokens are stored (no credentials). Session auth does not auto-refresh; user must re-auth when the access token expires.\n *\n * - API key: exchanges clientId + clientSecret for a fresh token (no credentials stored after exchange).\n * - Session: returns the stored access token. When it expires, the user must run \"grant start\" again to re-authenticate.\n */\nexport async function resolveAccessToken(config: GrantConfig): Promise<string> {\n if (config.authMethod === 'api-key' && config.apiKey) {\n const { accessToken } = await exchangeApiKey(config.apiUrl, {\n clientId: config.apiKey.clientId,\n clientSecret: config.apiKey.clientSecret,\n scope: config.apiKey.scope,\n });\n return accessToken;\n }\n if (config.authMethod === 'session' && config.session?.token) {\n return config.session.token;\n }\n throw new Error('No credentials in config. Run \"grant start\" to set up authentication.');\n}\n","import { existsSync } from 'node:fs';\n\nimport {\n getConfigPath,\n loadConfigFile,\n loadProfile,\n listProfileNames,\n saveConfigFile,\n} from '../config/index.js';\n\nimport type { GrantConfig, GrantConfigFile, GrantScope } from '../types/config.js';\nimport type { Command } from 'commander';\n\nconst VALID_TENANTS = ['accountProject', 'organizationProject'] as const;\n\nasync function requireProfile(profileFlag?: string): Promise<{\n file: GrantConfigFile;\n config: GrantConfig;\n profileName: string;\n}> {\n const result = await loadProfile(profileFlag);\n if (!result) {\n console.error('No config found, or profile does not exist. Run \"grant start\" first.');\n process.exit(1);\n }\n return result;\n}\n\nfunction isValidUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction normalizeApiUrl(input: string): string {\n return input.trim().replace(/\\/+$/, '') || input;\n}\n\nfunction isValidScopeId(s: string): boolean {\n const parts = s.trim().split(':');\n if (parts.length !== 1 && parts.length !== 2) return false;\n const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return parts.every((p) => uuidRe.test(p.trim()));\n}\n\nexport function createConfigCommand(program: Command): void {\n const configCmd = program\n .command('config')\n .description('View and edit Grant CLI config (path, list, show, set)');\n\n configCmd\n .command('path')\n .description('Print the path to the config file')\n .action(() => {\n console.log(getConfigPath());\n });\n\n configCmd\n .command('list')\n .description('List profile names and show which is the default')\n .action(async () => {\n const file = await loadConfigFile();\n const path = getConfigPath();\n const exists = existsSync(path);\n console.log('Config path:', path);\n console.log('Exists:', exists);\n if (!file || Object.keys(file.profiles).length === 0) {\n console.log('No profiles. Run \"grant start\" to create one.');\n return;\n }\n const names = listProfileNames(file);\n const defaultName = file.defaultProfile || names[0];\n console.log('Default profile:', defaultName);\n names.forEach((name) => {\n const marker = name === defaultName ? ' (default)' : '';\n console.log(' -', name + marker);\n });\n });\n\n configCmd\n .command('show')\n .description('Show config summary for a profile (path, apiUrl, authMethod, scope; no secrets)')\n .option('-p, --profile <name>', 'Profile to show (default: default profile)')\n .action(async (options: { profile?: string }) => {\n const path = getConfigPath();\n const exists = existsSync(path);\n console.log('Config path:', path);\n console.log('Exists:', exists);\n const result = await loadProfile(options.profile);\n if (!result) {\n console.log('No config or profile not found. Run \"grant start\" first.');\n return;\n }\n const { config, profileName } = result;\n console.log('Profile:', profileName);\n console.log('API URL:', config.apiUrl);\n console.log('Auth method:', config.authMethod);\n if (config.selectedScope) {\n console.log('Selected scope:', `${config.selectedScope.tenant}:${config.selectedScope.id}`);\n }\n if (config.generateTypesOutputPath) {\n console.log('Generate-types output:', config.generateTypesOutputPath);\n }\n });\n\n const setCmd = configCmd\n .command('set')\n .description(\n 'Set a config value for a profile (use a subcommand: api-url, auth-method, credentials, scope, generate-types-output, default-profile)'\n )\n .option('-p, --profile <name>', 'Profile to update (default: default profile)');\n\n setCmd\n .command('api-url <url>')\n .description('Set the Grant API base URL (e.g. http://localhost:4000)')\n .action(async (url: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const normalized = normalizeApiUrl(url);\n if (!normalized) {\n console.error('URL is required.');\n process.exit(1);\n }\n if (!isValidUrl(normalized)) {\n console.error('Enter a valid URL (e.g. https://grant.example.com)');\n process.exit(1);\n }\n config.apiUrl = normalized;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('api-url set to', config.apiUrl, '(profile:', profileName + ')');\n });\n\n setCmd\n .command('auth-method <method>')\n .description('Set authentication method: session or api-key')\n .action(async (method: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const m = method.toLowerCase();\n if (m !== 'session' && m !== 'api-key') {\n console.error('auth-method must be \"session\" or \"api-key\"');\n process.exit(1);\n }\n config.authMethod = m as 'session' | 'api-key';\n if (config.authMethod === 'session') {\n delete config.apiKey;\n } else {\n delete config.session;\n }\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('auth-method set to', config.authMethod, '(profile:', profileName + ')');\n });\n\n setCmd\n .command('credentials')\n .description('Set API key credentials (client ID, secret, and scope)')\n .option('--client-id <id>', 'API key client ID (UUID)')\n .option('--client-secret <secret>', 'API key client secret (min 32 characters)')\n .option('--scope-tenant <tenant>', `Scope tenant: ${VALID_TENANTS.join(' or ')}`)\n .option('--scope-id <id>', 'Scope ID (e.g. accountId:projectId or organizationId:projectId)')\n .action(\n async (\n opts: { clientId?: string; clientSecret?: string; scopeTenant?: string; scopeId?: string },\n cmd: Command\n ) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const { clientId, clientSecret, scopeTenant, scopeId } = opts;\n if (!clientId?.trim()) {\n console.error('--client-id is required');\n process.exit(1);\n }\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n clientId.trim()\n )\n ) {\n console.error('--client-id must be a valid UUID');\n process.exit(1);\n }\n if (!clientSecret || clientSecret.length < 32) {\n console.error('--client-secret is required and must be at least 32 characters');\n process.exit(1);\n }\n if (\n !scopeTenant ||\n !VALID_TENANTS.includes(scopeTenant as (typeof VALID_TENANTS)[number])\n ) {\n console.error('--scope-tenant is required and must be one of:', VALID_TENANTS.join(', '));\n process.exit(1);\n }\n if (!scopeId?.trim()) {\n console.error('--scope-id is required');\n process.exit(1);\n }\n if (!isValidScopeId(scopeId)) {\n console.error('--scope-id must be one UUID or two UUIDs separated by a colon');\n process.exit(1);\n }\n const scope: GrantScope = { tenant: scopeTenant, id: scopeId.trim() };\n config.authMethod = 'api-key';\n config.apiKey = {\n clientId: clientId.trim(),\n clientSecret,\n scope,\n };\n config.selectedScope = scope;\n delete config.session;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('credentials and scope updated (profile:', profileName + ')');\n }\n );\n\n setCmd\n .command('scope')\n .description('Set the selected project scope (tenant and ID)')\n .option('--tenant <tenant>', `Scope tenant: ${VALID_TENANTS.join(' or ')}`)\n .option('--scope-id <id>', 'Scope ID (e.g. accountId:projectId or organizationId:projectId)')\n .action(async (options: { tenant?: string; scopeId?: string }, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const { tenant, scopeId } = options;\n if (!tenant || !VALID_TENANTS.includes(tenant as (typeof VALID_TENANTS)[number])) {\n console.error('--tenant is required and must be one of:', VALID_TENANTS.join(', '));\n process.exit(1);\n }\n if (!scopeId?.trim()) {\n console.error('--scope-id is required');\n process.exit(1);\n }\n if (!isValidScopeId(scopeId)) {\n console.error('--scope-id must be one UUID or two UUIDs separated by a colon');\n process.exit(1);\n }\n config.selectedScope = { tenant, id: scopeId.trim() };\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'scope set to',\n config.selectedScope!.tenant + ':' + config.selectedScope!.id,\n '(profile:',\n profileName + ')'\n );\n });\n\n setCmd\n .command('generate-types-output <path>')\n .description('Set default output path for grant generate-types (e.g. ./src/grant-types.ts)')\n .action(async (path: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const trimmed = path.trim();\n if (!trimmed) {\n delete config.generateTypesOutputPath;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'generate-types-output cleared (will use ./grant-types.ts) (profile:',\n profileName + ')'\n );\n return;\n }\n if (!trimmed.endsWith('.ts')) {\n console.error('Path should end with .ts');\n process.exit(1);\n }\n config.generateTypesOutputPath = trimmed;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'generate-types-output set to',\n config.generateTypesOutputPath,\n '(profile:',\n profileName + ')'\n );\n });\n\n setCmd\n .command('default-profile <name>')\n .description('Set the default profile (used when --profile is not passed)')\n .action(async (name: string) => {\n const file = await loadConfigFile();\n if (!file) {\n console.error('No config found. Run \"grant start\" first.');\n process.exit(1);\n }\n const trimmed = name.trim();\n if (!file.profiles[trimmed]) {\n console.error(\n 'Profile \"' + trimmed + '\" does not exist. Use \"grant config list\" to see profiles.'\n );\n process.exit(1);\n }\n file.defaultProfile = trimmed;\n await saveConfigFile(file);\n console.log('default profile set to', trimmed);\n });\n}\n","/**\n * Generate TypeScript content for ResourceSlug and ResourceAction from project data.\n * Mirrors the shape of @grantjs/constants permissions/resources.ts.\n */\n\n/** Convert slug (e.g. \"user-documents\") or action (e.g. \"Create\") to PascalCase key. */\nexport function toPascalCase(s: string): string {\n return s\n .split(/[-_:.\\s]+/)\n .map((part) => (part.length > 0 ? part[0]!.toUpperCase() + part.slice(1).toLowerCase() : ''))\n .join('');\n}\n\n/**\n * Generate the TypeScript file content for ResourceSlug and ResourceAction.\n * - slugs: unique resource slugs from the project (e.g. from GET /api/resources).\n * - actions: unique permission actions from the project (e.g. from GET /api/permissions).\n */\nexport function generateTypesContent(slugs: string[], actions: string[]): string {\n const slugEntries = [...new Set(slugs)]\n .sort()\n .map((slug) => {\n const key = toPascalCase(slug);\n return key ? ` ${key}: ${JSON.stringify(slug)},` : null;\n })\n .filter(Boolean) as string[];\n\n const actionEntries = [...new Set(actions)]\n .sort()\n .map((action) => {\n const key = toPascalCase(action);\n return key ? ` ${key}: ${JSON.stringify(action)},` : null;\n })\n .filter(Boolean) as string[];\n\n const lines = [\n '// Generated by Grant CLI (grant generate-types). Do not edit by hand.',\n '// Project-specific resource slugs and actions for type-safe guards.',\n '',\n '// ResourceSlug: from project resources',\n 'export const ResourceSlug = {',\n ...slugEntries,\n '} as const;',\n '',\n 'export type ResourceSlug = (typeof ResourceSlug)[keyof typeof ResourceSlug];',\n '',\n '// ResourceAction: unique set from project permissions',\n 'export const ResourceAction = {',\n ...actionEntries,\n '} as const;',\n '',\n 'export type ResourceAction = (typeof ResourceAction)[keyof typeof ResourceAction];',\n '',\n ];\n\n return lines.join('\\n');\n}\n","import { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport { fetchPermissions, fetchResources } from '../api/client.js';\nimport { loadProfile, resolveAccessToken } from '../config/index.js';\n\nimport { generateTypesContent } from './generate-types-impl.js';\n\nimport type { Command } from 'commander';\n\nconst DEFAULT_OUTPUT = './grant-types.ts';\n\nexport function createGenerateTypesCommand(program: Command): void {\n program\n .command('generate-types')\n .description(\n \"Query the selected project's resources and permissions, then generate ResourceSlug and ResourceAction TypeScript constants\"\n )\n .option('-p, --profile <name>', 'Profile to use (default: default profile)')\n .option(\n '-o, --output <path>',\n 'Output file path (default: from grant start, or ./grant-types.ts)'\n )\n .option('--dry-run', 'Print what would be generated without writing')\n .addHelpText(\n 'after',\n '\\nExample:\\n grant generate-types --profile staging -o ./src/grant-types.ts\\n'\n )\n .action(async (options: { output?: string; dryRun?: boolean; profile?: string }) => {\n const result = await loadProfile(options.profile);\n if (!result?.config?.selectedScope) {\n console.error(\n 'No project selected for this profile. Run \"grant start\" first or use --profile <name>.'\n );\n process.exitCode = 1;\n return;\n }\n const config = result.config;\n const scope = result.config.selectedScope;\n\n const outputPath = resolve(\n process.cwd(),\n options.output ?? config.generateTypesOutputPath ?? DEFAULT_OUTPUT\n );\n const dryRun = options.dryRun === true;\n\n try {\n const accessToken = await resolveAccessToken(config);\n\n const [resources, permissions] = await Promise.all([\n fetchResources(config.apiUrl, accessToken, scope),\n fetchPermissions(config.apiUrl, accessToken, scope),\n ]);\n\n const slugs = resources.map((r) => r.slug).filter(Boolean);\n const actions = permissions.map((p) => p.action).filter(Boolean);\n\n const content = generateTypesContent(slugs, actions);\n\n if (dryRun) {\n console.log('Dry run: would write to', outputPath);\n console.log('---');\n console.log(content);\n return;\n }\n\n await writeFile(outputPath, content, { encoding: 'utf-8' });\n console.log('Generated', outputPath);\n console.log(' Resources:', resources.length, '→', slugs.length, 'unique slugs');\n console.log(' Permissions:', permissions.length, '→', actions.length, 'unique actions');\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const isUnauthorized =\n config.authMethod === 'session' &&\n (msg.includes('401') ||\n msg.includes('Unauthorized') ||\n /failed\\s*\\(\\s*401\\s*\\)/i.test(msg));\n if (isUnauthorized) {\n console.error('\\nSession expired or invalid. Run \"grant start\" to sign in again.');\n } else {\n console.error('\\n' + msg);\n }\n process.exitCode = 1;\n }\n });\n}\n","import { exec } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { platform } from 'node:os';\n\nimport inquirer from 'inquirer';\n\nimport {\n exchangeApiKey,\n exchangeCliCallback,\n fetchOrganizations,\n fetchProjects,\n loginWithEmail,\n type LoginAccount,\n type LoginResult,\n type OrganizationItem,\n type ProjectItem,\n} from '../api/client.js';\nimport {\n DEFAULT_PROFILE_NAME,\n getConfigPath,\n loadConfigFile,\n saveConfigFile,\n} from '../config/index.js';\n\nimport type { GrantConfig, GrantScope } from '../types/config.js';\nimport type { Command } from 'commander';\n\nconst AUTH_SESSION = 'session';\nconst AUTH_API_KEY = 'api-key';\n\nconst PROJECT_TENANTS = [\n { name: 'Account project (accountId:projectId)', value: 'accountProject' },\n { name: 'Organization project (organizationId:projectId)', value: 'organizationProject' },\n] as const;\n\nfunction isValidUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction normalizeApiUrl(input: string): string {\n const s = input.trim().replace(/\\/+$/, '');\n return s || input;\n}\n\n/** Scope ID must be one UUID or two UUIDs separated by a single colon (e.g. accountId:projectId). */\nfunction isValidScopeId(s: string): boolean {\n const parts = s.trim().split(':');\n if (parts.length !== 1 && parts.length !== 2) return false;\n const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return parts.every((p) => uuidRe.test(p.trim()));\n}\n\n/** Open URL in default browser (cross-platform). Do not encode the URL; it is already valid. */\nfunction openBrowser(url: string): void {\n const cmd =\n platform() === 'win32'\n ? `start \"\" \"${url}\"`\n : platform() === 'darwin'\n ? `open \"${url}\"`\n : `xdg-open \"${url}\"`;\n exec(cmd, (err) => {\n if (err) console.error('[Grant CLI] Could not open browser:', err.message);\n });\n}\n\n/**\n * Run local callback server and open GitHub OAuth; returns one-time code or throws on error.\n * Resolves when browser is redirected back with ?code= or ?error=.\n */\nfunction runGithubOAuthCallback(apiUrl: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n const rawUrl = req.url ?? '/';\n const url = new URL(rawUrl, `http://localhost`);\n const code = url.searchParams.get('code');\n const error = url.searchParams.get('error');\n const errorDescription = url.searchParams.get('error_description') ?? '';\n\n const html = (title: string, body: string) =>\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>${title}</title></head><body style=\"font-family:sans-serif;max-width:480px;margin:2rem auto;padding:0 1rem;\"><h2>${title}</h2><p>${body}</p><p>You can close this tab and return to the terminal.</p></body></html>`;\n\n if (code) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(html('Grant CLI – Signed in', 'Successfully signed in with GitHub.'));\n server.close();\n resolve(code);\n return;\n }\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(\n html(\n 'Grant CLI – Sign-in failed',\n `Error: ${error}${errorDescription ? `. ${errorDescription}` : ''}`\n )\n );\n server.close();\n reject(new Error(errorDescription || error));\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/html' });\n res.end(html('Grant CLI', 'Not found. Expecting ?code= or ?error= from OAuth redirect.'));\n });\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address();\n if (!addr || typeof addr === 'string') {\n server.close();\n reject(new Error('Could not bind callback server'));\n return;\n }\n const port = addr.port;\n const redirectUri = `http://localhost:${port}`;\n const initiateUrl = `${apiUrl.replace(/\\/+$/, '')}/api/auth/github?redirect=${encodeURIComponent(redirectUri)}`;\n openBrowser(initiateUrl);\n });\n\n server.on('error', (err) => {\n reject(err);\n });\n });\n}\n\nexport function createStartCommand(program: Command): void {\n program\n .command('start')\n .alias('setup')\n .description(\n 'Setup Grant: API URL, authentication (session or API key), account/project selection, and secure storage'\n )\n .option('-p, --profile <name>', 'Profile to create or update (default: default profile)')\n .addHelpText('after', '\\nExample:\\n grant start --profile staging # or grant setup\\n')\n .action(async (options: { profile?: string }) => {\n if (!process.stdin.isTTY) {\n console.error(\n 'Grant setup is interactive and requires a TTY. Run this command in a terminal.'\n );\n process.exit(1);\n }\n\n let file = await loadConfigFile();\n let profileName: string;\n if (options.profile?.trim()) {\n profileName = options.profile.trim();\n } else {\n const a = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'profileName',\n message: 'Profile name',\n default: file?.defaultProfile ?? DEFAULT_PROFILE_NAME,\n },\n ])) as { profileName: string };\n profileName = a.profileName.trim() || DEFAULT_PROFILE_NAME;\n }\n const existingProfile = file?.profiles[profileName];\n const baseApiUrl = existingProfile?.apiUrl ?? '';\n\n const { apiUrlRaw, authMethod } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'apiUrlRaw',\n message: 'Grant API base URL',\n default: baseApiUrl || 'http://localhost:4000',\n validate: (input: string) => {\n const url = normalizeApiUrl(input);\n if (!url) return 'API URL is required';\n if (!isValidUrl(url)) return 'Enter a valid URL (e.g. https://grant.example.com)';\n return true;\n },\n },\n {\n type: 'select' as const,\n name: 'authMethod',\n message: 'Authentication method',\n choices: [\n { name: 'Session (log in via browser)', value: AUTH_SESSION },\n { name: 'API key (clientId + secret)', value: AUTH_API_KEY },\n ],\n },\n ])) as { apiUrlRaw: string; authMethod: string };\n\n const apiUrl = normalizeApiUrl(apiUrlRaw);\n\n if (authMethod === AUTH_SESSION) {\n const { signInMethod } = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'signInMethod',\n message: 'Sign-in method',\n choices: [\n { name: 'Email', value: 'email' },\n { name: 'GitHub', value: 'github' },\n ],\n },\n ])) as { signInMethod: string };\n\n let loginResult: LoginResult;\n if (signInMethod === 'github') {\n console.log('\\nOpening browser for GitHub sign-in…');\n let code: string;\n try {\n code = await runGithubOAuthCallback(apiUrl);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\nGitHub sign-in failed:', msg);\n process.exit(1);\n }\n try {\n loginResult = await exchangeCliCallback(apiUrl, code);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n } else {\n const sessionQuestions = [\n {\n type: 'input' as const,\n name: 'email',\n message: 'Email',\n validate: (input: string) => {\n if (!input?.trim()) return 'Email is required';\n return true;\n },\n },\n {\n type: 'password' as const,\n name: 'password',\n message: 'Password',\n mask: '*',\n validate: (input: string) => {\n if (!input?.trim()) return 'Password is required';\n return true;\n },\n },\n ];\n const { email, password } = (await inquirer.prompt(\n sessionQuestions as Parameters<typeof inquirer.prompt>[0]\n )) as { email: string; password: string };\n\n try {\n loginResult = await loginWithEmail(apiUrl, email.trim(), password);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n }\n\n const { accounts, accessToken, refreshToken } = loginResult;\n if (accounts.length === 0) {\n console.error('\\nNo accounts in login response.');\n process.exit(1);\n }\n\n // Account selector: user picks which account to use (scope for organizations/projects)\n let selectedAccount: LoginAccount;\n if (accounts.length === 1) {\n selectedAccount = accounts[0];\n } else {\n const orgAccounts = accounts.filter((a: LoginAccount) => a.type === 'organization');\n const accountChoices = accounts.map((a: LoginAccount) => {\n const label =\n a.type === 'personal'\n ? 'Personal account'\n : orgAccounts.length > 1\n ? `Organization account (${a.id.slice(0, 8)})`\n : 'Organization account';\n return { name: label, value: a };\n });\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedAccount',\n message: 'Select account',\n choices: accountChoices,\n },\n ])) as { selectedAccount: LoginAccount };\n selectedAccount = result.selectedAccount;\n }\n\n let organizations: OrganizationItem[] = [];\n if (selectedAccount.type === 'organization') {\n try {\n organizations = await fetchOrganizations(apiUrl, accessToken, {\n id: selectedAccount.id,\n tenant: 'account',\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n }\n\n // Project scope: personal account → (account, id); organization account → (organization, orgId).\n // Projects live under account_projects (tenant=account) or organization_projects (tenant=organization).\n let selectedContext: { tenant: string; scopeId: string };\n if (selectedAccount.type === 'organization') {\n if (organizations.length === 0) {\n console.error(\n '\\nNo organizations in this account. Create an organization in the Grant web app, then run grant start again.'\n );\n process.exit(1);\n }\n if (organizations.length === 1) {\n selectedContext = { tenant: 'organization', scopeId: organizations[0].id };\n } else {\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedContext',\n message: 'Select organization',\n choices: organizations.map((o) => ({\n name: o.name,\n value: { tenant: 'organization', scopeId: o.id } as {\n tenant: string;\n scopeId: string;\n },\n })),\n },\n ])) as { selectedContext: { tenant: string; scopeId: string } };\n selectedContext = result.selectedContext;\n }\n } else {\n const contextChoices: Array<{\n name: string;\n value: { tenant: string; scopeId: string };\n }> = [\n { name: 'Personal account', value: { tenant: 'account', scopeId: selectedAccount.id } },\n ...organizations.map((o) => ({\n name: o.name,\n value: { tenant: 'organization', scopeId: o.id } as {\n tenant: string;\n scopeId: string;\n },\n })),\n ];\n if (contextChoices.length === 1) {\n selectedContext = contextChoices[0].value;\n } else {\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedContext',\n message: 'Select account or organization',\n choices: contextChoices,\n },\n ])) as { selectedContext: { tenant: string; scopeId: string } };\n selectedContext = result.selectedContext;\n }\n }\n\n let projects: ProjectItem[] = [];\n try {\n projects = await fetchProjects(apiUrl, accessToken, {\n tenant: selectedContext.tenant,\n id: selectedContext.scopeId,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n\n if (projects.length === 0) {\n console.error(\n '\\nNo projects in this scope. Create a project in the Grant web app, then run grant start again.'\n );\n process.exit(1);\n }\n\n const projectChoices = projects.map((p) => ({\n name: `${p.name} (${p.slug})`,\n value: p,\n }));\n const { selectedProject } = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedProject',\n message: 'Select project',\n choices: projectChoices,\n },\n ])) as { selectedProject: ProjectItem };\n\n const scope: GrantScope = {\n tenant: selectedContext.tenant === 'account' ? 'accountProject' : 'organizationProject',\n id: `${selectedContext.scopeId}:${selectedProject.id}`,\n };\n\n const { generateTypesOutputPathRaw: sessionGenPath } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'generateTypesOutputPathRaw',\n message:\n 'Default output path for generate-types (optional, leave empty for ./grant-types.ts)',\n default: existingProfile?.generateTypesOutputPath ?? '',\n validate: (input: string) => {\n const s = input.trim();\n if (!s) return true;\n if (!s.endsWith('.ts')) return 'Path should end with .ts';\n return true;\n },\n },\n ])) as { generateTypesOutputPathRaw: string };\n const generateTypesOutputPath = sessionGenPath.trim() || undefined;\n\n const sessionConfig: GrantConfig = {\n apiUrl,\n authMethod: 'session',\n session: {\n token: accessToken,\n ...(refreshToken && { refreshToken }),\n },\n selectedScope: scope,\n ...(generateTypesOutputPath && { generateTypesOutputPath }),\n };\n\n if (!file) {\n file = { defaultProfile: profileName, profiles: { [profileName]: sessionConfig } };\n } else {\n file.profiles[profileName] = sessionConfig;\n if (!file.defaultProfile) {\n file.defaultProfile = profileName;\n }\n }\n await saveConfigFile(file);\n\n console.log('\\nSetup complete. Config saved to:', getConfigPath());\n console.log(' Profile:', profileName);\n console.log(' API URL:', sessionConfig.apiUrl);\n console.log(' Auth: Session');\n console.log(' Scope tenant:', sessionConfig.selectedScope!.tenant);\n console.log(' Scope id:', sessionConfig.selectedScope!.id);\n if (sessionConfig.generateTypesOutputPath) {\n console.log(' Generate-types output:', sessionConfig.generateTypesOutputPath);\n }\n return;\n }\n\n // API-key path (inquirer v13 prompt array overload is strict; assert to satisfy types)\n const apiKeyQuestions = [\n {\n type: 'input' as const,\n name: 'clientId',\n message: 'API key client ID (UUID)',\n validate: (input: string) => {\n const trimmed = input.trim();\n if (!trimmed) return 'Client ID is required';\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n trimmed\n )\n ) {\n return 'Enter a valid UUID';\n }\n return true;\n },\n },\n {\n type: 'password' as const,\n name: 'clientSecret',\n message: 'API key client secret',\n mask: '*',\n validate: (input: string) => {\n if (!input || input.length < 32) return 'Client secret must be at least 32 characters';\n return true;\n },\n },\n {\n type: 'select' as const,\n name: 'scopeTenant',\n message: 'Scope tenant',\n choices: [...PROJECT_TENANTS],\n },\n {\n type: 'input' as const,\n name: 'scopeId',\n message: 'Scope ID (e.g. accountId:projectId or organizationId:projectId)',\n validate: (input: string) => {\n if (!input?.trim()) return 'Scope ID is required';\n if (!isValidScopeId(input))\n return 'Enter a valid scope ID: one UUID or two UUIDs separated by a colon';\n return true;\n },\n },\n ];\n const { clientId, clientSecret, scopeTenant, scopeId } = (await inquirer.prompt(\n apiKeyQuestions as Parameters<typeof inquirer.prompt>[0]\n )) as { clientId: string; clientSecret: string; scopeTenant: string; scopeId: string };\n\n const scope: GrantScope = {\n tenant: scopeTenant,\n id: scopeId.trim(),\n };\n\n try {\n await exchangeApiKey(apiUrl, {\n clientId: clientId.trim(),\n clientSecret,\n scope: { id: scope.id, tenant: scope.tenant },\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n\n const { generateTypesOutputPathRaw } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'generateTypesOutputPathRaw',\n message:\n 'Default output path for generate-types (optional, leave empty for ./grant-types.ts)',\n default: existingProfile?.generateTypesOutputPath ?? '',\n validate: (input: string) => {\n const s = input.trim();\n if (!s) return true;\n if (!s.endsWith('.ts')) return 'Path should end with .ts';\n return true;\n },\n },\n ])) as { generateTypesOutputPathRaw: string };\n\n const generateTypesOutputPath = generateTypesOutputPathRaw.trim() || undefined;\n\n const config: GrantConfig = {\n apiUrl,\n authMethod: 'api-key',\n apiKey: {\n clientId: clientId.trim(),\n clientSecret,\n scope,\n },\n selectedScope: scope,\n ...(generateTypesOutputPath && { generateTypesOutputPath }),\n };\n\n if (!file) {\n file = { defaultProfile: profileName, profiles: { [profileName]: config } };\n } else {\n file.profiles[profileName] = config;\n if (!file.defaultProfile) {\n file.defaultProfile = profileName;\n }\n }\n await saveConfigFile(file);\n\n console.log('\\nSetup complete. Config saved to:', getConfigPath());\n console.log(' Profile:', profileName);\n console.log(' API URL:', config.apiUrl);\n console.log(' Auth: API key');\n console.log(' Scope tenant:', config.selectedScope!.tenant);\n console.log(' Scope id:', config.selectedScope!.id);\n if (config.generateTypesOutputPath) {\n console.log(' Generate-types output:', config.generateTypesOutputPath);\n }\n });\n}\n","declare const __GRANT_CLI_VERSION__: string;\n\nexport function getPackageVersion(): string {\n return typeof __GRANT_CLI_VERSION__ === 'string' ? __GRANT_CLI_VERSION__ : '0.0.0';\n}\n","import { getPackageVersion } from '../utils/package.js';\n\nimport type { Command } from 'commander';\n\nexport function createVersionCommand(program: Command): void {\n program\n .command('version')\n .description('Show CLI version (use -j for JSON)')\n .option('-j, --json', 'Output version as JSON')\n .action((options: { json?: boolean }) => {\n const version = getPackageVersion();\n if (options.json) {\n console.log(JSON.stringify({ version }));\n } else {\n console.log(version);\n }\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\n\nimport { createConfigCommand } from './commands/config-cmd.js';\nimport { createGenerateTypesCommand } from './commands/generate-types.js';\nimport { createStartCommand } from './commands/start.js';\nimport { createVersionCommand } from './commands/version.js';\n\nconst program = new Command();\n\nprogram\n .name('grant')\n .description('Grant CLI - Setup, authentication, and typings generation for @grantjs/server')\n .enablePositionalOptions()\n .addHelpText(\n 'after',\n `\nExamples:\n grant start Interactive setup (API URL, auth, scope)\n grant start --profile staging Setup or update a named profile\n grant config list List profiles and default\n grant config show --profile staging Show config for a profile\n grant config set api-url http://localhost:4000 --profile default\n grant generate-types --profile staging Generate types for a profile\n grant --help Show this help\n grant config set --help Show help for config set subcommands\n`\n );\n\ncreateVersionCommand(program);\ncreateConfigCommand(program);\ncreateStartCommand(program);\ncreateGenerateTypesCommand(program);\n\nprogram.parse();\n"],"names":["CommanderError","InvalidArgumentError","require$$0","Argument","Help","cmd","option","argument","command","Option","str","suggestSimilar","suggestSimilar_1","process","require$$5","require$$6","require$$7","require$$8","require$$9","Command","path","require$$1","require$$2","require$$3","require$$4","commander","program","file","data","isValidUrl","normalizeApiUrl","isValidScopeId","resolve","error","scope","generateTypesOutputPath"],"mappings":";;;;;;;;;;;;;;;;;;;;EAGA,MAAMA,wBAAuB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,YAAM,OAAO;AAEb,YAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,WAAK,OAAO,KAAK,YAAY;AAC7B,WAAK,OAAO;AACZ,WAAK,WAAW;AAChB,WAAK,cAAc;AAAA,IACvB;AAAA,EACA;AAAA,EAKA,MAAMC,8BAA6BD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhD,YAAY,SAAS;AACnB,YAAM,GAAG,6BAA6B,OAAO;AAE7C,YAAM,kBAAkB,MAAM,KAAK,WAAW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AsC,eAAe;AACjE,YAAQ,IAAI,cAAc,WAAW;AACrC,YAAQ,IAAI,cAAc,OAAO,MAAM;AACvC,YAAQ,IAAI,iBAAiB;AAC7B,YAAQ,IAAI,mBAAmB,OAAO,cAAe,MAAM;AAC3D,YAAQ,IAAI,eAAe,OAAO,cAAe,EAAE;AACnD,QAAI,OAAO,yBAAyB;AAClC,cAAQ,IAAI,4BAA4B,OAAO,uBAAuB;AAAA,IACxE;AAAA,EACF,CAAC;AACL;ACljBO,SAAS,oBAA4B;AAC1C,SAAmD;AACrD;ACAO,SAAS,qBAAqBT,UAAwB;AAC3D,EAAAA,SACG,QAAQ,SAAS,EACjB,YAAY,oCAAoC,EAChD,OAAO,cAAc,wBAAwB,EAC7C,OAAO,CAAC,YAAgC;AACvC,UAAM,UAAU,kBAAA;AAChB,QAAI,QAAQ,MAAM;AAChB,cAAQ,IAAI,KAAK,UAAU,EAAE,QAAA,CAAS,CAAC;AAAA,IACzC,OAAO;AACL,cAAQ,IAAI,OAAO;AAAA,IACrB;AAAA,EACF,CAAC;AACL;ACRA,MAAM,UAAU,IAAI,QAAA;AAEpB,QACG,KAAK,OAAO,EACZ,YAAY,+EAA+E,EAC3F,0BACA;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF;AAEF,qBAAqB,OAAO;AAC5B,oBAAoB,OAAO;AAC3B,mBAAmB,OAAO;AAC1B,2BAA2B,OAAO;AAElC,QAAQ,MAAA;","x_google_ignoreList":[0,1,2,3,4,5,6,7]}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["process","commander"],"sources":["../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js","../../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs","../src/api/client.ts","../src/config/resolve-token.ts","../src/config/storage.ts","../src/commands/config-cmd.ts","../src/commands/generate-types-impl.ts","../src/commands/generate-types.ts","../src/commands/start.ts","../src/utils/package.ts","../src/commands/version.ts","../src/index.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help, stripColor } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","/**\n * Minimal REST client for Grant API.\n * Used by start (token exchange) and generate-types (resources/permissions).\n */\n\nexport interface TokenExchangeScope {\n id: string;\n tenant: string;\n}\n\nexport interface TokenExchangeRequest {\n clientId: string;\n clientSecret: string;\n scope: TokenExchangeScope;\n}\n\nexport interface TokenExchangeResponse {\n accessToken: string;\n expiresIn: number;\n}\n\nexport interface ApiErrorBody {\n success?: false;\n error?: { code?: string; message?: string };\n reason?: string;\n code?: string;\n}\n\n/** Set GRANT_CLI_DEBUG=1 for extra verbosity (e.g. request headers). */\nconst _DEBUG = process.env.GRANT_CLI_DEBUG === '1' || process.env.GRANT_CLI_DEBUG === 'true';\n\n/** Log request URL, status, and response body when an API call fails (always on failure). */\nfunction logFailedRequest(\n label: string,\n url: string,\n status: number,\n bodyText: string,\n extra?: Record<string, unknown>\n): void {\n console.error(`[Grant CLI] ${label} failed`);\n console.error(`[Grant CLI] URL: ${url}`);\n console.error(`[Grant CLI] Status: ${status}`);\n if (bodyText) {\n try {\n const parsed = JSON.parse(bodyText) as Record<string, unknown>;\n console.error(`[Grant CLI] Response: ${JSON.stringify(parsed, null, 2)}`);\n } catch {\n console.error(`[Grant CLI] Response (raw): ${bodyText.slice(0, 500)}`);\n }\n }\n if (extra && Object.keys(extra).length > 0) {\n console.error(`[Grant CLI] Extra: ${JSON.stringify(extra)}`);\n }\n}\n\nexport interface LoginAccount {\n id: string;\n type: string;\n ownerId: string | null;\n [key: string]: unknown;\n}\n\nexport interface LoginResult {\n /** Primary account (personal or first). */\n account: LoginAccount;\n /** All user accounts from login (personal + organization). Use for account selector. */\n accounts: LoginAccount[];\n accessToken: string;\n refreshToken: string;\n}\n\nexport interface OrganizationItem {\n id: string;\n name: string;\n [key: string]: unknown;\n}\n\nexport interface ProjectItem {\n id: string;\n name: string;\n slug: string;\n [key: string]: unknown;\n}\n\n/**\n * Build a detailed message when a request fails before or during fetch (e.g. connection refused, DNS, SSL).\n */\nfunction detailFetchError(url: string, err: unknown): string {\n const attempted = `Request URL: ${url}`;\n const msg = err instanceof Error ? err.message : String(err);\n const cause =\n err instanceof Error && err.cause instanceof Error\n ? err.cause.message\n : err instanceof Error && typeof (err as NodeJS.ErrnoException).code === 'string'\n ? (err as NodeJS.ErrnoException).code\n : null;\n if (cause && cause !== msg) {\n return `Token exchange failed: ${msg}. Cause: ${cause}. ${attempted}`;\n }\n return `Token exchange failed: ${msg}. ${attempted}`;\n}\n\n/**\n * Exchange API key (clientId + clientSecret) for an access token.\n * POST {baseUrl}/api/auth/token\n */\nexport async function exchangeApiKey(\n baseUrl: string,\n body: TokenExchangeRequest\n): Promise<TokenExchangeResponse> {\n const url = new URL('/api/auth/token', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err), { cause: err });\n }\n\n if (!res.ok) {\n const text = await res.text();\n let message = `Token exchange failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const data = (await res.json()) as { data?: TokenExchangeResponse };\n if (!data?.data?.accessToken) {\n throw new Error('Invalid token response: missing accessToken');\n }\n return data.data;\n}\n\n/**\n * Login with email and password. POST {baseUrl}/api/auth/login\n * Returns access token, refresh token, and primary account (personal).\n */\nexport async function loginWithEmail(\n baseUrl: string,\n email: string,\n password: string\n): Promise<LoginResult> {\n const url = new URL('/api/auth/login', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n provider: 'email',\n providerId: email.trim(),\n providerData: { password },\n }),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err), { cause: err });\n }\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Login', url, res.status, text);\n let message = `Login failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const json = (await res.json()) as {\n data?: {\n accounts?: Array<LoginAccount>;\n accessToken?: string;\n refreshToken?: string;\n };\n };\n const data = json.data;\n if (\n !data?.accessToken ||\n !data?.refreshToken ||\n !Array.isArray(data.accounts) ||\n data.accounts.length === 0\n ) {\n throw new Error('Invalid login response: missing accessToken, refreshToken, or accounts');\n }\n const primary = data.accounts.find((a) => a.type === 'personal') ?? data.accounts[0];\n return {\n account: primary,\n accounts: data.accounts,\n accessToken: data.accessToken,\n refreshToken: data.refreshToken,\n };\n}\n\n/**\n * Exchange one-time CLI OAuth code for session. POST {baseUrl}/api/auth/cli-callback\n * Used after browser redirect from GitHub OAuth when redirect_uri was localhost.\n */\nexport async function exchangeCliCallback(baseUrl: string, code: string): Promise<LoginResult> {\n const url = new URL('/api/auth/cli-callback', baseUrl).href;\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n });\n } catch (err) {\n throw new Error(detailFetchError(url, err), { cause: err });\n }\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('CLI callback exchange', url, res.status, text);\n let message = `Code exchange failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) message = data.error.message;\n } catch {\n if (text) message = text.slice(0, 200);\n }\n throw new Error(message);\n }\n\n const json = (await res.json()) as {\n data?: {\n accessToken?: string;\n refreshToken?: string;\n accounts?: Array<LoginAccount>;\n };\n };\n const data = json.data;\n if (\n !data?.accessToken ||\n !data?.refreshToken ||\n !Array.isArray(data.accounts) ||\n data.accounts.length === 0\n ) {\n throw new Error(\n 'Invalid CLI callback response: missing accessToken, refreshToken, or accounts'\n );\n }\n const primary = data.accounts.find((a) => a.type === 'personal') ?? data.accounts[0];\n return {\n account: primary,\n accounts: data.accounts,\n accessToken: data.accessToken,\n refreshToken: data.refreshToken,\n };\n}\n\n/**\n * Fetch organizations (paginated). Requires Bearer token. GET /api/organizations?scopeId=&tenant=\n * Scope is the account context (user's personal account id, tenant 'account').\n */\nexport async function fetchOrganizations(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<OrganizationItem[]> {\n const items: OrganizationItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/organizations', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Organizations request', url.href, res.status, text, {\n scopeId: scope.id,\n tenant: scope.tenant,\n });\n let msg = `Organizations request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n if (data?.reason) msg += ` — ${data.reason}`;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { items?: OrganizationItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid organizations response: missing data');\n\n const list = data.items ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\n/**\n * Fetch projects for a scope (account or organization). Paginated. Requires Bearer token.\n * GET /api/projects?scopeId=&tenant=\n */\nexport async function fetchProjects(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<ProjectItem[]> {\n const items: ProjectItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/projects', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n logFailedRequest('Projects request', url.href, res.status, text, {\n scopeId: scope.id,\n tenant: scope.tenant,\n });\n let msg = `Projects request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n if (data?.reason) msg += ` — ${data.reason}`;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { projects?: ProjectItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid projects response: missing data');\n\n const list = data.projects ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\nexport interface ApiScope {\n id: string;\n tenant: string;\n}\n\nexport interface ResourceItem {\n id: string;\n slug: string;\n name: string;\n actions: string[];\n [key: string]: unknown;\n}\n\nexport interface PermissionItem {\n id: string;\n action: string;\n name: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_PAGE_SIZE = 50;\n\n/**\n * Fetch all resources for a scope (paginated). Requires Bearer token.\n */\nexport async function fetchResources(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<ResourceItem[]> {\n const items: ResourceItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/resources', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n let msg = `Resources request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { resources?: ResourceItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid resources response: missing data');\n\n const list = data.resources ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n\n/**\n * Fetch all permissions for a scope (paginated). Requires Bearer token.\n */\nexport async function fetchPermissions(\n baseUrl: string,\n accessToken: string,\n scope: ApiScope\n): Promise<PermissionItem[]> {\n const items: PermissionItem[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const url = new URL('/api/permissions', baseUrl);\n url.searchParams.set('scopeId', scope.id);\n url.searchParams.set('tenant', scope.tenant);\n url.searchParams.set('page', String(page));\n url.searchParams.set('limit', String(DEFAULT_PAGE_SIZE));\n\n const res = await fetch(url.href, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n if (!res.ok) {\n const text = await res.text();\n let msg = `Permissions request failed (${res.status})`;\n try {\n const data = JSON.parse(text) as ApiErrorBody;\n if (data?.error?.message) msg = data.error.message;\n } catch {\n if (text) msg = text.slice(0, 200);\n }\n throw new Error(msg);\n }\n\n const json = (await res.json()) as {\n data?: { permissions?: PermissionItem[]; totalCount?: number; hasNextPage?: boolean };\n };\n const data = json.data;\n if (!data) throw new Error('Invalid permissions response: missing data');\n\n const list = data.permissions ?? [];\n items.push(...list);\n hasNextPage = data.hasNextPage === true && list.length > 0;\n page += 1;\n }\n\n return items;\n}\n","import { exchangeApiKey } from '../api/client.js';\nimport type { GrantConfig } from '../types/config.js';\n\n/**\n * Resolve a valid access token from stored config.\n * Only tokens are stored (no credentials). Session auth does not auto-refresh; user must re-auth when the access token expires.\n *\n * - API key: exchanges clientId + clientSecret for a fresh token (no credentials stored after exchange).\n * - Session: returns the stored access token. When it expires, the user must run \"grant start\" again to re-authenticate.\n */\nexport async function resolveAccessToken(config: GrantConfig): Promise<string> {\n if (config.authMethod === 'api-key' && config.apiKey) {\n const { accessToken } = await exchangeApiKey(config.apiUrl, {\n clientId: config.apiKey.clientId,\n clientSecret: config.apiKey.clientSecret,\n scope: config.apiKey.scope,\n });\n return accessToken;\n }\n if (config.authMethod === 'session' && config.session?.token) {\n return config.session.token;\n }\n throw new Error('No credentials in config. Run \"grant start\" to set up authentication.');\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nimport type { GrantConfig, GrantConfigFile } from '../types/config.js';\n\nconst CONFIG_DIR_NAME = 'grant';\nconst CONFIG_FILE_NAME = 'config.json';\nconst DEFAULT_PROFILE_NAME = 'default';\n\n/**\n * Returns the platform-specific config directory for Grant CLI.\n * - Windows: %APPDATA%\\grant\n * - Linux/macOS: $XDG_CONFIG_HOME/grant or ~/.config/grant\n */\nexport function getConfigDir(): string {\n if (platform() === 'win32') {\n const appData = process.env.APPDATA;\n if (!appData) {\n return join(homedir(), 'AppData', 'Roaming', CONFIG_DIR_NAME);\n }\n return join(appData, CONFIG_DIR_NAME);\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg) {\n return join(xdg, CONFIG_DIR_NAME);\n }\n return join(homedir(), '.config', CONFIG_DIR_NAME);\n}\n\n/**\n * Returns the path to the config file (config dir + config.json).\n */\nexport function getConfigPath(): string {\n return join(getConfigDir(), CONFIG_FILE_NAME);\n}\n\n/** Detect legacy single-profile config (apiUrl at top level, no profiles). */\nfunction isLegacyConfig(data: unknown): data is GrantConfig {\n if (!data || typeof data !== 'object') return false;\n const o = data as Record<string, unknown>;\n return typeof o.apiUrl === 'string' && !('profiles' in o);\n}\n\n/**\n * Load config file from disk. Migrates legacy single-config to profiles shape.\n * Returns null if file does not exist or is invalid.\n */\nexport async function loadConfigFile(): Promise<GrantConfigFile | null> {\n const path = getConfigPath();\n try {\n const raw = await readFile(path, 'utf-8');\n const data = JSON.parse(raw) as unknown;\n if (!data || typeof data !== 'object') return null;\n\n if (isLegacyConfig(data)) {\n const file: GrantConfigFile = {\n defaultProfile: DEFAULT_PROFILE_NAME,\n profiles: { [DEFAULT_PROFILE_NAME]: data },\n };\n await saveConfigFile(file);\n return file;\n }\n\n const file = data as GrantConfigFile;\n if (\n typeof file.defaultProfile !== 'string' ||\n !file.profiles ||\n typeof file.profiles !== 'object'\n ) {\n return null;\n }\n return file;\n } catch {\n return null;\n }\n}\n\n/**\n * Save config file to disk. Creates config dir if needed. Sets file mode to 0o600 (owner read/write only).\n */\nexport async function saveConfigFile(file: GrantConfigFile): Promise<void> {\n const dir = getConfigDir();\n const path = getConfigPath();\n await mkdir(dir, { recursive: true, mode: 0o700 });\n await writeFile(path, JSON.stringify(file, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n flag: 'w',\n });\n}\n\n/**\n * Resolve which profile name to use: explicit name, or file's default, or \"default\".\n */\nexport function resolveProfileName(file: GrantConfigFile, profileFlag: string | undefined): string {\n if (profileFlag?.trim()) return profileFlag.trim();\n return file.defaultProfile || DEFAULT_PROFILE_NAME;\n}\n\n/**\n * Get config for a profile. Returns null if profile does not exist.\n */\nexport function getProfileConfig(file: GrantConfigFile, profileName: string): GrantConfig | null {\n return file.profiles[profileName] ?? null;\n}\n\n/**\n * List profile names. Returns empty array if no file.\n */\nexport function listProfileNames(file: GrantConfigFile | null): string[] {\n if (!file?.profiles) return [];\n return Object.keys(file.profiles);\n}\n\n/** Default profile name constant for use in prompts/help. */\nexport { DEFAULT_PROFILE_NAME };\n\n/**\n * Load config file and return the default profile's config.\n * Convenience for callers that only need one profile (default). Returns null if no file or default profile missing.\n */\nexport async function loadConfig(): Promise<GrantConfig | null> {\n const file = await loadConfigFile();\n if (!file) return null;\n const name = resolveProfileName(file, undefined);\n return getProfileConfig(file, name) ?? null;\n}\n\n/**\n * Load config file and return the resolved profile's config plus file and name.\n * Use when you need to read and then update (save) the file. Returns null if no file or profile does not exist.\n */\nexport async function loadProfile(profileFlag?: string): Promise<{\n file: GrantConfigFile;\n config: GrantConfig;\n profileName: string;\n} | null> {\n const file = await loadConfigFile();\n if (!file) return null;\n const profileName = resolveProfileName(file, profileFlag);\n const config = getProfileConfig(file, profileName);\n if (!config) return null;\n return { file, config, profileName };\n}\n","import { existsSync } from 'node:fs';\n\nimport type { Command } from 'commander';\n\nimport {\n getConfigPath,\n listProfileNames,\n loadConfigFile,\n loadProfile,\n saveConfigFile,\n} from '../config/index.js';\nimport type { GrantConfig, GrantConfigFile, GrantScope } from '../types/config.js';\n\nconst VALID_TENANTS = ['accountProject', 'organizationProject'] as const;\n\nasync function requireProfile(profileFlag?: string): Promise<{\n file: GrantConfigFile;\n config: GrantConfig;\n profileName: string;\n}> {\n const result = await loadProfile(profileFlag);\n if (!result) {\n console.error('No config found, or profile does not exist. Run \"grant start\" first.');\n process.exit(1);\n }\n return result;\n}\n\nfunction isValidUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction normalizeApiUrl(input: string): string {\n return input.trim().replace(/\\/+$/, '') || input;\n}\n\nfunction isValidScopeId(s: string): boolean {\n const parts = s.trim().split(':');\n if (parts.length !== 1 && parts.length !== 2) return false;\n const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return parts.every((p) => uuidRe.test(p.trim()));\n}\n\nexport function createConfigCommand(program: Command): void {\n const configCmd = program\n .command('config')\n .description('View and edit Grant CLI config (path, list, show, set)');\n\n configCmd\n .command('path')\n .description('Print the path to the config file')\n .action(() => {\n console.log(getConfigPath());\n });\n\n configCmd\n .command('list')\n .description('List profile names and show which is the default')\n .action(async () => {\n const file = await loadConfigFile();\n const path = getConfigPath();\n const exists = existsSync(path);\n console.log('Config path:', path);\n console.log('Exists:', exists);\n if (!file || Object.keys(file.profiles).length === 0) {\n console.log('No profiles. Run \"grant start\" to create one.');\n return;\n }\n const names = listProfileNames(file);\n const defaultName = file.defaultProfile || names[0];\n console.log('Default profile:', defaultName);\n names.forEach((name) => {\n const marker = name === defaultName ? ' (default)' : '';\n console.log(' -', name + marker);\n });\n });\n\n configCmd\n .command('show')\n .description('Show config summary for a profile (path, apiUrl, authMethod, scope; no secrets)')\n .option('-p, --profile <name>', 'Profile to show (default: default profile)')\n .action(async (options: { profile?: string }) => {\n const path = getConfigPath();\n const exists = existsSync(path);\n console.log('Config path:', path);\n console.log('Exists:', exists);\n const result = await loadProfile(options.profile);\n if (!result) {\n console.log('No config or profile not found. Run \"grant start\" first.');\n return;\n }\n const { config, profileName } = result;\n console.log('Profile:', profileName);\n console.log('API URL:', config.apiUrl);\n console.log('Auth method:', config.authMethod);\n if (config.selectedScope) {\n console.log('Selected scope:', `${config.selectedScope.tenant}:${config.selectedScope.id}`);\n }\n if (config.generateTypesOutputPath) {\n console.log('Generate-types output:', config.generateTypesOutputPath);\n }\n });\n\n const setCmd = configCmd\n .command('set')\n .description(\n 'Set a config value for a profile (use a subcommand: api-url, auth-method, credentials, scope, generate-types-output, default-profile)'\n )\n .option('-p, --profile <name>', 'Profile to update (default: default profile)');\n\n setCmd\n .command('api-url <url>')\n .description('Set the Grant API base URL (e.g. http://localhost:4000)')\n .action(async (url: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const normalized = normalizeApiUrl(url);\n if (!normalized) {\n console.error('URL is required.');\n process.exit(1);\n }\n if (!isValidUrl(normalized)) {\n console.error('Enter a valid URL (e.g. https://grant.example.com)');\n process.exit(1);\n }\n config.apiUrl = normalized;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('api-url set to', config.apiUrl, '(profile:', profileName + ')');\n });\n\n setCmd\n .command('auth-method <method>')\n .description('Set authentication method: session or api-key')\n .action(async (method: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const m = method.toLowerCase();\n if (m !== 'session' && m !== 'api-key') {\n console.error('auth-method must be \"session\" or \"api-key\"');\n process.exit(1);\n }\n config.authMethod = m as 'session' | 'api-key';\n if (config.authMethod === 'session') {\n delete config.apiKey;\n } else {\n delete config.session;\n }\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('auth-method set to', config.authMethod, '(profile:', profileName + ')');\n });\n\n setCmd\n .command('credentials')\n .description('Set API key credentials (client ID, secret, and scope)')\n .option('--client-id <id>', 'API key client ID (UUID)')\n .option('--client-secret <secret>', 'API key client secret (min 32 characters)')\n .option('--scope-tenant <tenant>', `Scope tenant: ${VALID_TENANTS.join(' or ')}`)\n .option('--scope-id <id>', 'Scope ID (e.g. accountId:projectId or organizationId:projectId)')\n .action(\n async (\n opts: { clientId?: string; clientSecret?: string; scopeTenant?: string; scopeId?: string },\n cmd: Command\n ) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const { clientId, clientSecret, scopeTenant, scopeId } = opts;\n if (!clientId?.trim()) {\n console.error('--client-id is required');\n process.exit(1);\n }\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n clientId.trim()\n )\n ) {\n console.error('--client-id must be a valid UUID');\n process.exit(1);\n }\n if (!clientSecret || clientSecret.length < 32) {\n console.error('--client-secret is required and must be at least 32 characters');\n process.exit(1);\n }\n if (\n !scopeTenant ||\n !VALID_TENANTS.includes(scopeTenant as (typeof VALID_TENANTS)[number])\n ) {\n console.error('--scope-tenant is required and must be one of:', VALID_TENANTS.join(', '));\n process.exit(1);\n }\n if (!scopeId?.trim()) {\n console.error('--scope-id is required');\n process.exit(1);\n }\n if (!isValidScopeId(scopeId)) {\n console.error('--scope-id must be one UUID or two UUIDs separated by a colon');\n process.exit(1);\n }\n const scope: GrantScope = { tenant: scopeTenant, id: scopeId.trim() };\n config.authMethod = 'api-key';\n config.apiKey = {\n clientId: clientId.trim(),\n clientSecret,\n scope,\n };\n config.selectedScope = scope;\n delete config.session;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log('credentials and scope updated (profile:', profileName + ')');\n }\n );\n\n setCmd\n .command('scope')\n .description('Set the selected project scope (tenant and ID)')\n .option('--tenant <tenant>', `Scope tenant: ${VALID_TENANTS.join(' or ')}`)\n .option('--scope-id <id>', 'Scope ID (e.g. accountId:projectId or organizationId:projectId)')\n .action(async (options: { tenant?: string; scopeId?: string }, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const { tenant, scopeId } = options;\n if (!tenant || !VALID_TENANTS.includes(tenant as (typeof VALID_TENANTS)[number])) {\n console.error('--tenant is required and must be one of:', VALID_TENANTS.join(', '));\n process.exit(1);\n }\n if (!scopeId?.trim()) {\n console.error('--scope-id is required');\n process.exit(1);\n }\n if (!isValidScopeId(scopeId)) {\n console.error('--scope-id must be one UUID or two UUIDs separated by a colon');\n process.exit(1);\n }\n config.selectedScope = { tenant, id: scopeId.trim() };\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'scope set to',\n config.selectedScope!.tenant + ':' + config.selectedScope!.id,\n '(profile:',\n profileName + ')'\n );\n });\n\n setCmd\n .command('generate-types-output <path>')\n .description('Set default output path for grant generate-types (e.g. ./src/grant-types.ts)')\n .action(async (path: string, cmd: Command) => {\n const profileFlag = cmd.parent?.opts?.()?.profile;\n const { file, config, profileName } = await requireProfile(profileFlag);\n const trimmed = path.trim();\n if (!trimmed) {\n delete config.generateTypesOutputPath;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'generate-types-output cleared (will use ./grant-types.ts) (profile:',\n profileName + ')'\n );\n return;\n }\n if (!trimmed.endsWith('.ts')) {\n console.error('Path should end with .ts');\n process.exit(1);\n }\n config.generateTypesOutputPath = trimmed;\n file.profiles[profileName] = config;\n await saveConfigFile(file);\n console.log(\n 'generate-types-output set to',\n config.generateTypesOutputPath,\n '(profile:',\n profileName + ')'\n );\n });\n\n setCmd\n .command('default-profile <name>')\n .description('Set the default profile (used when --profile is not passed)')\n .action(async (name: string) => {\n const file = await loadConfigFile();\n if (!file) {\n console.error('No config found. Run \"grant start\" first.');\n process.exit(1);\n }\n const trimmed = name.trim();\n if (!file.profiles[trimmed]) {\n console.error(\n 'Profile \"' + trimmed + '\" does not exist. Use \"grant config list\" to see profiles.'\n );\n process.exit(1);\n }\n file.defaultProfile = trimmed;\n await saveConfigFile(file);\n console.log('default profile set to', trimmed);\n });\n}\n","/**\n * Generate TypeScript content for ResourceSlug and ResourceAction from project data.\n * Mirrors the shape of @grantjs/constants permissions/resources.ts.\n */\n\n/** Convert slug (e.g. \"user-documents\") or action (e.g. \"Create\") to PascalCase key. */\nexport function toPascalCase(s: string): string {\n return s\n .split(/[-_:.\\s]+/)\n .map((part) => (part.length > 0 ? part[0]!.toUpperCase() + part.slice(1).toLowerCase() : ''))\n .join('');\n}\n\n/**\n * Generate the TypeScript file content for ResourceSlug and ResourceAction.\n * - slugs: unique resource slugs from the project (e.g. from GET /api/resources).\n * - actions: unique permission actions from the project (e.g. from GET /api/permissions).\n */\nexport function generateTypesContent(slugs: string[], actions: string[]): string {\n const slugEntries = [...new Set(slugs)]\n .sort()\n .map((slug) => {\n const key = toPascalCase(slug);\n return key ? ` ${key}: ${JSON.stringify(slug)},` : null;\n })\n .filter(Boolean) as string[];\n\n const actionEntries = [...new Set(actions)]\n .sort()\n .map((action) => {\n const key = toPascalCase(action);\n return key ? ` ${key}: ${JSON.stringify(action)},` : null;\n })\n .filter(Boolean) as string[];\n\n const lines = [\n '// Generated by Grant CLI (grant generate-types). Do not edit by hand.',\n '// Project-specific resource slugs and actions for type-safe guards.',\n '',\n '// ResourceSlug: from project resources',\n 'export const ResourceSlug = {',\n ...slugEntries,\n '} as const;',\n '',\n 'export type ResourceSlug = (typeof ResourceSlug)[keyof typeof ResourceSlug];',\n '',\n '// ResourceAction: unique set from project permissions',\n 'export const ResourceAction = {',\n ...actionEntries,\n '} as const;',\n '',\n 'export type ResourceAction = (typeof ResourceAction)[keyof typeof ResourceAction];',\n '',\n ];\n\n return lines.join('\\n');\n}\n","import { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport type { Command } from 'commander';\n\nimport { fetchPermissions, fetchResources } from '../api/client.js';\nimport { loadProfile, resolveAccessToken } from '../config/index.js';\nimport { generateTypesContent } from './generate-types-impl.js';\n\nconst DEFAULT_OUTPUT = './grant-types.ts';\n\nexport function createGenerateTypesCommand(program: Command): void {\n program\n .command('generate-types')\n .description(\n \"Query the selected project's resources and permissions, then generate ResourceSlug and ResourceAction TypeScript constants\"\n )\n .option('-p, --profile <name>', 'Profile to use (default: default profile)')\n .option(\n '-o, --output <path>',\n 'Output file path (default: from grant start, or ./grant-types.ts)'\n )\n .option('--dry-run', 'Print what would be generated without writing')\n .addHelpText(\n 'after',\n '\\nExample:\\n grant generate-types --profile staging -o ./src/grant-types.ts\\n'\n )\n .action(async (options: { output?: string; dryRun?: boolean; profile?: string }) => {\n const result = await loadProfile(options.profile);\n if (!result?.config?.selectedScope) {\n console.error(\n 'No project selected for this profile. Run \"grant start\" first or use --profile <name>.'\n );\n process.exitCode = 1;\n return;\n }\n const config = result.config;\n const scope = result.config.selectedScope;\n\n const outputPath = resolve(\n process.cwd(),\n options.output ?? config.generateTypesOutputPath ?? DEFAULT_OUTPUT\n );\n const dryRun = options.dryRun === true;\n\n try {\n const accessToken = await resolveAccessToken(config);\n\n const [resources, permissions] = await Promise.all([\n fetchResources(config.apiUrl, accessToken, scope),\n fetchPermissions(config.apiUrl, accessToken, scope),\n ]);\n\n const slugs = resources.map((r) => r.slug).filter(Boolean);\n const actions = permissions.map((p) => p.action).filter(Boolean);\n\n const content = generateTypesContent(slugs, actions);\n\n if (dryRun) {\n console.log('Dry run: would write to', outputPath);\n console.log('---');\n console.log(content);\n return;\n }\n\n await writeFile(outputPath, content, { encoding: 'utf-8' });\n console.log('Generated', outputPath);\n console.log(' Resources:', resources.length, '→', slugs.length, 'unique slugs');\n console.log(' Permissions:', permissions.length, '→', actions.length, 'unique actions');\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const isUnauthorized =\n config.authMethod === 'session' &&\n (msg.includes('401') ||\n msg.includes('Unauthorized') ||\n /failed\\s*\\(\\s*401\\s*\\)/i.test(msg));\n if (isUnauthorized) {\n console.error('\\nSession expired or invalid. Run \"grant start\" to sign in again.');\n } else {\n console.error('\\n' + msg);\n }\n process.exitCode = 1;\n }\n });\n}\n","import { spawn } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { platform } from 'node:os';\n\nimport type { Command } from 'commander';\nimport inquirer from 'inquirer';\n\nimport {\n exchangeApiKey,\n exchangeCliCallback,\n fetchOrganizations,\n fetchProjects,\n type LoginAccount,\n type LoginResult,\n loginWithEmail,\n type OrganizationItem,\n type ProjectItem,\n} from '../api/client.js';\nimport {\n DEFAULT_PROFILE_NAME,\n getConfigPath,\n loadConfigFile,\n saveConfigFile,\n} from '../config/index.js';\nimport type { GrantConfig, GrantScope } from '../types/config.js';\n\nconst AUTH_SESSION = 'session';\nconst AUTH_API_KEY = 'api-key';\n\nconst PROJECT_TENANTS = [\n { name: 'Account project (accountId:projectId)', value: 'accountProject' },\n { name: 'Organization project (organizationId:projectId)', value: 'organizationProject' },\n] as const;\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\nfunction isValidUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction normalizeApiUrl(input: string): string {\n const s = input.trim().replace(/\\/+$/, '');\n return s || input;\n}\n\n/** Scope ID must be one UUID or two UUIDs separated by a single colon (e.g. accountId:projectId). */\nfunction isValidScopeId(s: string): boolean {\n const parts = s.trim().split(':');\n if (parts.length !== 1 && parts.length !== 2) return false;\n const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return parts.every((p) => uuidRe.test(p.trim()));\n}\n\n/** Open URL in default browser (cross-platform). Uses argv arrays to avoid shell injection. */\nfunction openBrowser(url: string): void {\n if (!isValidUrl(url)) {\n console.error('[Grant CLI] Refusing to open invalid URL');\n return;\n }\n const plat = platform();\n const child =\n plat === 'win32'\n ? spawn('cmd', ['/c', 'start', '', url], {\n detached: true,\n stdio: 'ignore',\n windowsHide: true,\n })\n : plat === 'darwin'\n ? spawn('open', [url], { detached: true, stdio: 'ignore' })\n : spawn('xdg-open', [url], { detached: true, stdio: 'ignore' });\n child.unref();\n child.on('error', (err) => console.error('[Grant CLI] Could not open browser:', err.message));\n}\n\n/**\n * Run local callback server and open GitHub OAuth; returns one-time code or throws on error.\n * Resolves when browser is redirected back with ?code= or ?error=.\n */\nfunction runGithubOAuthCallback(apiUrl: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n const rawUrl = req.url ?? '/';\n const url = new URL(rawUrl, `http://localhost`);\n const code = url.searchParams.get('code');\n const error = url.searchParams.get('error');\n const errorDescription = url.searchParams.get('error_description') ?? '';\n\n const html = (title: string, body: string) =>\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>${escapeHtml(title)}</title></head><body style=\"font-family:sans-serif;max-width:480px;margin:2rem auto;padding:0 1rem;\"><h2>${escapeHtml(title)}</h2><p>${escapeHtml(body)}</p><p>You can close this tab and return to the terminal.</p></body></html>`;\n\n if (code) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(html('Grant CLI – Signed in', 'Successfully signed in with GitHub.'));\n server.close();\n resolve(code);\n return;\n }\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(\n html(\n 'Grant CLI – Sign-in failed',\n `Error: ${error}${errorDescription ? `. ${errorDescription}` : ''}`\n )\n );\n server.close();\n reject(new Error(errorDescription || error));\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/html' });\n res.end(html('Grant CLI', 'Not found. Expecting ?code= or ?error= from OAuth redirect.'));\n });\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address();\n if (!addr || typeof addr === 'string') {\n server.close();\n reject(new Error('Could not bind callback server'));\n return;\n }\n const port = addr.port;\n const redirectUri = `http://localhost:${port}`;\n const initiateUrl = `${apiUrl.replace(/\\/+$/, '')}/api/auth/github?redirect=${encodeURIComponent(redirectUri)}`;\n openBrowser(initiateUrl);\n });\n\n server.on('error', (err) => {\n reject(err);\n });\n });\n}\n\nexport function createStartCommand(program: Command): void {\n program\n .command('start')\n .alias('setup')\n .description(\n 'Setup Grant: API URL, authentication (session or API key), account/project selection, and secure storage'\n )\n .option('-p, --profile <name>', 'Profile to create or update (default: default profile)')\n .addHelpText('after', '\\nExample:\\n grant start --profile staging # or grant setup\\n')\n .action(async (options: { profile?: string }) => {\n if (!process.stdin.isTTY) {\n console.error(\n 'Grant setup is interactive and requires a TTY. Run this command in a terminal.'\n );\n process.exit(1);\n }\n\n let file = await loadConfigFile();\n let profileName: string;\n if (options.profile?.trim()) {\n profileName = options.profile.trim();\n } else {\n const a = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'profileName',\n message: 'Profile name',\n default: file?.defaultProfile ?? DEFAULT_PROFILE_NAME,\n },\n ])) as { profileName: string };\n profileName = a.profileName.trim() || DEFAULT_PROFILE_NAME;\n }\n const existingProfile = file?.profiles[profileName];\n const baseApiUrl = existingProfile?.apiUrl ?? '';\n\n const { apiUrlRaw, authMethod } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'apiUrlRaw',\n message: 'Grant API base URL',\n default: baseApiUrl || 'http://localhost:4000',\n validate: (input: string) => {\n const url = normalizeApiUrl(input);\n if (!url) return 'API URL is required';\n if (!isValidUrl(url)) return 'Enter a valid URL (e.g. https://grant.example.com)';\n return true;\n },\n },\n {\n type: 'select' as const,\n name: 'authMethod',\n message: 'Authentication method',\n choices: [\n { name: 'Session (log in via browser)', value: AUTH_SESSION },\n { name: 'API key (clientId + secret)', value: AUTH_API_KEY },\n ],\n },\n ])) as { apiUrlRaw: string; authMethod: string };\n\n const apiUrl = normalizeApiUrl(apiUrlRaw);\n\n if (authMethod === AUTH_SESSION) {\n const { signInMethod } = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'signInMethod',\n message: 'Sign-in method',\n choices: [\n { name: 'Email', value: 'email' },\n { name: 'GitHub', value: 'github' },\n ],\n },\n ])) as { signInMethod: string };\n\n let loginResult: LoginResult;\n if (signInMethod === 'github') {\n console.log('\\nOpening browser for GitHub sign-in…');\n let code: string;\n try {\n code = await runGithubOAuthCallback(apiUrl);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\nGitHub sign-in failed:', msg);\n process.exit(1);\n }\n try {\n loginResult = await exchangeCliCallback(apiUrl, code);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n } else {\n const sessionQuestions = [\n {\n type: 'input' as const,\n name: 'email',\n message: 'Email',\n validate: (input: string) => {\n if (!input?.trim()) return 'Email is required';\n return true;\n },\n },\n {\n type: 'password' as const,\n name: 'password',\n message: 'Password',\n mask: '*',\n validate: (input: string) => {\n if (!input?.trim()) return 'Password is required';\n return true;\n },\n },\n ];\n const { email, password } = (await inquirer.prompt(\n sessionQuestions as Parameters<typeof inquirer.prompt>[0]\n )) as { email: string; password: string };\n\n try {\n loginResult = await loginWithEmail(apiUrl, email.trim(), password);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n }\n\n const { accounts, accessToken, refreshToken } = loginResult;\n if (accounts.length === 0) {\n console.error('\\nNo accounts in login response.');\n process.exit(1);\n }\n\n // Account selector: user picks which account to use (scope for organizations/projects)\n let selectedAccount: LoginAccount;\n if (accounts.length === 1) {\n selectedAccount = accounts[0];\n } else {\n const orgAccounts = accounts.filter((a: LoginAccount) => a.type === 'organization');\n const accountChoices = accounts.map((a: LoginAccount) => {\n const label =\n a.type === 'personal'\n ? 'Personal account'\n : orgAccounts.length > 1\n ? `Organization account (${a.id.slice(0, 8)})`\n : 'Organization account';\n return { name: label, value: a };\n });\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedAccount',\n message: 'Select account',\n choices: accountChoices,\n },\n ])) as { selectedAccount: LoginAccount };\n selectedAccount = result.selectedAccount;\n }\n\n let organizations: OrganizationItem[] = [];\n if (selectedAccount.type === 'organization') {\n try {\n organizations = await fetchOrganizations(apiUrl, accessToken, {\n id: selectedAccount.id,\n tenant: 'account',\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n }\n\n // Project scope: personal account → (account, id); organization account → (organization, orgId).\n // Projects live under account_projects (tenant=account) or organization_projects (tenant=organization).\n let selectedContext: { tenant: string; scopeId: string };\n if (selectedAccount.type === 'organization') {\n if (organizations.length === 0) {\n console.error(\n '\\nNo organizations in this account. Create an organization in the Grant web app, then run grant start again.'\n );\n process.exit(1);\n }\n if (organizations.length === 1) {\n selectedContext = { tenant: 'organization', scopeId: organizations[0].id };\n } else {\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedContext',\n message: 'Select organization',\n choices: organizations.map((o) => ({\n name: o.name,\n value: { tenant: 'organization', scopeId: o.id } as {\n tenant: string;\n scopeId: string;\n },\n })),\n },\n ])) as { selectedContext: { tenant: string; scopeId: string } };\n selectedContext = result.selectedContext;\n }\n } else {\n const contextChoices: Array<{\n name: string;\n value: { tenant: string; scopeId: string };\n }> = [\n { name: 'Personal account', value: { tenant: 'account', scopeId: selectedAccount.id } },\n ...organizations.map((o) => ({\n name: o.name,\n value: { tenant: 'organization', scopeId: o.id } as {\n tenant: string;\n scopeId: string;\n },\n })),\n ];\n if (contextChoices.length === 1) {\n selectedContext = contextChoices[0].value;\n } else {\n const result = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedContext',\n message: 'Select account or organization',\n choices: contextChoices,\n },\n ])) as { selectedContext: { tenant: string; scopeId: string } };\n selectedContext = result.selectedContext;\n }\n }\n\n let projects: ProjectItem[] = [];\n try {\n projects = await fetchProjects(apiUrl, accessToken, {\n tenant: selectedContext.tenant,\n id: selectedContext.scopeId,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n\n if (projects.length === 0) {\n console.error(\n '\\nNo projects in this scope. Create a project in the Grant web app, then run grant start again.'\n );\n process.exit(1);\n }\n\n const projectChoices = projects.map((p) => ({\n name: `${p.name} (${p.slug})`,\n value: p,\n }));\n const { selectedProject } = (await inquirer.prompt([\n {\n type: 'select' as const,\n name: 'selectedProject',\n message: 'Select project',\n choices: projectChoices,\n },\n ])) as { selectedProject: ProjectItem };\n\n const scope: GrantScope = {\n tenant: selectedContext.tenant === 'account' ? 'accountProject' : 'organizationProject',\n id: `${selectedContext.scopeId}:${selectedProject.id}`,\n };\n\n const { generateTypesOutputPathRaw: sessionGenPath } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'generateTypesOutputPathRaw',\n message:\n 'Default output path for generate-types (optional, leave empty for ./grant-types.ts)',\n default: existingProfile?.generateTypesOutputPath ?? '',\n validate: (input: string) => {\n const s = input.trim();\n if (!s) return true;\n if (!s.endsWith('.ts')) return 'Path should end with .ts';\n return true;\n },\n },\n ])) as { generateTypesOutputPathRaw: string };\n const generateTypesOutputPath = sessionGenPath.trim() || undefined;\n\n const sessionConfig: GrantConfig = {\n apiUrl,\n authMethod: 'session',\n session: {\n token: accessToken,\n ...(refreshToken && { refreshToken }),\n },\n selectedScope: scope,\n ...(generateTypesOutputPath && { generateTypesOutputPath }),\n };\n\n if (!file) {\n file = { defaultProfile: profileName, profiles: { [profileName]: sessionConfig } };\n } else {\n file.profiles[profileName] = sessionConfig;\n if (!file.defaultProfile) {\n file.defaultProfile = profileName;\n }\n }\n await saveConfigFile(file);\n\n console.log('\\nSetup complete. Config saved to:', getConfigPath());\n console.log(' Profile:', profileName);\n console.log(' API URL:', sessionConfig.apiUrl);\n console.log(' Auth: Session');\n console.log(' Scope tenant:', sessionConfig.selectedScope!.tenant);\n console.log(' Scope id:', sessionConfig.selectedScope!.id);\n if (sessionConfig.generateTypesOutputPath) {\n console.log(' Generate-types output:', sessionConfig.generateTypesOutputPath);\n }\n return;\n }\n\n // API-key path (inquirer v13 prompt array overload is strict; assert to satisfy types)\n const apiKeyQuestions = [\n {\n type: 'input' as const,\n name: 'clientId',\n message: 'API key client ID (UUID)',\n validate: (input: string) => {\n const trimmed = input.trim();\n if (!trimmed) return 'Client ID is required';\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n trimmed\n )\n ) {\n return 'Enter a valid UUID';\n }\n return true;\n },\n },\n {\n type: 'password' as const,\n name: 'clientSecret',\n message: 'API key client secret',\n mask: '*',\n validate: (input: string) => {\n if (!input || input.length < 32) return 'Client secret must be at least 32 characters';\n return true;\n },\n },\n {\n type: 'select' as const,\n name: 'scopeTenant',\n message: 'Scope tenant',\n choices: [...PROJECT_TENANTS],\n },\n {\n type: 'input' as const,\n name: 'scopeId',\n message: 'Scope ID (e.g. accountId:projectId or organizationId:projectId)',\n validate: (input: string) => {\n if (!input?.trim()) return 'Scope ID is required';\n if (!isValidScopeId(input))\n return 'Enter a valid scope ID: one UUID or two UUIDs separated by a colon';\n return true;\n },\n },\n ];\n const { clientId, clientSecret, scopeTenant, scopeId } = (await inquirer.prompt(\n apiKeyQuestions as Parameters<typeof inquirer.prompt>[0]\n )) as { clientId: string; clientSecret: string; scopeTenant: string; scopeId: string };\n\n const scope: GrantScope = {\n tenant: scopeTenant,\n id: scopeId.trim(),\n };\n\n try {\n await exchangeApiKey(apiUrl, {\n clientId: clientId.trim(),\n clientSecret,\n scope: { id: scope.id, tenant: scope.tenant },\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('\\n' + msg);\n process.exit(1);\n }\n\n const { generateTypesOutputPathRaw } = (await inquirer.prompt([\n {\n type: 'input' as const,\n name: 'generateTypesOutputPathRaw',\n message:\n 'Default output path for generate-types (optional, leave empty for ./grant-types.ts)',\n default: existingProfile?.generateTypesOutputPath ?? '',\n validate: (input: string) => {\n const s = input.trim();\n if (!s) return true;\n if (!s.endsWith('.ts')) return 'Path should end with .ts';\n return true;\n },\n },\n ])) as { generateTypesOutputPathRaw: string };\n\n const generateTypesOutputPath = generateTypesOutputPathRaw.trim() || undefined;\n\n const config: GrantConfig = {\n apiUrl,\n authMethod: 'api-key',\n apiKey: {\n clientId: clientId.trim(),\n clientSecret,\n scope,\n },\n selectedScope: scope,\n ...(generateTypesOutputPath && { generateTypesOutputPath }),\n };\n\n if (!file) {\n file = { defaultProfile: profileName, profiles: { [profileName]: config } };\n } else {\n file.profiles[profileName] = config;\n if (!file.defaultProfile) {\n file.defaultProfile = profileName;\n }\n }\n await saveConfigFile(file);\n\n console.log('\\nSetup complete. Config saved to:', getConfigPath());\n console.log(' Profile:', profileName);\n console.log(' API URL:', config.apiUrl);\n console.log(' Auth: API key');\n console.log(' Scope tenant:', config.selectedScope!.tenant);\n console.log(' Scope id:', config.selectedScope!.id);\n if (config.generateTypesOutputPath) {\n console.log(' Generate-types output:', config.generateTypesOutputPath);\n }\n });\n}\n","declare const __GRANT_CLI_VERSION__: string;\n\nexport function getPackageVersion(): string {\n return typeof __GRANT_CLI_VERSION__ === 'string' ? __GRANT_CLI_VERSION__ : '0.0.0';\n}\n","import type { Command } from 'commander';\n\nimport { getPackageVersion } from '../utils/package.js';\n\nexport function createVersionCommand(program: Command): void {\n program\n .command('version')\n .description('Show CLI version (use -j for JSON)')\n .option('-j, --json', 'Output version as JSON')\n .action((options: { json?: boolean }) => {\n const version = getPackageVersion();\n if (options.json) {\n console.log(JSON.stringify({ version }));\n } else {\n console.log(version);\n }\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\n\nimport { createConfigCommand } from './commands/config-cmd.js';\nimport { createGenerateTypesCommand } from './commands/generate-types.js';\nimport { createStartCommand } from './commands/start.js';\nimport { createVersionCommand } from './commands/version.js';\n\nconst program = new Command();\n\nprogram\n .name('grant')\n .description('Grant CLI - Setup, authentication, and typings generation for @grantjs/server')\n .enablePositionalOptions()\n .addHelpText(\n 'after',\n `\nExamples:\n grant start Interactive setup (API URL, auth, scope)\n grant start --profile staging Setup or update a named profile\n grant config list List profiles and default\n grant config show --profile staging Show config for a profile\n grant config set api-url http://localhost:4000 --profile default\n grant generate-types --profile staging Generate types for a profile\n grant --help Show this help\n grant config set --help Show help for config set subcommands\n`\n );\n\ncreateVersionCommand(program);\ncreateConfigCommand(program);\ncreateStartCommand(program);\ncreateGenerateTypesCommand(program);\n\nprogram.parse();\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGA,IAAM,iBAAN,cAA6B,MAAM;;;;;;;EAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,SAAM,QAAQ;AAEd,SAAM,kBAAkB,MAAM,KAAK,YAAY;AAC/C,QAAK,OAAO,KAAK,YAAY;AAC7B,QAAK,OAAO;AACZ,QAAK,WAAW;AAChB,QAAK,cAAc,KAAA;;;;;;CAOvB,IAAM,uBAAN,cAAmC,eAAe;;;;;EAKhD,YAAY,SAAS;AACnB,SAAM,GAAG,6BAA6B,QAAQ;AAE9C,SAAM,kBAAkB,MAAM,KAAK,YAAY;AAC/C,QAAK,OAAO,KAAK,YAAY;;;AAIjC,SAAQ,iBAAiB;AACzB,SAAQ,uBAAuB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