flightdesk 0.2.2 → 0.2.3

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.
Files changed (3) hide show
  1. package/main.js +19 -3
  2. package/main.js.map +2 -2
  3. package/package.json +1 -1
package/main.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "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", "../../../apps/cli/src/lib/config.ts", "../../../apps/cli/src/commands/init.ts", "../../../apps/cli/src/lib/api.ts", "../../../apps/cli/src/lib/session-monitor.ts", "../../../apps/cli/src/commands/auth.ts", "../../../apps/cli/src/lib/git.ts", "../../../apps/cli/src/commands/register.ts", "../../../apps/cli/src/commands/status.ts", "../../../apps/cli/src/commands/watch.ts", "../../../apps/cli/src/commands/task.ts", "../../../apps/cli/src/commands/prompt.ts", "../../../apps/cli/src/commands/org.ts", "../../../apps/cli/src/commands/context.ts", "../../../apps/cli/src/commands/sync.ts", "../../../apps/cli/src/lib/claude-selectors.ts", "../../../apps/cli/src/commands/import.ts", "../../../apps/cli/src/commands/project.ts", "../../../apps/cli/src/commands/preview.ts", "../../../apps/cli/src/main.ts"],
4
- "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\u2013Levenshtein_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 * as fs from 'fs'\nimport * as path from 'path'\nimport * as os from 'os'\n\nexport interface OrganizationInfo {\n id: string\n name: string\n}\n\nexport interface FlightDeskConfig {\n // Single API key for the user\n apiKey?: string\n // Currently active organization\n activeOrganization?: string\n // All organizations the user belongs to\n organizations: OrganizationInfo[]\n // Repo to project mappings\n repoMapping: Record<string, string>\n}\n\nconst CONFIG_FILE = path.join(os.homedir(), '.flightdeskrc')\nconst DEFAULT_API_URL = 'https://api.flightdesk.dev'\nconst DEV_API_URL = 'http://localhost:3000'\n\n// Global API URL override (set by --dev or --api options)\nlet apiUrlOverride: string | null = null\n\nexport function setDevMode(enabled: boolean): void {\n if (enabled) {\n apiUrlOverride = DEV_API_URL\n }\n}\n\nexport function setApiUrl(url: string): void {\n apiUrlOverride = url\n}\n\nexport function getApiUrl(): string {\n // Always use production URL unless --dev or --apiUrl flag is passed\n // API URL is never persisted in config\n return apiUrlOverride ?? DEFAULT_API_URL\n}\n\nexport function loadConfig(): FlightDeskConfig {\n try {\n if (fs.existsSync(CONFIG_FILE)) {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8')\n const parsed = JSON.parse(content)\n\n // Migrate old config format if needed\n if (parsed.organizations?.[0]?.apiKey) {\n return migrateOldConfig(parsed)\n }\n\n return {\n organizations: [],\n repoMapping: {},\n ...parsed,\n }\n }\n } catch (error) {\n console.error('Warning: Failed to load config file:', error)\n }\n\n return {\n organizations: [],\n repoMapping: {},\n }\n}\n\n/**\n * Migrate from old config format (apiKey per org) to new format (single apiKey)\n */\nfunction migrateOldConfig(oldConfig: any): FlightDeskConfig {\n console.log('\uD83D\uDCE6 Migrating config to new format...')\n\n // Take the API key from the first/default org\n const defaultOrg = oldConfig.defaultOrganization\n ? oldConfig.organizations.find((o: any) => o.id === oldConfig.defaultOrganization)\n : oldConfig.organizations[0]\n\n const newConfig: FlightDeskConfig = {\n apiKey: defaultOrg?.apiKey,\n activeOrganization: defaultOrg?.id,\n organizations: oldConfig.organizations.map((o: any) => ({\n id: o.id,\n name: o.name,\n })),\n repoMapping: oldConfig.repoMapping || {},\n }\n\n // Save migrated config\n saveConfig(newConfig)\n console.log('\u2705 Config migrated successfully')\n\n return newConfig\n}\n\nexport function saveConfig(config: FlightDeskConfig): void {\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2))\n}\n\nexport function getActiveOrganization(): OrganizationInfo | null {\n const config = loadConfig()\n\n if (!config.activeOrganization) {\n // Return first org if only one exists\n if (config.organizations.length === 1) {\n return config.organizations[0]\n }\n return null\n }\n\n return config.organizations.find(o => o.id === config.activeOrganization) || null\n}\n\nexport function setActiveOrganization(orgId: string): void {\n const config = loadConfig()\n\n const org = config.organizations.find(o => o.id === orgId || o.name.toLowerCase() === orgId.toLowerCase())\n if (!org) {\n throw new Error(`Organization not found: ${orgId}`)\n }\n\n config.activeOrganization = org.id\n saveConfig(config)\n}\n\nexport function updateOrganizations(orgs: OrganizationInfo[]): void {\n const config = loadConfig()\n config.organizations = orgs\n\n // If active org no longer exists, clear it\n if (config.activeOrganization && !orgs.some(o => o.id === config.activeOrganization)) {\n config.activeOrganization = orgs[0]?.id\n }\n\n saveConfig(config)\n}\n\nexport function updateRepoMapping(repo: string, orgId: string): void {\n const config = loadConfig()\n config.repoMapping[repo] = orgId\n saveConfig(config)\n}\n\n/**\n * Get organization by repository name (from repo mapping)\n */\nexport function getOrganizationByRepo(repoFullName: string): OrganizationInfo | null {\n const config = loadConfig()\n const orgId = config.repoMapping[repoFullName]\n if (!orgId) return null\n return config.organizations.find(o => o.id === orgId) || null\n}\n\nexport function isConfigured(): boolean {\n const config = loadConfig()\n return !!config.apiKey && config.organizations.length > 0\n}\n\nexport function requireConfig(): FlightDeskConfig {\n const config = loadConfig()\n\n if (!config.apiKey) {\n console.error('\u274C FlightDesk is not configured. Run: flightdesk init')\n process.exit(1)\n }\n\n if (config.organizations.length === 0) {\n console.error('\u274C No organizations found. Run: flightdesk init')\n process.exit(1)\n }\n\n return config\n}\n\nexport function requireActiveOrg(): { config: FlightDeskConfig; org: OrganizationInfo } {\n const config = requireConfig()\n const org = getActiveOrganization()\n\n if (!org) {\n console.error('\u274C No active organization. Run: flightdesk org switch <org-name>')\n console.log('\\nAvailable organizations:')\n config.organizations.forEach(o => console.log(` - ${o.name}`))\n process.exit(1)\n }\n\n return { config, org }\n}\n\nexport { CONFIG_FILE, DEFAULT_API_URL, DEV_API_URL }\n", "import * as readline from 'readline'\nimport {\n loadConfig,\n saveConfig,\n isConfigured,\n CONFIG_FILE,\n getApiUrl,\n} from '../lib/config'\nimport { fetchUserInfo } from '../lib/api'\n\nfunction question(rl: readline.Interface, prompt: string): Promise<string> {\n return new Promise((resolve) => {\n rl.question(prompt, (answer) => {\n resolve(answer.trim())\n })\n })\n}\n\nexport async function initCommand(): Promise<void> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n\n console.log('\\n\uD83D\uDEEB FlightDesk CLI Setup\\n')\n\n try {\n // Check if already configured\n if (isConfigured()) {\n const config = loadConfig()\n console.log('FlightDesk is already configured.')\n console.log(` API Key: ${config.apiKey?.substring(0, 20)}...`)\n console.log(` Organizations: ${config.organizations.map(o => o.name).join(', ')}`)\n console.log('')\n\n const reconfigure = await question(rl, 'Reconfigure? (y/N): ')\n if (reconfigure.toLowerCase() !== 'y') {\n console.log('\\nConfiguration unchanged.')\n console.log('Use \"flightdesk org refresh\" to update organizations.')\n console.log('Use \"flightdesk org switch <name>\" to change active organization.')\n return\n }\n }\n\n // Get API key\n console.log('Enter your FlightDesk API key.')\n console.log('You can find this at https://flightdesk.dev/settings/api-keys\\n')\n\n const apiKey = await question(rl, 'API Key: ')\n if (!apiKey) {\n console.error('API Key is required')\n return\n }\n\n // Use the API URL from --api/--dev flags or default to production\n const apiUrl = getApiUrl()\n\n // Test the connection and fetch user's organizations\n console.log('\\nConnecting to FlightDesk...')\n\n try {\n const userInfo = await fetchUserInfo(apiKey, apiUrl)\n\n const orgs = userInfo.organizations || []\n if (orgs.length === 0) {\n console.error('\u274C No organizations found for this user')\n console.log('Please make sure you are a member of at least one organization.')\n return\n }\n\n const primaryEmail = userInfo.emails?.find(e => e.primary)?.email || userInfo.emails?.[0]?.email || 'unknown'\n console.log('\u2705 Connection successful!')\n console.log(` Logged in as: ${primaryEmail}`)\n console.log(` Organizations: ${orgs.length}`)\n\n // Map to our OrganizationInfo format\n const organizations = orgs.map(m => ({\n id: m.organization.id,\n name: m.organization.name,\n }))\n\n // Let user choose active org if multiple\n let activeOrganization: string\n if (organizations.length === 1) {\n activeOrganization = organizations[0].id\n console.log(`\\n Active organization: ${organizations[0].name}`)\n } else {\n console.log('\\nYour organizations:')\n organizations.forEach((org, i) => {\n console.log(` ${i + 1}. ${org.name}`)\n })\n const choice = await question(rl, `\\nSelect active organization (1-${organizations.length}): `)\n const choiceIndex = Number.parseInt(choice, 10) - 1\n if (choiceIndex < 0 || choiceIndex >= organizations.length) {\n console.error('Invalid selection, using first organization')\n activeOrganization = organizations[0].id\n } else {\n activeOrganization = organizations[choiceIndex].id\n }\n }\n\n // Save configuration\n const config = loadConfig()\n config.apiKey = apiKey\n config.apiUrl = apiUrl\n config.organizations = organizations\n config.activeOrganization = activeOrganization\n saveConfig(config)\n\n console.log(`\\n\u2705 Configuration saved to ${CONFIG_FILE}`)\n console.log('\\nYou can now use:')\n console.log(' flightdesk project list - List projects')\n console.log(' flightdesk task create - Create a task')\n console.log(' flightdesk org list - Show organizations')\n console.log(' flightdesk org switch <name> - Switch active organization')\n } catch (error) {\n console.error(`\\n\u274C Connection failed: ${error}`)\n console.log('\\nPlease check:')\n console.log(' - Your API key is correct')\n console.log(' - You have network connectivity')\n console.log(' - The FlightDesk API is reachable')\n }\n } finally {\n rl.close()\n }\n}\n", "import { FlightDeskConfig, OrganizationInfo, getApiUrl } from './config'\n\n/**\n * Simple GraphQL client for CLI operations.\n * We avoid using the full Apollo client to keep the CLI bundle small.\n */\nexport class FlightDeskAPI {\n private readonly apiUrl: string\n private readonly apiKey: string\n private readonly organizationId: string\n\n constructor(config: FlightDeskConfig, org: OrganizationInfo) {\n this.apiUrl = getApiUrl()\n this.apiKey = config.apiKey!\n this.organizationId = org.id\n }\n\n /**\n * Create an API client from config, using the active organization\n */\n static fromConfig(config: FlightDeskConfig, org: OrganizationInfo): FlightDeskAPI {\n return new FlightDeskAPI(config, org)\n }\n\n async graphql<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T> {\n const response = await fetch(`${this.apiUrl}/graphql`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ query, variables }),\n })\n\n if (!response.ok) {\n throw new Error(`API request failed: ${response.status} ${response.statusText}`)\n }\n\n const result = await response.json() as { data?: T; errors?: Array<{ message: string }> }\n\n if (result.errors && result.errors.length > 0) {\n throw new Error(`GraphQL error: ${result.errors.map(e => e.message).join(', ')}`)\n }\n\n return result.data as T\n }\n\n // ============================================================================\n // Task Operations\n // ============================================================================\n\n async createTask(input: {\n projectId: string\n title: string\n description?: string\n }) {\n const query = `\n mutation CreateTask($input: UserCreateTaskInput!) {\n userCreateTask(input: $input) {\n id\n title\n status\n createdAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateTask: { id: string; title: string; status: string; createdAt: string } }>(query, { input })\n return result.userCreateTask\n }\n\n async updateTask(taskId: string, input: {\n status?: string\n branchName?: string\n prUrl?: string\n prNumber?: number\n sessionViewUrl?: string\n sessionTeleportId?: string\n }) {\n const query = `\n mutation UpdateTask($taskId: String!, $input: UserUpdateTaskInput!) {\n userUpdateTask(taskId: $taskId, input: $input) {\n id\n title\n status\n branchName\n prUrl\n }\n }\n `\n\n const result = await this.graphql<{ userUpdateTask: { id: string; title: string; status: string; branchName?: string; prUrl?: string } }>(query, { taskId, input })\n return result.userUpdateTask\n }\n\n async registerSession(taskId: string, input: { viewUrl: string; teleportId: string }) {\n const query = `\n mutation RegisterSession($taskId: String!, $input: RegisterSessionInput!) {\n userRegisterSession(taskId: $taskId, input: $input) {\n id\n title\n status\n sessionViewUrl\n sessionTeleportId\n }\n }\n `\n\n const result = await this.graphql<{ userRegisterSession: { id: string; title: string; status: string; sessionViewUrl?: string; sessionTeleportId?: string } }>(query, { taskId, input })\n return result.userRegisterSession\n }\n\n async getTask(taskId: string) {\n const query = `\n query GetTask($taskId: String!) {\n userTask(taskId: $taskId) {\n id\n title\n description\n status\n branchName\n prUrl\n prNumber\n sessionViewUrl\n sessionTeleportId\n createdAt\n updatedAt\n project {\n id\n name\n githubRepo\n }\n }\n }\n `\n\n const result = await this.graphql<{ userTask: unknown }>(query, { taskId })\n return result.userTask\n }\n\n async listTasks(options?: { projectId?: string; status?: string }) {\n const query = `\n query ListTasks($input: ListTasksInput!) {\n userTasks(input: $input) {\n id\n title\n status\n branchName\n prUrl\n sessionViewUrl\n createdAt\n project {\n id\n name\n }\n }\n }\n `\n\n // Build the input object - all fields are optional now\n const input: { projectId?: string; status?: string[] } = {}\n if (options?.projectId) {\n input.projectId = options.projectId\n }\n if (options?.status) {\n input.status = [options.status]\n }\n\n const result = await this.graphql<{ userTasks: Array<{ id: string; title: string; status: string; branchName?: string; prUrl?: string; createdAt: string; project: { id: string; name: string } }> }>(query, { input })\n return result.userTasks\n }\n\n // ============================================================================\n // Project Operations\n // ============================================================================\n\n async listProjects() {\n const query = `\n query ListProjects($organizationId: String!) {\n userProjects(organizationId: $organizationId) {\n id\n name\n githubRepo\n }\n }\n `\n\n const result = await this.graphql<{ userProjects: Array<{ id: string; name: string; githubRepo: string }> }>(query, { organizationId: this.organizationId })\n return result.userProjects\n }\n\n async getProject(projectId: string) {\n const query = `\n query GetProject($projectId: String!) {\n userProject(projectId: $projectId) {\n id\n name\n githubRepo\n tokenTtlHours\n }\n }\n `\n\n const result = await this.graphql<{ userProject: { id: string; name: string; githubRepo: string; tokenTtlHours: number } }>(query, { projectId })\n return result.userProject\n }\n\n async createProject(input: {\n name: string\n organizationId: string\n githubConnectionId: string\n githubRepo: string\n teamId?: string\n tokenTtlHours?: number\n previewEnabled?: boolean\n }) {\n const query = `\n mutation CreateProject($input: UserCreateProjectInput!) {\n userCreateProject(input: $input) {\n id\n name\n githubRepo\n organizationId\n createdAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateProject: { id: string; name: string; githubRepo: string; organizationId: string; createdAt: string } }>(query, { input })\n return result.userCreateProject\n }\n\n // ============================================================================\n // Task Token Operations (for agent authentication)\n // ============================================================================\n\n async createTaskToken(taskId: string) {\n const query = `\n mutation CreateTaskToken($taskId: String!) {\n userCreateTaskToken(taskId: $taskId) {\n token\n expiresAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateTaskToken: { token: string; expiresAt: string } }>(query, { taskId })\n return result.userCreateTaskToken\n }\n\n // ============================================================================\n // Prompt Operations\n // ============================================================================\n\n async getTaskPrompts(taskId: string) {\n const query = `\n query GetTaskPrompts($taskId: String!) {\n userTaskPrompts(taskId: $taskId) {\n type\n content\n available\n reason\n }\n }\n `\n\n const result = await this.graphql<{ userTaskPrompts: Array<{ type: string; content: string; available: boolean; reason?: string }> }>(query, { taskId })\n return result.userTaskPrompts\n }\n\n // ============================================================================\n // Preview Environment Operations\n // ============================================================================\n\n async getTaskInstance(taskId: string) {\n const query = `\n query GetTaskInstance($taskId: String!) {\n userTaskInstance(taskId: $taskId) {\n id\n taskId\n workerId\n containerId\n previewUrl\n sshHost\n sshPort\n sshUser\n status\n lastActivityAt\n suspendedAt\n createdAt\n updatedAt\n sshConnectionString\n }\n }\n `\n\n const result = await this.graphql<{ userTaskInstance: {\n id: string\n taskId: string\n workerId: string\n containerId: string\n previewUrl: string\n sshHost: string\n sshPort: number\n sshUser: string\n status: string\n lastActivityAt?: string\n suspendedAt?: string\n createdAt: string\n updatedAt: string\n sshConnectionString: string\n } | null }>(query, { taskId })\n return result.userTaskInstance\n }\n\n async getInstanceLogs(taskId: string, lines = 100) {\n const query = `\n query GetInstanceLogs($taskId: String!, $lines: Float) {\n userInstanceLogs(taskId: $taskId, lines: $lines) {\n logs\n }\n }\n `\n\n const result = await this.graphql<{ userInstanceLogs: { logs: string } }>(query, { taskId, lines })\n return result.userInstanceLogs\n }\n\n async restartInstance(taskId: string) {\n const query = `\n mutation RestartInstance($taskId: String!) {\n userRestartInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userRestartInstance: boolean }>(query, { taskId })\n return result.userRestartInstance\n }\n\n async resumeInstance(taskId: string) {\n const query = `\n mutation ResumeInstance($taskId: String!) {\n userResumeInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userResumeInstance: boolean }>(query, { taskId })\n return result.userResumeInstance\n }\n\n async tearDownInstance(taskId: string) {\n const query = `\n mutation TearDownInstance($taskId: String!) {\n userTearDownInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userTearDownInstance: boolean }>(query, { taskId })\n return result.userTearDownInstance\n }\n}\n\n// ============================================================================\n// Standalone API functions (for use without full config)\n// ============================================================================\n\nexport interface UserOrganization {\n organization: {\n id: string\n name: string\n }\n}\n\nexport interface MeResponse {\n id: string\n emails: Array<{ email: string; primary: boolean }>\n organizations: UserOrganization[]\n}\n\n/**\n * Fetch user info and organizations using an API key\n */\nexport async function fetchUserInfo(apiKey: string, apiUrl = 'https://api.flightdesk.dev'): Promise<MeResponse> {\n const response = await fetch(`${apiUrl}/graphql`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: `{\n me {\n id\n emails {\n email\n primary\n }\n organizations {\n organization {\n id\n name\n }\n }\n }\n }`,\n }),\n })\n\n if (!response.ok) {\n throw new Error(`API returned ${response.status}`)\n }\n\n const result = await response.json() as {\n data?: { me?: MeResponse }\n errors?: Array<{ message: string }>\n }\n\n if (result.errors?.length) {\n throw new Error(result.errors.map(e => e.message).join(', '))\n }\n\n if (!result.data?.me) {\n throw new Error('Invalid API response')\n }\n\n return result.data.me\n}\n", "/**\n * Playwright-based session monitoring for Claude Code sessions.\n *\n * This module opens Claude Code session URLs in headless Chromium,\n * detects branch names, and can auto-click \"Create PR\" buttons.\n *\n * Supports both:\n * - One-shot mode: Opens browser, performs action, closes (for auth commands)\n * - Persistent mode: Keeps browser alive for multiple session checks (for watch daemon)\n */\n\nimport type { Browser, Page, BrowserContext } from 'playwright'\nimport * as path from 'node:path'\nimport * as os from 'node:os'\nimport * as fs from 'node:fs'\nimport * as readline from 'node:readline'\n\n// Playwright is an optional dependency\nlet playwright: typeof import('playwright') | null = null\n\nexport interface SessionInfo {\n branchName?: string\n hasPrButton?: boolean\n prUrl?: string\n status?: 'active' | 'archived' | 'error'\n error?: string\n /** True if Claude is actively processing (spinner visible), false if idle/waiting for input */\n isActive?: boolean\n}\n\nexport interface MonitorOptions {\n headless?: boolean\n timeout?: number\n autoPr?: boolean // Automatically click \"Create PR\" if found\n}\n\nconst USER_DATA_DIR = path.join(os.homedir(), '.flightdesk', 'chromium-profile')\nconst STORAGE_STATE_FILE = path.join(os.homedir(), '.flightdesk', 'auth-state.json')\n\n/**\n * Persistent browser session manager.\n * Keeps the browser context alive for multiple operations.\n * Uses explicit storageState for auth persistence (more reliable than persistent context).\n */\nexport class PersistentBrowser {\n private browser: Browser | null = null\n private context: BrowserContext | null = null\n private page: Page | null = null\n private readonly headless: boolean\n\n constructor(headless = true) {\n this.headless = headless\n }\n\n /**\n * Initialize the browser context (if not already initialized)\n */\n async init(): Promise<void> {\n if (this.context) return\n\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not available')\n }\n\n ensureUserDataDir()\n\n // Launch a regular browser (not persistent context)\n this.browser = await playwright!.chromium.launch({\n headless: this.headless,\n })\n\n // Check if we have saved auth state\n const hasAuthState = fs.existsSync(STORAGE_STATE_FILE)\n\n // Create context with storage state if available\n const contextOptions: Parameters<Browser['newContext']>[0] = {\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n }\n\n if (hasAuthState) {\n contextOptions.storageState = STORAGE_STATE_FILE\n }\n\n this.context = await this.browser.newContext(contextOptions)\n this.page = await this.context.newPage()\n this.page.setDefaultTimeout(30000)\n }\n\n /**\n * Check if user is logged into Claude\n */\n async checkAuth(): Promise<boolean> {\n await this.init()\n\n try {\n await this.page!.goto('https://claude.ai/', { waitUntil: 'networkidle', timeout: 30000 })\n await this.page!.waitForTimeout(2000)\n\n const url = this.page!.url()\n console.log(' Final URL:', url)\n\n return !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n url.includes('claude.ai')\n } catch (error) {\n console.error('Auth check failed:', (error as Error).message)\n return false\n }\n }\n\n /**\n * Monitor a Claude Code session URL\n * Uses shared scrapeSession helper for consistent behavior with one-shot mode.\n */\n async monitorSession(\n sessionUrl: string,\n options: { timeout?: number; autoPr?: boolean } = {}\n ): Promise<SessionInfo> {\n await this.init()\n\n if (!this.page) {\n return { status: 'error', error: 'Browser page not initialized' }\n }\n\n return scrapeSession(this.page, sessionUrl, options)\n }\n\n /**\n * Close the browser context and browser\n */\n async close(): Promise<void> {\n if (this.context) {\n try {\n await this.context.close()\n } catch {\n // Already closed\n }\n this.context = null\n this.page = null\n }\n if (this.browser) {\n try {\n await this.browser.close()\n } catch {\n // Already closed\n }\n this.browser = null\n }\n }\n}\n\n/**\n * Check if Playwright is available\n */\nexport async function isPlaywrightAvailable(): Promise<boolean> {\n try {\n playwright = await import('playwright')\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Ensure the user data directory exists with restrictive permissions\n */\nfunction ensureUserDataDir(): void {\n if (!fs.existsSync(USER_DATA_DIR)) {\n fs.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 0o700 })\n }\n}\n\n/**\n * Ensure the storage directory exists with restrictive permissions\n */\nasync function ensureStorageDir(): Promise<void> {\n const storageDir = path.dirname(STORAGE_STATE_FILE)\n try {\n await fs.promises.mkdir(storageDir, { recursive: true, mode: 0o700 })\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') {\n throw err\n }\n }\n}\n\n/**\n * Set restrictive permissions on the storage state file (owner read/write only)\n */\nasync function setStorageFilePermissions(): Promise<void> {\n try {\n await fs.promises.chmod(STORAGE_STATE_FILE, 0o600)\n } catch {\n // If chmod fails, continue - the file may have broader permissions on some systems\n }\n}\n\n/**\n * Launch browser with storage state (uses saved auth cookies if available)\n * This is more reliable than persistent context for auth persistence.\n */\nasync function launchBrowser(headless: boolean): Promise<{ browser: Browser; context: BrowserContext }> {\n if (!playwright) {\n throw new Error('Playwright not available')\n }\n\n ensureUserDataDir()\n\n // Launch a regular browser (not persistent context)\n const browser = await playwright.chromium.launch({ headless })\n\n // Check if we have saved auth state\n const hasAuthState = fs.existsSync(STORAGE_STATE_FILE)\n\n // Create context with storage state if available\n const contextOptions: Parameters<Browser['newContext']>[0] = {\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n }\n\n if (hasAuthState) {\n contextOptions.storageState = STORAGE_STATE_FILE\n }\n\n const context = await browser.newContext(contextOptions)\n\n return { browser, context }\n}\n\n/**\n * Check if user is logged into Claude\n * Uses storageState for auth persistence (matching the new persistence strategy)\n */\nexport async function checkAuth(): Promise<boolean> {\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not installed')\n }\n\n const { browser, context } = await launchBrowser(true)\n\n try {\n const page = await context.newPage()\n page.setDefaultTimeout(30000)\n\n // Navigate and wait for network to settle (catches redirects better)\n await page.goto('https://claude.ai/', { waitUntil: 'networkidle', timeout: 30000 })\n\n // Extra wait for any JS redirects\n await page.waitForTimeout(2000)\n\n // Check final URL\n const url = page.url()\n console.log(' Final URL:', url)\n\n // Check for login/oauth redirects\n const isLoggedIn = !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n (url.includes('claude.ai'))\n\n return isLoggedIn\n } catch (error) {\n // Timeout or other error - assume not logged in\n console.error('Auth check failed:', (error as Error).message)\n return false\n } finally {\n await context.close()\n await browser.close()\n }\n}\n\n/**\n * Open browser for manual login (not headless)\n * Returns true if login was successful\n */\nexport async function openForLogin(): Promise<boolean> {\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not installed')\n }\n\n console.log('Opening browser for Claude login...')\n\n const { context } = await launchBrowser(false)\n\n try {\n const page = await context.newPage()\n await page.goto('https://claude.ai/', { waitUntil: 'domcontentloaded', timeout: 60000 })\n\n // Wait for user to press Enter instead of detecting browser close\n // (browser close event is unreliable with persistent contexts)\n console.log('\\n\uD83D\uDC49 Press ENTER here when you have logged in...\\n')\n await waitForEnter()\n\n // Check auth status NOW, before closing, using the same browser session\n console.log('Verifying login in current session...')\n await page.goto('https://claude.ai/', { waitUntil: 'domcontentloaded', timeout: 30000 })\n await page.waitForTimeout(2000)\n\n const url = page.url()\n console.log(' Final URL:', url)\n\n const isLoggedIn = !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n url.includes('claude.ai')\n\n if (isLoggedIn) {\n // Ensure storage directory exists with restrictive permissions\n await ensureStorageDir()\n\n // Save storage state (cookies, localStorage) to file for later use\n console.log('Saving session state...')\n await context.storageState({ path: STORAGE_STATE_FILE })\n\n // Restrict permissions on the storage state file (owner read/write only)\n await setStorageFilePermissions()\n console.log(` Saved to: ${STORAGE_STATE_FILE}`)\n }\n\n console.log('Closing browser...')\n return isLoggedIn\n } finally {\n try {\n await context.close()\n } catch {\n // Already closed\n }\n }\n}\n\n/**\n * Wait for user to press Enter\n */\nfunction waitForEnter(): Promise<void> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n rl.question('', () => {\n rl.close()\n resolve()\n })\n })\n}\n\n/**\n * Monitor a Claude Code session URL (one-shot mode)\n * Uses storageState for auth persistence (matching the new persistence strategy)\n */\nexport async function monitorSession(\n sessionUrl: string,\n options: MonitorOptions = {}\n): Promise<SessionInfo> {\n if (!await isPlaywrightAvailable()) {\n return { status: 'error', error: 'Playwright not installed' }\n }\n\n const { headless = true, timeout = 30000, autoPr = false } = options\n const { browser, context } = await launchBrowser(headless)\n\n try {\n const page = await context.newPage()\n return await scrapeSession(page, sessionUrl, { timeout, autoPr })\n } finally {\n await context.close()\n await browser.close()\n }\n}\n\n/**\n * Shared session-scraping logic used by both persistent and one-shot monitors.\n * Extracts branch name, PR button status, and optionally clicks \"Create PR\".\n */\nasync function scrapeSession(\n page: Page,\n sessionUrl: string,\n options: { timeout?: number; autoPr?: boolean } = {}\n): Promise<SessionInfo> {\n const { timeout = 30000, autoPr = false } = options\n\n try {\n page.setDefaultTimeout(timeout)\n\n // Navigate to session and wait for network to settle\n await page.goto(sessionUrl, { waitUntil: 'networkidle' })\n\n // Wait for the main content area to be visible before scraping\n // This is more reliable than a fixed timeout for varying network conditions\n await page.waitForSelector('[data-testid=\"conversation-turn\"], .code-spinner-animate, button:has-text(\"Create PR\")', {\n timeout: 10000,\n }).catch(() => {\n // If no expected elements found, continue anyway - page may be in unexpected state\n })\n\n const result: SessionInfo = { status: 'active' }\n\n // Check if session is archived\n const archiveIndicator = await page.$('text=This session has been archived')\n if (archiveIndicator) {\n return { status: 'archived' }\n }\n\n // Check if we're on a login page\n const url = page.url()\n if (url.includes('/login') || url.includes('/oauth')) {\n return {\n status: 'error',\n error: 'Not logged in to Claude. Run: flightdesk auth'\n }\n }\n\n // Detect if Claude is actively processing (spinner animation visible)\n // The spinner has class .code-spinner-animate and contains the spinning star characters\n const isActive = await detectActiveSpinner(page)\n result.isActive = isActive\n\n // Try to find branch name\n const branchName = await extractBranchName(page)\n if (branchName) {\n result.branchName = branchName\n }\n\n // Check for \"Create PR\" button (indicates work is ready but PR not yet created)\n // Note: PR detection is handled by GitHub webhooks, not CLI scraping\n const createPrButton = await page.$('button:has-text(\"Create PR\"):not([aria-haspopup])')\n const viewPrButton = await page.$('button:has-text(\"View PR\")')\n\n // Only report hasPrButton if there's a Create PR button (not View PR)\n result.hasPrButton = !!createPrButton && !viewPrButton\n\n // If auto-PR is enabled and Create PR button exists, click it\n if (autoPr && createPrButton && !viewPrButton) {\n console.log(' Clicking \"Create PR\" button...')\n await createPrButton.click()\n await page.waitForTimeout(5000)\n\n // Try to extract the PR URL from the page\n const prUrl = await extractPrUrl(page)\n if (prUrl) {\n result.prUrl = prUrl\n }\n }\n\n return result\n } catch (error) {\n return {\n status: 'error',\n error: error instanceof Error ? error.message : String(error)\n }\n }\n}\n\n/**\n * Check if a string looks like a valid branch name\n */\nfunction isValidBranchName(text: string | null): text is string {\n if (!text) return false\n const cleaned = text.trim()\n return cleaned.length > 2 && !cleaned.includes(' ')\n}\n\n/**\n * Check if a string matches a branch pattern (e.g., \"claude/feature-name\")\n */\nfunction matchesBranchPattern(text: string): boolean {\n return /^[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+/.test(text) && !text.includes(' ')\n}\n\n/**\n * Try to extract branch name from an element\n */\nasync function tryExtractFromElement(page: Page, selector: string): Promise<string | null> {\n try {\n const element = await page.$(selector)\n if (!element) return null\n const text = await element.textContent()\n const cleaned = text?.trim() ?? null\n return isValidBranchName(cleaned) ? cleaned : null\n } catch {\n return null\n }\n}\n\n/**\n * Extract branch name from a Claude Code session page\n * Uses verified selector from SELECTOR_SPEC.ts\n */\nasync function extractBranchName(page: Page | null): Promise<string | null> {\n if (!page) return null\n\n // Primary selector: branch name in the branch bar (button.group/copy span.truncate)\n // This is the new branch created by Claude, shown in the branch bar\n const primarySelectors = [\n String.raw`button.group\\/copy span.truncate`, // New branch name (verified)\n 'button[class*=\"group/copy\"] span.truncate', // Alternative escaping\n String.raw`button[class*=\"group\\/copy\"] span.truncate`, // CSS escape\n ]\n\n for (const selector of primarySelectors) {\n const result = await tryExtractFromElement(page, selector)\n if (result) return result\n }\n\n // Fallback: look for any element containing a branch-like pattern\n return await tryExtractBranchFromSpans(page)\n}\n\n/**\n * Fallback extraction: search all truncate spans for branch patterns\n */\nasync function tryExtractBranchFromSpans(page: Page): Promise<string | null> {\n try {\n const allSpans = await page.$$('span.truncate')\n for (const span of allSpans) {\n const text = await span.textContent()\n const cleaned = text?.trim()\n if (cleaned && matchesBranchPattern(cleaned)) {\n return cleaned\n }\n }\n } catch {\n // Ignore fallback errors\n }\n return null\n}\n\n/**\n * Extract PR URL from page after PR creation\n */\nasync function extractPrUrl(page: Page): Promise<string | null> {\n // Look for GitHub PR URL patterns\n const selectors = [\n 'a[href*=\"github.com\"][href*=\"/pull/\"]',\n 'a[href*=\"gitlab.com\"][href*=\"/merge_requests/\"]',\n 'a[href*=\"bitbucket.org\"][href*=\"/pull-requests/\"]',\n ]\n\n for (const selector of selectors) {\n try {\n const element = await page.$(selector)\n if (element) {\n const href = await element.getAttribute('href')\n if (href) {\n return href\n }\n }\n } catch {\n // Continue\n }\n }\n\n // Try to find PR URL in page content\n try {\n const pageContent = await page.content()\n const prPatterns = [\n /(https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/pull\\/\\d+)/,\n /(https:\\/\\/gitlab\\.com\\/[^/]+\\/[^/]+\\/-\\/merge_requests\\/\\d+)/,\n ]\n\n for (const pattern of prPatterns) {\n const match = pageContent.match(pattern)\n if (match && match[1]) {\n return match[1]\n }\n }\n } catch {\n // Ignore\n }\n\n return null\n}\n\n/**\n * Detect if Claude is actively processing (spinner animation is visible).\n * The Claude UI shows an animated spinner with class .code-spinner-animate\n * when Claude is actively working on a response.\n *\n * SELECTOR VERIFICATION: These selectors were verified against Claude Code UI on 2026-02-26.\n * If detection stops working, Claude may have updated their UI. Check:\n * - The spinner class name (.code-spinner-animate)\n * - The spinner characters (\u273D\u2736\u273B\u2722\u00B7)\n * - The animation keyframe name (codeSpinnerSpin)\n */\nasync function detectActiveSpinner(page: Page): Promise<boolean> {\n try {\n // Primary selector: the animated spinner element (verified 2026-02-26)\n const spinner = await page.$('.code-spinner-animate')\n if (spinner) {\n return true\n }\n\n // Fallback: look for the spinning star characters in a visible state\n // These are the characters used in the animation: \u273D\u2736\u273B\u2722\u00B7\n const spinnerByContent = await page.$('span:has-text(\"\u273D\")')\n if (spinnerByContent) {\n // Check if it's part of an animation (has the animation class on a parent or itself)\n const hasAnimation = await spinnerByContent.evaluate((el) => {\n let current: Element | null = el\n while (current) {\n const classList = current.classList\n if (classList?.contains('code-spinner-animate')) {\n return true\n }\n // Also check for any animation-related CSS\n const style = globalThis.getComputedStyle(current)\n if (style.animationName && style.animationName !== 'none') {\n return true\n }\n current = current.parentElement\n }\n return false\n })\n return hasAnimation\n }\n\n return false\n } catch {\n // If detection fails, default to false (idle)\n return false\n }\n}\n\nexport { USER_DATA_DIR }\n", "import {\n isPlaywrightAvailable,\n checkAuth,\n openForLogin,\n USER_DATA_DIR,\n} from '../lib/session-monitor'\n\nexport async function authCommand(): Promise<void> {\n console.log('\uD83D\uDD10 FlightDesk Authentication\\n')\n\n // Check if Playwright is available\n const playwrightAvailable = await isPlaywrightAvailable()\n if (!playwrightAvailable) {\n console.error('Playwright is not installed.')\n console.error('Install with: pnpm add playwright && npx playwright install chromium')\n process.exit(1)\n }\n\n console.log(`Profile directory: ${USER_DATA_DIR}\\n`)\n\n // Check current auth status\n console.log('Checking current authentication status...')\n const isAuthenticated = await checkAuth()\n\n if (isAuthenticated) {\n console.log('\u2705 Already logged in to Claude!')\n console.log('\\nThe watch daemon will be able to monitor your sessions.')\n return\n }\n\n console.log('\u274C Not logged in to Claude.\\n')\n console.log('Opening browser for login...')\n console.log('Please log in to your Claude account.\\n')\n\n // Open browser for login (verifies auth before closing)\n const loginSuccessful = await openForLogin()\n\n if (loginSuccessful) {\n console.log('\\n\u2705 Successfully logged in!')\n console.log('The watch daemon can now monitor your Claude Code sessions.')\n } else {\n console.log('\\n\u274C Login was not detected.')\n console.log('Please try again with: flightdesk auth')\n }\n}\n", "import { execSync } from 'node:child_process'\n\nexport interface GitRepoInfo {\n remote: string // owner/repo format\n branch: string\n remoteUrl: string\n}\n\n/**\n * Detect the current git repository information.\n * Returns null if not in a git repo or if detection fails.\n */\nexport function detectGitRepo(): GitRepoInfo | null {\n try {\n // Get git remote URL\n const remoteUrl = execSync('git remote get-url origin', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n // Parse remote URL to get owner/repo\n const repoFullName = parseGitRemoteUrl(remoteUrl)\n if (!repoFullName) {\n return null\n }\n\n // Get current branch\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n return {\n remote: repoFullName,\n branch,\n remoteUrl,\n }\n } catch {\n // Not in a git repo or git not available\n return null\n }\n}\n\n/**\n * Parse a git remote URL to extract the owner/repo format.\n * Handles both SSH and HTTPS URLs.\n */\nexport function parseGitRemoteUrl(remoteUrl: string): string | null {\n // Handle SSH URLs: git@github.com:owner/repo.git\n const sshPattern = /git@github\\.com:([^/]+\\/[^/]+?)(?:\\.git)?$/\n const sshMatch = sshPattern.exec(remoteUrl)\n if (sshMatch) {\n return sshMatch[1]\n }\n\n // Handle HTTPS URLs: https://github.com/owner/repo.git\n const httpsPattern = /https:\\/\\/github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?$/\n const httpsMatch = httpsPattern.exec(remoteUrl)\n if (httpsMatch) {\n return httpsMatch[1]\n }\n\n return null\n}\n", "import { requireActiveOrg, getOrganizationByRepo, OrganizationInfo } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport { detectGitRepo } from '../lib/git'\n\ninterface RegisterOptions {\n project?: string\n viewUrl?: string\n teleportId?: string\n title?: string\n description?: string\n}\n\nexport async function registerCommand(\n taskId: string | undefined,\n options: RegisterOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n // Auto-detect project if not provided via --project option\n let projectId = options.project\n if (!projectId) {\n projectId = await autoDetectProject(api, org)\n }\n\n // If piped input, try to parse Claude Code output\n let viewUrl = options.viewUrl\n let teleportId = options.teleportId\n\n if (!process.stdin.isTTY) {\n const input = await readStdin()\n const parsed = parseClaudeOutput(input)\n viewUrl = viewUrl || parsed.viewUrl\n teleportId = teleportId || parsed.teleportId\n }\n\n // Create task if no task ID provided\n let actualTaskId = taskId\n if (!actualTaskId) {\n if (!options.title) {\n console.error('Task title required when creating a new task. Use --title \"...\"')\n process.exit(1)\n }\n\n console.log(`Creating task: ${options.title}`)\n const task = await api.createTask({\n projectId,\n title: options.title,\n description: options.description,\n })\n actualTaskId = task.id\n console.log(`\u2705 Created task: ${task.id}`)\n }\n\n // Update task with session info\n if (viewUrl || teleportId) {\n console.log('Registering session with task...')\n await api.updateTask(actualTaskId, {\n sessionViewUrl: viewUrl,\n sessionTeleportId: teleportId,\n status: 'DISPATCHED',\n })\n console.log('\u2705 Session registered')\n }\n\n // Output task ID for scripting\n console.log(`\\nTask ID: ${actualTaskId}`)\n\n if (viewUrl) {\n console.log(`Session: ${viewUrl}`)\n }\n\n if (teleportId) {\n console.log(`Resume: claude --teleport ${teleportId}`)\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve) => {\n let data = ''\n process.stdin.setEncoding('utf8')\n process.stdin.on('data', (chunk) => {\n data += chunk\n })\n process.stdin.on('end', () => {\n resolve(data)\n })\n // If no data within 100ms, assume no piped input\n setTimeout(() => resolve(data), 100)\n })\n}\n\nfunction parseClaudeOutput(output: string): { viewUrl?: string; teleportId?: string } {\n const result: { viewUrl?: string; teleportId?: string } = {}\n\n // Parse view URL: \"View: https://claude.ai/code/session_...\"\n const viewMatch = output.match(/View:\\s+(https:\\/\\/claude\\.ai\\/code\\/session_[^\\s]+)/)\n if (viewMatch) {\n result.viewUrl = viewMatch[1]\n }\n\n // Parse teleport ID: \"Resume with: claude --teleport session_...\"\n const teleportMatch = output.match(/--teleport\\s+(session_[^\\s]+)/)\n if (teleportMatch) {\n result.teleportId = teleportMatch[1]\n }\n\n return result\n}\n\n/**\n * Auto-detect project from current git repository.\n * Looks up the project by matching the repo's githubRepo field.\n */\nasync function autoDetectProject(api: FlightDeskAPI, activeOrg: OrganizationInfo): Promise<string> {\n const repoInfo = detectGitRepo()\n\n if (!repoInfo) {\n console.error('\u274C Not in a git repository. Please provide a project ID.')\n console.error(' Usage: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n console.log(`\uD83D\uDD0D Detecting project from repository: ${repoInfo.remote}`)\n\n // Check if this repo is mapped to an organization\n const mappedOrg = getOrganizationByRepo(repoInfo.remote)\n if (!mappedOrg) {\n console.error(`\u274C Repository \"${repoInfo.remote}\" is not mapped to any organization.`)\n console.error(' Run: flightdesk sync')\n console.error(' Or provide a project ID: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n // Warn if mapped org differs from active org\n if (mappedOrg.id !== activeOrg.id) {\n console.error(`\u274C Repository \"${repoInfo.remote}\" is mapped to organization \"${mappedOrg.name}\",`)\n console.error(` but your active organization is \"${activeOrg.name}\".`)\n console.error(' Switch with: flightdesk org switch ' + mappedOrg.name)\n console.error(' Or provide a project ID: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n // List projects and find matching one\n const projects = await api.listProjects()\n const matchingProjects = projects.filter(\n (p) => p.githubRepo?.toLowerCase() === repoInfo.remote.toLowerCase()\n )\n\n if (matchingProjects.length === 0) {\n console.error(`\u274C No FlightDesk project found for repository \"${repoInfo.remote}\".`)\n console.error(' Available projects in this organization:')\n for (const p of projects) {\n console.error(` - ${p.name} (${p.githubRepo || 'no repo'}) [${p.id}]`)\n }\n console.error('\\n Create a project or provide a project ID explicitly.')\n process.exit(1)\n }\n\n if (matchingProjects.length > 1) {\n console.error(`\u274C Multiple projects found for repository \"${repoInfo.remote}\":`)\n for (const p of matchingProjects) {\n console.error(` - ${p.name} [${p.id}]`)\n }\n console.error('\\n Please specify the project ID explicitly.')\n process.exit(1)\n }\n\n const project = matchingProjects[0]\n console.log(`\u2705 Found project: ${project.name} (${project.id})`)\n\n return project.id\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface StatusOptions {\n project?: string\n}\n\nexport async function statusCommand(options: StatusOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n const tasks = await api.listTasks({ projectId: options.project })\n\n if (tasks.length === 0) {\n console.log('No tasks found.')\n return\n }\n\n // Group tasks by status\n const byStatus: Record<string, typeof tasks> = {}\n for (const task of tasks) {\n if (!byStatus[task.status]) {\n byStatus[task.status] = []\n }\n byStatus[task.status].push(task)\n }\n\n // Status order for display\n const statusOrder = [\n 'PENDING',\n 'DISPATCHED',\n 'IN_PROGRESS',\n 'BRANCH_CREATED',\n 'PR_OPEN',\n 'PREVIEW_STARTING',\n 'PREVIEW_READY',\n 'REVIEW_RUNNING',\n 'REVIEW_DONE',\n 'QA_READY',\n 'QA_APPROVED',\n 'MERGED',\n 'ARCHIVED',\n ]\n\n console.log('\\n\uD83D\uDCCB FlightDesk Tasks\\n')\n\n for (const status of statusOrder) {\n const statusTasks = byStatus[status]\n if (!statusTasks || statusTasks.length === 0) continue\n\n console.log(`${getStatusEmoji(status)} ${status} (${statusTasks.length})`)\n for (const task of statusTasks) {\n console.log(` ${task.id.slice(0, 8)} - ${task.title}`)\n if (task.branchName) {\n console.log(` Branch: ${task.branchName}`)\n }\n if (task.prUrl) {\n console.log(` PR: ${task.prUrl}`)\n }\n }\n console.log('')\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction getStatusEmoji(status: string): string {\n switch (status) {\n case 'PENDING':\n return '\u2B1C'\n case 'DISPATCHED':\n return '\uD83D\uDE80'\n case 'IN_PROGRESS':\n return '\uD83D\uDD04'\n case 'BRANCH_CREATED':\n return '\uD83C\uDF3F'\n case 'PR_OPEN':\n return '\uD83D\uDCDD'\n case 'PREVIEW_STARTING':\n return '\u23F3'\n case 'PREVIEW_READY':\n return '\uD83C\uDF10'\n case 'REVIEW_RUNNING':\n return '\uD83D\uDD0D'\n case 'REVIEW_DONE':\n return '\u2705'\n case 'QA_READY':\n return '\uD83E\uDDEA'\n case 'QA_APPROVED':\n return '\uD83D\uDC4D'\n case 'MERGED':\n return '\uD83C\uDF89'\n case 'ARCHIVED':\n return '\uD83D\uDCE6'\n default:\n return '\u2753'\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport {\n isPlaywrightAvailable,\n PersistentBrowser,\n type SessionInfo,\n} from '../lib/session-monitor'\n\ninterface WatchOptions {\n interval: string\n once?: boolean\n autoPr?: boolean\n headless?: boolean\n}\n\ninterface ActiveTask {\n id: string\n title: string\n status: string\n sessionViewUrl?: string\n branchName?: string\n prUrl?: string\n sessionActive?: boolean\n}\n\nexport async function watchCommand(options: WatchOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n\n const intervalMinutes = parseInt(options.interval, 10)\n if (isNaN(intervalMinutes) || intervalMinutes < 1) {\n console.error('Invalid interval. Must be a positive number of minutes.')\n process.exit(1)\n }\n\n console.log('\uD83D\uDEEB FlightDesk Watch Daemon')\n console.log(` Organization: ${org.name}`)\n console.log(` Interval: ${intervalMinutes} minutes`)\n console.log(` Auto-PR: ${options.autoPr ? 'enabled' : 'disabled'}`)\n console.log('')\n\n // Check if Playwright is available\n const playwrightAvailable = await isPlaywrightAvailable()\n let browser: PersistentBrowser | null = null\n\n if (!playwrightAvailable) {\n console.log('\u26A0\uFE0F Playwright not installed. Session monitoring disabled.')\n console.log(' Install with: pnpm add playwright && npx playwright install chromium')\n console.log('')\n } else {\n // Create persistent browser instance - keeps auth alive for entire watch session\n browser = new PersistentBrowser(options.headless !== false)\n\n // Check if authenticated using the persistent browser\n console.log('Checking Claude authentication...')\n const isAuthenticated = await browser.checkAuth()\n if (!isAuthenticated) {\n console.log('\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth')\n console.log('')\n // Close browser since we can't proceed without auth\n await browser.close()\n browser = null\n } else {\n console.log('\u2705 Playwright ready, Claude authenticated')\n console.log(' (Browser session kept alive for monitoring)')\n console.log('')\n }\n }\n\n const api = FlightDeskAPI.fromConfig(config, org)\n\n async function runCheck(): Promise<void> {\n const timestamp = new Date().toLocaleTimeString()\n console.log(`[${timestamp}] Checking tasks...`)\n\n try {\n // Get all tasks that need monitoring:\n // - Active tasks (DISPATCHED, IN_PROGRESS, BRANCH_CREATED)\n // - PENDING tasks with sessionViewUrl (may need status reconciliation)\n const tasks = await api.listTasks() as ActiveTask[]\n const activeTasks = tasks.filter(t =>\n ['DISPATCHED', 'IN_PROGRESS', 'BRANCH_CREATED'].includes(t.status) ||\n (t.status === 'PENDING' && t.sessionViewUrl)\n )\n\n if (activeTasks.length === 0) {\n console.log(' No active tasks to monitor')\n return\n }\n\n // Check for tasks that need status reconciliation (have data but wrong status)\n const needsReconciliation = activeTasks.filter(t => {\n if (t.prUrl && !['PR_OPEN', 'MERGED', 'ARCHIVED'].includes(t.status)) return true\n if (t.branchName && t.status === 'PENDING') return true\n if (t.sessionViewUrl && t.status === 'PENDING') return true\n return false\n })\n\n if (needsReconciliation.length > 0) {\n console.log(` \u26A0\uFE0F ${needsReconciliation.length} task(s) need status reconciliation`)\n }\n\n console.log(` Found ${activeTasks.length} active task(s)`)\n\n for (const task of activeTasks) {\n console.log(`\\n \uD83D\uDCCB ${task.title}`)\n console.log(` Status: ${task.status}`)\n\n // First, reconcile status based on existing data\n const reconciled = await reconcileTaskStatus(api, task)\n if (reconciled) {\n continue // Task was updated, skip session monitoring this cycle\n }\n\n // If task has a session URL and browser is available, monitor it\n if (task.sessionViewUrl && browser) {\n console.log(` Checking session...`)\n\n const sessionInfo = await browser.monitorSession(task.sessionViewUrl, {\n autoPr: options.autoPr && !task.prUrl, // Only auto-PR if no PR exists\n })\n\n await processSessionInfo(api, task, sessionInfo)\n } else if (!task.sessionViewUrl) {\n console.log(' No session URL registered')\n } else if (!browser) {\n console.log(' Browser not available - cannot monitor session')\n }\n }\n } catch (error) {\n console.error(` Error: ${error}`)\n }\n }\n\n // Use try/finally to ensure browser is always closed on all exit paths\n try {\n // Run immediately\n await runCheck()\n\n if (options.once) {\n console.log('\\nDone (--once flag specified)')\n return\n }\n\n // Then run on interval\n console.log(`\\nWatching... (Ctrl+C to stop)\\n`)\n\n const intervalId = setInterval(runCheck, intervalMinutes * 60 * 1000)\n\n // Handle graceful shutdown\n process.on('SIGINT', async () => {\n console.log('\\nShutting down...')\n clearInterval(intervalId)\n if (browser) {\n console.log('Closing browser...')\n await browser.close()\n }\n process.exit(0)\n })\n\n // Keep the process running indefinitely (until SIGINT)\n await new Promise((_resolve) => {\n // Intentionally never resolves - process runs until interrupted\n })\n } finally {\n // Ensure browser is closed on all exit paths (including --once and errors)\n if (browser) {\n await browser.close()\n }\n }\n}\n\n/**\n * Reconciles task status based on existing data.\n * This catches tasks that have data (prUrl, branchName, sessionViewUrl) but wrong status.\n * Returns true if status was updated.\n */\nasync function reconcileTaskStatus(\n api: FlightDeskAPI,\n task: ActiveTask\n): Promise<boolean> {\n let expectedStatus: string | null = null\n let reason = ''\n\n // Determine expected status based on available data\n // Priority: PR > Branch > Session\n if (task.prUrl) {\n if (!['PR_OPEN', 'PREVIEW_STARTING', 'PREVIEW_READY', 'MERGED', 'ARCHIVED', 'REVIEW_RUNNING', 'REVIEW_DONE', 'QA_READY', 'QA_APPROVED'].includes(task.status)) {\n expectedStatus = 'PR_OPEN'\n reason = `has PR URL but status is ${task.status}`\n }\n } else if (task.branchName) {\n if (['PENDING', 'DISPATCHED'].includes(task.status)) {\n expectedStatus = 'IN_PROGRESS'\n reason = `has branch but status is ${task.status}`\n }\n } else if (task.sessionViewUrl) {\n if (task.status === 'PENDING') {\n expectedStatus = 'DISPATCHED'\n reason = `has session URL but status is PENDING`\n }\n }\n\n if (expectedStatus) {\n console.log(` \uD83D\uDD27 Status reconciliation: ${reason}`)\n console.log(` Updating: ${task.status} \u2192 ${expectedStatus}`)\n try {\n await api.updateTask(task.id, { status: expectedStatus })\n console.log(' \u2705 Status reconciled')\n return true\n } catch (error) {\n console.log(` \u274C Failed to reconcile: ${error}`)\n return false\n }\n }\n\n return false\n}\n\nasync function processSessionInfo(\n api: FlightDeskAPI,\n task: ActiveTask,\n info: SessionInfo\n): Promise<void> {\n if (info.status === 'error') {\n console.log(` \u274C Error: ${info.error}`)\n return\n }\n\n if (info.status === 'archived') {\n console.log(' \uD83D\uDCE6 Session archived')\n return\n }\n\n // Display and track session activity state\n // Distinguish between: true (active), false (idle), undefined (detection failed)\n let activityIcon: string\n let activityLabel: string\n if (info.isActive === true) {\n activityIcon = '\u26A1'\n activityLabel = 'Claude is working'\n } else if (info.isActive === false) {\n activityIcon = '\uD83D\uDCA4'\n activityLabel = 'Waiting for input'\n } else {\n activityIcon = '\u2754'\n activityLabel = 'Activity unknown'\n }\n console.log(` ${activityIcon} ${activityLabel}`)\n\n const updates: Record<string, unknown> = {\n // Update session activity state and timestamp\n // Preserve null when activity detection fails (info.isActive is undefined)\n sessionActive: info.isActive ?? null,\n sessionCheckedAt: new Date().toISOString(),\n }\n\n // Update branch name if detected and not already set\n if (info.branchName && info.branchName !== task.branchName) {\n console.log(` \uD83C\uDF3F Branch detected: ${info.branchName}`)\n updates.branchName = info.branchName\n\n // Update status to IN_PROGRESS if still DISPATCHED\n if (task.status === 'DISPATCHED') {\n updates.status = 'IN_PROGRESS'\n }\n }\n\n // Update PR URL if detected\n if (info.prUrl && info.prUrl !== task.prUrl) {\n console.log(` \uD83D\uDD17 PR detected: ${info.prUrl}`)\n updates.prUrl = info.prUrl\n\n // Extract PR number from URL\n const prMatch = info.prUrl.match(/\\/pull\\/(\\d+)/)\n if (prMatch) {\n updates.prNumber = parseInt(prMatch[1], 10)\n }\n\n // Update status to PR_OPEN\n updates.status = 'PR_OPEN'\n }\n\n // Report if PR button available but no PR yet\n if (info.hasPrButton && !info.prUrl && !task.prUrl) {\n console.log(' \uD83D\uDCDD \"Create PR\" button available')\n }\n\n // Apply updates (always includes activity state)\n const hasNonActivityUpdates = Object.keys(updates).some(k => !['sessionActive', 'sessionCheckedAt'].includes(k))\n try {\n await api.updateTask(task.id, updates)\n if (hasNonActivityUpdates) {\n console.log(' \u2705 Task updated')\n }\n } catch (error) {\n console.log(` \u274C Failed to update task: ${error}`)\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface TaskCreateOptions {\n project: string\n title: string\n description?: string\n}\n\ninterface TaskListOptions {\n project?: string\n status?: string\n}\n\ninterface TaskStatusOptions {\n taskId: string\n}\n\ninterface TaskUpdateOptions {\n taskId: string\n status?: string\n branch?: string\n prUrl?: string\n}\n\ntype TaskOptions = TaskCreateOptions | TaskListOptions | TaskStatusOptions | TaskUpdateOptions\n\nexport async function taskCommand(\n action: 'create' | 'list' | 'status' | 'update',\n options: TaskOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n switch (action) {\n case 'create':\n await handleCreate(api, options as TaskCreateOptions)\n break\n case 'list':\n await handleList(api, options as TaskListOptions)\n break\n case 'status':\n await handleStatus(api, options as TaskStatusOptions)\n break\n case 'update':\n await handleUpdate(api, options as TaskUpdateOptions)\n break\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nasync function handleCreate(api: FlightDeskAPI, options: TaskCreateOptions): Promise<void> {\n console.log(`Creating task: ${options.title}`)\n\n const task = await api.createTask({\n projectId: options.project,\n title: options.title,\n description: options.description,\n })\n\n console.log(`\\n\u2705 Task created`)\n console.log(` ID: ${task.id}`)\n console.log(` Title: ${task.title}`)\n console.log(` Status: ${task.status}`)\n}\n\nasync function handleList(api: FlightDeskAPI, options: TaskListOptions): Promise<void> {\n const tasks = await api.listTasks({\n projectId: options.project,\n status: options.status,\n })\n\n if (tasks.length === 0) {\n console.log('No tasks found.')\n return\n }\n\n console.log('\\nTasks:\\n')\n for (const task of tasks) {\n const statusEmoji = getStatusEmoji(task.status)\n console.log(`${statusEmoji} ${task.id.slice(0, 8)} - ${task.title}`)\n if (task.project?.name) console.log(` Project: ${task.project.name}`)\n console.log(` Status: ${task.status}`)\n if (task.branchName) console.log(` Branch: ${task.branchName}`)\n if (task.prUrl) console.log(` PR: ${task.prUrl}`)\n console.log('')\n }\n}\n\nasync function handleStatus(api: FlightDeskAPI, options: TaskStatusOptions): Promise<void> {\n const task = await api.getTask(options.taskId) as {\n id: string\n title: string\n description?: string\n status: string\n branchName?: string\n prUrl?: string\n sessionViewUrl?: string\n sessionTeleportId?: string\n project: { name: string; githubRepo: string }\n createdAt: string\n updatedAt: string\n }\n\n if (!task) {\n console.error('Task not found')\n process.exit(1)\n }\n\n console.log(`\\n\uD83D\uDCCB Task: ${task.title}\\n`)\n console.log(`ID: ${task.id}`)\n console.log(`Status: ${getStatusEmoji(task.status)} ${task.status}`)\n if (task.project) {\n console.log(`Project: ${task.project.name}${task.project.githubRepo ? ` (${task.project.githubRepo})` : ''}`)\n }\n\n if (task.description) {\n console.log(`\\nDescription:\\n${task.description}`)\n }\n\n console.log('')\n if (task.branchName) console.log(`Branch: ${task.branchName}`)\n if (task.prUrl) console.log(`PR: ${task.prUrl}`)\n if (task.sessionViewUrl) console.log(`Session: ${task.sessionViewUrl}`)\n if (task.sessionTeleportId) {\n console.log(`Resume: claude --teleport ${task.sessionTeleportId}`)\n }\n\n console.log(`\\nCreated: ${new Date(task.createdAt).toLocaleString()}`)\n console.log(`Updated: ${new Date(task.updatedAt).toLocaleString()}`)\n}\n\nasync function handleUpdate(api: FlightDeskAPI, options: TaskUpdateOptions): Promise<void> {\n const input: Record<string, unknown> = {}\n\n if (options.status) input.status = options.status\n if (options.branch) input.branchName = options.branch\n if (options.prUrl) input.prUrl = options.prUrl\n\n if (Object.keys(input).length === 0) {\n console.error('No updates specified. Use --status, --branch, or --pr-url')\n process.exit(1)\n }\n\n console.log(`Updating task ${options.taskId}...`)\n\n const task = await api.updateTask(options.taskId, input)\n\n console.log(`\\n\u2705 Task updated`)\n console.log(` Status: ${task.status}`)\n if (task.branchName) console.log(` Branch: ${task.branchName}`)\n if (task.prUrl) console.log(` PR: ${task.prUrl}`)\n}\n\nfunction getStatusEmoji(status: string): string {\n switch (status) {\n case 'PENDING': return '\u2B1C'\n case 'DISPATCHED': return '\uD83D\uDE80'\n case 'IN_PROGRESS': return '\uD83D\uDD04'\n case 'BRANCH_CREATED': return '\uD83C\uDF3F'\n case 'PR_OPEN': return '\uD83D\uDCDD'\n case 'PREVIEW_STARTING': return '\u23F3'\n case 'PREVIEW_READY': return '\uD83C\uDF10'\n case 'REVIEW_RUNNING': return '\uD83D\uDD0D'\n case 'REVIEW_DONE': return '\u2705'\n case 'QA_READY': return '\uD83E\uDDEA'\n case 'QA_APPROVED': return '\uD83D\uDC4D'\n case 'MERGED': return '\uD83C\uDF89'\n case 'ARCHIVED': return '\uD83D\uDCE6'\n default: return '\u2753'\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface PromptOptions {\n type: string\n}\n\nexport async function promptCommand(taskId: string, options: PromptOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n const validTypes = ['review', 'test_plan', 'summary', 'handoff']\n\n if (!validTypes.includes(options.type)) {\n console.error(`Invalid prompt type: ${options.type}`)\n console.error(`Valid types: ${validTypes.join(', ')}`)\n process.exit(1)\n }\n\n try {\n const prompts = await api.getTaskPrompts(taskId)\n const prompt = prompts.find(p => p.type === options.type)\n\n if (!prompt) {\n console.error(`Prompt type \"${options.type}\" not found for this task`)\n process.exit(1)\n }\n\n if (!prompt.available) {\n console.error(`Prompt not available: ${prompt.reason || 'Unknown reason'}`)\n process.exit(1)\n }\n\n // Output the prompt content (ready for copy-paste)\n console.log(prompt.content)\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n", "import {\n loadConfig,\n getActiveOrganization,\n setActiveOrganization,\n updateOrganizations,\n isConfigured,\n getApiUrl,\n} from '../lib/config'\nimport { fetchUserInfo } from '../lib/api'\n\nexport async function orgListCommand(): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n const activeOrg = getActiveOrganization()\n\n console.log('\\n\uD83D\uDCCB Organizations\\n')\n\n if (config.organizations.length === 0) {\n console.log('No organizations found.')\n console.log('Run: flightdesk org refresh')\n return\n }\n\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n const activeTag = isActive ? ' \u2190 active' : ''\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${activeTag}`)\n }\n\n console.log('')\n console.log('Commands:')\n console.log(' flightdesk org switch <name> Switch active organization')\n console.log(' flightdesk org refresh Refresh organizations from API')\n console.log('')\n}\n\nexport async function orgSwitchCommand(orgIdentifier: string): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n\n // Find org by name or ID (case-insensitive)\n const org = config.organizations.find(\n o => o.id === orgIdentifier || o.name.toLowerCase() === orgIdentifier.toLowerCase()\n )\n\n if (!org) {\n console.error(`Organization not found: ${orgIdentifier}`)\n console.log('\\nAvailable organizations:')\n for (const o of config.organizations) {\n console.log(` - ${o.name}`)\n }\n process.exit(1)\n }\n\n const currentOrg = getActiveOrganization()\n if (currentOrg?.id === org.id) {\n console.log(`Already using organization: ${org.name}`)\n return\n }\n\n setActiveOrganization(org.id)\n console.log(`\u2705 Switched to organization: ${org.name}`)\n}\n\nexport async function orgRefreshCommand(): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n\n if (!config.apiKey) {\n console.error('No API key configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n console.log('Refreshing organizations...')\n\n try {\n const apiUrl = getApiUrl()\n const userInfo = await fetchUserInfo(config.apiKey, apiUrl)\n const orgs = userInfo.organizations || []\n\n if (orgs.length === 0) {\n console.log('No organizations found for this user.')\n return\n }\n\n // Map to our OrganizationInfo format\n const organizations = orgs.map(m => ({\n id: m.organization.id,\n name: m.organization.name,\n }))\n\n // Check for new orgs\n const currentIds = new Set(config.organizations.map(o => o.id))\n const newOrgs = organizations.filter(o => !currentIds.has(o.id))\n\n // Check for removed orgs\n const newIds = new Set(organizations.map(o => o.id))\n const removedOrgs = config.organizations.filter(o => !newIds.has(o.id))\n\n // Update organizations (this also handles active org validation)\n updateOrganizations(organizations)\n\n console.log(`\u2705 Found ${organizations.length} organization(s)`)\n\n if (newOrgs.length > 0) {\n console.log('\\n New organizations:')\n for (const org of newOrgs) {\n console.log(` + ${org.name}`)\n }\n }\n\n if (removedOrgs.length > 0) {\n console.log('\\n Removed organizations:')\n for (const org of removedOrgs) {\n console.log(` - ${org.name}`)\n }\n }\n\n // Show current active\n const activeOrg = getActiveOrganization()\n if (activeOrg) {\n console.log(`\\n Active: ${activeOrg.name}`)\n }\n } catch (error) {\n console.error(`\u274C Failed to refresh: ${error}`)\n }\n}\n", "import { execSync } from 'child_process'\nimport { loadConfig, getOrganizationByRepo, getActiveOrganization, getApiUrl } from '../lib/config'\n\nexport async function contextCommand(): Promise<void> {\n console.log('\\n\uD83D\uDD0D Current Context\\n')\n\n // Try to detect current git repository\n const repoInfo: { remote?: string; branch?: string } = {}\n\n try {\n // Get git remote URL\n const remoteUrl = execSync('git remote get-url origin', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n // Parse remote URL to get owner/repo\n let repoFullName: string | null = null\n\n // Handle SSH URLs: git@github.com:owner/repo.git\n const sshMatch = remoteUrl.match(/git@github\\.com:([^/]+\\/[^/]+?)(?:\\.git)?$/)\n if (sshMatch) {\n repoFullName = sshMatch[1]\n }\n\n // Handle HTTPS URLs: https://github.com/owner/repo.git\n const httpsMatch = remoteUrl.match(/https:\\/\\/github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?$/)\n if (httpsMatch) {\n repoFullName = httpsMatch[1]\n }\n\n if (repoFullName) {\n repoInfo.remote = repoFullName\n }\n\n // Get current branch\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n repoInfo.branch = branch\n } catch {\n // Not in a git repo or git not available\n }\n\n if (!repoInfo.remote) {\n console.log('\uD83D\uDCC1 Not in a git repository (or no remote configured)')\n console.log('')\n\n const config = loadConfig()\n const activeOrg = getActiveOrganization()\n if (config.organizations.length > 0) {\n console.log('Organizations:')\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${isActive ? ' (active)' : ''}`)\n }\n } else {\n console.log('No organizations configured. Run: flightdesk init')\n }\n return\n }\n\n console.log(`\uD83D\uDCC1 Repository: ${repoInfo.remote}`)\n console.log(`\uD83C\uDF3F Branch: ${repoInfo.branch}`)\n console.log('')\n\n // Look up organization mapping\n const mappedOrg = getOrganizationByRepo(repoInfo.remote)\n const activeOrg = getActiveOrganization()\n\n if (mappedOrg) {\n console.log(`\uD83C\uDFE2 Organization: ${mappedOrg.name}`)\n console.log(` API: ${getApiUrl()}`)\n console.log('')\n console.log('This repository is mapped to the above organization.')\n console.log('Commands will use this organization automatically.')\n } else {\n console.log('\u26A0\uFE0F This repository is not mapped to any organization.')\n console.log('')\n\n const config = loadConfig()\n if (config.organizations.length > 0) {\n console.log('Organizations:')\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${isActive ? ' (active)' : ''}`)\n }\n console.log('')\n console.log('Run: flightdesk sync to refresh repository mappings')\n } else {\n console.log('No organizations configured. Run: flightdesk init')\n }\n }\n}\n", "import { requireConfig, saveConfig } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\nexport async function syncCommand(): Promise<void> {\n const config = requireConfig()\n\n if (config.organizations.length === 0) {\n console.error('No organizations configured. Run: flightdesk init')\n process.exit(1)\n }\n\n console.log('\uD83D\uDD04 Syncing repository mappings...\\n')\n\n let totalProjects = 0\n const newMappings: Record<string, string> = {}\n\n for (const org of config.organizations) {\n console.log(` ${org.name}...`)\n\n try {\n const api = FlightDeskAPI.fromConfig(config, org)\n const projects = await api.listProjects()\n\n console.log(` Found ${projects.length} project(s)`)\n\n for (const project of projects) {\n if (project.githubRepo) {\n newMappings[project.githubRepo] = org.id\n totalProjects++\n }\n }\n } catch (error) {\n console.log(` \u274C Error: ${error}`)\n }\n }\n\n // Update config with new mappings\n config.repoMapping = newMappings\n saveConfig(config)\n\n console.log('')\n console.log(`\u2705 Synced ${totalProjects} project(s)`)\n\n if (totalProjects > 0) {\n console.log('')\n console.log('Repository mappings:')\n for (const [repo, orgId] of Object.entries(newMappings)) {\n const org = config.organizations.find(o => o.id === orgId)\n console.log(` ${repo} \u2192 ${org?.name || orgId}`)\n }\n }\n}\n", "/**\n * Claude.ai DOM Selectors for Playwright\n *\n * Based on comprehensive audit of Claude Code web interface.\n * These selectors are used for scraping session info and automation.\n */\n\nexport const ClaudeSelectors = {\n // ============================================================================\n // Sidebar - Session List (Verified 2026-02-23)\n // ============================================================================\n sidebar: {\n /** New task input (textarea in sidebar) */\n newTaskInput: 'textarea[placeholder=\"Ask Claude to write code...\"]',\n\n /** Session list container */\n sessionList: String.raw`.flex.flex-col.gap-0\\.5.px-1`,\n\n /** Individual session items - use :has-text() with title */\n sessionItem: (title: string) => `.cursor-pointer:has-text(\"${title}\")`,\n\n /** All session items (div elements with cursor-pointer class) */\n allSessions: String.raw`.flex.flex-col.gap-0\\.5.px-1 .cursor-pointer`,\n\n /** Session by index (0-indexed) */\n sessionByIndex: (index: number) => String.raw`.flex.flex-col.gap-0\\.5.px-1` + ` > div:nth-child(${index + 1}) .cursor-pointer`,\n\n /** Active/selected session (has bg-bg-300 class) */\n activeSession: '.cursor-pointer.bg-bg-300',\n\n /** Session title within a session item */\n sessionTitle: 'button.text-sm.font-medium.truncate',\n\n /** Session archive button (icon-only, no aria-label) */\n sessionArchiveButton: (title: string) => `.cursor-pointer:has-text(\"${title}\") button`,\n\n /** Search sessions button */\n searchButton: 'button[aria-label=\"Search \u2318K\"]',\n\n /** User profile button */\n userProfileButton: '[data-testid=\"code-user-menu-button\"]',\n },\n\n // ============================================================================\n // Branch Bar (between chat messages and chat input) - Verified 2026-02-23\n // ============================================================================\n branchBar: {\n /** Container for branch bar */\n container: '.flex.items-center.gap-2.w-full.p-2',\n\n /** Branch name display - the copyable span */\n branchName: 'button.group\\\\/copy span.truncate',\n\n /** Base/target branch dropdown (e.g., \"develop\") */\n baseBranchSelector: '.flex.items-center.gap-2.w-full.p-2 button[aria-haspopup=\"menu\"]',\n\n /** Copy branch button (click to copy branch name) */\n copyBranchButton: 'button.group\\\\/copy',\n\n /** Diff stats button (+N -M) */\n diffStatsButton: String.raw`.flex.items-center.gap-2.w-full.p-2 button.border-0\\.5`,\n },\n\n // ============================================================================\n // Pull Request Controls - Verified 2026-02-23\n // ============================================================================\n pullRequest: {\n /** Create PR button (left half - immediate action) - CAREFUL: clicks immediately! */\n createPrButton: 'button:has-text(\"Create PR\"):not([aria-haspopup])',\n\n /** PR dropdown trigger (right half - shows options) - SAFE to click */\n prDropdown: 'button.rounded-r-md[aria-haspopup=\"menu\"]',\n\n /** PR status indicator when PR exists */\n prStatus: 'a[href*=\"/pull/\"], a[href*=\"/merge_requests/\"]',\n\n /** View PR link */\n viewPrLink: 'a:has-text(\"View PR\"), a:has-text(\"View Pull Request\")',\n },\n\n // ============================================================================\n // Chat Area - Verified 2026-02-23\n // ============================================================================\n chat: {\n /** Main chat container */\n container: 'main',\n\n /** Chat messages */\n messages: 'div[data-testid=\"chat-message\"], div.prose',\n\n /** User messages */\n userMessages: 'div[data-testid=\"user-message\"]',\n\n /** Assistant messages */\n assistantMessages: 'div[data-testid=\"assistant-message\"]',\n\n /** Chat input (ProseMirror contenteditable) - NOT a textarea */\n input: '[aria-label=\"Enter your turn\"]',\n\n /** Chat input fallback */\n inputFallback: 'div.tiptap.ProseMirror[contenteditable=\"true\"]',\n\n /** Toggle menu button (+) */\n toggleMenuButton: 'button[aria-label=\"Toggle menu\"]',\n\n /** Send button */\n sendButton: 'form.w-full button[aria-label=\"Submit\"]',\n\n /** Stop button (during generation) */\n stopButton: 'button:has-text(\"Stop\")',\n },\n\n // ============================================================================\n // Model Selector - Verified 2026-02-23\n // ============================================================================\n model: {\n /** Model selector dropdown (sidebar) */\n sidebarSelector: 'form:not(.w-full) [data-testid=\"model-selector-dropdown\"]',\n\n /** Model selector dropdown (main chat) */\n chatSelector: 'form.w-full [data-testid=\"model-selector-dropdown\"]',\n\n /** Model options in dropdown (role=\"menuitem\") */\n options: '[role=\"menuitem\"]',\n\n /** Specific model option */\n option: (modelName: string) => `[role=\"menuitem\"]:has-text(\"${modelName}\")`,\n\n /** Quick model selectors */\n opus: '[role=\"menuitem\"]:has-text(\"Opus\")',\n sonnet: '[role=\"menuitem\"]:has-text(\"Sonnet\")',\n haiku: '[role=\"menuitem\"]:has-text(\"Haiku\")',\n },\n\n // ============================================================================\n // Mode Toggle - Verified 2026-02-23\n // Text alternates between \"Auto accept edits\" and \"Plan mode\"\n // ============================================================================\n mode: {\n /** Mode toggle button in sidebar - simple toggle, not dropdown */\n sidebarToggle: 'form:not(.w-full) button:has-text(\"Auto accept edits\"), form:not(.w-full) button:has-text(\"Plan mode\")',\n\n /** Mode toggle button in main chat */\n chatToggle: 'form.w-full button:has-text(\"Auto accept edits\"), form.w-full button:has-text(\"Plan mode\")',\n },\n\n // ============================================================================\n // Repository Connection - Verified 2026-02-23\n // ============================================================================\n repository: {\n /** Repo button in sidebar (shows current repo name) */\n repoButton: 'form:not(.w-full) button.flex.items-center.gap-1.min-w-0.rounded',\n\n /** Repo button by name */\n repoButtonByName: (repoName: string) => `form:not(.w-full) button:has-text(\"${repoName}\")`,\n\n /** Add repository button (hidden until hover) */\n addRepoButton: 'button[aria-label=\"Add repository\"]',\n\n /** Select repository dropdown */\n selectRepoDropdown: 'form:not(.w-full) button[aria-haspopup=\"menu\"]:has-text(\"Select repository\")',\n },\n\n // ============================================================================\n // Session Archive\n // ============================================================================\n archive: {\n /** Archive indicator text */\n indicator: 'text=This session has been archived',\n\n /** Archive button (if available) */\n archiveButton: 'button:has-text(\"Archive\")',\n },\n\n // ============================================================================\n // Authentication\n // ============================================================================\n auth: {\n /** Login page indicators */\n loginPage: 'text=Log in, text=Sign in, form[action*=\"login\"]',\n\n /** OAuth redirect */\n oauthRedirect: 'text=Redirecting',\n },\n\n // ============================================================================\n // Dropdowns (Radix UI pattern)\n // ============================================================================\n dropdown: {\n /** Open dropdown menu */\n menu: 'div[role=\"menu\"]',\n\n /** Menu items */\n items: 'div[role=\"menuitem\"]',\n\n /** Specific menu item */\n item: (text: string) => `div[role=\"menuitem\"]:has-text(\"${text}\")`,\n\n /** Listbox (for selects) */\n listbox: 'div[role=\"listbox\"]',\n\n /** Listbox options */\n listboxOptions: 'div[role=\"option\"]',\n },\n}\n\n/**\n * Session info extracted from Claude.ai\n */\nexport interface ClaudeSession {\n /** Session URL */\n url: string\n /** Session title from sidebar */\n title: string\n /** Branch name if connected to git */\n branchName?: string\n /** Repository name if connected */\n repoName?: string\n /** PR URL if one exists */\n prUrl?: string\n /** Whether the session is archived */\n archived: boolean\n}\n\n/**\n * Extract repo name from various formats\n */\nexport function parseRepoName(text: string): { owner: string; repo: string } | null {\n // Try owner/repo format\n const slashMatch = text.match(/^([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_.-]+)$/)\n if (slashMatch) {\n return { owner: slashMatch[1], repo: slashMatch[2] }\n }\n\n // Try GitHub URL format\n const urlMatch = text.match(/github\\.com\\/([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_.-]+)/)\n if (urlMatch) {\n return { owner: urlMatch[1], repo: urlMatch[2] }\n }\n\n return null\n}\n\n/**\n * Extract branch name from common patterns\n */\nexport function parseBranchName(text: string): string | null {\n // Common branch prefixes\n const prefixes = ['feature/', 'fix/', 'bugfix/', 'hotfix/', 'release/', 'chore/', 'docs/', 'refactor/', 'test/']\n\n for (const prefix of prefixes) {\n if (text.includes(prefix)) {\n const match = text.match(new RegExp(`(${prefix}[a-zA-Z0-9_-]+)`))\n if (match) return match[1]\n }\n }\n\n // Main branches\n if (['main', 'master', 'develop', 'development'].includes(text.trim())) {\n return text.trim()\n }\n\n // Generic branch pattern\n const branchMatch = text.match(/^[a-zA-Z][a-zA-Z0-9_/-]{2,50}$/)\n if (branchMatch) {\n return branchMatch[0]\n }\n\n return null\n}\n", "/**\n * Import command - scrapes existing Claude Code sessions and creates tasks in FlightDesk\n */\n\nimport type { Page, BrowserContext } from 'playwright'\nimport { isPlaywrightAvailable, USER_DATA_DIR } from '../lib/session-monitor'\nimport { ClaudeSelectors, ClaudeSession } from '../lib/claude-selectors'\nimport { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport * as fs from 'fs'\n\n// Playwright is dynamically imported\nlet playwright: typeof import('playwright') | null = null\n\ninterface ImportOptions {\n dryRun?: boolean\n limit?: number\n headless?: boolean\n project?: string\n verbose?: boolean\n}\n\ninterface DiscoveredSession {\n url: string\n title: string\n repoName?: string\n branchName?: string\n archived: boolean\n}\n\n/**\n * Main import command\n */\nexport async function importCommand(options: ImportOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n\n // Check Playwright\n if (!await isPlaywrightAvailable()) {\n console.error('Playwright is required for import. Install it with:')\n console.error(' npm install -g playwright')\n console.error(' npx playwright install chromium')\n process.exit(1)\n }\n\n playwright = await import('playwright')\n\n const api = FlightDeskAPI.fromConfig(config, org)\n\n console.log('\\n\uD83D\uDD0D FlightDesk Import - Scanning Claude Sessions\\n')\n\n if (options.dryRun) {\n console.log('\uD83D\uDCCB DRY RUN - No changes will be made\\n')\n }\n\n // Get existing projects to match repos\n let existingProjects: Array<{ id: string; name: string; githubRepo: string }> = []\n try {\n existingProjects = await api.listProjects()\n if (options.verbose) {\n console.log(`Found ${existingProjects.length} existing projects`)\n }\n } catch (error) {\n console.error('Warning: Could not fetch existing projects:', error)\n }\n\n // Launch browser and scan sessions\n const sessions = await scanClaudeSessions({\n headless: options.headless !== false,\n limit: options.limit || 50,\n verbose: options.verbose,\n })\n\n if (sessions.length === 0) {\n console.log('No sessions found. Make sure you are logged into Claude.')\n console.log('Run: flightdesk auth')\n return\n }\n\n console.log(`\\nFound ${sessions.length} sessions:\\n`)\n\n // Group sessions by repo\n const sessionsByRepo = new Map<string, DiscoveredSession[]>()\n const noRepoSessions: DiscoveredSession[] = []\n\n for (const session of sessions) {\n if (session.repoName) {\n const existing = sessionsByRepo.get(session.repoName) || []\n existing.push(session)\n sessionsByRepo.set(session.repoName, existing)\n } else {\n noRepoSessions.push(session)\n }\n }\n\n // Display grouped results\n for (const [repoName, repoSessions] of sessionsByRepo) {\n // Only match on githubRepo field - NOT project name for security\n // The repo name from Claude is just the repo part (e.g., \"mi-core\")\n // The project's githubRepo is the full path (e.g., \"monroe-institute/mi-core\")\n const matchingProject = existingProjects.find(p =>\n p.githubRepo?.endsWith(`/${repoName}`)\n )\n\n if (matchingProject) {\n console.log(`\uD83D\uDCC1 ${repoName} \u2192 Project: ${matchingProject.name} (${matchingProject.id.slice(0, 8)})`)\n } else {\n console.log(`\uD83D\uDCC1 ${repoName} \u2192 No matching project`)\n }\n\n for (const session of repoSessions) {\n const status = session.archived ? '\uD83D\uDCE6' : session.branchName ? '\uD83C\uDF3F' : '\uD83D\uDCAC'\n console.log(` ${status} ${session.title.slice(0, 50)}${session.title.length > 50 ? '...' : ''}`)\n if (session.branchName) {\n console.log(` Branch: ${session.branchName}`)\n }\n }\n console.log('')\n }\n\n if (noRepoSessions.length > 0) {\n console.log(`\uD83D\uDCC1 No Repository (${noRepoSessions.length} sessions)`)\n for (const session of noRepoSessions.slice(0, 5)) {\n const status = session.archived ? '\uD83D\uDCE6' : '\uD83D\uDCAC'\n console.log(` ${status} ${session.title.slice(0, 50)}${session.title.length > 50 ? '...' : ''}`)\n }\n if (noRepoSessions.length > 5) {\n console.log(` ... and ${noRepoSessions.length - 5} more`)\n }\n console.log('')\n }\n\n // Summary\n console.log('\u2500'.repeat(60))\n console.log(`\\nSummary:`)\n console.log(` Total sessions: ${sessions.length}`)\n console.log(` With repository: ${sessions.length - noRepoSessions.length}`)\n console.log(` Without repository: ${noRepoSessions.length}`)\n console.log(` Archived: ${sessions.filter(s => s.archived).length}`)\n console.log('')\n\n if (options.dryRun) {\n console.log('\uD83D\uDCA1 Run without --dry-run to create tasks in FlightDesk')\n return\n }\n\n // Collect sessions that can be imported (have matching projects)\n const importableSessions: Array<{ session: DiscoveredSession; project: { id: string; name: string; githubRepo: string } }> = []\n\n for (const [repoName, repoSessions] of sessionsByRepo) {\n const matchingProject = existingProjects.find(p =>\n p.githubRepo?.endsWith(`/${repoName}`)\n )\n if (matchingProject) {\n for (const session of repoSessions) {\n importableSessions.push({ session, project: matchingProject })\n }\n }\n }\n\n if (importableSessions.length === 0) {\n console.log('No sessions can be imported (no matching projects).')\n console.log('Create projects in FlightDesk first for the repositories you want to track.')\n return\n }\n\n console.log(`\\n\uD83D\uDE80 Importing ${importableSessions.length} sessions...\\n`)\n\n let created = 0\n let failed = 0\n\n for (const { session, project } of importableSessions) {\n try {\n // Create the task\n const task = await api.createTask({\n projectId: project.id,\n title: session.title,\n description: `Imported from Claude Code session`,\n })\n\n // Update with branch, session URL, and correct status\n // Determine status based on session state:\n // - Archived sessions \u2192 ARCHIVED\n // - Has branch \u2192 IN_PROGRESS (work is happening)\n // - Just session URL \u2192 DISPATCHED (assigned to Claude)\n let status = 'DISPATCHED'\n if (session.archived) {\n status = 'ARCHIVED'\n } else if (session.branchName) {\n status = 'IN_PROGRESS'\n }\n\n await api.updateTask(task.id, {\n branchName: session.branchName,\n sessionViewUrl: session.url,\n status,\n })\n\n console.log(` \u2705 ${session.title.slice(0, 50)}`)\n created++\n } catch (error) {\n console.error(` \u274C ${session.title.slice(0, 50)}: ${(error as Error).message}`)\n failed++\n }\n }\n\n console.log('')\n console.log('\u2500'.repeat(60))\n console.log(`\\nImport complete:`)\n console.log(` Created: ${created}`)\n console.log(` Failed: ${failed}`)\n console.log(` Skipped (no matching project): ${sessions.length - importableSessions.length}`)\n}\n\n/**\n * Scan Claude.ai for sessions\n */\nasync function scanClaudeSessions(options: {\n headless: boolean\n limit: number\n verbose?: boolean\n}): Promise<DiscoveredSession[]> {\n if (!playwright) {\n throw new Error('Playwright not loaded')\n }\n\n // Ensure user data dir exists\n if (!fs.existsSync(USER_DATA_DIR)) {\n fs.mkdirSync(USER_DATA_DIR, { recursive: true })\n }\n\n const context = await playwright.chromium.launchPersistentContext(USER_DATA_DIR, {\n headless: options.headless,\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',\n })\n\n try {\n const page = await context.newPage()\n page.setDefaultTimeout(60000)\n\n // Navigate to Claude Code\n console.log('Navigating to Claude Code...')\n await page.goto('https://claude.ai/code', { waitUntil: 'domcontentloaded', timeout: 60000 })\n\n // Wait for page to fully load\n if (options.verbose) {\n console.log('Waiting for page to load...')\n }\n await page.waitForTimeout(5000)\n\n // Check if logged in\n const url = page.url()\n if (options.verbose) {\n console.log('Current URL:', url)\n }\n if (url.includes('/login') || url.includes('/oauth')) {\n console.log('\\n\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth\\n')\n return []\n }\n\n console.log('Logged in. Scanning sessions...')\n\n // Wait for sidebar to render\n await page.waitForTimeout(3000)\n\n // Get all session items from sidebar (they're div.cursor-pointer, not links)\n const sessions: DiscoveredSession[] = []\n\n // Find all session items\n const sessionItems = await page.$$(ClaudeSelectors.sidebar.allSessions)\n\n if (options.verbose) {\n console.log(`Found ${sessionItems.length} session items in sidebar`)\n }\n\n const limit = Math.min(sessionItems.length, options.limit)\n\n for (let i = 0; i < limit; i++) {\n // Re-query items since DOM might change after clicking\n const items = await page.$$(ClaudeSelectors.sidebar.allSessions)\n if (i >= items.length) break\n\n const item = items[i]\n\n try {\n // Get title from the session item (the main text-text-100 span)\n const titleElement = await item.$('span.text-text-100')\n const title = titleElement ? (await titleElement.textContent())?.trim() || 'Untitled' : 'Untitled'\n\n // Get repo name from the session item metadata (span.truncate inside the metadata row)\n let repoName: string | undefined\n try {\n const repoElement = await item.$('span.text-text-500 span.truncate')\n if (repoElement) {\n const repoText = (await repoElement.textContent())?.trim()\n if (repoText && repoText.length > 0) {\n // The repo name is just the repo portion (e.g., \"mi-core\"), not owner/repo\n // It may be truncated visually but full text should be in DOM\n repoName = repoText\n }\n }\n } catch {\n // No repo\n }\n\n if (options.verbose) {\n const repoDisplay = repoName ? ` (${repoName})` : ''\n process.stdout.write(`\\r Scanning ${i + 1}/${limit}: ${title.slice(0, 35)}${repoDisplay}...`)\n }\n\n // Dismiss any modal dialogs that might be open (like notification prompts)\n try {\n await page.keyboard.press('Escape')\n await page.waitForTimeout(300)\n } catch {\n // No modal to dismiss\n }\n\n // Click the session item to navigate to it\n await item.click()\n await page.waitForTimeout(2000)\n\n // Get the session URL from the page after navigation\n const sessionUrl = page.url()\n\n // Extract branch name if present (from branch bar after navigation)\n let branchName: string | undefined\n try {\n const branchElement = await page.$(ClaudeSelectors.branchBar.branchName)\n if (branchElement) {\n branchName = (await branchElement.textContent())?.trim()\n }\n } catch {\n // No branch\n }\n\n // Check if archived\n const archived = !!(await page.$(ClaudeSelectors.archive.indicator))\n\n sessions.push({\n url: sessionUrl,\n title: title.trim(),\n branchName,\n repoName,\n archived,\n })\n } catch (error) {\n if (options.verbose) {\n console.error(`\\n Error scanning session ${i + 1}:`, error)\n }\n }\n }\n\n if (options.verbose) {\n console.log('\\n')\n }\n\n return sessions\n } finally {\n await context.close()\n }\n}\n\nexport { ImportOptions }\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\nexport async function projectCommand(action: string, options: Record<string, unknown>) {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n switch (action) {\n case 'list':\n await listProjects(api)\n break\n default:\n console.error(`Unknown action: ${action}`)\n process.exit(1)\n }\n}\n\nasync function listProjects(api: FlightDeskAPI) {\n const projects = await api.listProjects()\n\n if (projects.length === 0) {\n console.log('No projects found.')\n console.log('\\nCreate a project at https://app.flightdesk.dev/app/projects/new')\n return\n }\n\n console.log('Projects:\\n')\n\n // Find the longest name for alignment\n const maxNameLen = Math.max(...projects.map(p => p.name.length), 4)\n\n for (const project of projects) {\n const name = project.name.padEnd(maxNameLen)\n const repo = project.githubRepo || '(no repo)'\n console.log(` ${project.id} ${name} ${repo}`)\n }\n\n console.log(`\\n${projects.length} project(s)`)\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport { execSync, spawn, spawnSync } from 'node:child_process'\nimport * as path from 'node:path'\nimport * as os from 'node:os'\nimport * as fs from 'node:fs'\n\ninterface PreviewStatusOptions {\n taskId: string\n}\n\n/**\n * Validate that a container ID is safe (hex characters only)\n * Docker container IDs are 64-char hex strings (or 12-char truncated)\n */\nfunction isValidContainerId(id: string): boolean {\n return /^[a-fA-F0-9]+$/.test(id) && id.length >= 12 && id.length <= 64\n}\n\n/**\n * Validate SSH connection parameters to prevent injection\n */\nfunction validateSSHParams(instance: { sshUser: string; sshHost: string; sshPort: number; containerId?: string }): void {\n // Validate container ID if present (hex only)\n if (instance.containerId && !isValidContainerId(instance.containerId)) {\n throw new Error(`Invalid container ID format: ${instance.containerId}`)\n }\n // Validate SSH user (alphanumeric, underscore, hyphen)\n if (!/^[a-zA-Z0-9_-]+$/.test(instance.sshUser)) {\n throw new Error(`Invalid SSH user format: ${instance.sshUser}`)\n }\n // Validate SSH host (alphanumeric, dots, hyphens for hostname/IP)\n if (!/^[a-zA-Z0-9.-]+$/.test(instance.sshHost)) {\n throw new Error(`Invalid SSH host format: ${instance.sshHost}`)\n }\n // Validate port is a reasonable number\n if (!Number.isInteger(instance.sshPort) || instance.sshPort < 1 || instance.sshPort > 65535) {\n throw new Error(`Invalid SSH port: ${instance.sshPort}`)\n }\n}\n\ninterface PreviewLogsOptions {\n taskId: string\n lines?: number\n follow?: boolean\n}\n\ninterface PreviewMountOptions {\n taskId: string\n directory?: string\n}\n\ninterface PreviewUnmountOptions {\n taskId: string\n}\n\ninterface PreviewRestartOptions {\n taskId: string\n}\n\ninterface PreviewResumeOptions {\n taskId: string\n}\n\ninterface PreviewTeardownOptions {\n taskId: string\n}\n\ntype PreviewOptions =\n | PreviewStatusOptions\n | PreviewLogsOptions\n | PreviewMountOptions\n | PreviewUnmountOptions\n | PreviewRestartOptions\n | PreviewResumeOptions\n | PreviewTeardownOptions\n\n/**\n * Preview environment management commands\n */\nexport async function previewCommand(\n action: 'status' | 'logs' | 'mount' | 'unmount' | 'restart' | 'resume' | 'teardown',\n options: PreviewOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n switch (action) {\n case 'status':\n await handleStatus(api, options as PreviewStatusOptions)\n break\n case 'logs':\n await handleLogs(api, options as PreviewLogsOptions)\n break\n case 'mount':\n await handleMount(api, options as PreviewMountOptions)\n break\n case 'unmount':\n await handleUnmount(api, options as PreviewUnmountOptions)\n break\n case 'restart':\n await handleRestart(api, options as PreviewRestartOptions)\n break\n case 'resume':\n await handleResume(api, options as PreviewResumeOptions)\n break\n case 'teardown':\n await handleTeardown(api, options as PreviewTeardownOptions)\n break\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction getStatusEmoji(status: string): string {\n const statusEmojis: Record<string, string> = {\n STARTING: '\uD83D\uDD04',\n READY: '\u2705',\n SUSPENDED: '\uD83D\uDCA4',\n RESTARTING: '\uD83D\uDD04',\n TEARDOWN: '\uD83D\uDDD1\uFE0F',\n ERROR: '\u274C',\n }\n return statusEmojis[status] || '\u2753'\n}\n\nasync function handleStatus(api: FlightDeskAPI, options: PreviewStatusOptions): Promise<void> {\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.log('\\n\u26A0\uFE0F No preview environment found for this task')\n console.log(' The preview environment may not have been created yet,')\n console.log(' or the PR may be closed.')\n return\n }\n\n const emoji = getStatusEmoji(instance.status)\n\n console.log('\\n\uD83D\uDCE6 Preview Environment')\n console.log('\u2500'.repeat(50))\n console.log(`${emoji} Status: ${instance.status}`)\n console.log(` ID: ${instance.id.substring(0, 8)}`)\n console.log(` Preview URL: ${instance.previewUrl}`)\n console.log(` SSH: ${instance.sshConnectionString}`)\n console.log(` Container: ${instance.containerId.substring(0, 12)}`)\n\n if (instance.lastActivityAt) {\n const lastActivity = new Date(instance.lastActivityAt)\n const minutesAgo = Math.round((Date.now() - lastActivity.getTime()) / 60000)\n console.log(` Last Activity: ${minutesAgo} minutes ago`)\n }\n\n if (instance.suspendedAt) {\n const suspended = new Date(instance.suspendedAt)\n console.log(` Suspended At: ${suspended.toLocaleString()}`)\n }\n\n console.log(` Created: ${new Date(instance.createdAt).toLocaleString()}`)\n console.log('')\n}\n\nasync function handleLogs(api: FlightDeskAPI, options: PreviewLogsOptions): Promise<void> {\n const lines = options.lines || 100\n\n if (options.follow) {\n // For follow mode, we need the SSH details to tail logs directly\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.error('No preview environment found for this task')\n process.exit(1)\n }\n\n console.log(`\uD83D\uDCCB Streaming logs from ${instance.previewUrl}...\\n`)\n console.log(`(Press Ctrl+C to stop)\\n`)\n\n // Validate SSH parameters to prevent command injection\n validateSSHParams(instance)\n\n // Use SSH to tail the logs (containerId validated above)\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n const sshCommand = `docker logs -f ${instance.containerId}`\n const ssh = spawn('ssh', [\n '-o', 'StrictHostKeyChecking=no',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-p', String(instance.sshPort),\n `${instance.sshUser}@${instance.sshHost}`,\n sshCommand,\n ])\n\n ssh.stdout.pipe(process.stdout)\n ssh.stderr.pipe(process.stderr)\n\n ssh.on('close', (code) => {\n process.exit(code || 0)\n })\n\n // Handle Ctrl+C\n process.on('SIGINT', () => {\n ssh.kill()\n process.exit(0)\n })\n\n return\n }\n\n // Non-follow mode: fetch logs via API\n const result = await api.getInstanceLogs(options.taskId, lines)\n\n if (!result.logs) {\n console.log('No logs available')\n return\n }\n\n console.log(result.logs)\n}\n\nasync function handleMount(api: FlightDeskAPI, options: PreviewMountOptions): Promise<void> {\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.error('No preview environment found for this task')\n process.exit(1)\n }\n\n if (instance.status === 'SUSPENDED') {\n console.log('\u23F8\uFE0F Instance is suspended. Resuming...')\n await api.resumeInstance(options.taskId)\n // Wait a moment for resume\n await new Promise((resolve) => setTimeout(resolve, 3000))\n }\n\n // Check if sshfs is installed\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n try {\n execSync('which sshfs', { stdio: 'ignore' })\n } catch {\n console.error('\u274C sshfs is not installed.')\n console.error('')\n console.error('Install it with:')\n if (process.platform === 'darwin') {\n console.error(' brew install macfuse sshfs')\n } else if (process.platform === 'linux') {\n console.error(' sudo apt install sshfs')\n } else {\n console.error(' SSHFS is not supported on this platform')\n }\n process.exit(1)\n }\n\n // Sanitize taskId to prevent path traversal attacks\n const rawTaskIdPrefix = options.taskId.substring(0, 8)\n const safeTaskId = path.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, '') || 'task'\n const mountDir = options.directory || path.join(os.homedir(), 'flightdesk-mounts', safeTaskId)\n\n // Create mount directory if it doesn't exist\n if (!fs.existsSync(mountDir)) {\n fs.mkdirSync(mountDir, { recursive: true })\n }\n\n // Check if already mounted\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n try {\n const mounted = execSync('mount', { encoding: 'utf8' })\n if (mounted.includes(mountDir)) {\n console.log(`\uD83D\uDCC1 Already mounted at ${mountDir}`)\n return\n }\n } catch {\n // Ignore mount check errors\n }\n\n console.log(`\uD83D\uDCC1 Mounting preview environment to ${mountDir}...`)\n\n // Validate SSH parameters to prevent injection\n validateSSHParams(instance)\n\n // Use spawnSync with arguments array to avoid shell injection\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n const sshfsArgs = [\n '-o', 'StrictHostKeyChecking=no',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-o', 'reconnect',\n '-o', 'ServerAliveInterval=15',\n '-o', 'ServerAliveCountMax=3',\n '-p', String(instance.sshPort),\n `${instance.sshUser}@${instance.sshHost}:/app`,\n mountDir,\n ]\n\n try {\n const result = spawnSync('sshfs', sshfsArgs, { stdio: 'inherit' })\n if (result.status !== 0) {\n throw new Error(`sshfs exited with code ${result.status}`)\n }\n console.log('')\n console.log('\u2705 Mounted successfully!')\n console.log(` Location: ${mountDir}`)\n console.log('')\n console.log(' To unmount:')\n console.log(` fd preview unmount ${options.taskId}`)\n console.log('')\n console.log(' Or manually:')\n if (process.platform === 'darwin') {\n console.log(` umount ${mountDir}`)\n } else {\n console.log(` fusermount -u ${mountDir}`)\n }\n } catch (error) {\n console.error(`\u274C Mount failed: ${error}`)\n process.exit(1)\n }\n}\n\nasync function handleUnmount(_api: FlightDeskAPI, options: PreviewUnmountOptions): Promise<void> {\n // Sanitize taskId to prevent path traversal\n const rawTaskIdPrefix = options.taskId.substring(0, 8)\n const safeTaskId = path.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, '') || 'task'\n const mountDir = path.join(os.homedir(), 'flightdesk-mounts', safeTaskId)\n\n if (!fs.existsSync(mountDir)) {\n console.log('Mount directory does not exist')\n return\n }\n\n console.log(`\uD83D\uDCC1 Unmounting ${mountDir}...`)\n\n try {\n // Use spawnSync with arguments array to avoid shell injection\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n let result\n if (process.platform === 'darwin') {\n result = spawnSync('umount', [mountDir], { stdio: 'inherit' })\n } else {\n result = spawnSync('fusermount', ['-u', mountDir], { stdio: 'inherit' })\n }\n if (result.status !== 0) {\n throw new Error(`Unmount exited with code ${result.status}`)\n }\n console.log('\u2705 Unmounted successfully')\n\n // Try to remove the directory (and any nested contents)\n try {\n fs.rmSync(mountDir, { recursive: true, force: true })\n } catch {\n // Directory cleanup failure is non-fatal\n }\n } catch (error) {\n console.error(`\u274C Unmount failed: ${error}`)\n console.error('')\n console.error('Try force unmounting:')\n if (process.platform === 'darwin') {\n console.error(` diskutil unmount force ${mountDir}`)\n } else {\n console.error(` fusermount -uz ${mountDir}`)\n }\n process.exit(1)\n }\n}\n\nasync function handleRestart(api: FlightDeskAPI, options: PreviewRestartOptions): Promise<void> {\n console.log('\uD83D\uDD04 Restarting preview environment...')\n\n await api.restartInstance(options.taskId)\n\n console.log('\u2705 Restart initiated. The preview will be available shortly.')\n}\n\nasync function handleResume(api: FlightDeskAPI, options: PreviewResumeOptions): Promise<void> {\n console.log('\u25B6\uFE0F Resuming preview environment...')\n\n await api.resumeInstance(options.taskId)\n\n console.log('\u2705 Resume initiated. The preview should be ready in about 30 seconds.')\n}\n\nasync function handleTeardown(api: FlightDeskAPI, options: PreviewTeardownOptions): Promise<void> {\n console.log('\uD83D\uDDD1\uFE0F Tearing down preview environment...')\n\n await api.tearDownInstance(options.taskId)\n\n console.log('\u2705 Preview environment has been torn down.')\n}\n", "import { Command } from 'commander'\nimport { setDevMode, setApiUrl } from './lib/config'\n\n// Version injected by esbuild at build time\ndeclare const __CLI_VERSION__: string\n\n// Import commands\nimport { initCommand } from './commands/init'\nimport { authCommand } from './commands/auth'\nimport { registerCommand } from './commands/register'\nimport { statusCommand } from './commands/status'\nimport { watchCommand } from './commands/watch'\nimport { taskCommand } from './commands/task'\nimport { promptCommand } from './commands/prompt'\nimport { orgListCommand, orgSwitchCommand, orgRefreshCommand } from './commands/org'\nimport { contextCommand } from './commands/context'\nimport { syncCommand } from './commands/sync'\nimport { importCommand } from './commands/import'\nimport { projectCommand } from './commands/project'\nimport { previewCommand } from './commands/preview'\n\nconst program = new Command()\n\nprogram\n .name('flightdesk')\n .description('FlightDesk CLI - AI task management for Claude Code sessions')\n .version(__CLI_VERSION__)\n .option('--dev', 'Use local development API (localhost:3000)')\n .option('--api <url>', 'Use custom API URL')\n\n// Process --dev and --api flags before command execution\nprogram.hook('preAction', () => {\n const opts = program.opts()\n if (opts.api) {\n setApiUrl(opts.api)\n console.log(`\uD83D\uDD27 Using custom API: ${opts.api}\\n`)\n } else if (opts.dev) {\n setDevMode(true)\n console.log('\uD83D\uDD27 Development mode: using http://localhost:3000\\n')\n }\n})\n\n// Initialize configuration\nprogram\n .command('init')\n .description('Configure FlightDesk CLI with your API credentials')\n .action(initCommand)\n\n// Authenticate with Claude (for watch daemon)\nprogram\n .command('auth')\n .description('Log in to Claude for session monitoring')\n .action(authCommand)\n\n// Register a session with a task\nprogram\n .command('register [task-id]')\n .description('Register a Claude Code session with a FlightDesk task (auto-detects project from git repo)')\n .option('-p, --project <id>', 'Project ID (auto-detected from git repo if not provided)')\n .option('--view-url <url>', 'Claude Code session view URL')\n .option('--teleport-id <id>', 'Claude Code teleport ID')\n .option('--title <title>', 'Task title (creates new task if task-id not provided)')\n .option('--description <description>', 'Task description')\n .action(registerCommand)\n\n// Project management\nconst project = program\n .command('project')\n .description('Project management commands')\n\nproject\n .command('list')\n .description('List projects in the active organization')\n .action(() => projectCommand('list', {}))\n\n// Task management\nconst task = program\n .command('task')\n .description('Task management commands')\n\ntask\n .command('create')\n .description('Create a new task')\n .requiredOption('-p, --project <id>', 'Project ID')\n .requiredOption('-t, --title <title>', 'Task title')\n .option('-d, --description <description>', 'Task description')\n .action((options) => taskCommand('create', options))\n\ntask\n .command('list')\n .description('List tasks')\n .option('-p, --project <id>', 'Filter by project ID')\n .option('--status <status>', 'Filter by status')\n .action((options) => taskCommand('list', options))\n\ntask\n .command('status <task-id>')\n .description('Get task status')\n .action((taskId) => taskCommand('status', { taskId }))\n\ntask\n .command('update <task-id>')\n .description('Update task')\n .option('-s, --status <status>', 'New status')\n .option('--branch <branch>', 'Branch name')\n .option('--pr-url <url>', 'Pull request URL')\n .action((taskId, options) => taskCommand('update', { taskId, ...options }))\n\n// Watch daemon for monitoring sessions\nprogram\n .command('watch')\n .description('Start the Playwright daemon to monitor Claude Code sessions')\n .option('--interval <minutes>', 'Check interval in minutes', '5')\n .option('--once', 'Run once and exit')\n .option('--auto-pr', 'Automatically click \"Create PR\" button when found')\n .option('--no-headless', 'Run browser in visible mode (for debugging)')\n .action(watchCommand)\n\n// Import existing Claude sessions\nprogram\n .command('import')\n .description('Scan Claude.ai for existing sessions and import them as tasks')\n .option('--dry-run', 'Show what would be imported without making changes')\n .option('--limit <n>', 'Maximum number of sessions to scan', '50')\n .option('-p, --project <id>', 'Import all sessions into a specific project')\n .option('--no-headless', 'Run browser in visible mode (for debugging)')\n .option('-v, --verbose', 'Show detailed progress')\n .action(importCommand)\n\n// Status overview\nprogram\n .command('status')\n .description('Show status of all active tasks')\n .option('-p, --project <id>', 'Filter by project')\n .action(statusCommand)\n\n// Get prompt for a task\nprogram\n .command('prompt <task-id>')\n .description('Get a prompt for a task (ready to paste into Claude)')\n .option('--type <type>', 'Prompt type: review, test_plan, summary, handoff', 'review')\n .action(promptCommand)\n\n// Organization management\nconst org = program\n .command('org')\n .description('Organization management')\n\norg\n .command('list')\n .description('List your organizations')\n .action(orgListCommand)\n\norg\n .command('switch <name>')\n .description('Switch active organization')\n .action(orgSwitchCommand)\n\norg\n .command('refresh')\n .description('Refresh organizations from API')\n .action(orgRefreshCommand)\n\n// Context detection\nprogram\n .command('context')\n .description('Show current repository context and mapped organization')\n .action(contextCommand)\n\n// Sync repo mappings\nprogram\n .command('sync')\n .description('Refresh project-to-repository mappings from all organizations')\n .action(syncCommand)\n\n// Preview environment commands\nconst preview = program\n .command('preview')\n .description('Preview environment management')\n\npreview\n .command('status <task-id>')\n .description('Show preview environment status')\n .action((taskId) => previewCommand('status', { taskId }))\n\npreview\n .command('logs <task-id>')\n .description('Get logs from preview environment')\n .option('-n, --lines <lines>', 'Number of log lines (1-10000)', '100')\n .option('-f, --follow', 'Follow log output')\n .action((taskId, options) => {\n const lines = Math.min(Math.max(Number.parseInt(options.lines || '100'), 1), 10000)\n previewCommand('logs', { taskId, lines, follow: options.follow })\n })\n\npreview\n .command('mount <task-id>')\n .description('Mount preview environment filesystem via SSHFS')\n .option('-d, --directory <path>', 'Custom mount directory')\n .action((taskId, options) => previewCommand('mount', { taskId, directory: options.directory }))\n\npreview\n .command('unmount <task-id>')\n .description('Unmount preview environment filesystem')\n .action((taskId) => previewCommand('unmount', { taskId }))\n\npreview\n .command('restart <task-id>')\n .description('Restart preview environment processes')\n .action((taskId) => previewCommand('restart', { taskId }))\n\npreview\n .command('resume <task-id>')\n .description('Resume a suspended preview environment')\n .action((taskId) => previewCommand('resume', { taskId }))\n\npreview\n .command('teardown <task-id>')\n .description('Tear down preview environment')\n .action((taskId) => previewCommand('teardown', { taskId }))\n\n// Shorthand commands for common preview operations\nprogram\n .command('mount <task-id>')\n .description('Mount preview environment filesystem (shorthand for \"preview mount\")')\n .option('-d, --directory <path>', 'Custom mount directory')\n .action((taskId, options) => previewCommand('mount', { taskId, directory: options.directory }))\n\nprogram\n .command('unmount <task-id>')\n .description('Unmount preview environment filesystem (shorthand for \"preview unmount\")')\n .action((taskId) => previewCommand('unmount', { taskId }))\n\nprogram\n .command('logs <task-id>')\n .description('Get logs from preview environment (equivalent to \"preview logs\")')\n .option('-n, --lines <lines>', 'Number of log lines (1-10000)', '100')\n .option('-f, --follow', 'Follow log output')\n .action((taskId, options) => {\n const lines = Math.min(Math.max(Number.parseInt(options.lines || '100'), 1), 10000)\n previewCommand('logs', { taskId, lines, follow: options.follow })\n })\n\nprogram.parse()\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,4EAAAA,UAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,MAKhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAAA,MAC/B;AAAA,IACF;AAEA,IAAAD,SAAQ,iBAAiBC;AACzB,IAAAD,SAAQ,uBAAuBE;AAAA;AAAA;;;ACtC/B;AAAA,+EAAAC,UAAA;AAAA,QAAM,EAAE,sBAAAC,sBAAqB,IAAI;AAEjC,QAAMC,YAAN,MAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAUb,YAAY,MAAM,aAAa;AAC7B,aAAK,cAAc,eAAe;AAClC,aAAK,WAAW;AAChB,aAAK,WAAW;AAChB,aAAK,eAAe;AACpB,aAAK,0BAA0B;AAC/B,aAAK,aAAa;AAElB,gBAAQ,KAAK,CAAC,GAAG;AAAA,UACf,KAAK;AACH,iBAAK,WAAW;AAChB,iBAAK,QAAQ,KAAK,MAAM,GAAG,EAAE;AAC7B;AAAA,UACF,KAAK;A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O,0BAA0B,wBAAwB,EACzD,OAAO,CAAC,QAAQ,YAAY,eAAe,SAAS,EAAE,QAAQ,WAAW,QAAQ,UAAU,CAAC,CAAC;AAEhGA,SACG,QAAQ,mBAAmB,EAC3B,YAAY,0EAA0E,EACtF,OAAO,CAAC,WAAW,eAAe,WAAW,EAAE,OAAO,CAAC,CAAC;AAE3DA,SACG,QAAQ,gBAAgB,EACxB,YAAY,kEAAkE,EAC9E,OAAO,uBAAuB,iCAAiC,KAAK,EACpE,OAAO,gBAAgB,mBAAmB,EAC1C,OAAO,CAAC,QAAQ,YAAY;AAC3B,QAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,OAAO,SAAS,QAAQ,SAAS,KAAK,GAAG,CAAC,GAAG,GAAK;AAClF,iBAAe,QAAQ,EAAE,QAAQ,OAAO,QAAQ,QAAQ,OAAO,CAAC;AAClE,CAAC;AAEHA,SAAQ,MAAM;",
4
+ "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\u2013Levenshtein_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 * as fs from 'fs'\nimport * as path from 'path'\nimport * as os from 'os'\n\nexport interface OrganizationInfo {\n id: string\n name: string\n}\n\nexport interface FlightDeskConfig {\n // Single API key for the user\n apiKey?: string\n // Currently active organization\n activeOrganization?: string\n // All organizations the user belongs to\n organizations: OrganizationInfo[]\n // Repo to project mappings\n repoMapping: Record<string, string>\n}\n\nconst CONFIG_FILE = path.join(os.homedir(), '.flightdeskrc')\nconst DEFAULT_API_URL = 'https://api.flightdesk.dev'\nconst DEV_API_URL = 'http://localhost:3000'\n\n// Global API URL override (set by --dev or --api options)\nlet apiUrlOverride: string | null = null\n\nexport function setDevMode(enabled: boolean): void {\n if (enabled) {\n apiUrlOverride = DEV_API_URL\n }\n}\n\nexport function setApiUrl(url: string): void {\n apiUrlOverride = url\n}\n\nexport function getApiUrl(): string {\n // Always use production URL unless --dev or --apiUrl flag is passed\n // API URL is never persisted in config\n return apiUrlOverride ?? DEFAULT_API_URL\n}\n\nexport function loadConfig(): FlightDeskConfig {\n try {\n if (fs.existsSync(CONFIG_FILE)) {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8')\n const parsed = JSON.parse(content)\n\n // Migrate old config format if needed\n if (parsed.organizations?.[0]?.apiKey) {\n return migrateOldConfig(parsed)\n }\n\n return {\n organizations: [],\n repoMapping: {},\n ...parsed,\n }\n }\n } catch (error) {\n console.error('Warning: Failed to load config file:', error)\n }\n\n return {\n organizations: [],\n repoMapping: {},\n }\n}\n\n/**\n * Migrate from old config format (apiKey per org) to new format (single apiKey)\n */\nfunction migrateOldConfig(oldConfig: any): FlightDeskConfig {\n console.log('\uD83D\uDCE6 Migrating config to new format...')\n\n // Take the API key from the first/default org\n const defaultOrg = oldConfig.defaultOrganization\n ? oldConfig.organizations.find((o: any) => o.id === oldConfig.defaultOrganization)\n : oldConfig.organizations[0]\n\n const newConfig: FlightDeskConfig = {\n apiKey: defaultOrg?.apiKey,\n activeOrganization: defaultOrg?.id,\n organizations: oldConfig.organizations.map((o: any) => ({\n id: o.id,\n name: o.name,\n })),\n repoMapping: oldConfig.repoMapping || {},\n }\n\n // Save migrated config\n saveConfig(newConfig)\n console.log('\u2705 Config migrated successfully')\n\n return newConfig\n}\n\nexport function saveConfig(config: FlightDeskConfig): void {\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2))\n}\n\nexport function getActiveOrganization(): OrganizationInfo | null {\n const config = loadConfig()\n\n if (!config.activeOrganization) {\n // Return first org if only one exists\n if (config.organizations.length === 1) {\n return config.organizations[0]\n }\n return null\n }\n\n return config.organizations.find(o => o.id === config.activeOrganization) || null\n}\n\nexport function setActiveOrganization(orgId: string): void {\n const config = loadConfig()\n\n const org = config.organizations.find(o => o.id === orgId || o.name.toLowerCase() === orgId.toLowerCase())\n if (!org) {\n throw new Error(`Organization not found: ${orgId}`)\n }\n\n config.activeOrganization = org.id\n saveConfig(config)\n}\n\nexport function updateOrganizations(orgs: OrganizationInfo[]): void {\n const config = loadConfig()\n config.organizations = orgs\n\n // If active org no longer exists, clear it\n if (config.activeOrganization && !orgs.some(o => o.id === config.activeOrganization)) {\n config.activeOrganization = orgs[0]?.id\n }\n\n saveConfig(config)\n}\n\nexport function updateRepoMapping(repo: string, orgId: string): void {\n const config = loadConfig()\n config.repoMapping[repo] = orgId\n saveConfig(config)\n}\n\n/**\n * Get organization by repository name (from repo mapping)\n */\nexport function getOrganizationByRepo(repoFullName: string): OrganizationInfo | null {\n const config = loadConfig()\n const orgId = config.repoMapping[repoFullName]\n if (!orgId) return null\n return config.organizations.find(o => o.id === orgId) || null\n}\n\nexport function isConfigured(): boolean {\n const config = loadConfig()\n return !!config.apiKey && config.organizations.length > 0\n}\n\nexport function requireConfig(): FlightDeskConfig {\n const config = loadConfig()\n\n if (!config.apiKey) {\n console.error('\u274C FlightDesk is not configured. Run: flightdesk init')\n process.exit(1)\n }\n\n if (config.organizations.length === 0) {\n console.error('\u274C No organizations found. Run: flightdesk init')\n process.exit(1)\n }\n\n return config\n}\n\nexport function requireActiveOrg(): { config: FlightDeskConfig; org: OrganizationInfo } {\n const config = requireConfig()\n const org = getActiveOrganization()\n\n if (!org) {\n console.error('\u274C No active organization. Run: flightdesk org switch <org-name>')\n console.log('\\nAvailable organizations:')\n config.organizations.forEach(o => console.log(` - ${o.name}`))\n process.exit(1)\n }\n\n return { config, org }\n}\n\nexport { CONFIG_FILE, DEFAULT_API_URL, DEV_API_URL }\n", "import * as readline from 'readline'\nimport {\n loadConfig,\n saveConfig,\n isConfigured,\n CONFIG_FILE,\n getApiUrl,\n} from '../lib/config'\nimport { fetchUserInfo } from '../lib/api'\n\nfunction question(rl: readline.Interface, prompt: string): Promise<string> {\n return new Promise((resolve) => {\n rl.question(prompt, (answer) => {\n resolve(answer.trim())\n })\n })\n}\n\nexport async function initCommand(): Promise<void> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n\n console.log('\\n\uD83D\uDEEB FlightDesk CLI Setup\\n')\n\n try {\n // Check if already configured\n if (isConfigured()) {\n const config = loadConfig()\n console.log('FlightDesk is already configured.')\n console.log(` API Key: ${config.apiKey?.substring(0, 20)}...`)\n console.log(` Organizations: ${config.organizations.map(o => o.name).join(', ')}`)\n console.log('')\n\n const reconfigure = await question(rl, 'Reconfigure? (y/N): ')\n if (reconfigure.toLowerCase() !== 'y') {\n console.log('\\nConfiguration unchanged.')\n console.log('Use \"flightdesk org refresh\" to update organizations.')\n console.log('Use \"flightdesk org switch <name>\" to change active organization.')\n return\n }\n }\n\n // Get API key\n console.log('Enter your FlightDesk API key.')\n console.log('You can find this at https://flightdesk.dev/settings/api-keys\\n')\n\n const apiKey = await question(rl, 'API Key: ')\n if (!apiKey) {\n console.error('API Key is required')\n return\n }\n\n // Use the API URL from --api/--dev flags or default to production\n const apiUrl = getApiUrl()\n\n // Test the connection and fetch user's organizations\n console.log('\\nConnecting to FlightDesk...')\n\n try {\n const userInfo = await fetchUserInfo(apiKey, apiUrl)\n\n const orgs = userInfo.organizations || []\n if (orgs.length === 0) {\n console.error('\u274C No organizations found for this user')\n console.log('Please make sure you are a member of at least one organization.')\n return\n }\n\n const primaryEmail = userInfo.emails?.find(e => e.primary)?.email || userInfo.emails?.[0]?.email || 'unknown'\n console.log('\u2705 Connection successful!')\n console.log(` Logged in as: ${primaryEmail}`)\n console.log(` Organizations: ${orgs.length}`)\n\n // Map to our OrganizationInfo format\n const organizations = orgs.map(m => ({\n id: m.organization.id,\n name: m.organization.name,\n }))\n\n // Let user choose active org if multiple\n let activeOrganization: string\n if (organizations.length === 1) {\n activeOrganization = organizations[0].id\n console.log(`\\n Active organization: ${organizations[0].name}`)\n } else {\n console.log('\\nYour organizations:')\n organizations.forEach((org, i) => {\n console.log(` ${i + 1}. ${org.name}`)\n })\n const choice = await question(rl, `\\nSelect active organization (1-${organizations.length}): `)\n const choiceIndex = Number.parseInt(choice, 10) - 1\n if (choiceIndex < 0 || choiceIndex >= organizations.length) {\n console.error('Invalid selection, using first organization')\n activeOrganization = organizations[0].id\n } else {\n activeOrganization = organizations[choiceIndex].id\n }\n }\n\n // Save configuration\n const config = loadConfig()\n config.apiKey = apiKey\n config.apiUrl = apiUrl\n config.organizations = organizations\n config.activeOrganization = activeOrganization\n saveConfig(config)\n\n console.log(`\\n\u2705 Configuration saved to ${CONFIG_FILE}`)\n console.log('\\nYou can now use:')\n console.log(' flightdesk project list - List projects')\n console.log(' flightdesk task create - Create a task')\n console.log(' flightdesk org list - Show organizations')\n console.log(' flightdesk org switch <name> - Switch active organization')\n } catch (error) {\n console.error(`\\n\u274C Connection failed: ${error}`)\n console.log('\\nPlease check:')\n console.log(' - Your API key is correct')\n console.log(' - You have network connectivity')\n console.log(' - The FlightDesk API is reachable')\n }\n } finally {\n rl.close()\n }\n}\n", "import { FlightDeskConfig, OrganizationInfo, getApiUrl } from './config'\n\n/**\n * Simple GraphQL client for CLI operations.\n * We avoid using the full Apollo client to keep the CLI bundle small.\n */\nexport class FlightDeskAPI {\n private readonly apiUrl: string\n private readonly apiKey: string\n private readonly organizationId: string\n\n constructor(config: FlightDeskConfig, org: OrganizationInfo) {\n this.apiUrl = getApiUrl()\n this.apiKey = config.apiKey!\n this.organizationId = org.id\n }\n\n /**\n * Create an API client from config, using the active organization\n */\n static fromConfig(config: FlightDeskConfig, org: OrganizationInfo): FlightDeskAPI {\n return new FlightDeskAPI(config, org)\n }\n\n async graphql<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T> {\n const response = await fetch(`${this.apiUrl}/graphql`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ query, variables }),\n })\n\n if (!response.ok) {\n throw new Error(`API request failed: ${response.status} ${response.statusText}`)\n }\n\n const result = await response.json() as { data?: T; errors?: Array<{ message: string }> }\n\n if (result.errors && result.errors.length > 0) {\n throw new Error(`GraphQL error: ${result.errors.map(e => e.message).join(', ')}`)\n }\n\n return result.data as T\n }\n\n // ============================================================================\n // Task Operations\n // ============================================================================\n\n async createTask(input: {\n projectId: string\n title: string\n description?: string\n }) {\n const query = `\n mutation CreateTask($input: UserCreateTaskInput!) {\n userCreateTask(input: $input) {\n id\n title\n status\n createdAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateTask: { id: string; title: string; status: string; createdAt: string } }>(query, { input })\n return result.userCreateTask\n }\n\n async updateTask(taskId: string, input: {\n status?: string\n branchName?: string\n prUrl?: string\n prNumber?: number\n sessionViewUrl?: string\n sessionTeleportId?: string\n }) {\n const query = `\n mutation UpdateTask($taskId: String!, $input: UserUpdateTaskInput!) {\n userUpdateTask(taskId: $taskId, input: $input) {\n id\n title\n status\n branchName\n prUrl\n }\n }\n `\n\n const result = await this.graphql<{ userUpdateTask: { id: string; title: string; status: string; branchName?: string; prUrl?: string } }>(query, { taskId, input })\n return result.userUpdateTask\n }\n\n async registerSession(taskId: string, input: { viewUrl: string; teleportId: string }) {\n const query = `\n mutation RegisterSession($taskId: String!, $input: RegisterSessionInput!) {\n userRegisterSession(taskId: $taskId, input: $input) {\n id\n title\n status\n sessionViewUrl\n sessionTeleportId\n }\n }\n `\n\n const result = await this.graphql<{ userRegisterSession: { id: string; title: string; status: string; sessionViewUrl?: string; sessionTeleportId?: string } }>(query, { taskId, input })\n return result.userRegisterSession\n }\n\n async getTask(taskId: string) {\n const query = `\n query GetTask($taskId: String!) {\n userTask(taskId: $taskId) {\n id\n title\n description\n status\n branchName\n prUrl\n prNumber\n sessionViewUrl\n sessionTeleportId\n createdAt\n updatedAt\n project {\n id\n name\n githubRepo\n }\n }\n }\n `\n\n const result = await this.graphql<{ userTask: unknown }>(query, { taskId })\n return result.userTask\n }\n\n async listTasks(options?: { projectId?: string; status?: string }) {\n const query = `\n query ListTasks($input: ListTasksInput!) {\n userTasks(input: $input) {\n id\n title\n status\n branchName\n prUrl\n sessionViewUrl\n createdAt\n project {\n id\n name\n }\n }\n }\n `\n\n // Build the input object - all fields are optional now\n const input: { projectId?: string; status?: string[] } = {}\n if (options?.projectId) {\n input.projectId = options.projectId\n }\n if (options?.status) {\n input.status = [options.status]\n }\n\n const result = await this.graphql<{ userTasks: Array<{ id: string; title: string; status: string; branchName?: string; prUrl?: string; createdAt: string; project: { id: string; name: string } }> }>(query, { input })\n return result.userTasks\n }\n\n // ============================================================================\n // Project Operations\n // ============================================================================\n\n async listProjects() {\n const query = `\n query ListProjects($organizationId: String!) {\n userProjects(organizationId: $organizationId) {\n id\n name\n githubRepo\n }\n }\n `\n\n const result = await this.graphql<{ userProjects: Array<{ id: string; name: string; githubRepo: string }> }>(query, { organizationId: this.organizationId })\n return result.userProjects\n }\n\n async getProject(projectId: string) {\n const query = `\n query GetProject($projectId: String!) {\n userProject(projectId: $projectId) {\n id\n name\n githubRepo\n tokenTtlHours\n }\n }\n `\n\n const result = await this.graphql<{ userProject: { id: string; name: string; githubRepo: string; tokenTtlHours: number } }>(query, { projectId })\n return result.userProject\n }\n\n async createProject(input: {\n name: string\n organizationId: string\n githubConnectionId: string\n githubRepo: string\n teamId?: string\n tokenTtlHours?: number\n previewEnabled?: boolean\n }) {\n const query = `\n mutation CreateProject($input: UserCreateProjectInput!) {\n userCreateProject(input: $input) {\n id\n name\n githubRepo\n organizationId\n createdAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateProject: { id: string; name: string; githubRepo: string; organizationId: string; createdAt: string } }>(query, { input })\n return result.userCreateProject\n }\n\n // ============================================================================\n // Task Token Operations (for agent authentication)\n // ============================================================================\n\n async createTaskToken(taskId: string) {\n const query = `\n mutation CreateTaskToken($taskId: String!) {\n userCreateTaskToken(taskId: $taskId) {\n token\n expiresAt\n }\n }\n `\n\n const result = await this.graphql<{ userCreateTaskToken: { token: string; expiresAt: string } }>(query, { taskId })\n return result.userCreateTaskToken\n }\n\n // ============================================================================\n // Prompt Operations\n // ============================================================================\n\n async getTaskPrompts(taskId: string) {\n const query = `\n query GetTaskPrompts($taskId: String!) {\n userTaskPrompts(taskId: $taskId) {\n type\n content\n available\n reason\n }\n }\n `\n\n const result = await this.graphql<{ userTaskPrompts: Array<{ type: string; content: string; available: boolean; reason?: string }> }>(query, { taskId })\n return result.userTaskPrompts\n }\n\n // ============================================================================\n // Preview Environment Operations\n // ============================================================================\n\n async getTaskInstance(taskId: string) {\n const query = `\n query GetTaskInstance($taskId: String!) {\n userTaskInstance(taskId: $taskId) {\n id\n taskId\n workerId\n containerId\n previewUrl\n sshHost\n sshPort\n sshUser\n status\n lastActivityAt\n suspendedAt\n createdAt\n updatedAt\n sshConnectionString\n }\n }\n `\n\n const result = await this.graphql<{ userTaskInstance: {\n id: string\n taskId: string\n workerId: string\n containerId: string\n previewUrl: string\n sshHost: string\n sshPort: number\n sshUser: string\n status: string\n lastActivityAt?: string\n suspendedAt?: string\n createdAt: string\n updatedAt: string\n sshConnectionString: string\n } | null }>(query, { taskId })\n return result.userTaskInstance\n }\n\n async getInstanceLogs(taskId: string, lines = 100) {\n const query = `\n query GetInstanceLogs($taskId: String!, $lines: Float) {\n userInstanceLogs(taskId: $taskId, lines: $lines) {\n logs\n }\n }\n `\n\n const result = await this.graphql<{ userInstanceLogs: { logs: string } }>(query, { taskId, lines })\n return result.userInstanceLogs\n }\n\n async restartInstance(taskId: string) {\n const query = `\n mutation RestartInstance($taskId: String!) {\n userRestartInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userRestartInstance: boolean }>(query, { taskId })\n return result.userRestartInstance\n }\n\n async resumeInstance(taskId: string) {\n const query = `\n mutation ResumeInstance($taskId: String!) {\n userResumeInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userResumeInstance: boolean }>(query, { taskId })\n return result.userResumeInstance\n }\n\n async tearDownInstance(taskId: string) {\n const query = `\n mutation TearDownInstance($taskId: String!) {\n userTearDownInstance(taskId: $taskId)\n }\n `\n\n const result = await this.graphql<{ userTearDownInstance: boolean }>(query, { taskId })\n return result.userTearDownInstance\n }\n}\n\n// ============================================================================\n// Standalone API functions (for use without full config)\n// ============================================================================\n\nexport interface UserOrganization {\n organization: {\n id: string\n name: string\n }\n}\n\nexport interface MeResponse {\n id: string\n emails: Array<{ email: string; primary: boolean }>\n organizations: UserOrganization[]\n}\n\n/**\n * Fetch user info and organizations using an API key\n */\nexport async function fetchUserInfo(apiKey: string, apiUrl = 'https://api.flightdesk.dev'): Promise<MeResponse> {\n const response = await fetch(`${apiUrl}/graphql`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: `{\n me {\n id\n emails {\n email\n primary\n }\n organizations {\n organization {\n id\n name\n }\n }\n }\n }`,\n }),\n })\n\n if (!response.ok) {\n throw new Error(`API returned ${response.status}`)\n }\n\n const result = await response.json() as {\n data?: { me?: MeResponse }\n errors?: Array<{ message: string }>\n }\n\n if (result.errors?.length) {\n throw new Error(result.errors.map(e => e.message).join(', '))\n }\n\n if (!result.data?.me) {\n throw new Error('Invalid API response')\n }\n\n return result.data.me\n}\n", "/**\n * Playwright-based session monitoring for Claude Code sessions.\n *\n * This module opens Claude Code session URLs in headless Chromium,\n * detects branch names, and can auto-click \"Create PR\" buttons.\n *\n * Supports both:\n * - One-shot mode: Opens browser, performs action, closes (for auth commands)\n * - Persistent mode: Keeps browser alive for multiple session checks (for watch daemon)\n */\n\nimport type { Browser, Page, BrowserContext } from 'playwright'\nimport * as path from 'node:path'\nimport * as os from 'node:os'\nimport * as fs from 'node:fs'\nimport * as readline from 'node:readline'\n\n// Playwright is an optional dependency\nlet playwright: typeof import('playwright') | null = null\n\nexport interface SessionInfo {\n branchName?: string\n hasPrButton?: boolean\n prUrl?: string\n status?: 'active' | 'archived' | 'error'\n error?: string\n /** True if Claude is actively processing (spinner visible), false if idle/waiting for input */\n isActive?: boolean\n}\n\nexport interface MonitorOptions {\n headless?: boolean\n timeout?: number\n autoPr?: boolean // Automatically click \"Create PR\" if found\n}\n\nconst USER_DATA_DIR = path.join(os.homedir(), '.flightdesk', 'chromium-profile')\nconst STORAGE_STATE_FILE = path.join(os.homedir(), '.flightdesk', 'auth-state.json')\n\n/**\n * Persistent browser session manager.\n * Keeps the browser context alive for multiple operations.\n * Uses explicit storageState for auth persistence (more reliable than persistent context).\n */\nexport class PersistentBrowser {\n private browser: Browser | null = null\n private context: BrowserContext | null = null\n private page: Page | null = null\n private readonly headless: boolean\n\n constructor(headless = true) {\n this.headless = headless\n }\n\n /**\n * Initialize the browser context (if not already initialized)\n */\n async init(): Promise<void> {\n if (this.context) return\n\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not available')\n }\n\n ensureUserDataDir()\n\n // Launch a regular browser (not persistent context)\n this.browser = await playwright!.chromium.launch({\n headless: this.headless,\n })\n\n // Check if we have saved auth state\n const hasAuthState = fs.existsSync(STORAGE_STATE_FILE)\n\n // Create context with storage state if available\n const contextOptions: Parameters<Browser['newContext']>[0] = {\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n }\n\n if (hasAuthState) {\n contextOptions.storageState = STORAGE_STATE_FILE\n }\n\n this.context = await this.browser.newContext(contextOptions)\n this.page = await this.context.newPage()\n this.page.setDefaultTimeout(30000)\n }\n\n /**\n * Check if user is logged into Claude\n */\n async checkAuth(): Promise<boolean> {\n await this.init()\n\n try {\n await this.page!.goto('https://claude.ai/', { waitUntil: 'networkidle', timeout: 30000 })\n await this.page!.waitForTimeout(2000)\n\n const url = this.page!.url()\n console.log(' Final URL:', url)\n\n return !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n url.includes('claude.ai')\n } catch (error) {\n console.error('Auth check failed:', (error as Error).message)\n return false\n }\n }\n\n /**\n * Monitor a Claude Code session URL\n * Uses shared scrapeSession helper for consistent behavior with one-shot mode.\n */\n async monitorSession(\n sessionUrl: string,\n options: { timeout?: number; autoPr?: boolean } = {}\n ): Promise<SessionInfo> {\n await this.init()\n\n if (!this.page) {\n return { status: 'error', error: 'Browser page not initialized' }\n }\n\n return scrapeSession(this.page, sessionUrl, options)\n }\n\n /**\n * Close the browser context and browser\n */\n async close(): Promise<void> {\n if (this.context) {\n try {\n await this.context.close()\n } catch {\n // Already closed\n }\n this.context = null\n this.page = null\n }\n if (this.browser) {\n try {\n await this.browser.close()\n } catch {\n // Already closed\n }\n this.browser = null\n }\n }\n}\n\n/**\n * Check if Playwright is available\n */\nexport async function isPlaywrightAvailable(): Promise<boolean> {\n try {\n playwright = await import('playwright')\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Ensure the user data directory exists with restrictive permissions\n */\nfunction ensureUserDataDir(): void {\n if (!fs.existsSync(USER_DATA_DIR)) {\n fs.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 0o700 })\n }\n}\n\n/**\n * Ensure the storage directory exists with restrictive permissions\n */\nasync function ensureStorageDir(): Promise<void> {\n const storageDir = path.dirname(STORAGE_STATE_FILE)\n try {\n await fs.promises.mkdir(storageDir, { recursive: true, mode: 0o700 })\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') {\n throw err\n }\n }\n}\n\n/**\n * Set restrictive permissions on the storage state file (owner read/write only)\n */\nasync function setStorageFilePermissions(): Promise<void> {\n try {\n await fs.promises.chmod(STORAGE_STATE_FILE, 0o600)\n } catch {\n // If chmod fails, continue - the file may have broader permissions on some systems\n }\n}\n\n/**\n * Launch browser with storage state (uses saved auth cookies if available)\n * This is more reliable than persistent context for auth persistence.\n */\nasync function launchBrowser(headless: boolean): Promise<{ browser: Browser; context: BrowserContext }> {\n if (!playwright) {\n throw new Error('Playwright not available')\n }\n\n ensureUserDataDir()\n\n // Launch a regular browser (not persistent context)\n const browser = await playwright.chromium.launch({ headless })\n\n // Check if we have saved auth state\n const hasAuthState = fs.existsSync(STORAGE_STATE_FILE)\n\n // Create context with storage state if available\n const contextOptions: Parameters<Browser['newContext']>[0] = {\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n }\n\n if (hasAuthState) {\n contextOptions.storageState = STORAGE_STATE_FILE\n }\n\n const context = await browser.newContext(contextOptions)\n\n return { browser, context }\n}\n\n/**\n * Check if user is logged into Claude\n * Uses storageState for auth persistence (matching the new persistence strategy)\n */\nexport async function checkAuth(): Promise<boolean> {\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not installed')\n }\n\n const { browser, context } = await launchBrowser(true)\n\n try {\n const page = await context.newPage()\n page.setDefaultTimeout(30000)\n\n // Navigate and wait for network to settle (catches redirects better)\n await page.goto('https://claude.ai/', { waitUntil: 'networkidle', timeout: 30000 })\n\n // Extra wait for any JS redirects\n await page.waitForTimeout(2000)\n\n // Check final URL\n const url = page.url()\n console.log(' Final URL:', url)\n\n // Check for login/oauth redirects\n const isLoggedIn = !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n (url.includes('claude.ai'))\n\n return isLoggedIn\n } catch (error) {\n // Timeout or other error - assume not logged in\n console.error('Auth check failed:', (error as Error).message)\n return false\n } finally {\n await context.close()\n await browser.close()\n }\n}\n\n/**\n * Open browser for manual login (not headless)\n * Returns true if login was successful\n */\nexport async function openForLogin(): Promise<boolean> {\n if (!await isPlaywrightAvailable()) {\n throw new Error('Playwright not installed')\n }\n\n console.log('Opening browser for Claude login...')\n\n const { context } = await launchBrowser(false)\n\n try {\n const page = await context.newPage()\n await page.goto('https://claude.ai/', { waitUntil: 'domcontentloaded', timeout: 60000 })\n\n // Wait for user to press Enter instead of detecting browser close\n // (browser close event is unreliable with persistent contexts)\n console.log('\\n\uD83D\uDC49 Press ENTER here when you have logged in...\\n')\n await waitForEnter()\n\n // Check auth status NOW, before closing, using the same browser session\n console.log('Verifying login in current session...')\n await page.goto('https://claude.ai/', { waitUntil: 'domcontentloaded', timeout: 30000 })\n await page.waitForTimeout(2000)\n\n const url = page.url()\n console.log(' Final URL:', url)\n\n const isLoggedIn = !url.includes('/login') &&\n !url.includes('/oauth') &&\n !url.includes('accounts.google') &&\n url.includes('claude.ai')\n\n if (isLoggedIn) {\n // Ensure storage directory exists with restrictive permissions\n await ensureStorageDir()\n\n // Save storage state (cookies, localStorage) to file for later use\n console.log('Saving session state...')\n await context.storageState({ path: STORAGE_STATE_FILE })\n\n // Restrict permissions on the storage state file (owner read/write only)\n await setStorageFilePermissions()\n console.log(` Saved to: ${STORAGE_STATE_FILE}`)\n }\n\n console.log('Closing browser...')\n return isLoggedIn\n } finally {\n try {\n await context.close()\n } catch {\n // Already closed\n }\n }\n}\n\n/**\n * Wait for user to press Enter\n */\nfunction waitForEnter(): Promise<void> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n rl.question('', () => {\n rl.close()\n resolve()\n })\n })\n}\n\n/**\n * Monitor a Claude Code session URL (one-shot mode)\n * Uses storageState for auth persistence (matching the new persistence strategy)\n */\nexport async function monitorSession(\n sessionUrl: string,\n options: MonitorOptions = {}\n): Promise<SessionInfo> {\n if (!await isPlaywrightAvailable()) {\n return { status: 'error', error: 'Playwright not installed' }\n }\n\n const { headless = true, timeout = 30000, autoPr = false } = options\n const { browser, context } = await launchBrowser(headless)\n\n try {\n const page = await context.newPage()\n return await scrapeSession(page, sessionUrl, { timeout, autoPr })\n } finally {\n await context.close()\n await browser.close()\n }\n}\n\n/**\n * Shared session-scraping logic used by both persistent and one-shot monitors.\n * Extracts branch name, PR button status, and optionally clicks \"Create PR\".\n */\nasync function scrapeSession(\n page: Page,\n sessionUrl: string,\n options: { timeout?: number; autoPr?: boolean } = {}\n): Promise<SessionInfo> {\n const { timeout = 30000, autoPr = false } = options\n\n try {\n page.setDefaultTimeout(timeout)\n\n // Navigate to session and wait for network to settle\n await page.goto(sessionUrl, { waitUntil: 'networkidle' })\n\n // Wait for the main content area to be visible before scraping\n // This is more reliable than a fixed timeout for varying network conditions\n await page.waitForSelector('[data-testid=\"conversation-turn\"], .code-spinner-animate, button:has-text(\"Create PR\")', {\n timeout: 10000,\n }).catch(() => {\n // If no expected elements found, continue anyway - page may be in unexpected state\n })\n\n const result: SessionInfo = { status: 'active' }\n\n // Check if session is archived\n const archiveIndicator = await page.$('text=This session has been archived')\n if (archiveIndicator) {\n return { status: 'archived' }\n }\n\n // Check if we're on a login page\n const url = page.url()\n if (url.includes('/login') || url.includes('/oauth')) {\n return {\n status: 'error',\n error: 'Not logged in to Claude. Run: flightdesk auth'\n }\n }\n\n // Detect if Claude is actively processing (spinner animation visible)\n // The spinner has class .code-spinner-animate and contains the spinning star characters\n const isActive = await detectActiveSpinner(page)\n result.isActive = isActive\n\n // Try to find branch name\n const branchName = await extractBranchName(page)\n if (branchName) {\n result.branchName = branchName\n }\n\n // Check for \"Create PR\" button (indicates work is ready but PR not yet created)\n // Note: PR detection is handled by GitHub webhooks, not CLI scraping\n const createPrButton = await page.$('button:has-text(\"Create PR\"):not([aria-haspopup])')\n const viewPrButton = await page.$('button:has-text(\"View PR\")')\n\n // Only report hasPrButton if there's a Create PR button (not View PR)\n result.hasPrButton = !!createPrButton && !viewPrButton\n\n // If auto-PR is enabled and Create PR button exists, click it\n if (autoPr && createPrButton && !viewPrButton) {\n console.log(' Clicking \"Create PR\" button...')\n await createPrButton.click()\n await page.waitForTimeout(5000)\n\n // Try to extract the PR URL from the page\n const prUrl = await extractPrUrl(page)\n if (prUrl) {\n result.prUrl = prUrl\n }\n }\n\n return result\n } catch (error) {\n return {\n status: 'error',\n error: error instanceof Error ? error.message : String(error)\n }\n }\n}\n\n/**\n * Check if a string looks like a valid branch name\n */\nfunction isValidBranchName(text: string | null): text is string {\n if (!text) return false\n const cleaned = text.trim()\n return cleaned.length > 2 && !cleaned.includes(' ')\n}\n\n/**\n * Check if a string matches a branch pattern (e.g., \"claude/feature-name\")\n */\nfunction matchesBranchPattern(text: string): boolean {\n return /^[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+/.test(text) && !text.includes(' ')\n}\n\n/**\n * Try to extract branch name from an element\n */\nasync function tryExtractFromElement(page: Page, selector: string): Promise<string | null> {\n try {\n const element = await page.$(selector)\n if (!element) return null\n const text = await element.textContent()\n const cleaned = text?.trim() ?? null\n return isValidBranchName(cleaned) ? cleaned : null\n } catch {\n return null\n }\n}\n\n/**\n * Extract branch name from a Claude Code session page\n * Uses verified selector from SELECTOR_SPEC.ts\n */\nasync function extractBranchName(page: Page | null): Promise<string | null> {\n if (!page) return null\n\n // Primary selector: branch name in the branch bar (button.group/copy span.truncate)\n // This is the new branch created by Claude, shown in the branch bar\n const primarySelectors = [\n String.raw`button.group\\/copy span.truncate`, // New branch name (verified)\n 'button[class*=\"group/copy\"] span.truncate', // Alternative escaping\n String.raw`button[class*=\"group\\/copy\"] span.truncate`, // CSS escape\n ]\n\n for (const selector of primarySelectors) {\n const result = await tryExtractFromElement(page, selector)\n if (result) return result\n }\n\n // Fallback: look for any element containing a branch-like pattern\n return await tryExtractBranchFromSpans(page)\n}\n\n/**\n * Fallback extraction: search all truncate spans for branch patterns\n */\nasync function tryExtractBranchFromSpans(page: Page): Promise<string | null> {\n try {\n const allSpans = await page.$$('span.truncate')\n for (const span of allSpans) {\n const text = await span.textContent()\n const cleaned = text?.trim()\n if (cleaned && matchesBranchPattern(cleaned)) {\n return cleaned\n }\n }\n } catch {\n // Ignore fallback errors\n }\n return null\n}\n\n/**\n * Extract PR URL from page after PR creation\n */\nasync function extractPrUrl(page: Page): Promise<string | null> {\n // Look for GitHub PR URL patterns\n const selectors = [\n 'a[href*=\"github.com\"][href*=\"/pull/\"]',\n 'a[href*=\"gitlab.com\"][href*=\"/merge_requests/\"]',\n 'a[href*=\"bitbucket.org\"][href*=\"/pull-requests/\"]',\n ]\n\n for (const selector of selectors) {\n try {\n const element = await page.$(selector)\n if (element) {\n const href = await element.getAttribute('href')\n if (href) {\n return href\n }\n }\n } catch {\n // Continue\n }\n }\n\n // Try to find PR URL in page content\n try {\n const pageContent = await page.content()\n const prPatterns = [\n /(https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/pull\\/\\d+)/,\n /(https:\\/\\/gitlab\\.com\\/[^/]+\\/[^/]+\\/-\\/merge_requests\\/\\d+)/,\n ]\n\n for (const pattern of prPatterns) {\n const match = pageContent.match(pattern)\n if (match && match[1]) {\n return match[1]\n }\n }\n } catch {\n // Ignore\n }\n\n return null\n}\n\n/**\n * Detect if Claude is actively processing (spinner animation is visible).\n * The Claude UI shows an animated spinner with class .code-spinner-animate\n * when Claude is actively working on a response.\n *\n * SELECTOR VERIFICATION: These selectors were verified against Claude Code UI on 2026-02-26.\n * If detection stops working, Claude may have updated their UI. Check:\n * - The spinner class name (.code-spinner-animate)\n * - The spinner characters (\u273D\u2736\u273B\u2722\u00B7)\n * - The animation keyframe name (codeSpinnerSpin)\n */\nasync function detectActiveSpinner(page: Page): Promise<boolean> {\n try {\n // Primary selector: the animated spinner element (verified 2026-02-26)\n const spinner = await page.$('.code-spinner-animate')\n if (spinner) {\n return true\n }\n\n // Fallback: look for the spinning star characters in a visible state\n // These are the characters used in the animation: \u273D\u2736\u273B\u2722\u00B7\n const spinnerByContent = await page.$('span:has-text(\"\u273D\")')\n if (spinnerByContent) {\n // Check if it's part of an animation (has the animation class on a parent or itself)\n const hasAnimation = await spinnerByContent.evaluate((el) => {\n let current: Element | null = el\n while (current) {\n const classList = current.classList\n if (classList?.contains('code-spinner-animate')) {\n return true\n }\n // Also check for any animation-related CSS\n const style = globalThis.getComputedStyle(current)\n if (style.animationName && style.animationName !== 'none') {\n return true\n }\n current = current.parentElement\n }\n return false\n })\n return hasAnimation\n }\n\n return false\n } catch {\n // If detection fails, default to false (idle)\n return false\n }\n}\n\nexport { USER_DATA_DIR }\n", "import {\n isPlaywrightAvailable,\n checkAuth,\n openForLogin,\n USER_DATA_DIR,\n} from '../lib/session-monitor'\n\nexport async function authCommand(): Promise<void> {\n console.log('\uD83D\uDD10 FlightDesk Authentication\\n')\n\n // Check if Playwright is available\n const playwrightAvailable = await isPlaywrightAvailable()\n if (!playwrightAvailable) {\n console.error('Playwright is not installed.')\n console.error('Install with: pnpm add playwright && npx playwright install chromium')\n process.exit(1)\n }\n\n console.log(`Profile directory: ${USER_DATA_DIR}\\n`)\n\n // Check current auth status\n console.log('Checking current authentication status...')\n const isAuthenticated = await checkAuth()\n\n if (isAuthenticated) {\n console.log('\u2705 Already logged in to Claude!')\n console.log('\\nThe watch daemon will be able to monitor your sessions.')\n return\n }\n\n console.log('\u274C Not logged in to Claude.\\n')\n console.log('Opening browser for login...')\n console.log('Please log in to your Claude account.\\n')\n\n // Open browser for login (verifies auth before closing)\n const loginSuccessful = await openForLogin()\n\n if (loginSuccessful) {\n console.log('\\n\u2705 Successfully logged in!')\n console.log('The watch daemon can now monitor your Claude Code sessions.')\n } else {\n console.log('\\n\u274C Login was not detected.')\n console.log('Please try again with: flightdesk auth')\n }\n}\n", "import { execSync } from 'node:child_process'\n\nexport interface GitRepoInfo {\n remote: string // owner/repo format\n branch: string\n remoteUrl: string\n}\n\n/**\n * Detect the current git repository information.\n * Returns null if not in a git repo or if detection fails.\n */\nexport function detectGitRepo(): GitRepoInfo | null {\n try {\n // Get git remote URL\n const remoteUrl = execSync('git remote get-url origin', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n // Parse remote URL to get owner/repo\n const repoFullName = parseGitRemoteUrl(remoteUrl)\n if (!repoFullName) {\n return null\n }\n\n // Get current branch\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n return {\n remote: repoFullName,\n branch,\n remoteUrl,\n }\n } catch {\n // Not in a git repo or git not available\n return null\n }\n}\n\n/**\n * Parse a git remote URL to extract the owner/repo format.\n * Handles both SSH and HTTPS URLs.\n */\nexport function parseGitRemoteUrl(remoteUrl: string): string | null {\n // Handle SSH URLs: git@github.com:owner/repo.git\n const sshPattern = /git@github\\.com:([^/]+\\/[^/]+?)(?:\\.git)?$/\n const sshMatch = sshPattern.exec(remoteUrl)\n if (sshMatch) {\n return sshMatch[1]\n }\n\n // Handle HTTPS URLs: https://github.com/owner/repo.git\n const httpsPattern = /https:\\/\\/github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?$/\n const httpsMatch = httpsPattern.exec(remoteUrl)\n if (httpsMatch) {\n return httpsMatch[1]\n }\n\n return null\n}\n", "import { requireActiveOrg, getOrganizationByRepo, OrganizationInfo } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport { detectGitRepo } from '../lib/git'\n\ninterface RegisterOptions {\n project?: string\n viewUrl?: string\n teleportId?: string\n title?: string\n description?: string\n}\n\nexport async function registerCommand(\n taskId: string | undefined,\n options: RegisterOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n // Auto-detect project if not provided via --project option\n let projectId = options.project\n if (!projectId) {\n projectId = await autoDetectProject(api, org)\n }\n\n // If piped input, try to parse Claude Code output\n let viewUrl = options.viewUrl\n let teleportId = options.teleportId\n\n if (!process.stdin.isTTY) {\n console.log('\u23F3 Waiting for Claude session output...')\n const input = await readStdin()\n const parsed = parseClaudeOutput(input)\n viewUrl = viewUrl || parsed.viewUrl\n teleportId = teleportId || parsed.teleportId\n }\n\n // Create task if no task ID provided\n let actualTaskId = taskId\n if (!actualTaskId) {\n if (!options.title) {\n console.error('Task title required when creating a new task. Use --title \"...\"')\n process.exit(1)\n }\n\n console.log(`Creating task: ${options.title}`)\n const task = await api.createTask({\n projectId,\n title: options.title,\n description: options.description,\n })\n actualTaskId = task.id\n console.log(`\u2705 Created task: ${task.id}`)\n }\n\n // Update task with session info\n if (viewUrl || teleportId) {\n console.log('Registering session with task...')\n await api.updateTask(actualTaskId, {\n sessionViewUrl: viewUrl,\n sessionTeleportId: teleportId,\n status: 'DISPATCHED',\n })\n console.log('\u2705 Session registered')\n }\n\n // Output task ID for scripting\n console.log(`\\nTask ID: ${actualTaskId}`)\n\n if (viewUrl) {\n console.log(`Session: ${viewUrl}`)\n }\n\n if (teleportId) {\n console.log(`Resume: claude --teleport ${teleportId}`)\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve) => {\n let data = ''\n let resolved = false\n\n process.stdin.setEncoding('utf8')\n process.stdin.on('data', (chunk) => {\n data += chunk\n })\n process.stdin.on('end', () => {\n if (!resolved) {\n resolved = true\n resolve(data)\n }\n })\n process.stdin.on('close', () => {\n if (!resolved) {\n resolved = true\n resolve(data)\n }\n })\n\n // Wait up to 30 seconds for claude --remote to create a session\n // Most remote sessions are created within 5-10 seconds\n setTimeout(() => {\n if (!resolved) {\n resolved = true\n resolve(data)\n }\n }, 30000)\n })\n}\n\nfunction parseClaudeOutput(output: string): { viewUrl?: string; teleportId?: string } {\n const result: { viewUrl?: string; teleportId?: string } = {}\n\n // Parse view URL: \"View: https://claude.ai/code/session_...\"\n const viewMatch = output.match(/View:\\s+(https:\\/\\/claude\\.ai\\/code\\/session_[^\\s]+)/)\n if (viewMatch) {\n result.viewUrl = viewMatch[1]\n }\n\n // Parse teleport ID: \"Resume with: claude --teleport session_...\"\n const teleportMatch = output.match(/--teleport\\s+(session_[^\\s]+)/)\n if (teleportMatch) {\n result.teleportId = teleportMatch[1]\n }\n\n return result\n}\n\n/**\n * Auto-detect project from current git repository.\n * Looks up the project by matching the repo's githubRepo field.\n */\nasync function autoDetectProject(api: FlightDeskAPI, activeOrg: OrganizationInfo): Promise<string> {\n const repoInfo = detectGitRepo()\n\n if (!repoInfo) {\n console.error('\u274C Not in a git repository. Please provide a project ID.')\n console.error(' Usage: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n console.log(`\uD83D\uDD0D Detecting project from repository: ${repoInfo.remote}`)\n\n // Check if this repo is mapped to an organization\n const mappedOrg = getOrganizationByRepo(repoInfo.remote)\n if (!mappedOrg) {\n console.error(`\u274C Repository \"${repoInfo.remote}\" is not mapped to any organization.`)\n console.error(' Run: flightdesk sync')\n console.error(' Or provide a project ID: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n // Warn if mapped org differs from active org\n if (mappedOrg.id !== activeOrg.id) {\n console.error(`\u274C Repository \"${repoInfo.remote}\" is mapped to organization \"${mappedOrg.name}\",`)\n console.error(` but your active organization is \"${activeOrg.name}\".`)\n console.error(' Switch with: flightdesk org switch ' + mappedOrg.name)\n console.error(' Or provide a project ID: flightdesk register --project <project-id> [task-id]')\n process.exit(1)\n }\n\n // List projects and find matching one\n const projects = await api.listProjects()\n const matchingProjects = projects.filter(\n (p) => p.githubRepo?.toLowerCase() === repoInfo.remote.toLowerCase()\n )\n\n if (matchingProjects.length === 0) {\n console.error(`\u274C No FlightDesk project found for repository \"${repoInfo.remote}\".`)\n console.error(' Available projects in this organization:')\n for (const p of projects) {\n console.error(` - ${p.name} (${p.githubRepo || 'no repo'}) [${p.id}]`)\n }\n console.error('\\n Create a project or provide a project ID explicitly.')\n process.exit(1)\n }\n\n if (matchingProjects.length > 1) {\n console.error(`\u274C Multiple projects found for repository \"${repoInfo.remote}\":`)\n for (const p of matchingProjects) {\n console.error(` - ${p.name} [${p.id}]`)\n }\n console.error('\\n Please specify the project ID explicitly.')\n process.exit(1)\n }\n\n const project = matchingProjects[0]\n console.log(`\u2705 Found project: ${project.name} (${project.id})`)\n\n return project.id\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface StatusOptions {\n project?: string\n}\n\nexport async function statusCommand(options: StatusOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n const tasks = await api.listTasks({ projectId: options.project })\n\n if (tasks.length === 0) {\n console.log('No tasks found.')\n return\n }\n\n // Group tasks by status\n const byStatus: Record<string, typeof tasks> = {}\n for (const task of tasks) {\n if (!byStatus[task.status]) {\n byStatus[task.status] = []\n }\n byStatus[task.status].push(task)\n }\n\n // Status order for display\n const statusOrder = [\n 'PENDING',\n 'DISPATCHED',\n 'IN_PROGRESS',\n 'BRANCH_CREATED',\n 'PR_OPEN',\n 'PREVIEW_STARTING',\n 'PREVIEW_READY',\n 'REVIEW_RUNNING',\n 'REVIEW_DONE',\n 'QA_READY',\n 'QA_APPROVED',\n 'MERGED',\n 'ARCHIVED',\n ]\n\n console.log('\\n\uD83D\uDCCB FlightDesk Tasks\\n')\n\n for (const status of statusOrder) {\n const statusTasks = byStatus[status]\n if (!statusTasks || statusTasks.length === 0) continue\n\n console.log(`${getStatusEmoji(status)} ${status} (${statusTasks.length})`)\n for (const task of statusTasks) {\n console.log(` ${task.id.slice(0, 8)} - ${task.title}`)\n if (task.branchName) {\n console.log(` Branch: ${task.branchName}`)\n }\n if (task.prUrl) {\n console.log(` PR: ${task.prUrl}`)\n }\n }\n console.log('')\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction getStatusEmoji(status: string): string {\n switch (status) {\n case 'PENDING':\n return '\u2B1C'\n case 'DISPATCHED':\n return '\uD83D\uDE80'\n case 'IN_PROGRESS':\n return '\uD83D\uDD04'\n case 'BRANCH_CREATED':\n return '\uD83C\uDF3F'\n case 'PR_OPEN':\n return '\uD83D\uDCDD'\n case 'PREVIEW_STARTING':\n return '\u23F3'\n case 'PREVIEW_READY':\n return '\uD83C\uDF10'\n case 'REVIEW_RUNNING':\n return '\uD83D\uDD0D'\n case 'REVIEW_DONE':\n return '\u2705'\n case 'QA_READY':\n return '\uD83E\uDDEA'\n case 'QA_APPROVED':\n return '\uD83D\uDC4D'\n case 'MERGED':\n return '\uD83C\uDF89'\n case 'ARCHIVED':\n return '\uD83D\uDCE6'\n default:\n return '\u2753'\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport {\n isPlaywrightAvailable,\n PersistentBrowser,\n type SessionInfo,\n} from '../lib/session-monitor'\n\ninterface WatchOptions {\n interval: string\n once?: boolean\n autoPr?: boolean\n headless?: boolean\n}\n\ninterface ActiveTask {\n id: string\n title: string\n status: string\n sessionViewUrl?: string\n branchName?: string\n prUrl?: string\n sessionActive?: boolean\n}\n\nexport async function watchCommand(options: WatchOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n\n const intervalMinutes = parseInt(options.interval, 10)\n if (isNaN(intervalMinutes) || intervalMinutes < 1) {\n console.error('Invalid interval. Must be a positive number of minutes.')\n process.exit(1)\n }\n\n console.log('\uD83D\uDEEB FlightDesk Watch Daemon')\n console.log(` Organization: ${org.name}`)\n console.log(` Interval: ${intervalMinutes} minutes`)\n console.log(` Auto-PR: ${options.autoPr ? 'enabled' : 'disabled'}`)\n console.log('')\n\n // Check if Playwright is available\n const playwrightAvailable = await isPlaywrightAvailable()\n let browser: PersistentBrowser | null = null\n\n if (!playwrightAvailable) {\n console.log('\u26A0\uFE0F Playwright not installed. Session monitoring disabled.')\n console.log(' Install with: pnpm add playwright && npx playwright install chromium')\n console.log('')\n } else {\n // Create persistent browser instance - keeps auth alive for entire watch session\n browser = new PersistentBrowser(options.headless !== false)\n\n // Check if authenticated using the persistent browser\n console.log('Checking Claude authentication...')\n const isAuthenticated = await browser.checkAuth()\n if (!isAuthenticated) {\n console.log('\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth')\n console.log('')\n // Close browser since we can't proceed without auth\n await browser.close()\n browser = null\n } else {\n console.log('\u2705 Playwright ready, Claude authenticated')\n console.log(' (Browser session kept alive for monitoring)')\n console.log('')\n }\n }\n\n const api = FlightDeskAPI.fromConfig(config, org)\n\n async function runCheck(): Promise<void> {\n const timestamp = new Date().toLocaleTimeString()\n console.log(`[${timestamp}] Checking tasks...`)\n\n try {\n // Get all tasks that need monitoring:\n // - Active tasks (DISPATCHED, IN_PROGRESS, BRANCH_CREATED)\n // - PENDING tasks with sessionViewUrl (may need status reconciliation)\n const tasks = await api.listTasks() as ActiveTask[]\n const activeTasks = tasks.filter(t =>\n ['DISPATCHED', 'IN_PROGRESS', 'BRANCH_CREATED'].includes(t.status) ||\n (t.status === 'PENDING' && t.sessionViewUrl)\n )\n\n if (activeTasks.length === 0) {\n console.log(' No active tasks to monitor')\n return\n }\n\n // Check for tasks that need status reconciliation (have data but wrong status)\n const needsReconciliation = activeTasks.filter(t => {\n if (t.prUrl && !['PR_OPEN', 'MERGED', 'ARCHIVED'].includes(t.status)) return true\n if (t.branchName && t.status === 'PENDING') return true\n if (t.sessionViewUrl && t.status === 'PENDING') return true\n return false\n })\n\n if (needsReconciliation.length > 0) {\n console.log(` \u26A0\uFE0F ${needsReconciliation.length} task(s) need status reconciliation`)\n }\n\n console.log(` Found ${activeTasks.length} active task(s)`)\n\n for (const task of activeTasks) {\n console.log(`\\n \uD83D\uDCCB ${task.title}`)\n console.log(` Status: ${task.status}`)\n\n // First, reconcile status based on existing data\n const reconciled = await reconcileTaskStatus(api, task)\n if (reconciled) {\n continue // Task was updated, skip session monitoring this cycle\n }\n\n // If task has a session URL and browser is available, monitor it\n if (task.sessionViewUrl && browser) {\n console.log(` Checking session...`)\n\n const sessionInfo = await browser.monitorSession(task.sessionViewUrl, {\n autoPr: options.autoPr && !task.prUrl, // Only auto-PR if no PR exists\n })\n\n await processSessionInfo(api, task, sessionInfo)\n } else if (!task.sessionViewUrl) {\n console.log(' No session URL registered')\n } else if (!browser) {\n console.log(' Browser not available - cannot monitor session')\n }\n }\n } catch (error) {\n console.error(` Error: ${error}`)\n }\n }\n\n // Use try/finally to ensure browser is always closed on all exit paths\n try {\n // Run immediately\n await runCheck()\n\n if (options.once) {\n console.log('\\nDone (--once flag specified)')\n return\n }\n\n // Then run on interval\n console.log(`\\nWatching... (Ctrl+C to stop)\\n`)\n\n const intervalId = setInterval(runCheck, intervalMinutes * 60 * 1000)\n\n // Handle graceful shutdown\n process.on('SIGINT', async () => {\n console.log('\\nShutting down...')\n clearInterval(intervalId)\n if (browser) {\n console.log('Closing browser...')\n await browser.close()\n }\n process.exit(0)\n })\n\n // Keep the process running indefinitely (until SIGINT)\n await new Promise((_resolve) => {\n // Intentionally never resolves - process runs until interrupted\n })\n } finally {\n // Ensure browser is closed on all exit paths (including --once and errors)\n if (browser) {\n await browser.close()\n }\n }\n}\n\n/**\n * Reconciles task status based on existing data.\n * This catches tasks that have data (prUrl, branchName, sessionViewUrl) but wrong status.\n * Returns true if status was updated.\n */\nasync function reconcileTaskStatus(\n api: FlightDeskAPI,\n task: ActiveTask\n): Promise<boolean> {\n let expectedStatus: string | null = null\n let reason = ''\n\n // Determine expected status based on available data\n // Priority: PR > Branch > Session\n if (task.prUrl) {\n if (!['PR_OPEN', 'PREVIEW_STARTING', 'PREVIEW_READY', 'MERGED', 'ARCHIVED', 'REVIEW_RUNNING', 'REVIEW_DONE', 'QA_READY', 'QA_APPROVED'].includes(task.status)) {\n expectedStatus = 'PR_OPEN'\n reason = `has PR URL but status is ${task.status}`\n }\n } else if (task.branchName) {\n if (['PENDING', 'DISPATCHED'].includes(task.status)) {\n expectedStatus = 'IN_PROGRESS'\n reason = `has branch but status is ${task.status}`\n }\n } else if (task.sessionViewUrl) {\n if (task.status === 'PENDING') {\n expectedStatus = 'DISPATCHED'\n reason = `has session URL but status is PENDING`\n }\n }\n\n if (expectedStatus) {\n console.log(` \uD83D\uDD27 Status reconciliation: ${reason}`)\n console.log(` Updating: ${task.status} \u2192 ${expectedStatus}`)\n try {\n await api.updateTask(task.id, { status: expectedStatus })\n console.log(' \u2705 Status reconciled')\n return true\n } catch (error) {\n console.log(` \u274C Failed to reconcile: ${error}`)\n return false\n }\n }\n\n return false\n}\n\nasync function processSessionInfo(\n api: FlightDeskAPI,\n task: ActiveTask,\n info: SessionInfo\n): Promise<void> {\n if (info.status === 'error') {\n console.log(` \u274C Error: ${info.error}`)\n return\n }\n\n if (info.status === 'archived') {\n console.log(' \uD83D\uDCE6 Session archived')\n return\n }\n\n // Display and track session activity state\n // Distinguish between: true (active), false (idle), undefined (detection failed)\n let activityIcon: string\n let activityLabel: string\n if (info.isActive === true) {\n activityIcon = '\u26A1'\n activityLabel = 'Claude is working'\n } else if (info.isActive === false) {\n activityIcon = '\uD83D\uDCA4'\n activityLabel = 'Waiting for input'\n } else {\n activityIcon = '\u2754'\n activityLabel = 'Activity unknown'\n }\n console.log(` ${activityIcon} ${activityLabel}`)\n\n const updates: Record<string, unknown> = {\n // Update session activity state and timestamp\n // Preserve null when activity detection fails (info.isActive is undefined)\n sessionActive: info.isActive ?? null,\n sessionCheckedAt: new Date().toISOString(),\n }\n\n // Update branch name if detected and not already set\n if (info.branchName && info.branchName !== task.branchName) {\n console.log(` \uD83C\uDF3F Branch detected: ${info.branchName}`)\n updates.branchName = info.branchName\n\n // Update status to IN_PROGRESS if still DISPATCHED\n if (task.status === 'DISPATCHED') {\n updates.status = 'IN_PROGRESS'\n }\n }\n\n // Update PR URL if detected\n if (info.prUrl && info.prUrl !== task.prUrl) {\n console.log(` \uD83D\uDD17 PR detected: ${info.prUrl}`)\n updates.prUrl = info.prUrl\n\n // Extract PR number from URL\n const prMatch = info.prUrl.match(/\\/pull\\/(\\d+)/)\n if (prMatch) {\n updates.prNumber = parseInt(prMatch[1], 10)\n }\n\n // Update status to PR_OPEN\n updates.status = 'PR_OPEN'\n }\n\n // Report if PR button available but no PR yet\n if (info.hasPrButton && !info.prUrl && !task.prUrl) {\n console.log(' \uD83D\uDCDD \"Create PR\" button available')\n }\n\n // Apply updates (always includes activity state)\n const hasNonActivityUpdates = Object.keys(updates).some(k => !['sessionActive', 'sessionCheckedAt'].includes(k))\n try {\n await api.updateTask(task.id, updates)\n if (hasNonActivityUpdates) {\n console.log(' \u2705 Task updated')\n }\n } catch (error) {\n console.log(` \u274C Failed to update task: ${error}`)\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface TaskCreateOptions {\n project: string\n title: string\n description?: string\n}\n\ninterface TaskListOptions {\n project?: string\n status?: string\n}\n\ninterface TaskStatusOptions {\n taskId: string\n}\n\ninterface TaskUpdateOptions {\n taskId: string\n status?: string\n branch?: string\n prUrl?: string\n}\n\ntype TaskOptions = TaskCreateOptions | TaskListOptions | TaskStatusOptions | TaskUpdateOptions\n\nexport async function taskCommand(\n action: 'create' | 'list' | 'status' | 'update',\n options: TaskOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n switch (action) {\n case 'create':\n await handleCreate(api, options as TaskCreateOptions)\n break\n case 'list':\n await handleList(api, options as TaskListOptions)\n break\n case 'status':\n await handleStatus(api, options as TaskStatusOptions)\n break\n case 'update':\n await handleUpdate(api, options as TaskUpdateOptions)\n break\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nasync function handleCreate(api: FlightDeskAPI, options: TaskCreateOptions): Promise<void> {\n console.log(`Creating task: ${options.title}`)\n\n const task = await api.createTask({\n projectId: options.project,\n title: options.title,\n description: options.description,\n })\n\n console.log(`\\n\u2705 Task created`)\n console.log(` ID: ${task.id}`)\n console.log(` Title: ${task.title}`)\n console.log(` Status: ${task.status}`)\n}\n\nasync function handleList(api: FlightDeskAPI, options: TaskListOptions): Promise<void> {\n const tasks = await api.listTasks({\n projectId: options.project,\n status: options.status,\n })\n\n if (tasks.length === 0) {\n console.log('No tasks found.')\n return\n }\n\n console.log('\\nTasks:\\n')\n for (const task of tasks) {\n const statusEmoji = getStatusEmoji(task.status)\n console.log(`${statusEmoji} ${task.id.slice(0, 8)} - ${task.title}`)\n if (task.project?.name) console.log(` Project: ${task.project.name}`)\n console.log(` Status: ${task.status}`)\n if (task.branchName) console.log(` Branch: ${task.branchName}`)\n if (task.prUrl) console.log(` PR: ${task.prUrl}`)\n console.log('')\n }\n}\n\nasync function handleStatus(api: FlightDeskAPI, options: TaskStatusOptions): Promise<void> {\n const task = await api.getTask(options.taskId) as {\n id: string\n title: string\n description?: string\n status: string\n branchName?: string\n prUrl?: string\n sessionViewUrl?: string\n sessionTeleportId?: string\n project: { name: string; githubRepo: string }\n createdAt: string\n updatedAt: string\n }\n\n if (!task) {\n console.error('Task not found')\n process.exit(1)\n }\n\n console.log(`\\n\uD83D\uDCCB Task: ${task.title}\\n`)\n console.log(`ID: ${task.id}`)\n console.log(`Status: ${getStatusEmoji(task.status)} ${task.status}`)\n if (task.project) {\n console.log(`Project: ${task.project.name}${task.project.githubRepo ? ` (${task.project.githubRepo})` : ''}`)\n }\n\n if (task.description) {\n console.log(`\\nDescription:\\n${task.description}`)\n }\n\n console.log('')\n if (task.branchName) console.log(`Branch: ${task.branchName}`)\n if (task.prUrl) console.log(`PR: ${task.prUrl}`)\n if (task.sessionViewUrl) console.log(`Session: ${task.sessionViewUrl}`)\n if (task.sessionTeleportId) {\n console.log(`Resume: claude --teleport ${task.sessionTeleportId}`)\n }\n\n console.log(`\\nCreated: ${new Date(task.createdAt).toLocaleString()}`)\n console.log(`Updated: ${new Date(task.updatedAt).toLocaleString()}`)\n}\n\nasync function handleUpdate(api: FlightDeskAPI, options: TaskUpdateOptions): Promise<void> {\n const input: Record<string, unknown> = {}\n\n if (options.status) input.status = options.status\n if (options.branch) input.branchName = options.branch\n if (options.prUrl) input.prUrl = options.prUrl\n\n if (Object.keys(input).length === 0) {\n console.error('No updates specified. Use --status, --branch, or --pr-url')\n process.exit(1)\n }\n\n console.log(`Updating task ${options.taskId}...`)\n\n const task = await api.updateTask(options.taskId, input)\n\n console.log(`\\n\u2705 Task updated`)\n console.log(` Status: ${task.status}`)\n if (task.branchName) console.log(` Branch: ${task.branchName}`)\n if (task.prUrl) console.log(` PR: ${task.prUrl}`)\n}\n\nfunction getStatusEmoji(status: string): string {\n switch (status) {\n case 'PENDING': return '\u2B1C'\n case 'DISPATCHED': return '\uD83D\uDE80'\n case 'IN_PROGRESS': return '\uD83D\uDD04'\n case 'BRANCH_CREATED': return '\uD83C\uDF3F'\n case 'PR_OPEN': return '\uD83D\uDCDD'\n case 'PREVIEW_STARTING': return '\u23F3'\n case 'PREVIEW_READY': return '\uD83C\uDF10'\n case 'REVIEW_RUNNING': return '\uD83D\uDD0D'\n case 'REVIEW_DONE': return '\u2705'\n case 'QA_READY': return '\uD83E\uDDEA'\n case 'QA_APPROVED': return '\uD83D\uDC4D'\n case 'MERGED': return '\uD83C\uDF89'\n case 'ARCHIVED': return '\uD83D\uDCE6'\n default: return '\u2753'\n }\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\ninterface PromptOptions {\n type: string\n}\n\nexport async function promptCommand(taskId: string, options: PromptOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n const validTypes = ['review', 'test_plan', 'summary', 'handoff']\n\n if (!validTypes.includes(options.type)) {\n console.error(`Invalid prompt type: ${options.type}`)\n console.error(`Valid types: ${validTypes.join(', ')}`)\n process.exit(1)\n }\n\n try {\n const prompts = await api.getTaskPrompts(taskId)\n const prompt = prompts.find(p => p.type === options.type)\n\n if (!prompt) {\n console.error(`Prompt type \"${options.type}\" not found for this task`)\n process.exit(1)\n }\n\n if (!prompt.available) {\n console.error(`Prompt not available: ${prompt.reason || 'Unknown reason'}`)\n process.exit(1)\n }\n\n // Output the prompt content (ready for copy-paste)\n console.log(prompt.content)\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n", "import {\n loadConfig,\n getActiveOrganization,\n setActiveOrganization,\n updateOrganizations,\n isConfigured,\n getApiUrl,\n} from '../lib/config'\nimport { fetchUserInfo } from '../lib/api'\n\nexport async function orgListCommand(): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n const activeOrg = getActiveOrganization()\n\n console.log('\\n\uD83D\uDCCB Organizations\\n')\n\n if (config.organizations.length === 0) {\n console.log('No organizations found.')\n console.log('Run: flightdesk org refresh')\n return\n }\n\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n const activeTag = isActive ? ' \u2190 active' : ''\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${activeTag}`)\n }\n\n console.log('')\n console.log('Commands:')\n console.log(' flightdesk org switch <name> Switch active organization')\n console.log(' flightdesk org refresh Refresh organizations from API')\n console.log('')\n}\n\nexport async function orgSwitchCommand(orgIdentifier: string): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n\n // Find org by name or ID (case-insensitive)\n const org = config.organizations.find(\n o => o.id === orgIdentifier || o.name.toLowerCase() === orgIdentifier.toLowerCase()\n )\n\n if (!org) {\n console.error(`Organization not found: ${orgIdentifier}`)\n console.log('\\nAvailable organizations:')\n for (const o of config.organizations) {\n console.log(` - ${o.name}`)\n }\n process.exit(1)\n }\n\n const currentOrg = getActiveOrganization()\n if (currentOrg?.id === org.id) {\n console.log(`Already using organization: ${org.name}`)\n return\n }\n\n setActiveOrganization(org.id)\n console.log(`\u2705 Switched to organization: ${org.name}`)\n}\n\nexport async function orgRefreshCommand(): Promise<void> {\n if (!isConfigured()) {\n console.log('FlightDesk is not configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n const config = loadConfig()\n\n if (!config.apiKey) {\n console.error('No API key configured.')\n console.log('Run: flightdesk init')\n return\n }\n\n console.log('Refreshing organizations...')\n\n try {\n const apiUrl = getApiUrl()\n const userInfo = await fetchUserInfo(config.apiKey, apiUrl)\n const orgs = userInfo.organizations || []\n\n if (orgs.length === 0) {\n console.log('No organizations found for this user.')\n return\n }\n\n // Map to our OrganizationInfo format\n const organizations = orgs.map(m => ({\n id: m.organization.id,\n name: m.organization.name,\n }))\n\n // Check for new orgs\n const currentIds = new Set(config.organizations.map(o => o.id))\n const newOrgs = organizations.filter(o => !currentIds.has(o.id))\n\n // Check for removed orgs\n const newIds = new Set(organizations.map(o => o.id))\n const removedOrgs = config.organizations.filter(o => !newIds.has(o.id))\n\n // Update organizations (this also handles active org validation)\n updateOrganizations(organizations)\n\n console.log(`\u2705 Found ${organizations.length} organization(s)`)\n\n if (newOrgs.length > 0) {\n console.log('\\n New organizations:')\n for (const org of newOrgs) {\n console.log(` + ${org.name}`)\n }\n }\n\n if (removedOrgs.length > 0) {\n console.log('\\n Removed organizations:')\n for (const org of removedOrgs) {\n console.log(` - ${org.name}`)\n }\n }\n\n // Show current active\n const activeOrg = getActiveOrganization()\n if (activeOrg) {\n console.log(`\\n Active: ${activeOrg.name}`)\n }\n } catch (error) {\n console.error(`\u274C Failed to refresh: ${error}`)\n }\n}\n", "import { execSync } from 'child_process'\nimport { loadConfig, getOrganizationByRepo, getActiveOrganization, getApiUrl } from '../lib/config'\n\nexport async function contextCommand(): Promise<void> {\n console.log('\\n\uD83D\uDD0D Current Context\\n')\n\n // Try to detect current git repository\n const repoInfo: { remote?: string; branch?: string } = {}\n\n try {\n // Get git remote URL\n const remoteUrl = execSync('git remote get-url origin', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n\n // Parse remote URL to get owner/repo\n let repoFullName: string | null = null\n\n // Handle SSH URLs: git@github.com:owner/repo.git\n const sshMatch = remoteUrl.match(/git@github\\.com:([^/]+\\/[^/]+?)(?:\\.git)?$/)\n if (sshMatch) {\n repoFullName = sshMatch[1]\n }\n\n // Handle HTTPS URLs: https://github.com/owner/repo.git\n const httpsMatch = remoteUrl.match(/https:\\/\\/github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?$/)\n if (httpsMatch) {\n repoFullName = httpsMatch[1]\n }\n\n if (repoFullName) {\n repoInfo.remote = repoFullName\n }\n\n // Get current branch\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim()\n repoInfo.branch = branch\n } catch {\n // Not in a git repo or git not available\n }\n\n if (!repoInfo.remote) {\n console.log('\uD83D\uDCC1 Not in a git repository (or no remote configured)')\n console.log('')\n\n const config = loadConfig()\n const activeOrg = getActiveOrganization()\n if (config.organizations.length > 0) {\n console.log('Organizations:')\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${isActive ? ' (active)' : ''}`)\n }\n } else {\n console.log('No organizations configured. Run: flightdesk init')\n }\n return\n }\n\n console.log(`\uD83D\uDCC1 Repository: ${repoInfo.remote}`)\n console.log(`\uD83C\uDF3F Branch: ${repoInfo.branch}`)\n console.log('')\n\n // Look up organization mapping\n const mappedOrg = getOrganizationByRepo(repoInfo.remote)\n const activeOrg = getActiveOrganization()\n\n if (mappedOrg) {\n console.log(`\uD83C\uDFE2 Organization: ${mappedOrg.name}`)\n console.log(` API: ${getApiUrl()}`)\n console.log('')\n console.log('This repository is mapped to the above organization.')\n console.log('Commands will use this organization automatically.')\n } else {\n console.log('\u26A0\uFE0F This repository is not mapped to any organization.')\n console.log('')\n\n const config = loadConfig()\n if (config.organizations.length > 0) {\n console.log('Organizations:')\n for (const org of config.organizations) {\n const isActive = org.id === activeOrg?.id\n console.log(` ${isActive ? '\u25CF' : '\u25CB'} ${org.name}${isActive ? ' (active)' : ''}`)\n }\n console.log('')\n console.log('Run: flightdesk sync to refresh repository mappings')\n } else {\n console.log('No organizations configured. Run: flightdesk init')\n }\n }\n}\n", "import { requireConfig, saveConfig } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\nexport async function syncCommand(): Promise<void> {\n const config = requireConfig()\n\n if (config.organizations.length === 0) {\n console.error('No organizations configured. Run: flightdesk init')\n process.exit(1)\n }\n\n console.log('\uD83D\uDD04 Syncing repository mappings...\\n')\n\n let totalProjects = 0\n const newMappings: Record<string, string> = {}\n\n for (const org of config.organizations) {\n console.log(` ${org.name}...`)\n\n try {\n const api = FlightDeskAPI.fromConfig(config, org)\n const projects = await api.listProjects()\n\n console.log(` Found ${projects.length} project(s)`)\n\n for (const project of projects) {\n if (project.githubRepo) {\n newMappings[project.githubRepo] = org.id\n totalProjects++\n }\n }\n } catch (error) {\n console.log(` \u274C Error: ${error}`)\n }\n }\n\n // Update config with new mappings\n config.repoMapping = newMappings\n saveConfig(config)\n\n console.log('')\n console.log(`\u2705 Synced ${totalProjects} project(s)`)\n\n if (totalProjects > 0) {\n console.log('')\n console.log('Repository mappings:')\n for (const [repo, orgId] of Object.entries(newMappings)) {\n const org = config.organizations.find(o => o.id === orgId)\n console.log(` ${repo} \u2192 ${org?.name || orgId}`)\n }\n }\n}\n", "/**\n * Claude.ai DOM Selectors for Playwright\n *\n * Based on comprehensive audit of Claude Code web interface.\n * These selectors are used for scraping session info and automation.\n */\n\nexport const ClaudeSelectors = {\n // ============================================================================\n // Sidebar - Session List (Verified 2026-02-23)\n // ============================================================================\n sidebar: {\n /** New task input (textarea in sidebar) */\n newTaskInput: 'textarea[placeholder=\"Ask Claude to write code...\"]',\n\n /** Session list container */\n sessionList: String.raw`.flex.flex-col.gap-0\\.5.px-1`,\n\n /** Individual session items - use :has-text() with title */\n sessionItem: (title: string) => `.cursor-pointer:has-text(\"${title}\")`,\n\n /** All session items (div elements with cursor-pointer class) */\n allSessions: String.raw`.flex.flex-col.gap-0\\.5.px-1 .cursor-pointer`,\n\n /** Session by index (0-indexed) */\n sessionByIndex: (index: number) => String.raw`.flex.flex-col.gap-0\\.5.px-1` + ` > div:nth-child(${index + 1}) .cursor-pointer`,\n\n /** Active/selected session (has bg-bg-300 class) */\n activeSession: '.cursor-pointer.bg-bg-300',\n\n /** Session title within a session item */\n sessionTitle: 'button.text-sm.font-medium.truncate',\n\n /** Session archive button (icon-only, no aria-label) */\n sessionArchiveButton: (title: string) => `.cursor-pointer:has-text(\"${title}\") button`,\n\n /** Search sessions button */\n searchButton: 'button[aria-label=\"Search \u2318K\"]',\n\n /** User profile button */\n userProfileButton: '[data-testid=\"code-user-menu-button\"]',\n },\n\n // ============================================================================\n // Branch Bar (between chat messages and chat input) - Verified 2026-02-23\n // ============================================================================\n branchBar: {\n /** Container for branch bar */\n container: '.flex.items-center.gap-2.w-full.p-2',\n\n /** Branch name display - the copyable span */\n branchName: 'button.group\\\\/copy span.truncate',\n\n /** Base/target branch dropdown (e.g., \"develop\") */\n baseBranchSelector: '.flex.items-center.gap-2.w-full.p-2 button[aria-haspopup=\"menu\"]',\n\n /** Copy branch button (click to copy branch name) */\n copyBranchButton: 'button.group\\\\/copy',\n\n /** Diff stats button (+N -M) */\n diffStatsButton: String.raw`.flex.items-center.gap-2.w-full.p-2 button.border-0\\.5`,\n },\n\n // ============================================================================\n // Pull Request Controls - Verified 2026-02-23\n // ============================================================================\n pullRequest: {\n /** Create PR button (left half - immediate action) - CAREFUL: clicks immediately! */\n createPrButton: 'button:has-text(\"Create PR\"):not([aria-haspopup])',\n\n /** PR dropdown trigger (right half - shows options) - SAFE to click */\n prDropdown: 'button.rounded-r-md[aria-haspopup=\"menu\"]',\n\n /** PR status indicator when PR exists */\n prStatus: 'a[href*=\"/pull/\"], a[href*=\"/merge_requests/\"]',\n\n /** View PR link */\n viewPrLink: 'a:has-text(\"View PR\"), a:has-text(\"View Pull Request\")',\n },\n\n // ============================================================================\n // Chat Area - Verified 2026-02-23\n // ============================================================================\n chat: {\n /** Main chat container */\n container: 'main',\n\n /** Chat messages */\n messages: 'div[data-testid=\"chat-message\"], div.prose',\n\n /** User messages */\n userMessages: 'div[data-testid=\"user-message\"]',\n\n /** Assistant messages */\n assistantMessages: 'div[data-testid=\"assistant-message\"]',\n\n /** Chat input (ProseMirror contenteditable) - NOT a textarea */\n input: '[aria-label=\"Enter your turn\"]',\n\n /** Chat input fallback */\n inputFallback: 'div.tiptap.ProseMirror[contenteditable=\"true\"]',\n\n /** Toggle menu button (+) */\n toggleMenuButton: 'button[aria-label=\"Toggle menu\"]',\n\n /** Send button */\n sendButton: 'form.w-full button[aria-label=\"Submit\"]',\n\n /** Stop button (during generation) */\n stopButton: 'button:has-text(\"Stop\")',\n },\n\n // ============================================================================\n // Model Selector - Verified 2026-02-23\n // ============================================================================\n model: {\n /** Model selector dropdown (sidebar) */\n sidebarSelector: 'form:not(.w-full) [data-testid=\"model-selector-dropdown\"]',\n\n /** Model selector dropdown (main chat) */\n chatSelector: 'form.w-full [data-testid=\"model-selector-dropdown\"]',\n\n /** Model options in dropdown (role=\"menuitem\") */\n options: '[role=\"menuitem\"]',\n\n /** Specific model option */\n option: (modelName: string) => `[role=\"menuitem\"]:has-text(\"${modelName}\")`,\n\n /** Quick model selectors */\n opus: '[role=\"menuitem\"]:has-text(\"Opus\")',\n sonnet: '[role=\"menuitem\"]:has-text(\"Sonnet\")',\n haiku: '[role=\"menuitem\"]:has-text(\"Haiku\")',\n },\n\n // ============================================================================\n // Mode Toggle - Verified 2026-02-23\n // Text alternates between \"Auto accept edits\" and \"Plan mode\"\n // ============================================================================\n mode: {\n /** Mode toggle button in sidebar - simple toggle, not dropdown */\n sidebarToggle: 'form:not(.w-full) button:has-text(\"Auto accept edits\"), form:not(.w-full) button:has-text(\"Plan mode\")',\n\n /** Mode toggle button in main chat */\n chatToggle: 'form.w-full button:has-text(\"Auto accept edits\"), form.w-full button:has-text(\"Plan mode\")',\n },\n\n // ============================================================================\n // Repository Connection - Verified 2026-02-23\n // ============================================================================\n repository: {\n /** Repo button in sidebar (shows current repo name) */\n repoButton: 'form:not(.w-full) button.flex.items-center.gap-1.min-w-0.rounded',\n\n /** Repo button by name */\n repoButtonByName: (repoName: string) => `form:not(.w-full) button:has-text(\"${repoName}\")`,\n\n /** Add repository button (hidden until hover) */\n addRepoButton: 'button[aria-label=\"Add repository\"]',\n\n /** Select repository dropdown */\n selectRepoDropdown: 'form:not(.w-full) button[aria-haspopup=\"menu\"]:has-text(\"Select repository\")',\n },\n\n // ============================================================================\n // Session Archive\n // ============================================================================\n archive: {\n /** Archive indicator text */\n indicator: 'text=This session has been archived',\n\n /** Archive button (if available) */\n archiveButton: 'button:has-text(\"Archive\")',\n },\n\n // ============================================================================\n // Authentication\n // ============================================================================\n auth: {\n /** Login page indicators */\n loginPage: 'text=Log in, text=Sign in, form[action*=\"login\"]',\n\n /** OAuth redirect */\n oauthRedirect: 'text=Redirecting',\n },\n\n // ============================================================================\n // Dropdowns (Radix UI pattern)\n // ============================================================================\n dropdown: {\n /** Open dropdown menu */\n menu: 'div[role=\"menu\"]',\n\n /** Menu items */\n items: 'div[role=\"menuitem\"]',\n\n /** Specific menu item */\n item: (text: string) => `div[role=\"menuitem\"]:has-text(\"${text}\")`,\n\n /** Listbox (for selects) */\n listbox: 'div[role=\"listbox\"]',\n\n /** Listbox options */\n listboxOptions: 'div[role=\"option\"]',\n },\n}\n\n/**\n * Session info extracted from Claude.ai\n */\nexport interface ClaudeSession {\n /** Session URL */\n url: string\n /** Session title from sidebar */\n title: string\n /** Branch name if connected to git */\n branchName?: string\n /** Repository name if connected */\n repoName?: string\n /** PR URL if one exists */\n prUrl?: string\n /** Whether the session is archived */\n archived: boolean\n}\n\n/**\n * Extract repo name from various formats\n */\nexport function parseRepoName(text: string): { owner: string; repo: string } | null {\n // Try owner/repo format\n const slashMatch = text.match(/^([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_.-]+)$/)\n if (slashMatch) {\n return { owner: slashMatch[1], repo: slashMatch[2] }\n }\n\n // Try GitHub URL format\n const urlMatch = text.match(/github\\.com\\/([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_.-]+)/)\n if (urlMatch) {\n return { owner: urlMatch[1], repo: urlMatch[2] }\n }\n\n return null\n}\n\n/**\n * Extract branch name from common patterns\n */\nexport function parseBranchName(text: string): string | null {\n // Common branch prefixes\n const prefixes = ['feature/', 'fix/', 'bugfix/', 'hotfix/', 'release/', 'chore/', 'docs/', 'refactor/', 'test/']\n\n for (const prefix of prefixes) {\n if (text.includes(prefix)) {\n const match = text.match(new RegExp(`(${prefix}[a-zA-Z0-9_-]+)`))\n if (match) return match[1]\n }\n }\n\n // Main branches\n if (['main', 'master', 'develop', 'development'].includes(text.trim())) {\n return text.trim()\n }\n\n // Generic branch pattern\n const branchMatch = text.match(/^[a-zA-Z][a-zA-Z0-9_/-]{2,50}$/)\n if (branchMatch) {\n return branchMatch[0]\n }\n\n return null\n}\n", "/**\n * Import command - scrapes existing Claude Code sessions and creates tasks in FlightDesk\n */\n\nimport type { Page, BrowserContext } from 'playwright'\nimport { isPlaywrightAvailable, USER_DATA_DIR } from '../lib/session-monitor'\nimport { ClaudeSelectors, ClaudeSession } from '../lib/claude-selectors'\nimport { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport * as fs from 'fs'\n\n// Playwright is dynamically imported\nlet playwright: typeof import('playwright') | null = null\n\ninterface ImportOptions {\n dryRun?: boolean\n limit?: number\n headless?: boolean\n project?: string\n verbose?: boolean\n}\n\ninterface DiscoveredSession {\n url: string\n title: string\n repoName?: string\n branchName?: string\n archived: boolean\n}\n\n/**\n * Main import command\n */\nexport async function importCommand(options: ImportOptions): Promise<void> {\n const { config, org } = requireActiveOrg()\n\n // Check Playwright\n if (!await isPlaywrightAvailable()) {\n console.error('Playwright is required for import. Install it with:')\n console.error(' npm install -g playwright')\n console.error(' npx playwright install chromium')\n process.exit(1)\n }\n\n playwright = await import('playwright')\n\n const api = FlightDeskAPI.fromConfig(config, org)\n\n console.log('\\n\uD83D\uDD0D FlightDesk Import - Scanning Claude Sessions\\n')\n\n if (options.dryRun) {\n console.log('\uD83D\uDCCB DRY RUN - No changes will be made\\n')\n }\n\n // Get existing projects to match repos\n let existingProjects: Array<{ id: string; name: string; githubRepo: string }> = []\n try {\n existingProjects = await api.listProjects()\n if (options.verbose) {\n console.log(`Found ${existingProjects.length} existing projects`)\n }\n } catch (error) {\n console.error('Warning: Could not fetch existing projects:', error)\n }\n\n // Launch browser and scan sessions\n const sessions = await scanClaudeSessions({\n headless: options.headless !== false,\n limit: options.limit || 50,\n verbose: options.verbose,\n })\n\n if (sessions.length === 0) {\n console.log('No sessions found. Make sure you are logged into Claude.')\n console.log('Run: flightdesk auth')\n return\n }\n\n console.log(`\\nFound ${sessions.length} sessions:\\n`)\n\n // Group sessions by repo\n const sessionsByRepo = new Map<string, DiscoveredSession[]>()\n const noRepoSessions: DiscoveredSession[] = []\n\n for (const session of sessions) {\n if (session.repoName) {\n const existing = sessionsByRepo.get(session.repoName) || []\n existing.push(session)\n sessionsByRepo.set(session.repoName, existing)\n } else {\n noRepoSessions.push(session)\n }\n }\n\n // Display grouped results\n for (const [repoName, repoSessions] of sessionsByRepo) {\n // Only match on githubRepo field - NOT project name for security\n // The repo name from Claude is just the repo part (e.g., \"mi-core\")\n // The project's githubRepo is the full path (e.g., \"monroe-institute/mi-core\")\n const matchingProject = existingProjects.find(p =>\n p.githubRepo?.endsWith(`/${repoName}`)\n )\n\n if (matchingProject) {\n console.log(`\uD83D\uDCC1 ${repoName} \u2192 Project: ${matchingProject.name} (${matchingProject.id.slice(0, 8)})`)\n } else {\n console.log(`\uD83D\uDCC1 ${repoName} \u2192 No matching project`)\n }\n\n for (const session of repoSessions) {\n const status = session.archived ? '\uD83D\uDCE6' : session.branchName ? '\uD83C\uDF3F' : '\uD83D\uDCAC'\n console.log(` ${status} ${session.title.slice(0, 50)}${session.title.length > 50 ? '...' : ''}`)\n if (session.branchName) {\n console.log(` Branch: ${session.branchName}`)\n }\n }\n console.log('')\n }\n\n if (noRepoSessions.length > 0) {\n console.log(`\uD83D\uDCC1 No Repository (${noRepoSessions.length} sessions)`)\n for (const session of noRepoSessions.slice(0, 5)) {\n const status = session.archived ? '\uD83D\uDCE6' : '\uD83D\uDCAC'\n console.log(` ${status} ${session.title.slice(0, 50)}${session.title.length > 50 ? '...' : ''}`)\n }\n if (noRepoSessions.length > 5) {\n console.log(` ... and ${noRepoSessions.length - 5} more`)\n }\n console.log('')\n }\n\n // Summary\n console.log('\u2500'.repeat(60))\n console.log(`\\nSummary:`)\n console.log(` Total sessions: ${sessions.length}`)\n console.log(` With repository: ${sessions.length - noRepoSessions.length}`)\n console.log(` Without repository: ${noRepoSessions.length}`)\n console.log(` Archived: ${sessions.filter(s => s.archived).length}`)\n console.log('')\n\n if (options.dryRun) {\n console.log('\uD83D\uDCA1 Run without --dry-run to create tasks in FlightDesk')\n return\n }\n\n // Collect sessions that can be imported (have matching projects)\n const importableSessions: Array<{ session: DiscoveredSession; project: { id: string; name: string; githubRepo: string } }> = []\n\n for (const [repoName, repoSessions] of sessionsByRepo) {\n const matchingProject = existingProjects.find(p =>\n p.githubRepo?.endsWith(`/${repoName}`)\n )\n if (matchingProject) {\n for (const session of repoSessions) {\n importableSessions.push({ session, project: matchingProject })\n }\n }\n }\n\n if (importableSessions.length === 0) {\n console.log('No sessions can be imported (no matching projects).')\n console.log('Create projects in FlightDesk first for the repositories you want to track.')\n return\n }\n\n console.log(`\\n\uD83D\uDE80 Importing ${importableSessions.length} sessions...\\n`)\n\n let created = 0\n let failed = 0\n\n for (const { session, project } of importableSessions) {\n try {\n // Create the task\n const task = await api.createTask({\n projectId: project.id,\n title: session.title,\n description: `Imported from Claude Code session`,\n })\n\n // Update with branch, session URL, and correct status\n // Determine status based on session state:\n // - Archived sessions \u2192 ARCHIVED\n // - Has branch \u2192 IN_PROGRESS (work is happening)\n // - Just session URL \u2192 DISPATCHED (assigned to Claude)\n let status = 'DISPATCHED'\n if (session.archived) {\n status = 'ARCHIVED'\n } else if (session.branchName) {\n status = 'IN_PROGRESS'\n }\n\n await api.updateTask(task.id, {\n branchName: session.branchName,\n sessionViewUrl: session.url,\n status,\n })\n\n console.log(` \u2705 ${session.title.slice(0, 50)}`)\n created++\n } catch (error) {\n console.error(` \u274C ${session.title.slice(0, 50)}: ${(error as Error).message}`)\n failed++\n }\n }\n\n console.log('')\n console.log('\u2500'.repeat(60))\n console.log(`\\nImport complete:`)\n console.log(` Created: ${created}`)\n console.log(` Failed: ${failed}`)\n console.log(` Skipped (no matching project): ${sessions.length - importableSessions.length}`)\n}\n\n/**\n * Scan Claude.ai for sessions\n */\nasync function scanClaudeSessions(options: {\n headless: boolean\n limit: number\n verbose?: boolean\n}): Promise<DiscoveredSession[]> {\n if (!playwright) {\n throw new Error('Playwright not loaded')\n }\n\n // Ensure user data dir exists\n if (!fs.existsSync(USER_DATA_DIR)) {\n fs.mkdirSync(USER_DATA_DIR, { recursive: true })\n }\n\n const context = await playwright.chromium.launchPersistentContext(USER_DATA_DIR, {\n headless: options.headless,\n viewport: { width: 1280, height: 720 },\n userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',\n })\n\n try {\n const page = await context.newPage()\n page.setDefaultTimeout(60000)\n\n // Navigate to Claude Code\n console.log('Navigating to Claude Code...')\n await page.goto('https://claude.ai/code', { waitUntil: 'domcontentloaded', timeout: 60000 })\n\n // Wait for page to fully load\n if (options.verbose) {\n console.log('Waiting for page to load...')\n }\n await page.waitForTimeout(5000)\n\n // Check if logged in\n const url = page.url()\n if (options.verbose) {\n console.log('Current URL:', url)\n }\n if (url.includes('/login') || url.includes('/oauth')) {\n console.log('\\n\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth\\n')\n return []\n }\n\n console.log('Logged in. Scanning sessions...')\n\n // Wait for sidebar to render\n await page.waitForTimeout(3000)\n\n // Get all session items from sidebar (they're div.cursor-pointer, not links)\n const sessions: DiscoveredSession[] = []\n\n // Find all session items\n const sessionItems = await page.$$(ClaudeSelectors.sidebar.allSessions)\n\n if (options.verbose) {\n console.log(`Found ${sessionItems.length} session items in sidebar`)\n }\n\n const limit = Math.min(sessionItems.length, options.limit)\n\n for (let i = 0; i < limit; i++) {\n // Re-query items since DOM might change after clicking\n const items = await page.$$(ClaudeSelectors.sidebar.allSessions)\n if (i >= items.length) break\n\n const item = items[i]\n\n try {\n // Get title from the session item (the main text-text-100 span)\n const titleElement = await item.$('span.text-text-100')\n const title = titleElement ? (await titleElement.textContent())?.trim() || 'Untitled' : 'Untitled'\n\n // Get repo name from the session item metadata (span.truncate inside the metadata row)\n let repoName: string | undefined\n try {\n const repoElement = await item.$('span.text-text-500 span.truncate')\n if (repoElement) {\n const repoText = (await repoElement.textContent())?.trim()\n if (repoText && repoText.length > 0) {\n // The repo name is just the repo portion (e.g., \"mi-core\"), not owner/repo\n // It may be truncated visually but full text should be in DOM\n repoName = repoText\n }\n }\n } catch {\n // No repo\n }\n\n if (options.verbose) {\n const repoDisplay = repoName ? ` (${repoName})` : ''\n process.stdout.write(`\\r Scanning ${i + 1}/${limit}: ${title.slice(0, 35)}${repoDisplay}...`)\n }\n\n // Dismiss any modal dialogs that might be open (like notification prompts)\n try {\n await page.keyboard.press('Escape')\n await page.waitForTimeout(300)\n } catch {\n // No modal to dismiss\n }\n\n // Click the session item to navigate to it\n await item.click()\n await page.waitForTimeout(2000)\n\n // Get the session URL from the page after navigation\n const sessionUrl = page.url()\n\n // Extract branch name if present (from branch bar after navigation)\n let branchName: string | undefined\n try {\n const branchElement = await page.$(ClaudeSelectors.branchBar.branchName)\n if (branchElement) {\n branchName = (await branchElement.textContent())?.trim()\n }\n } catch {\n // No branch\n }\n\n // Check if archived\n const archived = !!(await page.$(ClaudeSelectors.archive.indicator))\n\n sessions.push({\n url: sessionUrl,\n title: title.trim(),\n branchName,\n repoName,\n archived,\n })\n } catch (error) {\n if (options.verbose) {\n console.error(`\\n Error scanning session ${i + 1}:`, error)\n }\n }\n }\n\n if (options.verbose) {\n console.log('\\n')\n }\n\n return sessions\n } finally {\n await context.close()\n }\n}\n\nexport { ImportOptions }\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\n\nexport async function projectCommand(action: string, options: Record<string, unknown>) {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n switch (action) {\n case 'list':\n await listProjects(api)\n break\n default:\n console.error(`Unknown action: ${action}`)\n process.exit(1)\n }\n}\n\nasync function listProjects(api: FlightDeskAPI) {\n const projects = await api.listProjects()\n\n if (projects.length === 0) {\n console.log('No projects found.')\n console.log('\\nCreate a project at https://app.flightdesk.dev/app/projects/new')\n return\n }\n\n console.log('Projects:\\n')\n\n // Find the longest name for alignment\n const maxNameLen = Math.max(...projects.map(p => p.name.length), 4)\n\n for (const project of projects) {\n const name = project.name.padEnd(maxNameLen)\n const repo = project.githubRepo || '(no repo)'\n console.log(` ${project.id} ${name} ${repo}`)\n }\n\n console.log(`\\n${projects.length} project(s)`)\n}\n", "import { requireActiveOrg } from '../lib/config'\nimport { FlightDeskAPI } from '../lib/api'\nimport { execSync, spawn, spawnSync } from 'node:child_process'\nimport * as path from 'node:path'\nimport * as os from 'node:os'\nimport * as fs from 'node:fs'\n\ninterface PreviewStatusOptions {\n taskId: string\n}\n\n/**\n * Validate that a container ID is safe (hex characters only)\n * Docker container IDs are 64-char hex strings (or 12-char truncated)\n */\nfunction isValidContainerId(id: string): boolean {\n return /^[a-fA-F0-9]+$/.test(id) && id.length >= 12 && id.length <= 64\n}\n\n/**\n * Validate SSH connection parameters to prevent injection\n */\nfunction validateSSHParams(instance: { sshUser: string; sshHost: string; sshPort: number; containerId?: string }): void {\n // Validate container ID if present (hex only)\n if (instance.containerId && !isValidContainerId(instance.containerId)) {\n throw new Error(`Invalid container ID format: ${instance.containerId}`)\n }\n // Validate SSH user (alphanumeric, underscore, hyphen)\n if (!/^[a-zA-Z0-9_-]+$/.test(instance.sshUser)) {\n throw new Error(`Invalid SSH user format: ${instance.sshUser}`)\n }\n // Validate SSH host (alphanumeric, dots, hyphens for hostname/IP)\n if (!/^[a-zA-Z0-9.-]+$/.test(instance.sshHost)) {\n throw new Error(`Invalid SSH host format: ${instance.sshHost}`)\n }\n // Validate port is a reasonable number\n if (!Number.isInteger(instance.sshPort) || instance.sshPort < 1 || instance.sshPort > 65535) {\n throw new Error(`Invalid SSH port: ${instance.sshPort}`)\n }\n}\n\ninterface PreviewLogsOptions {\n taskId: string\n lines?: number\n follow?: boolean\n}\n\ninterface PreviewMountOptions {\n taskId: string\n directory?: string\n}\n\ninterface PreviewUnmountOptions {\n taskId: string\n}\n\ninterface PreviewRestartOptions {\n taskId: string\n}\n\ninterface PreviewResumeOptions {\n taskId: string\n}\n\ninterface PreviewTeardownOptions {\n taskId: string\n}\n\ntype PreviewOptions =\n | PreviewStatusOptions\n | PreviewLogsOptions\n | PreviewMountOptions\n | PreviewUnmountOptions\n | PreviewRestartOptions\n | PreviewResumeOptions\n | PreviewTeardownOptions\n\n/**\n * Preview environment management commands\n */\nexport async function previewCommand(\n action: 'status' | 'logs' | 'mount' | 'unmount' | 'restart' | 'resume' | 'teardown',\n options: PreviewOptions\n): Promise<void> {\n const { config, org } = requireActiveOrg()\n const api = FlightDeskAPI.fromConfig(config, org)\n\n try {\n switch (action) {\n case 'status':\n await handleStatus(api, options as PreviewStatusOptions)\n break\n case 'logs':\n await handleLogs(api, options as PreviewLogsOptions)\n break\n case 'mount':\n await handleMount(api, options as PreviewMountOptions)\n break\n case 'unmount':\n await handleUnmount(api, options as PreviewUnmountOptions)\n break\n case 'restart':\n await handleRestart(api, options as PreviewRestartOptions)\n break\n case 'resume':\n await handleResume(api, options as PreviewResumeOptions)\n break\n case 'teardown':\n await handleTeardown(api, options as PreviewTeardownOptions)\n break\n }\n } catch (error) {\n console.error(`Error: ${error}`)\n process.exit(1)\n }\n}\n\nfunction getStatusEmoji(status: string): string {\n const statusEmojis: Record<string, string> = {\n STARTING: '\uD83D\uDD04',\n READY: '\u2705',\n SUSPENDED: '\uD83D\uDCA4',\n RESTARTING: '\uD83D\uDD04',\n TEARDOWN: '\uD83D\uDDD1\uFE0F',\n ERROR: '\u274C',\n }\n return statusEmojis[status] || '\u2753'\n}\n\nasync function handleStatus(api: FlightDeskAPI, options: PreviewStatusOptions): Promise<void> {\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.log('\\n\u26A0\uFE0F No preview environment found for this task')\n console.log(' The preview environment may not have been created yet,')\n console.log(' or the PR may be closed.')\n return\n }\n\n const emoji = getStatusEmoji(instance.status)\n\n console.log('\\n\uD83D\uDCE6 Preview Environment')\n console.log('\u2500'.repeat(50))\n console.log(`${emoji} Status: ${instance.status}`)\n console.log(` ID: ${instance.id.substring(0, 8)}`)\n console.log(` Preview URL: ${instance.previewUrl}`)\n console.log(` SSH: ${instance.sshConnectionString}`)\n console.log(` Container: ${instance.containerId.substring(0, 12)}`)\n\n if (instance.lastActivityAt) {\n const lastActivity = new Date(instance.lastActivityAt)\n const minutesAgo = Math.round((Date.now() - lastActivity.getTime()) / 60000)\n console.log(` Last Activity: ${minutesAgo} minutes ago`)\n }\n\n if (instance.suspendedAt) {\n const suspended = new Date(instance.suspendedAt)\n console.log(` Suspended At: ${suspended.toLocaleString()}`)\n }\n\n console.log(` Created: ${new Date(instance.createdAt).toLocaleString()}`)\n console.log('')\n}\n\nasync function handleLogs(api: FlightDeskAPI, options: PreviewLogsOptions): Promise<void> {\n const lines = options.lines || 100\n\n if (options.follow) {\n // For follow mode, we need the SSH details to tail logs directly\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.error('No preview environment found for this task')\n process.exit(1)\n }\n\n console.log(`\uD83D\uDCCB Streaming logs from ${instance.previewUrl}...\\n`)\n console.log(`(Press Ctrl+C to stop)\\n`)\n\n // Validate SSH parameters to prevent command injection\n validateSSHParams(instance)\n\n // Use SSH to tail the logs (containerId validated above)\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n const sshCommand = `docker logs -f ${instance.containerId}`\n const ssh = spawn('ssh', [\n '-o', 'StrictHostKeyChecking=no',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-p', String(instance.sshPort),\n `${instance.sshUser}@${instance.sshHost}`,\n sshCommand,\n ])\n\n ssh.stdout.pipe(process.stdout)\n ssh.stderr.pipe(process.stderr)\n\n ssh.on('close', (code) => {\n process.exit(code || 0)\n })\n\n // Handle Ctrl+C\n process.on('SIGINT', () => {\n ssh.kill()\n process.exit(0)\n })\n\n return\n }\n\n // Non-follow mode: fetch logs via API\n const result = await api.getInstanceLogs(options.taskId, lines)\n\n if (!result.logs) {\n console.log('No logs available')\n return\n }\n\n console.log(result.logs)\n}\n\nasync function handleMount(api: FlightDeskAPI, options: PreviewMountOptions): Promise<void> {\n const instance = await api.getTaskInstance(options.taskId)\n\n if (!instance) {\n console.error('No preview environment found for this task')\n process.exit(1)\n }\n\n if (instance.status === 'SUSPENDED') {\n console.log('\u23F8\uFE0F Instance is suspended. Resuming...')\n await api.resumeInstance(options.taskId)\n // Wait a moment for resume\n await new Promise((resolve) => setTimeout(resolve, 3000))\n }\n\n // Check if sshfs is installed\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n try {\n execSync('which sshfs', { stdio: 'ignore' })\n } catch {\n console.error('\u274C sshfs is not installed.')\n console.error('')\n console.error('Install it with:')\n if (process.platform === 'darwin') {\n console.error(' brew install macfuse sshfs')\n } else if (process.platform === 'linux') {\n console.error(' sudo apt install sshfs')\n } else {\n console.error(' SSHFS is not supported on this platform')\n }\n process.exit(1)\n }\n\n // Sanitize taskId to prevent path traversal attacks\n const rawTaskIdPrefix = options.taskId.substring(0, 8)\n const safeTaskId = path.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, '') || 'task'\n const mountDir = options.directory || path.join(os.homedir(), 'flightdesk-mounts', safeTaskId)\n\n // Create mount directory if it doesn't exist\n if (!fs.existsSync(mountDir)) {\n fs.mkdirSync(mountDir, { recursive: true })\n }\n\n // Check if already mounted\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n try {\n const mounted = execSync('mount', { encoding: 'utf8' })\n if (mounted.includes(mountDir)) {\n console.log(`\uD83D\uDCC1 Already mounted at ${mountDir}`)\n return\n }\n } catch {\n // Ignore mount check errors\n }\n\n console.log(`\uD83D\uDCC1 Mounting preview environment to ${mountDir}...`)\n\n // Validate SSH parameters to prevent injection\n validateSSHParams(instance)\n\n // Use spawnSync with arguments array to avoid shell injection\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n const sshfsArgs = [\n '-o', 'StrictHostKeyChecking=no',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-o', 'reconnect',\n '-o', 'ServerAliveInterval=15',\n '-o', 'ServerAliveCountMax=3',\n '-p', String(instance.sshPort),\n `${instance.sshUser}@${instance.sshHost}:/app`,\n mountDir,\n ]\n\n try {\n const result = spawnSync('sshfs', sshfsArgs, { stdio: 'inherit' })\n if (result.status !== 0) {\n throw new Error(`sshfs exited with code ${result.status}`)\n }\n console.log('')\n console.log('\u2705 Mounted successfully!')\n console.log(` Location: ${mountDir}`)\n console.log('')\n console.log(' To unmount:')\n console.log(` fd preview unmount ${options.taskId}`)\n console.log('')\n console.log(' Or manually:')\n if (process.platform === 'darwin') {\n console.log(` umount ${mountDir}`)\n } else {\n console.log(` fusermount -u ${mountDir}`)\n }\n } catch (error) {\n console.error(`\u274C Mount failed: ${error}`)\n process.exit(1)\n }\n}\n\nasync function handleUnmount(_api: FlightDeskAPI, options: PreviewUnmountOptions): Promise<void> {\n // Sanitize taskId to prevent path traversal\n const rawTaskIdPrefix = options.taskId.substring(0, 8)\n const safeTaskId = path.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, '') || 'task'\n const mountDir = path.join(os.homedir(), 'flightdesk-mounts', safeTaskId)\n\n if (!fs.existsSync(mountDir)) {\n console.log('Mount directory does not exist')\n return\n }\n\n console.log(`\uD83D\uDCC1 Unmounting ${mountDir}...`)\n\n try {\n // Use spawnSync with arguments array to avoid shell injection\n // NOSONAR: PATH-based lookup is standard for CLI tools; user controls their own environment\n let result\n if (process.platform === 'darwin') {\n result = spawnSync('umount', [mountDir], { stdio: 'inherit' })\n } else {\n result = spawnSync('fusermount', ['-u', mountDir], { stdio: 'inherit' })\n }\n if (result.status !== 0) {\n throw new Error(`Unmount exited with code ${result.status}`)\n }\n console.log('\u2705 Unmounted successfully')\n\n // Try to remove the directory (and any nested contents)\n try {\n fs.rmSync(mountDir, { recursive: true, force: true })\n } catch {\n // Directory cleanup failure is non-fatal\n }\n } catch (error) {\n console.error(`\u274C Unmount failed: ${error}`)\n console.error('')\n console.error('Try force unmounting:')\n if (process.platform === 'darwin') {\n console.error(` diskutil unmount force ${mountDir}`)\n } else {\n console.error(` fusermount -uz ${mountDir}`)\n }\n process.exit(1)\n }\n}\n\nasync function handleRestart(api: FlightDeskAPI, options: PreviewRestartOptions): Promise<void> {\n console.log('\uD83D\uDD04 Restarting preview environment...')\n\n await api.restartInstance(options.taskId)\n\n console.log('\u2705 Restart initiated. The preview will be available shortly.')\n}\n\nasync function handleResume(api: FlightDeskAPI, options: PreviewResumeOptions): Promise<void> {\n console.log('\u25B6\uFE0F Resuming preview environment...')\n\n await api.resumeInstance(options.taskId)\n\n console.log('\u2705 Resume initiated. The preview should be ready in about 30 seconds.')\n}\n\nasync function handleTeardown(api: FlightDeskAPI, options: PreviewTeardownOptions): Promise<void> {\n console.log('\uD83D\uDDD1\uFE0F Tearing down preview environment...')\n\n await api.tearDownInstance(options.taskId)\n\n console.log('\u2705 Preview environment has been torn down.')\n}\n", "import { Command } from 'commander'\nimport { setDevMode, setApiUrl } from './lib/config'\n\n// Version injected by esbuild at build time\ndeclare const __CLI_VERSION__: string\n\n// Import commands\nimport { initCommand } from './commands/init'\nimport { authCommand } from './commands/auth'\nimport { registerCommand } from './commands/register'\nimport { statusCommand } from './commands/status'\nimport { watchCommand } from './commands/watch'\nimport { taskCommand } from './commands/task'\nimport { promptCommand } from './commands/prompt'\nimport { orgListCommand, orgSwitchCommand, orgRefreshCommand } from './commands/org'\nimport { contextCommand } from './commands/context'\nimport { syncCommand } from './commands/sync'\nimport { importCommand } from './commands/import'\nimport { projectCommand } from './commands/project'\nimport { previewCommand } from './commands/preview'\n\nconst program = new Command()\n\nprogram\n .name('flightdesk')\n .description('FlightDesk CLI - AI task management for Claude Code sessions')\n .version(__CLI_VERSION__)\n .option('--dev', 'Use local development API (localhost:3000)')\n .option('--api <url>', 'Use custom API URL')\n\n// Process --dev and --api flags before command execution\nprogram.hook('preAction', () => {\n const opts = program.opts()\n if (opts.api) {\n setApiUrl(opts.api)\n console.log(`\uD83D\uDD27 Using custom API: ${opts.api}\\n`)\n } else if (opts.dev) {\n setDevMode(true)\n console.log('\uD83D\uDD27 Development mode: using http://localhost:3000\\n')\n }\n})\n\n// Initialize configuration\nprogram\n .command('init')\n .description('Configure FlightDesk CLI with your API credentials')\n .action(initCommand)\n\n// Authenticate with Claude (for watch daemon)\nprogram\n .command('auth')\n .description('Log in to Claude for session monitoring')\n .action(authCommand)\n\n// Register a session with a task\nprogram\n .command('register [task-id]')\n .description('Register a Claude Code session with a FlightDesk task (auto-detects project from git repo)')\n .option('-p, --project <id>', 'Project ID (auto-detected from git repo if not provided)')\n .option('--view-url <url>', 'Claude Code session view URL')\n .option('--teleport-id <id>', 'Claude Code teleport ID')\n .option('--title <title>', 'Task title (creates new task if task-id not provided)')\n .option('--description <description>', 'Task description')\n .action(registerCommand)\n\n// Project management\nconst project = program\n .command('project')\n .description('Project management commands')\n\nproject\n .command('list')\n .description('List projects in the active organization')\n .action(() => projectCommand('list', {}))\n\n// Task management\nconst task = program\n .command('task')\n .description('Task management commands')\n\ntask\n .command('create')\n .description('Create a new task')\n .requiredOption('-p, --project <id>', 'Project ID')\n .requiredOption('-t, --title <title>', 'Task title')\n .option('-d, --description <description>', 'Task description')\n .action((options) => taskCommand('create', options))\n\ntask\n .command('list')\n .description('List tasks')\n .option('-p, --project <id>', 'Filter by project ID')\n .option('--status <status>', 'Filter by status')\n .action((options) => taskCommand('list', options))\n\ntask\n .command('status <task-id>')\n .description('Get task status')\n .action((taskId) => taskCommand('status', { taskId }))\n\ntask\n .command('update <task-id>')\n .description('Update task')\n .option('-s, --status <status>', 'New status')\n .option('--branch <branch>', 'Branch name')\n .option('--pr-url <url>', 'Pull request URL')\n .action((taskId, options) => taskCommand('update', { taskId, ...options }))\n\n// Watch daemon for monitoring sessions\nprogram\n .command('watch')\n .description('Start the Playwright daemon to monitor Claude Code sessions')\n .option('--interval <minutes>', 'Check interval in minutes', '5')\n .option('--once', 'Run once and exit')\n .option('--auto-pr', 'Automatically click \"Create PR\" button when found')\n .option('--no-headless', 'Run browser in visible mode (for debugging)')\n .action(watchCommand)\n\n// Import existing Claude sessions\nprogram\n .command('import')\n .description('Scan Claude.ai for existing sessions and import them as tasks')\n .option('--dry-run', 'Show what would be imported without making changes')\n .option('--limit <n>', 'Maximum number of sessions to scan', '50')\n .option('-p, --project <id>', 'Import all sessions into a specific project')\n .option('--no-headless', 'Run browser in visible mode (for debugging)')\n .option('-v, --verbose', 'Show detailed progress')\n .action(importCommand)\n\n// Status overview\nprogram\n .command('status')\n .description('Show status of all active tasks')\n .option('-p, --project <id>', 'Filter by project')\n .action(statusCommand)\n\n// Get prompt for a task\nprogram\n .command('prompt <task-id>')\n .description('Get a prompt for a task (ready to paste into Claude)')\n .option('--type <type>', 'Prompt type: review, test_plan, summary, handoff', 'review')\n .action(promptCommand)\n\n// Organization management\nconst org = program\n .command('org')\n .description('Organization management')\n\norg\n .command('list')\n .description('List your organizations')\n .action(orgListCommand)\n\norg\n .command('switch <name>')\n .description('Switch active organization')\n .action(orgSwitchCommand)\n\norg\n .command('refresh')\n .description('Refresh organizations from API')\n .action(orgRefreshCommand)\n\n// Context detection\nprogram\n .command('context')\n .description('Show current repository context and mapped organization')\n .action(contextCommand)\n\n// Sync repo mappings\nprogram\n .command('sync')\n .description('Refresh project-to-repository mappings from all organizations')\n .action(syncCommand)\n\n// Preview environment commands\nconst preview = program\n .command('preview')\n .description('Preview environment management')\n\npreview\n .command('status <task-id>')\n .description('Show preview environment status')\n .action((taskId) => previewCommand('status', { taskId }))\n\npreview\n .command('logs <task-id>')\n .description('Get logs from preview environment')\n .option('-n, --lines <lines>', 'Number of log lines (1-10000)', '100')\n .option('-f, --follow', 'Follow log output')\n .action((taskId, options) => {\n const lines = Math.min(Math.max(Number.parseInt(options.lines || '100'), 1), 10000)\n previewCommand('logs', { taskId, lines, follow: options.follow })\n })\n\npreview\n .command('mount <task-id>')\n .description('Mount preview environment filesystem via SSHFS')\n .option('-d, --directory <path>', 'Custom mount directory')\n .action((taskId, options) => previewCommand('mount', { taskId, directory: options.directory }))\n\npreview\n .command('unmount <task-id>')\n .description('Unmount preview environment filesystem')\n .action((taskId) => previewCommand('unmount', { taskId }))\n\npreview\n .command('restart <task-id>')\n .description('Restart preview environment processes')\n .action((taskId) => previewCommand('restart', { taskId }))\n\npreview\n .command('resume <task-id>')\n .description('Resume a suspended preview environment')\n .action((taskId) => previewCommand('resume', { taskId }))\n\npreview\n .command('teardown <task-id>')\n .description('Tear down preview environment')\n .action((taskId) => previewCommand('teardown', { taskId }))\n\n// Shorthand commands for common preview operations\nprogram\n .command('mount <task-id>')\n .description('Mount preview environment filesystem (shorthand for \"preview mount\")')\n .option('-d, --directory <path>', 'Custom mount directory')\n .action((taskId, options) => previewCommand('mount', { taskId, directory: options.directory }))\n\nprogram\n .command('unmount <task-id>')\n .description('Unmount preview environment filesystem (shorthand for \"preview unmount\")')\n .action((taskId) => previewCommand('unmount', { taskId }))\n\nprogram\n .command('logs <task-id>')\n .description('Get logs from preview environment (equivalent to \"preview logs\")')\n .option('-n, --lines <lines>', 'Number of log lines (1-10000)', '100')\n .option('-f, --follow', 'Follow log output')\n .action((taskId, options) => {\n const lines = Math.min(Math.max(Number.parseInt(options.lines || '100'), 1), 10000)\n previewCommand('logs', { taskId, lines, follow: options.follow })\n })\n\nprogram.parse()\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,4EAAAA,UAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM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E,QAAQ,WAAW,QAAQ,UAAU,CAAC,CAAC;AAEhGA,SACG,QAAQ,mBAAmB,EAC3B,YAAY,0EAA0E,EACtF,OAAO,CAAC,WAAW,eAAe,WAAW,EAAE,OAAO,CAAC,CAAC;AAE3DA,SACG,QAAQ,gBAAgB,EACxB,YAAY,kEAAkE,EAC9E,OAAO,uBAAuB,iCAAiC,KAAK,EACpE,OAAO,gBAAgB,mBAAmB,EAC1C,OAAO,CAAC,QAAQ,YAAY;AAC3B,QAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,OAAO,SAAS,QAAQ,SAAS,KAAK,GAAG,CAAC,GAAG,GAAK;AAClF,iBAAe,QAAQ,EAAE,QAAQ,OAAO,QAAQ,QAAQ,OAAO,CAAC;AAClE,CAAC;AAEHA,SAAQ,MAAM;",
6
6
  "names": ["exports", "CommanderError", "InvalidArgumentError", "exports", "InvalidArgumentError", "Argument", "exports", "Help", "cmd", "exports", "InvalidArgumentError", "Option", "str", "exports", "exports", "path", "fs", "process", "Argument", "CommanderError", "Help", "Option", "Command", "option", "exports", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "commander", "org", "org", "org", "org", "path", "os", "fs", "readline", "org", "task", "project", "org", "task", "org", "task", "org", "task", "getStatusEmoji", "org", "org", "activeOrg", "org", "org", "project", "fs", "playwright", "org", "project", "task", "org", "project", "import_node_child_process", "path", "os", "fs", "org", "handleStatus", "getStatusEmoji", "program"]
7
7
  }