@rockcarver/frodo-cli 5.0.0-6 → 5.0.0-8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FrodoCommand-DueD-n-I.cjs","names":["stripVTControlCharacters","EventEmitter","process","stripVTControlCharacters","fs","path","childProcess","os","tty","mkdir","stat","statSync","mkdirSync","dirname","path","path","dirname","dirname","path","platform","path","resolve","parse","mkdirSync","mkdir","readFileSync","open","resolve","sep","dirname","exists","FOLDER","fs","process","os","fs","execFile","promisify","childProcess","powerShellPath","process","executePowerShell","Buffer","execFile","promisify","childProcess","fs","fsConstants","powerShellPath","isWsl","windowsPowerShellPath","executePowerShell","path","execFile","promisify","childProcess","process","Buffer","execFileAsync","promisify","execFile","process","execFileAsync","promisify","execFile","process","execFileAsync","promisify","execFile","defaultBrowser","process","promisify","execFile","process","windows","process","__dirname","path","fileURLToPath","process","isWsl","powerShellPath","fs","fsConstants","childProcess","open","readSync","frodo","open","DEPLOYMENT_TYPES","state","canPrompt","EXIT_ALL_SIGNAL","frodo","createTable","createProgressIndicator","getTypedFilename","getWorkingDirectory","getFilePath","readFiles","frodo","getOneLineDescription","c","getTableHeaderMd","getTableRowMd","createTable","getTypedFilename","getFilePath","createProgressIndicator","FrodoError","getWorkingDirectory","Readable","lstat","stat","presolve","psep","readdir","pjoin","realpath","osType","sp","fs_watch","open","watchFile","stat","fsrealpath","sp","readdir","EventEmitter","EV","stat","frodo","getOneLineDescription","c","getTableHeaderMd","getTableRowMd","createProgressIndicator","createTable","createKeyValueTable","printMessage","showSpinner","getTypedFilename","getFilePath","state","FrodoError","chokidar","getWorkingDirectory","frodo","createTable","c","getFilePath","FrodoError","createKeyValueTable","EmailTemplate.getOneLineDescription","createProgressIndicator","getTypedFilename","getWorkingDirectory","styleText","createPrompt","useState","makeTheme","usePrefix","isEnterKey","isTabKey","frodo","createTable","c","getTypedFilename","getFilePath","createProgressIndicator","getWorkingDirectory","readFiles","FrodoError","frodo","getTypedFilename","getFilePath","FrodoError","createProgressIndicator","confirm","path","c","navigateToPropertyContainer","parseSubPropertyPath","printMessage","createTable","navigatePropertyPath","createObjectTable","extractSchemaPropertyFields","buildSchemaPropertyPayload","inferReverseIdentity","extractRelationshipFields","buildRelationshipPropertyPayload","toReverseDescriptorFields","getWorkingDirectory","readFiles","frodo","getOneLineDescription","c","getTableHeaderMd","getTableRowMd","createTable","createKeyValueTable","createProgressIndicator","getTypedFilename","getFilePath","getWorkingDirectory","FrodoError","frodo","c","theme","createTable","createProgressIndicator","uuidv4","getFilePath","frodo","state","HUE_NAME_TO_FUNCTION","FRODO_COLOR_THEME_ENV_KEY","detectTerminalBackgroundRgb","matchBackgroundPreset","frodo","state","FrodoError","printMessage","verboseMessage","debugMessage","curlirizeMessage","createProgressIndicator","updateProgressIndicator","stopProgressIndicator","resolveInteractiveInputs","canPrompt","escapableSelect","RIGHT","EXIT_ALL","EXIT_ALL_SIGNAL","ESCAPE","getOneOfGroups","getEntityPicks"],"sources":["../node_modules/commander/lib/error.js","../node_modules/commander/lib/argument.js","../node_modules/commander/lib/help.js","../node_modules/commander/lib/option.js","../node_modules/commander/lib/suggestSimilar.js","../node_modules/commander/lib/command.js","../node_modules/commander/index.js","../node_modules/ms/index.js","../node_modules/debug/src/common.js","../node_modules/debug/src/browser.js","../node_modules/has-flag/index.js","../node_modules/supports-color/index.js","../node_modules/debug/src/node.js","../node_modules/debug/src/index.js","../node_modules/@kwsites/file-exists/dist/src/index.js","../node_modules/@kwsites/file-exists/dist/index.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/opts-arg.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/mkdirp-manual.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/find-made.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/mkdirp-native.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/path-arg.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/use-native.js","../node_modules/properties-reader/node_modules/mkdirp/dist/mjs/index.js","../node_modules/properties-reader/dist/esm/index.mjs","../node_modules/is-docker/index.js","../node_modules/is-inside-container/index.js","../node_modules/is-wsl/index.js","../node_modules/wsl-utils/node_modules/powershell-utils/index.js","../node_modules/wsl-utils/utilities.js","../node_modules/wsl-utils/index.js","../node_modules/powershell-utils/index.js","../node_modules/define-lazy-prop/index.js","../node_modules/default-browser-id/index.js","../node_modules/run-applescript/index.js","../node_modules/bundle-name/index.js","../node_modules/default-browser/windows.js","../node_modules/default-browser/index.js","../node_modules/is-in-ssh/index.js","../node_modules/open/index.js","../src/utils/interactive/ActiveActionCommandState.ts","../src/utils/Prompt.ts","../src/ops/AuthenticateOps.ts","../src/ops/classic/ServerOps.ts","../src/ops/utils/OpsUtils.ts","../src/ops/utils/Wordwrap.ts","../src/ops/EmailTemplateOps.ts","../node_modules/readdirp/index.js","../node_modules/chokidar/handler.js","../node_modules/chokidar/index.js","../src/ops/utils/ScriptFilters.js","../src/ops/ScriptOps.ts","../src/ops/cloud/iga/IgaWorkflowOps.ts","../node_modules/@inquirer/confirm/dist/index.js","../src/ops/MappingOps.ts","../src/ops/IdmOps.ts","../src/ops/NodeOps.ts","../src/ops/ThemeOps.ts","../src/utils/Config.ts","../src/utils/ThemeConfig.ts","../src/cli/FrodoCommand.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nexport class 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 */\nexport class 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","import { InvalidArgumentError } from './error.js';\n\nexport class Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nexport function humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n","import { humanReadableArgName } from './argument.js';\nimport { stripVTControlCharacters } from 'node:util';\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.\nexport class Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripVTControlCharacters(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n","import { InvalidArgumentError } from './error.js';\n\nexport class Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nexport class DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost;\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\nexport function 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","import { EventEmitter } from 'node:events';\nimport childProcess from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport process from 'node:process';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport { Argument, humanReadableArgName } from './argument.js';\nimport { CommanderError } from './error.js';\nimport { Help } from './help.js';\nimport { Option, DualOptions } from './option.js';\nimport { suggestSimilar } from './suggestSimilar.js';\n\nexport class Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripVTControlCharacters(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n // Save the state the first time, then restore the state before each subsequent parse.\n if (this._savedState === null) {\n // Do the special default of lone negated option to true, now that we have all the options.\n // Filter for negated options that have not been processed already.\n this.options\n .filter(\n (option) =>\n option.negate &&\n option.defaultValue === undefined &&\n this.getOptionValue(option.attributeName()) === undefined,\n )\n .forEach((option) => {\n // check for lone negated option: --no-foo without a --foo option\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n option.attributeName(),\n true,\n 'default',\n );\n }\n });\n\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n const launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const received = receivedArgs.length;\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const details = receivedArgs.join(', ');\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or import.meta.filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(import.meta.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(import.meta.dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * Exported for using from tests, not otherwise used outside this file.\n *\n * @returns {boolean | undefined}\n * @package\n */\nexport function useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n","import { Argument } from './lib/argument.js';\nimport { Command } from './lib/command.js';\nimport { CommanderError, InvalidArgumentError } from './lib/error.js';\nimport { Help } from './lib/help.js';\nimport { Option } from './lib/option.js';\n\nexport const program = new Command();\n\nexport const createCommand = (name) => new Command(name);\nexport const createOption = (flags, description) =>\n new Option(flags, description);\nexport const createArgument = (name, description) =>\n new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexport { Command, Option, Argument, Help };\nexport { CommanderError, InvalidArgumentError };\nexport { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = require(\"fs\");\nconst debug_1 = __importDefault(require(\"debug\"));\nconst log = debug_1.default('@kwsites/file-exists');\nfunction check(path, isFile, isDirectory) {\n log(`checking %s`, path);\n try {\n const stat = fs_1.statSync(path);\n if (stat.isFile() && isFile) {\n log(`[OK] path represents a file`);\n return true;\n }\n if (stat.isDirectory() && isDirectory) {\n log(`[OK] path represents a directory`);\n return true;\n }\n log(`[FAIL] path represents something other than a file or directory`);\n return false;\n }\n catch (e) {\n if (e.code === 'ENOENT') {\n log(`[FAIL] path is not accessible: %o`, e);\n return false;\n }\n log(`[FATAL] %o`, e);\n throw e;\n }\n}\n/**\n * Synchronous validation of a path existing either as a file or as a directory.\n *\n * @param {string} path The path to check\n * @param {number} type One or both of the exported numeric constants\n */\nfunction exists(path, type = exports.READABLE) {\n return check(path, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0);\n}\nexports.exists = exists;\n/**\n * Constant representing a file\n */\nexports.FILE = 1;\n/**\n * Constant representing a folder\n */\nexports.FOLDER = 2;\n/**\n * Constant representing either a file or a folder\n */\nexports.READABLE = exports.FILE + exports.FOLDER;\n//# sourceMappingURL=index.js.map","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./src\"));\n//# sourceMappingURL=index.js.map","import { mkdir, mkdirSync, stat, statSync, } from 'fs';\nexport const optsArg = (opts) => {\n if (!opts) {\n opts = { mode: 0o777 };\n }\n else if (typeof opts === 'object') {\n opts = { mode: 0o777, ...opts };\n }\n else if (typeof opts === 'number') {\n opts = { mode: opts };\n }\n else if (typeof opts === 'string') {\n opts = { mode: parseInt(opts, 8) };\n }\n else {\n throw new TypeError('invalid options argument');\n }\n const resolved = opts;\n const optsFs = opts.fs || {};\n opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir;\n opts.mkdirAsync = opts.mkdirAsync\n ? opts.mkdirAsync\n : async (path, options) => {\n return new Promise((res, rej) => resolved.mkdir(path, options, (er, made) => er ? rej(er) : res(made)));\n };\n opts.stat = opts.stat || optsFs.stat || stat;\n opts.statAsync = opts.statAsync\n ? opts.statAsync\n : async (path) => new Promise((res, rej) => resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats))));\n opts.statSync = opts.statSync || optsFs.statSync || statSync;\n opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync;\n return resolved;\n};\n//# sourceMappingURL=opts-arg.js.map","import { dirname } from 'path';\nimport { optsArg } from './opts-arg.js';\nexport const mkdirpManualSync = (path, options, made) => {\n const parent = dirname(path);\n const opts = { ...optsArg(options), recursive: false };\n if (parent === path) {\n try {\n return opts.mkdirSync(path, opts);\n }\n catch (er) {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er;\n if (fer && fer.code !== 'EISDIR') {\n throw er;\n }\n return;\n }\n }\n try {\n opts.mkdirSync(path, opts);\n return made || path;\n }\n catch (er) {\n const fer = er;\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made));\n }\n if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {\n throw er;\n }\n try {\n if (!opts.statSync(path).isDirectory())\n throw er;\n }\n catch (_) {\n throw er;\n }\n }\n};\nexport const mkdirpManual = Object.assign(async (path, options, made) => {\n const opts = optsArg(options);\n opts.recursive = false;\n const parent = dirname(path);\n if (parent === path) {\n return opts.mkdirAsync(path, opts).catch(er => {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er;\n if (fer && fer.code !== 'EISDIR') {\n throw er;\n }\n });\n }\n return opts.mkdirAsync(path, opts).then(() => made || path, async (er) => {\n const fer = er;\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(parent, opts).then((made) => mkdirpManual(path, opts, made));\n }\n if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {\n throw er;\n }\n return opts.statAsync(path).then(st => {\n if (st.isDirectory()) {\n return made;\n }\n else {\n throw er;\n }\n }, () => {\n throw er;\n });\n });\n}, { sync: mkdirpManualSync });\n//# sourceMappingURL=mkdirp-manual.js.map","import { dirname } from 'path';\nexport const findMade = async (opts, parent, path) => {\n // we never want the 'made' return value to be a root directory\n if (path === parent) {\n return;\n }\n return opts.statAsync(parent).then(st => (st.isDirectory() ? path : undefined), // will fail later\n // will fail later\n er => {\n const fer = er;\n return fer && fer.code === 'ENOENT'\n ? findMade(opts, dirname(parent), parent)\n : undefined;\n });\n};\nexport const findMadeSync = (opts, parent, path) => {\n if (path === parent) {\n return undefined;\n }\n try {\n return opts.statSync(parent).isDirectory() ? path : undefined;\n }\n catch (er) {\n const fer = er;\n return fer && fer.code === 'ENOENT'\n ? findMadeSync(opts, dirname(parent), parent)\n : undefined;\n }\n};\n//# sourceMappingURL=find-made.js.map","import { dirname } from 'path';\nimport { findMade, findMadeSync } from './find-made.js';\nimport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';\nimport { optsArg } from './opts-arg.js';\nexport const mkdirpNativeSync = (path, options) => {\n const opts = optsArg(options);\n opts.recursive = true;\n const parent = dirname(path);\n if (parent === path) {\n return opts.mkdirSync(path, opts);\n }\n const made = findMadeSync(opts, path);\n try {\n opts.mkdirSync(path, opts);\n return made;\n }\n catch (er) {\n const fer = er;\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts);\n }\n else {\n throw er;\n }\n }\n};\nexport const mkdirpNative = Object.assign(async (path, options) => {\n const opts = { ...optsArg(options), recursive: true };\n const parent = dirname(path);\n if (parent === path) {\n return await opts.mkdirAsync(path, opts);\n }\n return findMade(opts, path).then((made) => opts\n .mkdirAsync(path, opts)\n .then(m => made || m)\n .catch(er => {\n const fer = er;\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(path, opts);\n }\n else {\n throw er;\n }\n }));\n}, { sync: mkdirpNativeSync });\n//# sourceMappingURL=mkdirp-native.js.map","const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;\nimport { parse, resolve } from 'path';\nexport const pathArg = (path) => {\n if (/\\0/.test(path)) {\n // simulate same failure that node raises\n throw Object.assign(new TypeError('path must be a string without null bytes'), {\n path,\n code: 'ERR_INVALID_ARG_VALUE',\n });\n }\n path = resolve(path);\n if (platform === 'win32') {\n const badWinChars = /[*|\"<>?:]/;\n const { root } = parse(path);\n if (badWinChars.test(path.substring(root.length))) {\n throw Object.assign(new Error('Illegal characters in path.'), {\n path,\n code: 'EINVAL',\n });\n }\n }\n return path;\n};\n//# sourceMappingURL=path-arg.js.map","import { mkdir, mkdirSync } from 'fs';\nimport { optsArg } from './opts-arg.js';\nconst version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;\nconst versArr = version.replace(/^v/, '').split('.');\nconst hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12);\nexport const useNativeSync = !hasNative\n ? () => false\n : (opts) => optsArg(opts).mkdirSync === mkdirSync;\nexport const useNative = Object.assign(!hasNative\n ? () => false\n : (opts) => optsArg(opts).mkdir === mkdir, {\n sync: useNativeSync,\n});\n//# sourceMappingURL=use-native.js.map","import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';\nimport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';\nimport { optsArg } from './opts-arg.js';\nimport { pathArg } from './path-arg.js';\nimport { useNative, useNativeSync } from './use-native.js';\n/* c8 ignore start */\nexport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';\nexport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';\nexport { useNative, useNativeSync } from './use-native.js';\n/* c8 ignore stop */\nexport const mkdirpSync = (path, opts) => {\n path = pathArg(path);\n const resolved = optsArg(opts);\n return useNativeSync(resolved)\n ? mkdirpNativeSync(path, resolved)\n : mkdirpManualSync(path, resolved);\n};\nexport const sync = mkdirpSync;\nexport const manual = mkdirpManual;\nexport const manualSync = mkdirpManualSync;\nexport const native = mkdirpNative;\nexport const nativeSync = mkdirpNativeSync;\nexport const mkdirp = Object.assign(async (path, opts) => {\n path = pathArg(path);\n const resolved = optsArg(opts);\n return useNative(resolved)\n ? mkdirpNative(path, resolved)\n : mkdirpManual(path, resolved);\n}, {\n mkdirpSync,\n mkdirpNative,\n mkdirpNativeSync,\n mkdirpManual,\n mkdirpManualSync,\n sync: mkdirpSync,\n native: mkdirpNative,\n nativeSync: mkdirpNativeSync,\n manual: mkdirpManual,\n manualSync: mkdirpManualSync,\n useNative,\n useNativeSync,\n});\n//# sourceMappingURL=index.js.map","// src/actions/append.ts\nimport { readFileSync } from \"fs\";\n\n// src/actions/read.ts\nfunction readLine(line, task) {\n const trimmed = line.trim();\n if (!trimmed) {\n return task;\n }\n const section = /^\\[([^=]+)]$/.exec(trimmed);\n const property = !section && /^([^#=]+)(={0,1})(.*)$/.exec(trimmed);\n if (section) {\n task.section = section[1];\n } else if (property) {\n const currentSection = task.section ? `${task.section}.` : \"\";\n task.properties.set(currentSection + property[1].trim(), property[3].trim());\n }\n return task;\n}\nfunction read(input, task) {\n return String(input).split(\"\\n\").reduce(\n (task2, line) => {\n return readLine(line, task2);\n },\n { ...task, section: \"\" }\n );\n}\n\n// src/actions/append.ts\nfunction newTask() {\n return { section: \"\", properties: /* @__PURE__ */ new Map() };\n}\nfunction append(sourceFile, encoding, task = newTask()) {\n if (!sourceFile) {\n return task;\n }\n const file = readFileSync(sourceFile, encoding);\n return read(file, task);\n}\n\n// src/actions/save.ts\nimport { open } from \"fs/promises\";\nasync function save(destFile, props) {\n let pointer = null;\n try {\n pointer = await open(destFile, \"w\");\n for (const line of props) {\n await pointer.writeFile(`${line}\n`, \"utf8\");\n }\n } finally {\n await pointer?.close();\n }\n}\n\n// src/bind-to-express.ts\nimport { dirname, resolve, sep } from \"path\";\nimport { exists, FOLDER } from \"@kwsites/file-exists\";\nimport { mkdirp } from \"mkdirp\";\nfunction expressBasePath(basePath) {\n return resolve(basePath || process.cwd(), \"./\") + sep;\n}\nfunction bindToExpress(reader, app, basePath, makePaths) {\n for (const [key, value] of reader.entries()) {\n if (value && /\\.(path|dir)$/.test(key)) {\n const resolvedValue = resolve(basePath, value);\n reader.set(key, resolvedValue);\n try {\n const directoryPath = /dir$/.test(key) ? resolvedValue : dirname(resolvedValue);\n if (makePaths) {\n mkdirp.sync(directoryPath);\n } else if (!exists(directoryPath, FOLDER)) {\n throw new Error(\"Path is not a directory that already exists\");\n }\n } catch {\n throw new Error(`Unable to create directory ${value}`);\n }\n }\n app.set(key, reader.get(key));\n if (/^browser\\./.test(key) && app.locals) {\n app.locals[key.substr(8)] = reader.get(key);\n }\n }\n app.set(\"properties\", reader);\n return reader;\n}\n\n// src/parse-value.ts\nfunction parseValue(input) {\n const parsedValue = String(input).trim();\n switch (parsedValue) {\n case \"undefined\":\n case \"null\":\n return null;\n case (!isNaN(parsedValue) && !!parsedValue && parsedValue):\n return +parsedValue;\n case \"false\":\n case \"true\":\n return parsedValue === \"true\";\n default: {\n const replacements = { \"\\\\n\": \"\\n\", \"\\\\r\": \"\\r\", \"\\\\t\": \"\t\" };\n return parsedValue.replace(/\\\\[nrt]/g, (key) => replacements[key]);\n }\n }\n}\n\n// src/get-by-root.ts\nfunction getByRoot(store, root = \"\") {\n return Object.fromEntries(parsedEntries(store, `${root}.`));\n}\nfunction* parsedEntries(store, prefix = \"\") {\n for (const [storeKey, storeValue] of store.entries()) {\n const key = parsedKey(storeKey, prefix);\n if (key) {\n yield [key, parseValue(storeValue)];\n }\n }\n}\nfunction parsedKey(key, prefix) {\n if (!prefix) {\n return key;\n }\n if (key.startsWith(prefix)) {\n return key.substring(prefix.length);\n }\n}\n\n// src/output.ts\nfunction output(properties, allowDuplicateSections, saveSections) {\n if (!allowDuplicateSections) {\n properties = collapseSections(properties);\n }\n return saveSections ? generatePropertiesWithSections(properties) : generatePropertiesWithoutSections(properties);\n}\nfunction* generatePropertiesWithoutSections(properties) {\n for (const [key, value] of properties.entries()) {\n yield `${key}=${value}`;\n }\n}\nfunction* generatePropertiesWithSections(properties) {\n let section = null;\n for (let [key, value] of properties.entries()) {\n const [prefix, ...tokens] = key.split(\".\");\n if (tokens.length) {\n if (section !== prefix) {\n section = prefix;\n yield `[${section}]`;\n }\n key = tokens.join(\".\");\n } else {\n section = null;\n }\n yield `${key}=${value}`;\n }\n}\nfunction collapseSections(properties) {\n const sections = /* @__PURE__ */ new Map();\n for (const [key, value] of properties.entries()) {\n const [section] = key.split(\".\");\n const map = sections.get(section) ?? [];\n map.push([key, value]);\n sections.set(section, map);\n }\n return new Map(Array.from(sections.values()).flat());\n}\n\n// src/properties-path.ts\nfunction addLeaf(branch, leaf, key) {\n branch.leaves.set(leaf, key);\n if (Object.hasOwn(branch.branches, leaf)) {\n branch.branches[leaf].dual = true;\n }\n}\nfunction addBranch(branch, token) {\n const next = branch.branches[token] ??= childBranch(branch, token);\n if (branch.leaves.has(token)) {\n next.dual = true;\n }\n return next;\n}\nfunction childBranch(parent, child = \"\") {\n return {\n dual: false,\n leaves: /* @__PURE__ */ new Map(),\n branches: /* @__PURE__ */ Object.create(null),\n path: (parent?.path ? `${parent.path}.` : \"\") + child,\n parent\n };\n}\nfunction pathLayers(map) {\n const paths = childBranch(null);\n for (const key of map.keys()) {\n const tokens = key.split(\".\");\n const leaf = tokens.pop();\n const path = tokens.reduce((branch, token) => addBranch(branch, token), paths);\n addLeaf(path, leaf, key);\n }\n return paths;\n}\nfunction memoize(fn) {\n const cache = /* @__PURE__ */ new Map();\n return (key) => {\n if (!cache.has(key)) {\n cache.set(key, fn(key));\n }\n return cache.get(key);\n };\n}\nfunction propertiesPath(map) {\n const shape = pathLayers(map);\n const value = (layer, key) => {\n if (!key) {\n return map.get(layer.path);\n }\n const leaf = layer.leaves.get(key);\n const branch = Object.hasOwn(layer.branches, key);\n if (branch) {\n return make(layer.branches[key]);\n }\n return typeof leaf === \"string\" ? map.get(leaf) : void 0;\n };\n const make = memoize((layer) => {\n const ownKeys = /* @__PURE__ */ new Set([...layer.leaves.keys(), ...Object.keys(layer.branches)]);\n const target = Object.defineProperties(\n /* @__PURE__ */ Object.create(null),\n Object.fromEntries(\n [...ownKeys].map((name) => [\n name,\n {\n configurable: false,\n enumerable: true,\n get() {\n return value(layer, name);\n }\n }\n ])\n )\n );\n if (layer.dual) {\n Object.defineProperty(target, \"\", {\n configurable: false,\n enumerable: true,\n get() {\n return value(layer, \"\");\n }\n });\n }\n return target;\n });\n return make(shape);\n}\n\n// src/reader.ts\nvar createPropertiesReader = ({\n sourceFile,\n encoding = \"utf-8\",\n allowDuplicateSections = false,\n saveSections = true\n} = {}) => {\n const store = append(sourceFile, encoding);\n function entries(options = {}) {\n return options.parsed === true ? parsedEntries(store.properties) : store.properties.entries();\n }\n const instance = {\n get length() {\n return store.properties.size;\n },\n append(sourceFile2, enc = encoding) {\n append(sourceFile2, enc, store);\n return instance;\n },\n clone() {\n const next = createPropertiesReader({ allowDuplicateSections, encoding, saveSections });\n for (const [key, value] of store.properties.entries()) {\n next.set(key, value);\n }\n return next;\n },\n bindToExpress(app, basePath, makePaths = false) {\n return bindToExpress(instance, app, expressBasePath(basePath), makePaths);\n },\n each(fn, scope) {\n for (const [key, value] of store.properties.entries()) {\n fn.call(scope || instance, key, value);\n }\n return instance;\n },\n entries,\n get(key) {\n return parseValue(store.properties.get(key));\n },\n getAllProperties() {\n return Object.fromEntries(store.properties.entries());\n },\n getByRoot(root) {\n return getByRoot(store.properties, root);\n },\n getRaw(key) {\n return store.properties.has(key) ? store.properties.get(key) : null;\n },\n out() {\n return output(store.properties, allowDuplicateSections, saveSections);\n },\n path() {\n return propertiesPath(store.properties);\n },\n read(input) {\n read(typeof input === \"string\" ? input : input.toString(encoding), store);\n return instance;\n },\n save(destFile) {\n return save(destFile, instance.out());\n },\n set(key, value) {\n store.properties.set(key, String(value));\n return instance;\n }\n };\n return instance;\n};\n\n// src/index.ts\nvar index_default = createPropertiesReader;\nvar propertiesReader = createPropertiesReader;\nexport {\n bindToExpress,\n index_default as default,\n expressBasePath,\n propertiesReader\n};\n//# sourceMappingURL=index.mjs.map","import fs from 'node:fs';\n\nlet isDockerCached;\n\nfunction hasDockerEnv() {\n\ttry {\n\t\tfs.statSync('/.dockerenv');\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport default function isDocker() {\n\t// TODO: Use `??=` when targeting Node.js 16.\n\tif (isDockerCached === undefined) {\n\t\tisDockerCached = hasDockerEnv() || hasDockerCGroup();\n\t}\n\n\treturn isDockerCached;\n}\n","import fs from 'node:fs';\nimport isDocker from 'is-docker';\n\nlet cachedResult;\n\n// Podman detection\nconst hasContainerEnv = () => {\n\ttry {\n\t\tfs.statSync('/run/.containerenv');\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport default function isInsideContainer() {\n\t// TODO: Use `??=` when targeting Node.js 16.\n\tif (cachedResult === undefined) {\n\t\tcachedResult = hasContainerEnv() || isDocker();\n\t}\n\n\treturn cachedResult;\n}\n","import process from 'node:process';\nimport os from 'node:os';\nimport fs from 'node:fs';\nimport isInsideContainer from 'is-inside-container';\n\nconst isWsl = () => {\n\tif (process.platform !== 'linux') {\n\t\treturn false;\n\t}\n\n\tif (os.release().toLowerCase().includes('microsoft')) {\n\t\tif (isInsideContainer()) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tif (fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')) {\n\t\t\treturn !isInsideContainer();\n\t\t}\n\t} catch {}\n\n\t// Fallback for custom kernels: check WSL-specific paths.\n\tif (\n\t\tfs.existsSync('/proc/sys/fs/binfmt_misc/WSLInterop')\n\t\t|| fs.existsSync('/run/WSL')\n\t) {\n\t\treturn !isInsideContainer();\n\t}\n\n\treturn false;\n};\n\nexport default process.env.__IS_WSL_TEST__ ? isWsl : isWsl();\n","import process from 'node:process';\nimport {Buffer} from 'node:buffer';\nimport {promisify} from 'node:util';\nimport childProcess from 'node:child_process';\nimport fs, {constants as fsConstants} from 'node:fs/promises';\n\nconst execFile = promisify(childProcess.execFile);\n\nexport const powerShellPath = () => `${process.env.SYSTEMROOT || process.env.windir || String.raw`C:\\Windows`}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`;\n\n// Cache for PowerShell accessibility check\nlet canAccessCache;\n\nexport const canAccessPowerShell = async () => {\n\tcanAccessCache ??= (async () => {\n\t\ttry {\n\t\t\tawait fs.access(powerShellPath(), fsConstants.X_OK);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t})();\n\n\treturn canAccessCache;\n};\n\nexport const executePowerShell = async (command, options = {}) => {\n\tconst {\n\t\tpowerShellPath: psPath,\n\t\t...execFileOptions\n\t} = options;\n\n\tconst encodedCommand = executePowerShell.encodeCommand(command);\n\n\treturn execFile(\n\t\tpsPath ?? powerShellPath(),\n\t\t[\n\t\t\t...executePowerShell.argumentsPrefix,\n\t\t\tencodedCommand,\n\t\t],\n\t\t{\n\t\t\tencoding: 'utf8',\n\t\t\t...execFileOptions,\n\t\t},\n\t);\n};\n\nexecutePowerShell.argumentsPrefix = [\n\t'-NoProfile',\n\t'-NonInteractive',\n\t'-ExecutionPolicy',\n\t'Bypass',\n\t'-EncodedCommand',\n];\n\nexecutePowerShell.encodeCommand = command => Buffer.from(command, 'utf16le').toString('base64');\n\nexecutePowerShell.escapeArgument = value => `'${String(value).replaceAll('\\'', '\\'\\'')}'`;\n","export function parseMountPointFromConfig(content) {\n\tfor (const line of content.split('\\n')) {\n\t\t// Skip comment lines\n\t\tif (/^\\s*#/.test(line)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Match root at start of line (after optional whitespace)\n\t\tconst match = /^\\s*root\\s*=\\s*(?<mountPoint>\"[^\"]*\"|'[^']*'|[^#]*)/.exec(line);\n\t\tif (!match) {\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn match.groups.mountPoint\n\t\t\t.trim()\n\t\t\t// Strip surrounding quotes\n\t\t\t.replaceAll(/^[\"']|[\"']$/g, '');\n\t}\n}\n","import path from 'node:path';\nimport {promisify} from 'node:util';\nimport childProcess from 'node:child_process';\nimport fs, {constants as fsConstants} from 'node:fs/promises';\nimport isWsl from 'is-wsl';\nimport {powerShellPath as windowsPowerShellPath, executePowerShell} from 'powershell-utils';\nimport {parseMountPointFromConfig} from './utilities.js';\n\nconst execFile = promisify(childProcess.execFile);\n\nexport const wslDrivesMountPoint = (() => {\n\t// Default value for \"root\" param\n\t// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config\n\tconst defaultMountPoint = '/mnt/';\n\n\tlet mountPoint;\n\n\treturn async function () {\n\t\tif (mountPoint) {\n\t\t\t// Return memoized mount point value\n\t\t\treturn mountPoint;\n\t\t}\n\n\t\tconst configFilePath = '/etc/wsl.conf';\n\n\t\tlet isConfigFileExists = false;\n\t\ttry {\n\t\t\tawait fs.access(configFilePath, fsConstants.F_OK);\n\t\t\tisConfigFileExists = true;\n\t\t} catch {}\n\n\t\tif (!isConfigFileExists) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tconst configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});\n\t\tconst parsedMountPoint = parseMountPointFromConfig(configContent);\n\n\t\tif (parsedMountPoint === undefined) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tmountPoint = parsedMountPoint;\n\t\tmountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;\n\n\t\treturn mountPoint;\n\t};\n})();\n\nexport const powerShellPathFromWsl = async () => {\n\tconst mountPoint = await wslDrivesMountPoint();\n\treturn `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;\n};\n\nexport const powerShellPath = isWsl ? powerShellPathFromWsl : windowsPowerShellPath;\n\n// Cache for PowerShell accessibility check\nlet canAccessPowerShellPromise;\n\nexport const canAccessPowerShell = async () => {\n\tcanAccessPowerShellPromise ??= (async () => {\n\t\ttry {\n\t\t\tconst psPath = await powerShellPath();\n\t\t\tawait fs.access(psPath, fsConstants.X_OK);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// PowerShell is not accessible (either doesn't exist, no execute permission, or other error)\n\t\t\treturn false;\n\t\t}\n\t})();\n\n\treturn canAccessPowerShellPromise;\n};\n\nexport const wslDefaultBrowser = async () => {\n\tconst psPath = await powerShellPath();\n\tconst command = String.raw`(Get-ItemProperty -Path \"HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice\").ProgId`;\n\n\t// The spawned Windows process inherits the Linux working directory, which WSL exposes to Windows as a `\\\\wsl.localhost\\…` UNC path served by the distro's default user, so a directory that user cannot traverse makes the launch fail. PowerShell's own directory is on the Windows drive, so it always resolves to a plain `C:\\…` path.\n\tconst {stdout} = await executePowerShell(command, {\n\t\tpowerShellPath: psPath,\n\t\tcwd: path.dirname(psPath),\n\t});\n\n\treturn stdout.trim();\n};\n\nconst isUrl = path => /^[a-z]+:\\/\\//i.test(path);\n\nexport const convertWslPathToWindows = async paths => {\n\tconst isBatch = Array.isArray(paths);\n\tconst pathArray = isBatch ? paths : [paths];\n\n\t// Find indices of non-URL paths that need conversion\n\tconst indicesToConvert = [];\n\tconst pathsToConvert = [];\n\n\tfor (const [index, path] of pathArray.entries()) {\n\t\tif (!isUrl(path)) {\n\t\t\tindicesToConvert.push(index);\n\t\t\tpathsToConvert.push(path);\n\t\t}\n\t}\n\n\t// Start with original paths (URLs stay as-is)\n\tconst results = [...pathArray];\n\n\tif (pathsToConvert.length > 0) {\n\t\ttry {\n\t\t\tconst {stdout} = await execFile('wslpath', ['-aw', ...pathsToConvert], {encoding: 'utf8'});\n\t\t\tconst convertedPaths = stdout.split(/\\r?\\n/).filter(Boolean);\n\n\t\t\tfor (const [index, originalIndex] of indicesToConvert.entries()) {\n\t\t\t\tresults[originalIndex] = convertedPaths[index] ?? pathArray[originalIndex];\n\t\t\t}\n\t\t} catch {\n\t\t\t// If wslpath fails, keep original paths\n\t\t}\n\t}\n\n\treturn isBatch ? results : results[0];\n};\n\nexport const isUncPath = path => /^\\\\\\\\/u.test(path);\n\nexport const isPathOnWindowsFilesystem = async path => {\n\tconst windowsPath = await convertWslPathToWindows(path);\n\treturn !isUncPath(windowsPath);\n};\n\nexport const convertWindowsPathToWsl = async paths => {\n\tconst isBatch = Array.isArray(paths);\n\tconst pathArray = isBatch ? paths : [paths];\n\n\ttry {\n\t\tconst {stdout} = await execFile('wslpath', ['-u', ...pathArray], {encoding: 'utf8'});\n\t\tconst convertedPaths = stdout.split(/\\r?\\n/).filter(Boolean);\n\t\tconst results = pathArray.map((original, index) => convertedPaths[index] ?? original);\n\t\treturn isBatch ? results : results[0];\n\t} catch {\n\t\treturn isBatch ? pathArray : pathArray[0];\n\t}\n};\n\nexport {default as isWsl} from 'is-wsl';\n","import process from 'node:process';\nimport {Buffer} from 'node:buffer';\nimport {promisify} from 'node:util';\nimport childProcess from 'node:child_process';\nimport fs, {constants as fsConstants} from 'node:fs/promises';\n\nconst execFile = promisify(childProcess.execFile);\n\nexport const powerShellPath = () => `${process.env.SYSTEMROOT || process.env.windir || String.raw`C:\\Windows`}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`;\n\n// Cache for PowerShell accessibility check\nlet canAccessCache;\n\nexport const canAccessPowerShell = async () => {\n\tcanAccessCache ??= (async () => {\n\t\ttry {\n\t\t\tawait fs.access(powerShellPath(), fsConstants.X_OK);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t})();\n\n\treturn canAccessCache;\n};\n\nconst argumentsPrefix = [\n\t'-NoProfile',\n\t'-NonInteractive',\n\t'-ExecutionPolicy',\n\t'Bypass',\n\t'-EncodedCommand',\n];\n\nconst encodeCommand = command => Buffer.from(command, 'utf16le').toString('base64');\n\n/*\nPowerShell's tokenizer treats the typographic single quotes U+2018, U+2019, U+201A, and U+201B as string delimiters, exactly like the ASCII one, and it does not require the closing quote to match the opening quote. Escaping only the ASCII quote would let any of the others terminate the string and inject a statement. Doubling works for all of them.\n*/\nconst escapeArgument = value => `'${String(value).replaceAll(/['‘’‚‛]/g, match => match + match)}'`;\n\nconst createArguments = command => [...argumentsPrefix, encodeCommand(command)];\n\nconst createExecFileOptions = options => ({\n\tencoding: 'utf8',\n\t...options,\n\tshell: false,\n});\n\nexport const executePowerShell = async (command, options = {}) => {\n\tconst {\n\t\tpowerShellPath: psPath,\n\t\t...execFileOptions\n\t} = options;\n\n\treturn execFile(\n\t\tpsPath ?? powerShellPath(),\n\t\tcreateArguments(command),\n\t\tcreateExecFileOptions(execFileOptions),\n\t);\n};\n\nexecutePowerShell.argumentsPrefix = argumentsPrefix;\nexecutePowerShell.encodeCommand = encodeCommand;\nexecutePowerShell.escapeArgument = escapeArgument;\nexecutePowerShell.createArguments = createArguments;\n\nexport const executePowerShellSync = (command, options = {}) => {\n\tconst {\n\t\tpowerShellPath: psPath,\n\t\t...execFileOptions\n\t} = options;\n\n\treturn childProcess.execFileSync(\n\t\tpsPath ?? powerShellPath(),\n\t\tcreateArguments(command),\n\t\tcreateExecFileOptions(execFileOptions),\n\t);\n};\n","export default function defineLazyProperty(object, propertyName, valueGetter) {\n\tconst define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});\n\n\tObject.defineProperty(object, propertyName, {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\tget() {\n\t\t\tconst result = valueGetter();\n\t\t\tdefine(result);\n\t\t\treturn result;\n\t\t},\n\t\tset(value) {\n\t\t\tdefine(value);\n\t\t}\n\t});\n\n\treturn object;\n}\n","import {promisify} from 'node:util';\nimport process from 'node:process';\nimport {execFile} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\nexport default async function defaultBrowserId() {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst {stdout} = await execFileAsync('defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure', 'LSHandlers']);\n\n\t// `(?!-)` is to prevent matching `LSHandlerRoleAll = \"-\";`.\n\tconst match = /LSHandlerRoleAll = \"(?!-)(?<id>[^\"]+?)\";\\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);\n\n\tconst browserId = match?.groups.id ?? 'com.apple.Safari';\n\n\t// Correct the case for Safari's bundle identifier\n\tif (browserId === 'com.apple.safari') {\n\t\treturn 'com.apple.Safari';\n\t}\n\n\treturn browserId;\n}\n","import process from 'node:process';\nimport {promisify} from 'node:util';\nimport {execFile, execFileSync} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function runAppleScript(script, {humanReadableOutput = true, signal} = {}) {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst outputArguments = humanReadableOutput ? [] : ['-ss'];\n\n\tconst execOptions = {};\n\tif (signal) {\n\t\texecOptions.signal = signal;\n\t}\n\n\tconst {stdout} = await execFileAsync('osascript', ['-e', script, outputArguments], execOptions);\n\treturn stdout.trim();\n}\n\nexport function runAppleScriptSync(script, {humanReadableOutput = true} = {}) {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst outputArguments = humanReadableOutput ? [] : ['-ss'];\n\n\tconst stdout = execFileSync('osascript', ['-e', script, ...outputArguments], {\n\t\tencoding: 'utf8',\n\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\ttimeout: 500,\n\t});\n\n\treturn stdout.trim();\n}\n","import {runAppleScript} from 'run-applescript';\n\nexport default async function bundleName(bundleId) {\n\treturn runAppleScript(`tell application \"Finder\" to set app_path to application file id \"${bundleId}\" as string\\ntell application \"System Events\" to get value of property list item \"CFBundleName\" of property list file (app_path & \":Contents:Info.plist\")`);\n}\n","import process from 'node:process';\nimport {promisify} from 'node:util';\nimport {execFile} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\n// TODO: Fix the casing of bundle identifiers in the next major version.\n\n// Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake\n// ones that look real and match the macOS/Linux versions for cross-platform apps.\nconst windowsBrowserProgIds = {\n\tMSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // The missing `L` is correct.\n\tMSEdgeBHTML: {name: 'Edge Beta', id: 'com.microsoft.edge.beta'},\n\tMSEdgeDHTML: {name: 'Edge Dev', id: 'com.microsoft.edge.dev'},\n\tAppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'},\n\tChromeHTML: {name: 'Chrome', id: 'com.google.chrome'},\n\tChromeBHTML: {name: 'Chrome Beta', id: 'com.google.chrome.beta'},\n\tChromeDHTML: {name: 'Chrome Dev', id: 'com.google.chrome.dev'},\n\tChromiumHTM: {name: 'Chromium', id: 'org.chromium.Chromium'},\n\tBraveHTML: {name: 'Brave', id: 'com.brave.Browser'},\n\tBraveBHTML: {name: 'Brave Beta', id: 'com.brave.Browser.beta'},\n\tBraveDHTML: {name: 'Brave Dev', id: 'com.brave.Browser.dev'},\n\tBraveSSHTM: {name: 'Brave Nightly', id: 'com.brave.Browser.nightly'},\n\tFirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'},\n\tOperaStable: {name: 'Opera', id: 'com.operasoftware.Opera'},\n\tVivaldiHTM: {name: 'Vivaldi', id: 'com.vivaldi.Vivaldi'},\n\t'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'},\n};\n\nexport const _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));\n\nexport class UnknownBrowserError extends Error {}\n\nexport default async function defaultBrowser(_execFileAsync = execFileAsync) {\n\tconst regPath = `${process.env.SYSTEMROOT ?? process.env.windir ?? 'C:\\\\Windows'}\\\\System32\\\\reg.exe`;\n\tconst {stdout} = await _execFileAsync(regPath, [\n\t\t'QUERY',\n\t\t' HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\Shell\\\\Associations\\\\UrlAssociations\\\\http\\\\UserChoice',\n\t\t'/v',\n\t\t'ProgId',\n\t]);\n\n\tconst match = /ProgId\\s*REG_SZ\\s*(?<id>\\S+)/.exec(stdout);\n\tif (!match) {\n\t\tthrow new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);\n\t}\n\n\tconst {id} = match.groups;\n\n\t// Windows can append a hash suffix to ProgIds using a dot or hyphen\n\t// (e.g., `ChromeHTML.ABC123`, `FirefoxURL-6F193CCC56814779`).\n\t// Try exact match first, then try without the suffix.\n\tconst dotIndex = id.lastIndexOf('.');\n\tconst hyphenIndex = id.lastIndexOf('-');\n\tconst baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);\n\tconst baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);\n\n\treturn windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {name: id, id};\n}\n","import {promisify} from 'node:util';\nimport process from 'node:process';\nimport {execFile} from 'node:child_process';\nimport defaultBrowserId from 'default-browser-id';\nimport bundleName from 'bundle-name';\nimport windows from './windows.js';\n\nexport {_windowsBrowserProgIdMap} from './windows.js';\n\nconst execFileAsync = promisify(execFile);\n\n// Inlined: https://github.com/sindresorhus/titleize/blob/main/index.js\nconst titleize = string => string.toLowerCase().replaceAll(/(?:^|\\s|-)\\S/g, x => x.toUpperCase());\n\nexport default async function defaultBrowser() {\n\tif (process.platform === 'darwin') {\n\t\tconst id = await defaultBrowserId();\n\t\tconst name = await bundleName(id);\n\t\treturn {name, id};\n\t}\n\n\tif (process.platform === 'linux') {\n\t\tconst {stdout} = await execFileAsync('xdg-mime', ['query', 'default', 'x-scheme-handler/http']);\n\t\tconst id = stdout.trim();\n\t\tconst name = titleize(id.replace(/.desktop$/, '').replace('-', ' '));\n\t\treturn {name, id};\n\t}\n\n\tif (process.platform === 'win32') {\n\t\treturn windows();\n\t}\n\n\tthrow new Error('Only macOS, Linux, and Windows are supported');\n}\n","import process from 'node:process';\n\nconst isInSsh = Boolean(process.env.SSH_CONNECTION\n\t|| process.env.SSH_CLIENT\n\t|| process.env.SSH_TTY);\n\nexport default isInSsh;\n","import process from 'node:process';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport childProcess from 'node:child_process';\nimport fs, {constants as fsConstants} from 'node:fs/promises';\nimport {\n\tisWsl,\n\tpowerShellPath,\n\tconvertWslPathToWindows,\n\tcanAccessPowerShell,\n\twslDefaultBrowser,\n} from 'wsl-utils';\nimport {executePowerShell} from 'powershell-utils';\nimport defineLazyProperty from 'define-lazy-prop';\nimport defaultBrowser, {_windowsBrowserProgIdMap} from 'default-browser';\nimport isInsideContainer from 'is-inside-container';\nimport isInSsh from 'is-in-ssh';\n\nconst fallbackAttemptSymbol = Symbol('fallbackAttempt');\n\n// Path to included `xdg-open`.\nconst __dirname = import.meta.url ? path.dirname(fileURLToPath(import.meta.url)) : '';\nconst localXdgOpenPath = path.join(__dirname, 'xdg-open');\n\nconst {platform, arch} = process;\n\nconst tryEachApp = async (apps, opener) => {\n\tif (apps.length === 0) {\n\t\t// No app was provided\n\t\treturn;\n\t}\n\n\tconst errors = [];\n\n\tfor (const app of apps) {\n\t\ttry {\n\t\t\treturn await opener(app); // eslint-disable-line no-await-in-loop\n\t\t} catch (error) {\n\t\t\terrors.push(error);\n\t\t}\n\t}\n\n\tthrow new AggregateError(errors, 'Failed to open in all supported apps');\n};\n\n// eslint-disable-next-line complexity\nconst baseOpen = async options => {\n\toptions = {\n\t\twait: false,\n\t\tbackground: false,\n\t\tnewInstance: false,\n\t\tallowNonzeroExitCode: false,\n\t\t...options,\n\t};\n\n\tconst isFallbackAttempt = options[fallbackAttemptSymbol] === true;\n\tdelete options[fallbackAttemptSymbol];\n\n\tif (Array.isArray(options.app)) {\n\t\treturn tryEachApp(options.app, singleApp => baseOpen({\n\t\t\t...options,\n\t\t\tapp: singleApp,\n\t\t\t[fallbackAttemptSymbol]: true,\n\t\t}));\n\t}\n\n\tlet {name: app, arguments: appArguments = []} = options.app ?? {};\n\tappArguments = [...appArguments];\n\n\tif (Array.isArray(app)) {\n\t\treturn tryEachApp(app, appName => baseOpen({\n\t\t\t...options,\n\t\t\tapp: {\n\t\t\t\tname: appName,\n\t\t\t\targuments: appArguments,\n\t\t\t},\n\t\t\t[fallbackAttemptSymbol]: true,\n\t\t}));\n\t}\n\n\tif (app === 'browser' || app === 'browserPrivate') {\n\t\t// IDs from default-browser for macOS and windows are the same.\n\t\t// IDs are lowercased to increase chances of a match.\n\t\tconst ids = {\n\t\t\t'com.google.chrome': 'chrome',\n\t\t\t'google-chrome.desktop': 'chrome',\n\t\t\t'com.brave.browser': 'brave',\n\t\t\t'org.mozilla.firefox': 'firefox',\n\t\t\t'firefox.desktop': 'firefox',\n\t\t\t'com.microsoft.msedge': 'edge',\n\t\t\t'com.microsoft.edge': 'edge',\n\t\t\t'com.microsoft.edgemac': 'edge',\n\t\t\t'microsoft-edge.desktop': 'edge',\n\t\t\t'com.apple.safari': 'safari',\n\t\t};\n\n\t\t// Incognito flags for each browser in `apps`.\n\t\tconst flags = {\n\t\t\tchrome: '--incognito',\n\t\t\tbrave: '--incognito',\n\t\t\tfirefox: '--private-window',\n\t\t\tedge: '--inPrivate',\n\t\t\t// Safari doesn't support private mode via command line\n\t\t};\n\n\t\tlet browser;\n\t\tif (isWsl) {\n\t\t\tconst progId = await wslDefaultBrowser();\n\t\t\tconst browserInfo = _windowsBrowserProgIdMap.get(progId);\n\t\t\tbrowser = browserInfo ?? {};\n\t\t} else {\n\t\t\tbrowser = await defaultBrowser();\n\t\t}\n\n\t\tconst browserId = browser.id?.toLowerCase();\n\t\tif (Object.hasOwn(ids, browserId)) {\n\t\t\tconst browserName = ids[browserId];\n\n\t\t\tif (app === 'browserPrivate') {\n\t\t\t\t// Safari doesn't support private mode via command line\n\t\t\t\tif (browserName === 'safari') {\n\t\t\t\t\tthrow new Error('Safari doesn\\'t support opening in private mode via command line');\n\t\t\t\t}\n\n\t\t\t\tappArguments.push(flags[browserName]);\n\t\t\t}\n\n\t\t\treturn baseOpen({\n\t\t\t\t...options,\n\t\t\t\tapp: {\n\t\t\t\t\tname: apps[browserName],\n\t\t\t\t\targuments: appArguments,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tthrow new Error(`${browser.name} is not supported as a default browser`);\n\t}\n\n\tlet command;\n\tconst cliArguments = [];\n\tconst childProcessOptions = {};\n\n\t// Determine if we should use Windows/PowerShell behavior in WSL.\n\t// We only use Windows integration if PowerShell is actually accessible.\n\t// This allows the package to work in sandboxed WSL environments where Windows access is restricted.\n\tlet shouldUseWindowsInWsl = false;\n\tif (isWsl && !isInsideContainer() && !isInSsh && !app) {\n\t\tshouldUseWindowsInWsl = await canAccessPowerShell();\n\t}\n\n\tif (platform === 'darwin') {\n\t\tcommand = 'open';\n\n\t\tif (options.wait) {\n\t\t\tcliArguments.push('--wait-apps');\n\t\t}\n\n\t\tif (options.background) {\n\t\t\tcliArguments.push('--background');\n\t\t}\n\n\t\tif (options.newInstance) {\n\t\t\tcliArguments.push('--new');\n\t\t}\n\n\t\tif (app) {\n\t\t\tcliArguments.push('-a', app);\n\t\t}\n\t} else if (platform === 'win32' || shouldUseWindowsInWsl) {\n\t\tcommand = await powerShellPath();\n\n\t\tcliArguments.push(...executePowerShell.argumentsPrefix);\n\n\t\tif (!isWsl) {\n\t\t\tchildProcessOptions.windowsVerbatimArguments = true;\n\t\t}\n\n\t\t// Convert WSL Linux paths to Windows paths\n\t\tif (isWsl && options.target) {\n\t\t\toptions.target = await convertWslPathToWindows(options.target);\n\t\t}\n\n\t\t// Suppress PowerShell progress messages that are written to stderr\n\t\tconst encodedArguments = ['$ProgressPreference = \\'SilentlyContinue\\';', 'Start'];\n\n\t\tif (options.wait) {\n\t\t\tencodedArguments.push('-Wait');\n\t\t}\n\n\t\tif (app) {\n\t\t\tencodedArguments.push(executePowerShell.escapeArgument(app));\n\t\t\tif (options.target) {\n\t\t\t\tappArguments.push(options.target);\n\t\t\t}\n\t\t} else if (options.target) {\n\t\t\tencodedArguments.push(executePowerShell.escapeArgument(options.target));\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tappArguments = appArguments.map(argument => executePowerShell.escapeArgument(argument));\n\t\t\tencodedArguments.push('-ArgumentList', appArguments.join(','));\n\t\t}\n\n\t\t// Using Base64-encoded command, accepted by PowerShell, to allow special characters.\n\t\toptions.target = executePowerShell.encodeCommand(encodedArguments.join(' '));\n\n\t\tif (!options.wait) {\n\t\t\t// PowerShell will keep the parent process alive unless stdio is ignored.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t}\n\n\t\tif (isWsl) {\n\t\t\t// The spawned Windows process inherits the Linux working directory, which WSL exposes to Windows as a `\\\\wsl.localhost\\…` UNC path served by the distro's default user, so a directory that user cannot traverse makes the launch fail. PowerShell's own directory is on the Windows drive, so it always resolves to a plain `C:\\…` path. Nothing here uses the working directory as the target is a URL or an absolute Windows path.\n\t\t\tchildProcessOptions.cwd = path.dirname(command);\n\t\t}\n\t} else {\n\t\tif (app) {\n\t\t\tcommand = app;\n\t\t} else {\n\t\t\t// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.\n\t\t\tconst isBundled = !__dirname || __dirname === '/';\n\n\t\t\t// Check if local `xdg-open` exists and is executable.\n\t\t\tlet exeLocalXdgOpen = false;\n\t\t\ttry {\n\t\t\t\tawait fs.access(localXdgOpenPath, fsConstants.X_OK);\n\t\t\t\texeLocalXdgOpen = true;\n\t\t\t} catch {}\n\n\t\t\tconst useSystemXdgOpen = process.versions.electron\n\t\t\t\t?? (platform === 'android' || isBundled || !exeLocalXdgOpen);\n\t\t\tcommand = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tcliArguments.push(...appArguments);\n\t\t}\n\n\t\tif (!options.wait) {\n\t\t\t// `xdg-open` will block the process unless stdio is ignored\n\t\t\t// and it's detached from the parent even if it's unref'd.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t\tchildProcessOptions.detached = true;\n\t\t}\n\t}\n\n\tif (platform === 'darwin' && appArguments.length > 0) {\n\t\tcliArguments.push('--args', ...appArguments);\n\t}\n\n\t// IMPORTANT: On macOS, the target MUST come AFTER '--args'.\n\t// When using --args, ALL following arguments are passed to the app.\n\t// Example: open -a \"chrome\" --args --incognito https://site.com\n\t// This passes BOTH --incognito AND https://site.com to Chrome.\n\t// Without this order, Chrome won't open in incognito. See #332.\n\tif (options.target) {\n\t\tcliArguments.push(options.target);\n\t}\n\n\tconst subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);\n\n\tif (options.wait) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\tif (!options.allowNonzeroExitCode && exitCode !== 0) {\n\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve(subprocess);\n\t\t\t});\n\t\t});\n\t}\n\n\t// When we're in a fallback attempt, we need to detect launch failures before trying the next app.\n\t// Wait for the close event to check the exit code before unreffing.\n\t// The launcher (open/xdg-open/PowerShell) exits quickly (~10-30ms) even on success.\n\n\t/*\n\tThe PowerShell launcher must ALWAYS be awaited until it closes, even when not waiting for the app. Do not change this to resolve on `spawn`. See #367.\n\n\tPowerShell needs a few hundred milliseconds before it runs `Start-Process`, and libuv puts non-detached children in a job object that kills them when the parent exits. So a CLI that exits right after `await open()` silently kills PowerShell before anything opens. The launched app itself survives, since the job object allows breakaway for grandchildren, and `Start-Process` returns as soon as it has launched the app, so this does not wait for the app.\n\n\tBefore v11, piped stdio kept the parent alive until PowerShell exited, which hid this. Detaching the launcher instead is unverified (PowerShell would get no console), while waiting is what worked before.\n\t*/\n\tif (isFallbackAttempt || platform === 'win32' || shouldUseWindowsInWsl) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('spawn', () => {\n\t\t\t\t// Keep error handler active for post-spawn errors\n\t\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\t\tsubprocess.off('error', reject);\n\n\t\t\t\t\t// Only fallback attempts check the exit code, to detect a missing app. Other launches never do when not waiting for the app.\n\t\t\t\t\tif (isFallbackAttempt && exitCode !== 0) {\n\t\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tsubprocess.unref();\n\t\t\t\t\tresolve(subprocess);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}\n\n\tsubprocess.unref();\n\n\t// Handle spawn errors before the caller can attach listeners.\n\t// This prevents unhandled error events from crashing the process.\n\treturn new Promise((resolve, reject) => {\n\t\tsubprocess.once('error', reject);\n\n\t\t// Wait for the subprocess to spawn before resolving.\n\t\t// This ensures the process is established before the caller continues,\n\t\t// preventing issues when process.exit() is called immediately after.\n\t\tsubprocess.once('spawn', () => {\n\t\t\tsubprocess.off('error', reject);\n\t\t\tresolve(subprocess);\n\t\t});\n\t});\n};\n\nconst open = (target, options) => {\n\tif (typeof target !== 'string') {\n\t\tthrow new TypeError('Expected a `target`');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\ttarget,\n\t});\n};\n\nexport const openApp = (name, options) => {\n\tif (typeof name !== 'string' && !Array.isArray(name)) {\n\t\tthrow new TypeError('Expected a valid `name`');\n\t}\n\n\tconst {arguments: appArguments = []} = options ?? {};\n\tif (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {\n\t\tthrow new TypeError('Expected `appArguments` as Array type');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\tapp: {\n\t\t\tname,\n\t\t\targuments: appArguments,\n\t\t},\n\t});\n};\n\nfunction detectArchBinary(binary) {\n\tif (typeof binary === 'string' || Array.isArray(binary)) {\n\t\treturn binary;\n\t}\n\n\tconst {[arch]: archBinary} = binary;\n\n\tif (!archBinary) {\n\t\tthrow new Error(`${arch} is not supported`);\n\t}\n\n\treturn archBinary;\n}\n\nfunction detectPlatformBinary({[platform]: platformBinary}, {wsl} = {}) {\n\tif (wsl && isWsl) {\n\t\treturn detectArchBinary(wsl);\n\t}\n\n\tif (!platformBinary) {\n\t\tthrow new Error(`${platform} is not supported`);\n\t}\n\n\treturn detectArchBinary(platformBinary);\n}\n\nexport const apps = {\n\tbrowser: 'browser',\n\tbrowserPrivate: 'browserPrivate',\n};\n\ndefineLazyProperty(apps, 'chrome', () => detectPlatformBinary({\n\tdarwin: 'google chrome',\n\twin32: 'chrome',\n\t// `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.\n\tlinux: ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'],\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',\n\t\tx64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'],\n\t},\n}));\n\ndefineLazyProperty(apps, 'brave', () => detectPlatformBinary({\n\tdarwin: 'brave browser',\n\twin32: 'brave',\n\tlinux: ['brave-browser', 'brave'],\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe',\n\t\tx64: ['/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe', '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe'],\n\t},\n}));\n\ndefineLazyProperty(apps, 'firefox', () => detectPlatformBinary({\n\tdarwin: 'firefox',\n\twin32: String.raw`C:\\Program Files\\Mozilla Firefox\\firefox.exe`,\n\tlinux: 'firefox',\n}, {\n\twsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe',\n}));\n\ndefineLazyProperty(apps, 'edge', () => detectPlatformBinary({\n\tdarwin: 'microsoft edge',\n\twin32: 'msedge',\n\tlinux: ['microsoft-edge', 'microsoft-edge-dev'],\n}, {\n\twsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',\n}));\n\ndefineLazyProperty(apps, 'safari', () => detectPlatformBinary({\n\tdarwin: 'Safari',\n}));\n\nexport default open;\n","/**\n * The active action command's registry, split from\n * `ResolveInteractiveInputs.ts` the same way PromptGateState is split from\n * PromptGate: a zero-import state module that heavier layers (ops/ --\n * specifically AuthenticateOps's post-auth realm picker) can import\n * without dragging the resolution pass's graph along.\n *\n * That matters for tests that mock `@rockcarver/frodo-lib` wholesale\n * (test/unit/mcp-server-ops.test.js): the mock's namespace only carries\n * what its graph actually loads, so any ops->cli edge pulling in the\n * frodo-lib-importing interactive prompts (ColorTheme's `theme` import)\n * fails the graph walk with \"does not provide an export named 'theme'\".\n * Importing this leaf module instead keeps that edge dependency-free.\n */\n\nimport type { Command } from 'commander';\n\n/**\n * The leaf command whose action is about to run, recorded by the\n * resolution pass. Post-auth hooks that have no command reference of\n * their own (the getTokens wrapper consults the realm picker, which\n * needs the command to check for a realm argument) read this instead of\n * threading the command through every call site.\n */\nlet activeActionCommand: Command | undefined;\n\n/**\n * Records the leaf command about to execute (and clears it, for test\n * hygiene between invocations).\n */\nexport function setActiveActionCommand(command: Command | undefined): void {\n activeActionCommand = command;\n}\n\n/**\n * The leaf command recorded by the resolution pass, if any.\n */\nexport function getActiveActionCommand(): Command | undefined {\n return activeActionCommand;\n}\n","import { readSync } from 'node:fs';\n\n/**\n * Prompt the user and return the line they typed. Synchronous, because the\n * one caller (the MFA OTP callback handler in `ops/AuthenticateOps.ts`) is\n * invoked from frodo-lib's *synchronous* `CallbackHandler` contract, which\n * cannot await a promise.\n *\n * Replaces `readline-sync` (unmaintained since 2016). Reading stdin directly\n * is what readline-sync itself did; `readSync` on fd 0 blocks until a full\n * line is available.\n *\n * @param {string} question text printed before reading input\n * @returns {string} the user's answer with the trailing newline removed\n */\nexport function question(question: string): string {\n process.stdout.write(question);\n const buffer = Buffer.alloc(1024);\n const bytesRead = readSync(0, buffer, 0, buffer.length, null);\n return buffer\n .subarray(0, bytesRead)\n .toString('utf8')\n .replace(/\\r?\\n$/, '');\n}\n","import {\n frodo,\n state,\n type BrowserLoginOptions,\n type BrowserLoginPrompt,\n type BrowserLoginPromptHandler,\n type Callback,\n type CallbackHandler,\n type Tokens,\n} from '@rockcarver/frodo-lib';\nimport open from 'open';\nimport { printError, printMessage, verboseMessage } from '../utils/Console';\n// The active-command registry, not ResolveInteractiveInputs itself: that\n// file's graph reaches the frodo-lib-importing interactive prompts, which\n// breaks tests that mock frodo-lib wholesale (see ActiveActionCommandState).\nimport { getActiveActionCommand } from '../utils/interactive/ActiveActionCommandState';\n// The credential vocabulary lives in the interactive layer\n// (ConnectionProfilePickers -- both the profile preference picker and\n// this per-invocation override speak the same words); imported for use\n// below AND re-exported so ops/ and cli/ consumers keep their\n// established import path.\nimport type { CredentialOverrideType } from '../utils/interactive/ConnectionProfilePickers';\nimport { EXIT_ALL_SIGNAL } from '../utils/interactive/ExitAll';\nimport { canPrompt } from '../utils/interactive/PromptGateState';\nimport { question } from '../utils/Prompt';\n\nexport type { CredentialOverrideType };\n\nconst { getTokens: _getTokens, getTokensInteractive: _getTokensInteractive } =\n frodo.login;\nconst { DEPLOYMENT_TYPES } = frodo.utils.constants;\n\nconst otpCallbackHandler: CallbackHandler = (callback: Callback) => {\n if (callback.type != 'NameCallback')\n throw new Error(`Unsupported callback: ${callback.type}`);\n printMessage(\n `Multi-factor authentication is enabled and required for this user.`\n );\n callback.input[0].value = question(`${callback.output[0].value}: `);\n return callback;\n};\n\n/**\n * Whether an interactive browser login started via this CLI process should\n * use the OAuth2 Device Authorization Grant instead of the default\n * loopback-redirect flow. Set by `--device`/`FRODO_LOGIN_DEVICE_FLOW` (see\n * `FrodoCommand.ts`) or by `frodo login --device`. Kept as module-scoped\n * state rather than on frodo-lib's `state`, since it's a one-shot,\n * per-invocation UX choice, not session identity.\n */\nlet useDeviceFlowOverride: boolean | undefined;\n\nexport function setUseDeviceFlow(value: boolean): void {\n useDeviceFlowOverride = value;\n}\n\nexport function getUseDeviceFlow(): boolean {\n return (\n useDeviceFlowOverride ?? process.env.FRODO_LOGIN_DEVICE_FLOW === 'true'\n );\n}\n\n/**\n * Whether an implicit (non-interactive) command's own `getTokens()` call\n * should force a plain username/password login even when the resolved\n * connection profile also has a service account (or Amster) credential\n * configured — set by `--force-login-as-user`/`FRODO_FORCE_LOGIN_AS_USER`\n * (see `FrodoCommand.ts`). Same reasoning as `useDeviceFlowOverride` above:\n * a one-shot, per-invocation choice, not session identity, so it lives here\n * rather than on frodo-lib's `state`. Threads straight through to\n * frodo-lib's own `getTokens({forceLoginAsUser})` parameter — this is not a\n * new mechanism, just the first way to reach it from an arbitrary command\n * instead of only the one hardcoded internal call site (`conn-save.ts`).\n */\nlet forceLoginAsUserOverride: boolean | undefined;\n\nexport function setForceLoginAsUser(value: boolean): void {\n forceLoginAsUserOverride = value;\n}\n\nexport function getForceLoginAsUserOverride(): boolean {\n // Truthy-string check (not a strict === 'true'), matching frodo-lib's own\n // reading of this exact same env var name in AuthenticateOps.ts's\n // getTokens() default parameter — frodo-cli's wrapper always passes an\n // explicit boolean through, so that default never actually applies once\n // routed through here, but the same env var name should mean the same\n // thing regardless of which layer happens to read it.\n return forceLoginAsUserOverride ?? !!process.env.FRODO_FORCE_LOGIN_AS_USER;\n}\n\n/**\n * Which configured credential type this one invocation should use,\n * overriding ambient browser-session cache reuse and any saved\n * defaultCredential/forceLoginAsUser preference — set by\n * `--credential`/`FRODO_CREDENTIAL` (see `FrodoCommand.ts`). The union\n * itself lives in the interactive layer (ConnectionProfilePickers --\n * both the profile preference picker and this per-invocation override\n * speak the same credential vocabulary), re-exported here so ops/ and\n * cli/ consumers keep their established import path.\n */\nlet credentialOverride: CredentialOverrideType | undefined;\n\nexport function setCredentialOverride(value: CredentialOverrideType): void {\n credentialOverride = value;\n}\n\nexport function getCredentialOverride(): CredentialOverrideType | undefined {\n const envValue = process.env.FRODO_CREDENTIAL;\n return (\n credentialOverride ??\n (envValue === 'user' ||\n envValue === 'svcacct' ||\n envValue === 'amster' ||\n envValue === 'browser'\n ? envValue\n : undefined)\n );\n}\n\n/**\n * Whether `cliBrowserLoginPromptHandler` should try to launch a local\n * browser for the loopback-redirect flow, as opposed to only ever printing\n * the URL (for remote/SSH sessions with no usable local browser). Defaults\n * to true; set to false via `frodo login --no-open`.\n */\nlet openBrowser = true;\n\nexport function setOpenBrowser(value: boolean): void {\n openBrowser = value;\n}\n\n/**\n * Presents an interactive browser-login step on the CLI: launches the\n * system browser for the loopback-redirect flow, or prints the user code\n * and verification URL for the device-authorization flow.\n *\n * @remarks\n * The authorize URL itself is always printed too, even when the system\n * browser opens successfully — not just as a fallback for when launching\n * one fails or was disabled via `setOpenBrowser(false)`. The auto-opened\n * browser is whatever the OS considers the default, which isn't\n * necessarily the one the login should actually happen in (e.g. a profile\n * with the right admin session, or a clean one with no extensions that\n * might interfere with the loopback redirect) — printing the URL\n * unconditionally lets the user open it in a different browser themselves\n * without having to first watch the automatic launch fail.\n */\nexport const cliBrowserLoginPromptHandler: BrowserLoginPromptHandler = async (\n prompt: BrowserLoginPrompt\n) => {\n if (prompt.userCode && prompt.verificationUri) {\n printMessage(`To complete login, open this URL in any browser:`);\n printMessage(` ${prompt.verificationUri}`);\n printMessage(`and enter this code when prompted:`);\n printMessage(` ${prompt.userCode}`);\n return;\n }\n if (prompt.authorizeUrl) {\n if (openBrowser) {\n printMessage(`Opening browser to complete login...`);\n try {\n await open(prompt.authorizeUrl);\n printMessage(\n `If you'd rather use a different browser, open this URL manually:`\n );\n } catch {\n printMessage(\n `Could not open a browser automatically. Open this URL manually to complete login:`,\n 'warn'\n );\n }\n } else {\n printMessage(`Open this URL in any browser to complete login:`);\n }\n printMessage(` ${prompt.authorizeUrl}`);\n }\n};\n\n/**\n * Get tokens and store them in State\n * @param {boolean} forceLoginAsUser true to force login as user even if a service account is available (default: false). Also forced by the global --force-login-as-user option/FRODO_FORCE_LOGIN_AS_USER env var (see getForceLoginAsUserOverride()) regardless of this parameter. Deprecated — use --credential user (getCredentialOverride()) instead; kept for backward compatibility and overridden by it when both are set.\n * @param {boolean} autoRefresh true to automatically refresh tokens before they expire (default: true)\n * @param {string[]} types Array of supported deployment types. The function will throw an error if an unsupported type is detected (default: ['classic', 'cloud', 'forgeops'])\n * @returns {Promise<Tokens>} object containing the tokens\n */\nexport async function getTokens(\n forceLoginAsUser: boolean = false,\n autoRefresh: boolean = true,\n types: string[] = DEPLOYMENT_TYPES\n): Promise<boolean> {\n try {\n const tokens = await _getTokens(\n // The caller's own explicit request always wins; otherwise fall back\n // to the global --force-login-as-user/FRODO_FORCE_LOGIN_AS_USER\n // override, so any implicit command (not just conn-save.ts's own\n // hardcoded call) can force a plain username/password login over a\n // profile's configured service account/Amster credential. Ignored by\n // frodo-lib whenever credentialOverride below is also set.\n forceLoginAsUser || getForceLoginAsUserOverride(),\n autoRefresh,\n types,\n otpCallbackHandler,\n getUseDeviceFlow(),\n cliBrowserLoginPromptHandler,\n getCredentialOverride()\n );\n verboseMessage(\n `Connected to ${state.getHost()} [${\n state.getRealm() ? state.getRealm() : 'root'\n }] as ${tokens.subject}`\n );\n // Post-auth realm picker: offers the target system's realms\n // when the command has a realm argument, the user left it at its\n // default, and the system has more than one realm. Never throws; a\n // declined offer or an unlistable realm set keeps the default. The\n // active command is recorded by the resolution pass (preAction), so\n // commands that bypass it (login/conn's own stub actions) naturally\n // never see a picker.\n //\n // Gated on canPrompt() and lazy-imported: this module must stay\n // loadable in tests that mock frodo-lib wholesale (the picker's graph\n // reaches ColorTheme's `theme` import, which such mocks don't carry),\n // and a non-interactive session never needs the picker's machinery.\n if (canPrompt()) {\n const { resolveRealmPick } =\n await import('../utils/interactive/RealmPickers');\n await resolveRealmPick(getActiveActionCommand());\n }\n // The deferred authoring print: flushed\n // HERE so the eventual command lands directly above the action's\n // results (the print is a header for the output, not a footer after\n // it) -- every auth command's action prints its results only after\n // getTokens returns true, and the realm pick (which can still change\n // the command) has concluded by now. SKIPPED when the command has\n // entity picks still PENDING (registered and their option unset --\n // they run later in the action body and may still change the\n // command): resolveEntityPicks flushes after its picks conclude\n // instead. Picks already applied before auth (the pick-first pattern)\n // do NOT block this flush -- their option is set, nothing pending.\n // Arming-only sessions (no prompts, not explicitly interactive) flush\n // as a no-op via the closure's gate.\n {\n const { noteAuthSucceeded, flushAuthoringPrint } =\n await import('../utils/interactive/AuthoringPrintState');\n noteAuthSucceeded();\n const activeCommand = getActiveActionCommand();\n const hasPendingPicks = await (async () => {\n if (!activeCommand) return false;\n const { getEntityPicks } =\n await import('../utils/interactive/EntityPickers');\n return getEntityPicks(activeCommand).some(\n (pick) => !activeCommand.getOptionValue(pick.name)\n );\n })();\n if (!hasPendingPicks) {\n flushAuthoringPrint();\n }\n }\n return true;\n } catch (error) {\n // The exit-all unwind is not an auth failure -- rethrow it so it\n // reaches app.ts's top-level handler (the realm/entity pickers throw\n // the signal from inside this try).\n if (error === EXIT_ALL_SIGNAL) throw error;\n printError(error);\n // Auth failed: the command never ran -- revoke the deferred print so\n // the postAction fallback (whose only remaining purpose is non-auth\n // commands) leaves nothing behind for a failed auth attempt.\n {\n const { revokeAuthoringPrint } =\n await import('../utils/interactive/AuthoringPrintState');\n revokeAuthoringPrint();\n }\n }\n return false;\n}\n\n/**\n * Get tokens via a real interactive browser login (loopback-redirect or\n * device-authorization grant), bypassing `getTokens()`'s password/service-\n * account/Amster fallback chain entirely. Used by `frodo login --browser`.\n * @param {Omit<BrowserLoginOptions, 'promptHandler'>} options browser-login options; the CLI always supplies its own promptHandler\n * @returns {Promise<Tokens>} object containing the tokens, or null on failure\n */\nexport async function getTokensInteractive(\n options: Omit<BrowserLoginOptions, 'promptHandler'>\n): Promise<Tokens> {\n try {\n const tokens = await _getTokensInteractive({\n ...options,\n useDeviceFlow: options.useDeviceFlow ?? getUseDeviceFlow(),\n promptHandler: cliBrowserLoginPromptHandler,\n });\n verboseMessage(\n `Connected to ${state.getHost()} [${\n state.getRealm() ? state.getRealm() : 'root'\n }] as ${tokens.subject}`\n );\n return tokens;\n } catch (error) {\n printError(error);\n }\n return null;\n}\n","import fs from 'fs';\nimport {\n frodo,\n type ServerExportInterface,\n type ServerExportOptions,\n type ServerExportSkeleton,\n type ServerImportOptions,\n} from '@rockcarver/frodo-lib';\nimport { extractDataToFile, getExtractedJsonData } from '../../utils/Config';\nimport {\n createProgressIndicator,\n createTable,\n debugMessage,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../../utils/Console';\n\nconst {\n getTypedFilename,\n saveJsonToFile,\n getFilePath,\n getWorkingDirectory,\n readFiles,\n} = frodo.utils;\n\nconst {\n readServers,\n exportServer,\n exportServerByUrl,\n exportServers,\n importServers,\n importFirstServer,\n} = frodo.server;\n\n/**\n * List servers\n * @param {boolean} [long=false] detailed list\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listServers(long: boolean = false): Promise<boolean> {\n try {\n const servers = await readServers();\n if (long) {\n const table = createTable(['Id', 'Url', 'Site Name']);\n for (const server of servers) {\n table.push([server._id, server.url, server.siteName]);\n }\n printMessage(table.toString(), 'data');\n } else {\n servers.forEach((server) => {\n printMessage(`${server.url}`, 'data');\n });\n }\n return true;\n } catch (error) {\n printError(error, `Error listing servers`);\n }\n return false;\n}\n\n/**\n * Export server to file\n * @param {string} serverId server id\n * @param {string} serverUrl server url\n * @param {string} file file name\n * @param {boolean} extract true to extract the server properties from the export, false otherwise\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {ServerExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportServerToFile(\n serverId: string,\n serverUrl: string,\n file: string,\n extract: boolean = false,\n includeMeta: boolean = true,\n options: ServerExportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n const name = serverUrl ? serverUrl : serverId;\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${name}...`\n );\n try {\n let exportData: ServerExportInterface;\n if (serverId) {\n exportData = await exportServer(serverId, options);\n } else {\n exportData = await exportServerByUrl(serverUrl, options);\n }\n updateProgressIndicator(indicatorId, `Saving ${name} to file...`);\n saveServersToFiles(exportData, file, undefined, extract, includeMeta);\n stopProgressIndicator(\n indicatorId,\n `Exported server ${name} to file`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error exporting server ${name} to file`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all servers to file\n * @param {string} file file name\n * @param {boolean} extract true to extract the server properties from the export, false otherwise\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {ServerExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportServersToFile(\n file: string,\n extract: boolean = false,\n includeMeta: boolean = true,\n options: ServerExportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportServers(options);\n let fileName = getTypedFilename(`allServers`, 'server');\n if (file) {\n fileName = file;\n }\n saveServersToFiles(exportData, fileName, undefined, extract, includeMeta);\n return true;\n } catch (error) {\n printError(error, `Error exporting servers to file`);\n }\n return false;\n}\n\n/**\n * Export all servers to separate files\n * @param {boolean} extract true to extract the server properties from the export, false otherwise\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {ServerExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportServersToFiles(\n extract: boolean = false,\n includeMeta: boolean = true,\n options: ServerExportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportServers(options);\n saveServersToFiles(\n exportData,\n undefined,\n getWorkingDirectory(true),\n extract,\n includeMeta\n );\n return true;\n } catch (error) {\n printError(error, `Error exporting servers to files`);\n }\n return false;\n}\n\n/**\n * Import a server from file\n * @param {string} serverId server id\n * @param {string} serverUrl server url\n * @param {string} file import file name\n * @param {ServerImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importServerFromFile(\n serverId: string,\n serverUrl: string,\n file: string,\n options: ServerImportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Reading server from file...'\n );\n const path = getFilePath(file);\n const content = fs.readFileSync(path, 'utf8');\n const importData = readServersFromFiles([\n {\n path,\n content,\n },\n ]);\n updateProgressIndicator(indicatorId, 'Importing server...');\n await importServers(importData, options, serverId, serverUrl);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported server ${serverUrl ? serverUrl : serverId}.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing server ${serverUrl ? serverUrl : serverId}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Import servers from file\n * @param {String} file file name\n * @param {ServerImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importServersFromFile(\n file: string,\n options: ServerImportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n try {\n debugMessage(`importServersFromFile: start`);\n debugMessage(`importServersFromFile: importing ${file}`);\n const path = getFilePath(file);\n const content = fs.readFileSync(path, 'utf8');\n const importData = readServersFromFiles([\n {\n path,\n content,\n },\n ]);\n await importServers(importData, options);\n debugMessage(`importServersFromFile: end`);\n return true;\n } catch (error) {\n printError(error, `Error importing servers from file`);\n }\n return false;\n}\n\n/**\n * Import all servers from separate files\n * @param {ServerImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importServersFromFiles(\n options: ServerImportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n try {\n const importData = readServersFromFiles(\n (await readFiles(getWorkingDirectory())).filter(\n (f) =>\n f.path.endsWith('.server.json') &&\n !f.path.endsWith('.properties.server.json')\n )\n );\n await importServers(importData, options);\n return true;\n } catch (error) {\n printError(error, `Error importing servers from files`);\n }\n return false;\n}\n\n/**\n * Import first server from file\n * @param {string} file import file name\n * @param {ServerImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importFirstServerFromFile(\n file: string,\n options: ServerImportOptions = {\n includeDefault: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Importing server...'\n );\n const path = getFilePath(file);\n const content = fs.readFileSync(path, 'utf8');\n const importData = readServersFromFiles([\n {\n path,\n content,\n },\n ]);\n await importFirstServer(importData, options);\n stopProgressIndicator(\n indicatorId,\n `Imported server from ${file}`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing server from ${file}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Helper that saves servers from export to files in a directory, or to a single file, depending on which is provided.\n *\n * @param {ServerExportInterface} exportData the server export\n * @param {string} file the file to save to; overrides directory if both are provided.\n * @param {string} directory the optional directory to save to; default is working directory\n * @param {boolean} extract true to extract server properties to separate files. Default: false\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n */\nexport function saveServersToFiles(\n exportData: ServerExportInterface,\n file?: string,\n directory: string = getWorkingDirectory(true),\n extract: boolean = false,\n includeMeta: boolean = true\n): void {\n const workingDirectory = getWorkingDirectory();\n const relativeDirectory = directory.substring(\n workingDirectory.length + (workingDirectory.endsWith('/') ? 0 : 1)\n );\n if (\n extract &&\n exportData.defaultProperties &&\n Object.keys(exportData.defaultProperties).length > 0\n ) {\n // Save default server properties separately in their own directory\n Object.entries(exportData.defaultProperties).forEach(\n ([name, props]: [string, any]) => {\n exportData.defaultProperties[name] = extractDataToFile(\n props,\n `default/${getTypedFilename(name, 'default.properties.server')}`,\n relativeDirectory\n );\n }\n );\n }\n Object.entries(exportData.server).forEach(\n ([serverId, server]: [string, any]) => {\n if (extract) {\n // Save server properties separately in their own directories\n for (const [name, props] of Object.entries(server.properties)) {\n server.properties[name] = extractDataToFile(\n props,\n `${serverId}/${getTypedFilename(name, 'properties.server')}`,\n relativeDirectory\n );\n }\n }\n if (!file) {\n // Save server export data\n const fileName = getTypedFilename(serverId, 'server');\n saveJsonToFile(\n {\n server: {\n [serverId]: server,\n },\n defaultProperties: exportData.defaultProperties,\n },\n `${directory}/${fileName}`,\n includeMeta\n );\n }\n }\n );\n if (file) {\n saveJsonToFile(exportData, getFilePath(file, true), includeMeta);\n }\n}\n\n/**\n * Helper that reads servers from export files\n *\n * @param {Array} files the server files to read from\n */\nexport function readServersFromFiles(\n files: {\n path: string;\n content: string;\n }[]\n): ServerExportInterface {\n const exportData = {\n server: {},\n defaultProperties: {},\n };\n for (const f of files) {\n const data = JSON.parse(f.content);\n for (const [id, server] of Object.entries(data.server)) {\n for (const [key, value] of Object.entries(\n (server as ServerExportSkeleton).properties\n )) {\n if (typeof value === 'string') {\n (server as ServerExportSkeleton).properties[key] =\n getExtractedJsonData(\n value,\n f.path.substring(0, f.path.lastIndexOf('/'))\n );\n }\n }\n exportData.server[id] = server as ServerExportSkeleton;\n }\n for (const [id, props] of Object.entries(data.defaultProperties)) {\n exportData.defaultProperties[id.substring(id.lastIndexOf('/') + 1)] =\n typeof props === 'string'\n ? getExtractedJsonData(\n props,\n f.path.substring(0, f.path.lastIndexOf('/'))\n )\n : props;\n }\n }\n return exportData as ServerExportInterface;\n}\n","import { FrodoError } from '@rockcarver/frodo-lib';\nimport { printError } from '../../utils/Console';\n\n/**\n * Deep clone object\n * @param {any} obj object to deep clone\n * @returns {any} new object cloned from obj\n */\nexport function cloneDeep(obj: any): any {\n return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Result callback that handles errors when they occur by printing them and setting the process exit code\n * @param error The error to handle\n */\nexport function errorHandler(error?: FrodoError) {\n if (!error) return;\n printError(error);\n process.exitCode = 1;\n}\n","export default function wordwrap(\n str: string,\n len: number,\n indent: string = undefined\n) {\n if (!str) return '';\n return (\n str.match(\n new RegExp(\n `(\\\\S.{0,${len - 1 - (indent ? indent.length : 0)}})(?=\\\\s+|$)`,\n 'g'\n )\n ) || []\n ).join(indent ? `\\n${indent}` : '\\n');\n}\n","import fs from 'fs';\nimport path from 'path';\nimport {\n frodo,\n FrodoError,\n type EmailTemplateSkeleton,\n} from '@rockcarver/frodo-lib';\nimport c from '../utils/ColorTheme';\nimport {\n createProgressIndicator,\n createTable,\n debugMessage,\n failSpinner,\n printError,\n printMessage,\n showSpinner,\n stopProgressIndicator,\n succeedSpinner,\n updateProgressIndicator,\n} from '../utils/Console';\nimport { cloneDeep } from './utils/OpsUtils';\nimport wordwrap from './utils/Wordwrap';\n\nconst {\n validateImport,\n getTypedFilename,\n saveJsonToFile,\n getFilePath,\n getWorkingDirectory,\n} = frodo.utils;\nconst {\n EMAIL_TEMPLATE_TYPE,\n readEmailTemplates,\n readEmailTemplate,\n exportEmailTemplates,\n updateEmailTemplate,\n importEmailTemplates,\n deleteEmailTemplate,\n} = frodo.email.template;\n\nconst EMAIL_TEMPLATE_FILE_TYPE = 'template.email';\n\nconst regexEmailTemplateType = new RegExp(`${EMAIL_TEMPLATE_TYPE}/`, 'g');\n\n// use a function vs a template variable to avoid problems in loops\nfunction getFileDataTemplate() {\n return {\n meta: {},\n emailTemplate: {},\n };\n}\n\n/**\n * Get a one-line description of the email template\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(\n templateObj: EmailTemplateSkeleton\n): string {\n const description = `[${c.heading(templateObj._id.split('/')[1])}] ${\n templateObj.displayName ? templateObj.displayName : ''\n } - ${\n templateObj.defaultLocale\n ? templateObj.subject[templateObj.defaultLocale]\n : Object.values(templateObj.subject)[0]\n }`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Display Name | Locale(s) | Subject | Id |\\n';\n markdown += '| ------------ | --------- | ------- | ---|';\n return markdown;\n}\n\n/**\n * Get a table-row of the email template in markdown\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a table-row of the email template in markdown\n */\nexport function getTableRowMd(templateObj: EmailTemplateSkeleton): string {\n const templateId = templateObj._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');\n const locales = `${templateObj.defaultLocale}${\n Object.keys(templateObj.subject).length > 1\n ? ` (${Object.keys(templateObj.subject)\n .filter((locale) => locale !== templateObj.defaultLocale)\n .join(',')})`\n : ''\n }`;\n const row = `| ${\n templateObj.name ? templateObj.name : templateId\n } | ${locales} | ${\n templateObj.subject[templateObj.defaultLocale]\n } | \\`${templateId}\\` |`;\n return row;\n}\n\n/**\n * List email templates\n * @param {boolean} long Long list format with details\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function listEmailTemplates(\n long: boolean = false\n): Promise<boolean> {\n let emailTemplates;\n try {\n emailTemplates = await readEmailTemplates(true);\n } catch (error) {\n printError(error);\n return false;\n }\n emailTemplates.sort((a, b) => a._id.localeCompare(b._id));\n if (!long) {\n for (const [, emailTemplate] of emailTemplates.entries()) {\n printMessage(\n `${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`,\n 'data'\n );\n }\n } else {\n const table = createTable([\n c.heading('Id'),\n c.heading('Name'),\n c.heading('Status'),\n c.heading('Locale(s)'),\n c.heading('From'),\n c.heading('Subject'),\n ]);\n for (const emailTemplate of emailTemplates) {\n table.push([\n // Id\n `${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`,\n // Name\n `${emailTemplate.displayName ? emailTemplate.displayName : ''}`,\n // Status\n emailTemplate.enabled === false\n ? c.negative('disabled')\n : c.positive('enabled'),\n // Locale(s)\n `${emailTemplate.defaultLocale}${\n Object.keys(emailTemplate.subject).length > 1\n ? ` (${Object.keys(emailTemplate.subject)\n .filter((locale) => locale !== emailTemplate.defaultLocale)\n .join(',')})`\n : ''\n }`,\n // From\n `${emailTemplate.from ? emailTemplate.from : ''}`,\n // Subject\n wordwrap(emailTemplate.subject[emailTemplate.defaultLocale], 40),\n ]);\n }\n printMessage(table.toString(), 'data');\n }\n return true;\n}\n\n/**\n * Export single email template to a file\n * @param {string} templateId email template id to export\n * @param {string} file filename where to export the template data\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportEmailTemplateToFile(\n templateId: string,\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n let indicatorId: string;\n try {\n let fileName = file;\n if (!fileName) {\n fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);\n }\n const filePath = getFilePath(fileName, true);\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${templateId}`\n );\n const templateData = await readEmailTemplate(templateId);\n updateProgressIndicator(indicatorId, `Writing file ${filePath}`);\n const fileData = getFileDataTemplate();\n fileData.emailTemplate[templateId] = templateData;\n saveJsonToFile(fileData, filePath, includeMeta);\n stopProgressIndicator(\n indicatorId,\n `Exported ${c.heading(templateId)} to ${c.heading(filePath)}.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `${error}`);\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all email templates to file\n * @param {string} file optional filename\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportEmailTemplatesToFile(\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n try {\n let fileName = file;\n if (!fileName) {\n fileName = getTypedFilename(\n `allEmailTemplates`,\n EMAIL_TEMPLATE_FILE_TYPE\n );\n }\n const filePath = getFilePath(fileName, true);\n const exportData = await exportEmailTemplates(true);\n saveJsonToFile(exportData, filePath, includeMeta);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all email templates to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportEmailTemplatesToFiles(\n includeMeta: boolean = true\n): Promise<boolean> {\n let indicatorId;\n try {\n const exportData = Object.entries(\n (await exportEmailTemplates(true)).emailTemplate\n );\n indicatorId = createProgressIndicator(\n 'determinate',\n exportData.length,\n 'Writing email templates'\n );\n for (const [templateId, template] of exportData) {\n const fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);\n const fileData = getFileDataTemplate();\n updateProgressIndicator(indicatorId, `Exporting ${templateId}`);\n fileData.emailTemplate[templateId] = template;\n saveJsonToFile(fileData, getFilePath(fileName, true), includeMeta);\n }\n stopProgressIndicator(\n indicatorId,\n `${exportData.length} templates written.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `${error}`);\n printError(error);\n }\n return false;\n}\n\n/**\n * Import email template by id from file\n * @param {string} templateId email template id\n * @param {string} file optional filename\n * @param {boolean} raw import raw data file lacking frodo export envelop\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importEmailTemplateFromFile(\n templateId: string,\n file: string,\n raw: boolean = false\n): Promise<boolean> {\n templateId = templateId.replaceAll(`${EMAIL_TEMPLATE_TYPE}/`, '');\n const filePath = getFilePath(file);\n try {\n const data = fs.readFileSync(filePath, 'utf8');\n const fileData = JSON.parse(data);\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Importing ${templateId}`\n );\n if (\n (fileData.emailTemplate && fileData.emailTemplate[templateId]) ||\n (raw && getTemplateIdFromFileName(file) === templateId)\n ) {\n try {\n const emailTemplateData = raw\n ? s2sConvert(fileData)\n : fileData.emailTemplate[templateId];\n await updateEmailTemplate(templateId, emailTemplateData);\n updateProgressIndicator(indicatorId, `Importing ${templateId}`);\n stopProgressIndicator(indicatorId, `Imported ${templateId}`);\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `${error}`);\n printError(error);\n }\n } else {\n stopProgressIndicator(\n indicatorId,\n `Email template ${templateId} not found in ${filePath}!`\n );\n printMessage(\n `Email template ${templateId} not found in ${filePath}!`,\n 'error'\n );\n }\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Import all email templates from file\n * @param {string} file optional filename\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importEmailTemplatesFromFile(\n file: string\n): Promise<boolean> {\n const filePath = getFilePath(file);\n const indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing email templates from ${filePath}...`\n );\n try {\n const data = fs.readFileSync(filePath, 'utf8');\n const fileData = JSON.parse(data);\n await importEmailTemplates(fileData);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported email templates from ${filePath}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing email templates from ${filePath}.`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Helper function to get email template id from file name\n * @param {string} file file name\n * @returns {string} email template id/name\n */\nfunction getTemplateIdFromFileName(file: string): string {\n debugMessage(`cli.EmailTemplateOps.getTemplateIdFromFileName: file=${file}`);\n const basename = path.basename(file);\n const keys = basename.split('-');\n if (keys[0] !== EMAIL_TEMPLATE_TYPE || keys.length <= 1)\n throw new FrodoError(\n `Filename does not indicate a raw email template: ${file}`\n );\n const templateId = keys[1].split('.')[0];\n debugMessage(\n `cli.EmailTemplateOps.getTemplateIdFromFileName: templateId=${templateId}`\n );\n return templateId;\n}\n\n/**\n * Convert template for s2s purposes (software-to-saas migration)\n * @param {EmailTemplateSkeleton} templateData template object\n * @returns {EmailTemplateSkeleton} converted template object\n */\nfunction s2sConvert(\n templateData: EmailTemplateSkeleton\n): EmailTemplateSkeleton {\n if (templateData.message && !templateData.html) {\n const convertedData = cloneDeep(templateData);\n convertedData.html = cloneDeep(templateData.message);\n debugMessage(`cli.EmailTemplateOps.s2sConvert: templateData:`);\n debugMessage(templateData);\n debugMessage(`cli.EmailTemplateOps.s2sConvert: convertedData:`);\n debugMessage(convertedData);\n return convertedData;\n }\n return templateData;\n}\n\n/**\n * Import all email templates from separate files\n * @param {boolean} raw import raw data file lacking frodo export envelop\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importEmailTemplatesFromFiles(\n raw: boolean = false\n): Promise<boolean> {\n const names = fs.readdirSync(getWorkingDirectory());\n const jsonFiles = names\n .filter((name) =>\n raw\n ? name.startsWith(`${EMAIL_TEMPLATE_TYPE}-`) && name.endsWith(`.json`)\n : name.toLowerCase().endsWith(`${EMAIL_TEMPLATE_FILE_TYPE}.json`)\n )\n .map((name) => getFilePath(name));\n const indicatorId = createProgressIndicator(\n 'determinate',\n jsonFiles.length,\n 'Importing email templates...'\n );\n let total = 0;\n let totalErrors = 0;\n for (const file of jsonFiles) {\n const data = fs.readFileSync(file, 'utf8');\n const fileData = JSON.parse(data);\n if (\n (raw && file.startsWith('emailTemplate-')) ||\n validateImport(fileData.meta)\n ) {\n let errors = 0;\n if (raw) {\n total++;\n const templateId = getTemplateIdFromFileName(file);\n try {\n const templateData = s2sConvert(fileData);\n await updateEmailTemplate(templateId, templateData);\n } catch (error) {\n errors += 1;\n printError(error);\n }\n } else {\n total += Object.keys(fileData.emailTemplate).length;\n for (const id in fileData.emailTemplate) {\n if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {\n const templateId = id.replace(regexEmailTemplateType, '');\n try {\n await updateEmailTemplate(\n templateId,\n fileData.emailTemplate[templateId]\n );\n } catch (error) {\n errors += 1;\n printError(error);\n }\n }\n }\n }\n totalErrors += errors;\n updateProgressIndicator(indicatorId, `Imported ${file}`);\n } else {\n printMessage(`Validation of ${file} failed!`, 'error');\n }\n }\n stopProgressIndicator(\n indicatorId,\n `Imported ${total - totalErrors} of ${total} email template(s) from ${\n jsonFiles.length\n } file(s).`\n );\n if (totalErrors === 0) return true;\n return false;\n}\n\n/**\n * Import first email template from file\n * @param {string} file optional filename\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importFirstEmailTemplateFromFile(\n file: string,\n raw: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n const data = fs.readFileSync(getFilePath(file), 'utf8');\n const fileData = JSON.parse(data);\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing first email template`\n );\n if (raw) {\n try {\n const templateId = getTemplateIdFromFileName(file);\n const templateData = s2sConvert(fileData);\n await updateEmailTemplate(templateId, templateData);\n stopProgressIndicator(indicatorId, `Imported ${templateId}`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing email template: ${error}`,\n 'fail'\n );\n printError(error);\n }\n } else {\n for (const id of Object.keys(fileData.emailTemplate)) {\n try {\n await updateEmailTemplate(\n id.replace(regexEmailTemplateType, ''),\n fileData.emailTemplate[id]\n );\n stopProgressIndicator(indicatorId, `Imported ${id}`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing ${id}`, 'fail');\n printError(error);\n }\n break;\n }\n }\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing first email template`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete email template by id\n * @param {string} templateId email template id/name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteEmailTemplateById(\n templateId: string\n): Promise<boolean> {\n debugMessage(`cli.EmailTemplateOps.deleteEmailTemplateById: begin`);\n showSpinner(`Deleting ${templateId}...`);\n try {\n debugMessage(`Deleting email template ${templateId}`);\n await deleteEmailTemplate(templateId);\n succeedSpinner(`Deleted ${templateId}.`);\n debugMessage(`cli.EmailTemplateOps.deleteEmailTemplateById: end`);\n return true;\n } catch (error) {\n failSpinner(`Error deleting email template ${templateId}`);\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete all email templates\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteAllEmailTemplates(): Promise<boolean> {\n debugMessage(`cli.EmailTemplateOps.deleteAllEmailTemplates: begin`);\n const errors = [];\n let templates: EmailTemplateSkeleton[] = [];\n let indicatorId: string;\n try {\n showSpinner(`Retrieving all email templates...`);\n try {\n templates = await readEmailTemplates(true);\n succeedSpinner(`Found ${templates.length} email templates.`);\n } catch (error) {\n failSpinner(`Error retrieving all email templates`);\n throw new FrodoError(`Error retrieving all email templates`, error);\n }\n if (templates.length)\n indicatorId = createProgressIndicator(\n 'determinate',\n templates.length,\n `Deleting ${templates.length} email templates...`\n );\n for (const template of templates) {\n const templateId = template._id.split('/')[1];\n try {\n debugMessage(`Deleting email template ${templateId}`);\n await deleteEmailTemplate(templateId);\n updateProgressIndicator(indicatorId, `Deleted ${templateId}`);\n } catch (error) {\n errors.push(\n new FrodoError(`Error deleting email template ${templateId}`, error)\n );\n }\n }\n } catch (error) {\n errors.push(new FrodoError(`Error deleting all email templates`, error));\n } finally {\n if (errors.length > 0) {\n if (templates.length)\n stopProgressIndicator(\n indicatorId,\n `Error deleting all email templates`,\n 'fail'\n );\n for (const error of errors) {\n printError(error);\n }\n } else {\n if (templates.length)\n stopProgressIndicator(\n indicatorId,\n `Deleted ${templates.length} email templates.`\n );\n }\n }\n debugMessage(`cli.EmailTemplateOps.deleteAllEmailTemplates: end`);\n return errors.length === 0;\n}\n","import { lstat, readdir, realpath, stat } from 'node:fs/promises';\nimport { join as pjoin, resolve as presolve, sep as psep } from 'node:path';\nimport { Readable } from 'node:stream';\nexport const EntryTypes = {\n FILE_TYPE: 'files',\n DIR_TYPE: 'directories',\n FILE_DIR_TYPE: 'files_directories',\n EVERYTHING_TYPE: 'all',\n};\nconst defaultOptions = {\n root: '.',\n fileFilter: (_entryInfo) => true,\n directoryFilter: (_entryInfo) => true,\n type: EntryTypes.FILE_TYPE,\n lstat: false,\n depth: 2147483648,\n alwaysStat: false,\n // Throughput is flat from 16 to 65536 (traversal is I/O-bound), but\n // batches of 1024+ entries survive young-gen GC and bloat RSS ~20-60%.\n highWaterMark: 256,\n};\nObject.freeze(defaultOptions);\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst ALL_TYPES = [\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n];\nconst DIR_TYPES = new Set([\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n]);\nconst FILE_TYPES = new Set([\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n]);\nconst isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);\nconst wantBigintFsStats = process.platform === 'win32';\nconst emptyFn = (_entryInfo) => true;\nconst normalizeFilter = (filter) => {\n if (filter === undefined)\n return emptyFn;\n if (typeof filter === 'function')\n return filter;\n if (typeof filter === 'string') {\n const fl = filter.trim();\n return (entry) => entry.basename === fl;\n }\n if (Array.isArray(filter)) {\n const trItems = filter.map((item) => item.trim());\n return (entry) => trItems.some((f) => entry.basename === f);\n }\n return emptyFn;\n};\nexport class ReaddirpStream extends Readable {\n /**\n * Directories discovered but not yet emitted from. Listings are read\n * lazily (on pop, plus one prefetch) instead of eagerly on discovery:\n * keeping whole listings for every queued dir balloons RAM on wide trees.\n */\n parents;\n reading;\n parent;\n _stat;\n _maxDepth;\n _wantsDir;\n _wantsFile;\n _wantsEverything;\n _root;\n _isDirent;\n _statsProp;\n _rdOptions;\n _fileFilter;\n _directoryFilter;\n _relStart;\n constructor(options = {}) {\n super({\n objectMode: true,\n autoDestroy: true,\n highWaterMark: options.highWaterMark ?? defaultOptions.highWaterMark,\n });\n const opts = { ...defaultOptions, ...options };\n // Use ?? so an explicit `undefined` in user options doesn't shadow defaults.\n const root = opts.root ?? defaultOptions.root;\n const type = opts.type ?? defaultOptions.type;\n this._fileFilter = normalizeFilter(opts.fileFilter);\n this._directoryFilter = normalizeFilter(opts.directoryFilter);\n const statMethod = opts.lstat ? lstat : stat;\n // Use bigint stats if it's windows and stat() supports options (node 10+).\n if (wantBigintFsStats) {\n this._stat = (path) => statMethod(path, { bigint: true });\n }\n else {\n this._stat = statMethod;\n }\n this._maxDepth =\n opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;\n this._wantsDir = DIR_TYPES.has(type);\n this._wantsFile = FILE_TYPES.has(type);\n this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;\n this._root = presolve(root);\n // Every fullPath is `_root + sep + relative path` (see _formatEntry), so\n // the relative path is a slice starting past the root and its trailing\n // separator (which resolved paths lack, except fs roots like '/', 'C:\\').\n this._relStart = this._root.endsWith(psep) ? this._root.length : this._root.length + 1;\n this._isDirent = !opts.alwaysStat;\n this._statsProp = this._isDirent ? 'dirent' : 'stats';\n this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n // Launch stream with one parent, the root dir, whose readdir starts\n // right away. Explore the resolved root so all parent paths stay\n // absolute even if process.cwd() changes mid-iteration.\n const rootDir = { path: this._root, depth: 1 };\n rootDir.pending = this._exploreDir(this._root, 1);\n this.parents = [rootDir];\n this.reading = false;\n this.parent = undefined;\n }\n async _read(batch) {\n if (this.reading)\n return;\n this.reading = true;\n try {\n while (!this.destroyed && batch > 0) {\n const par = this.parent;\n const fil = par && par.files;\n if (fil && fil.length > 0) {\n const { path, depth } = par;\n const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));\n // In dirent mode _formatEntry is synchronous: skip Promise.all and\n // its per-entry microtask overhead.\n const awaited = this._isDirent\n ? slice\n : await Promise.all(slice);\n for (const entry of awaited) {\n if (!entry)\n continue;\n if (this.destroyed)\n return;\n // Only symlinks require async work; plain files / dirs resolve synchronously.\n let entryType = this._getEntryType(entry);\n if (typeof entryType !== 'string')\n entryType = await entryType;\n if (entryType === 'directory' && this._directoryFilter(entry)) {\n if (depth <= this._maxDepth) {\n // Lazy: don't readdir until this dir is popped. Keeping whole\n // listings for every queued dir would balloon RAM on wide trees.\n this.parents.push({ path: entry.fullPath, depth: depth + 1 });\n }\n if (this._wantsDir) {\n this.push(entry);\n batch--;\n }\n }\n else if ((entryType === 'file' || this._includeAsFile(entry)) &&\n this._fileFilter(entry)) {\n if (this._wantsFile) {\n this.push(entry);\n batch--;\n }\n }\n }\n }\n else {\n const parent = this.parents.pop();\n if (!parent) {\n this.push(null);\n break;\n }\n const dir = parent.pending ?? this._exploreDir(parent.path, parent.depth);\n // Prefetch the next dir so its readdir overlaps with processing\n // this one's entries. Only the stack top is prefetched, keeping at\n // most a handful of listings (~tree depth) in RAM at once.\n const next = this.parents[this.parents.length - 1];\n if (next && !next.pending) {\n next.pending = this._exploreDir(next.path, next.depth);\n }\n this.parent = await dir;\n if (this.destroyed)\n return;\n }\n }\n }\n catch (error) {\n this.destroy(error);\n }\n finally {\n this.reading = false;\n }\n }\n // NOTE: native `readdir(path, { recursive: true })` was evaluated as a\n // replacement for this per-directory traversal and rejected:\n // - Not faster: node implements it in JS, walking directories sequentially\n // just like this loop, but with extra path bookkeeping. Benchmarks\n // (node 24): ~10% slower on wide trees, ~40% slower on small ones,\n // parity on deep ones.\n // - Much more RAM: it buffers the entire subtree listing in one array,\n // instead of one directory at a time, defeating streaming.\n // - Semantics diverge: it can't limit depth, can't skip directories a\n // directoryFilter rejects, doesn't follow symlinked dirs, and fails\n // wholesale (all entries lost) if anything in the subtree is unreadable,\n // instead of emitting a 'warn' and continuing.\n async _exploreDir(path, depth) {\n let files;\n try {\n files = await readdir(path, this._rdOptions);\n }\n catch (error) {\n this._onError(error);\n }\n return { files, depth, path };\n }\n // Synchronous in dirent mode; returns a promise only when stats are needed.\n _formatEntry(dirent, path) {\n const basename = this._isDirent ? dirent.name : dirent;\n // `path` is always an absolute, normalized parent dir (see _exploreDir\n // seeding in the constructor), so a plain join is enough — resolve()\n // would re-read cwd on every entry.\n const fullPath = pjoin(path, basename);\n // Slice instead of path.relative(): equivalent here (fullPath is always\n // under _root) and avoids several intermediate allocations per entry.\n const entry = { path: fullPath.slice(this._relStart), fullPath, basename };\n if (this._isDirent) {\n entry.dirent = dirent;\n return entry;\n }\n return this._stat(fullPath).then((stats) => {\n entry.stats = stats;\n return entry;\n }, (err) => {\n this._onError(err);\n return undefined;\n });\n }\n _onError(err) {\n if (isNormalFlowError(err) && !this.destroyed) {\n this.emit('warn', err);\n }\n else {\n this.destroy(err);\n }\n }\n // Synchronous for regular files and directories; returns a promise only for\n // symlinks, which need realpath() to be classified.\n _getEntryType(entry) {\n // entry may be undefined, because a warning or an error were emitted\n // and the statsProp is undefined\n if (!entry || !(this._statsProp in entry)) {\n return '';\n }\n const stats = entry[this._statsProp];\n if (stats.isFile())\n return 'file';\n if (stats.isDirectory())\n return 'directory';\n if (stats.isSymbolicLink())\n return this._getSymlinkEntryType(entry);\n return '';\n }\n async _getSymlinkEntryType(entry) {\n const full = entry.fullPath;\n try {\n const entryRealPath = await realpath(full);\n const entryRealPathStats = await lstat(entryRealPath);\n if (entryRealPathStats.isFile()) {\n return 'file';\n }\n if (entryRealPathStats.isDirectory()) {\n const len = entryRealPath.length;\n if (full.startsWith(entryRealPath) && full[len] === psep) {\n const recursiveError = new Error(`Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`);\n // @ts-ignore\n recursiveError.code = RECURSIVE_ERROR_CODE;\n this._onError(recursiveError);\n return '';\n }\n return 'directory';\n }\n }\n catch (error) {\n this._onError(error);\n }\n return '';\n }\n _includeAsFile(entry) {\n const stats = entry && entry[this._statsProp];\n return stats && this._wantsEverything && !stats.isDirectory();\n }\n}\n/**\n * Streaming version: Reads all files and directories in given root recursively.\n * Consumes ~constant small amount of RAM.\n * @param root Root directory\n * @param options Options to specify root (start directory), filters and recursion depth\n */\nexport function readdirp(root, options = {}) {\n // @ts-ignore\n let type = options.entryType || options.type;\n if (type === 'both')\n type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility\n if (!root) {\n throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n }\n else if (typeof root !== 'string') {\n throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n }\n else if (type && !ALL_TYPES.includes(type)) {\n throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n }\n // Copy options instead of mutating the caller's object.\n const opts = { ...options, root };\n if (type)\n opts.type = type;\n return new ReaddirpStream(opts);\n}\n/**\n * Promise version: Reads all files and directories in given root recursively.\n * Compared to streaming version, will consume a lot of RAM e.g. when 1 million files are listed.\n * @returns array of paths and their entry infos\n */\nexport function readdirpPromise(root, options = {}) {\n return new Promise((resolve, reject) => {\n const files = [];\n readdirp(root, options)\n .on('data', (entry) => files.push(entry))\n .on('end', () => resolve(files))\n .on('error', (error) => reject(error));\n });\n}\nexport default readdirp;\n","import { watch as fs_watch, unwatchFile, watchFile } from 'node:fs';\nimport { realpath as fsrealpath, lstat, open, stat } from 'node:fs/promises';\nimport { type as osType } from 'node:os';\nimport * as sp from 'node:path';\nexport const STR_DATA = 'data';\nexport const STR_END = 'end';\nexport const STR_CLOSE = 'close';\nexport const EMPTY_FN = () => { };\nexport const IDENTITY_FN = (val) => val;\nconst pl = process.platform;\nexport const isWindows = pl === 'win32';\nexport const isMacos = pl === 'darwin';\nexport const isLinux = pl === 'linux';\nexport const isFreeBSD = pl === 'freebsd';\nexport const isIBMi = osType() === 'OS400';\nexport const EVENTS = {\n ALL: 'all',\n READY: 'ready',\n ADD: 'add',\n CHANGE: 'change',\n ADD_DIR: 'addDir',\n UNLINK: 'unlink',\n UNLINK_DIR: 'unlinkDir',\n RAW: 'raw',\n ERROR: 'error',\n};\nconst EV = EVENTS;\nconst THROTTLE_MODE_WATCH = 'watch';\nconst statMethods = { lstat, stat };\nconst KEY_LISTENERS = 'listeners';\nconst KEY_ERR = 'errHandlers';\nconst KEY_RAW = 'rawEmitters';\nconst HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];\n// prettier-ignore\nconst binaryExtensions = new Set([\n '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',\n 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',\n 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',\n 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',\n 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',\n 'dtshd', 'dvb', 'dwg', 'dxf',\n 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',\n 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',\n 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',\n 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',\n 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',\n 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',\n 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',\n 'mobi', 'mov', 'movie', 'mp3',\n 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',\n 'nef', 'npx', 'numbers', 'nupkg',\n 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',\n 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',\n 'potx', 'ppa', 'ppam',\n 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',\n 'qt',\n 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',\n 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',\n 'stl', 'suo', 'sub', 'swf',\n 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',\n 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',\n 'viv', 'vob',\n 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',\n 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',\n 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',\n 'xmind', 'xpi', 'xpm', 'xwd', 'xz',\n 'z', 'zip', 'zipx',\n]);\nconst isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n if (val instanceof Set) {\n val.forEach(fn);\n }\n else {\n fn(val);\n }\n};\nconst addAndConvert = (main, prop, item) => {\n let container = main[prop];\n if (!(container instanceof Set)) {\n main[prop] = container = new Set([container]);\n }\n container.add(item);\n};\nconst clearItem = (cont) => (key) => {\n const set = cont[key];\n if (set instanceof Set) {\n set.clear();\n }\n else {\n delete cont[key];\n }\n};\nconst delFromSet = (main, prop, item) => {\n const container = main[prop];\n if (container instanceof Set) {\n container.delete(item);\n }\n else if (container === item) {\n delete main[prop];\n }\n};\nconst isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);\nconst FsWatchInstances = new Map();\n/**\n * Instantiates the fs_watch interface\n * @param path to be watched\n * @param options to be passed to fs_watch\n * @param listener main event handler\n * @param errHandler emits info about errors\n * @param emitRaw emits raw event data\n * @returns {NativeFsWatcher}\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n const handleEvent = (rawEvent, evPath) => {\n listener(path);\n emitRaw(rawEvent, evPath, { watchedPath: path });\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));\n }\n };\n try {\n return fs_watch(path, {\n persistent: options.persistent,\n }, handleEvent);\n }\n catch (error) {\n errHandler(error);\n return undefined;\n }\n}\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param fullPath absolute path bound to fs_watch instance\n */\nconst fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {\n const cont = FsWatchInstances.get(fullPath);\n if (!cont)\n return;\n foreach(cont[listenerType], (listener) => {\n listener(val1, val2, val3);\n });\n};\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path\n * @param fullPath absolute path\n * @param options to be passed to fs_watch\n * @param handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n const { listener, errHandler, rawEmitter } = handlers;\n let cont = FsWatchInstances.get(fullPath);\n let watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);\n if (!watcher)\n return;\n return watcher.close.bind(watcher);\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_ERR, errHandler);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, KEY_RAW));\n if (!watcher)\n return;\n watcher.on(EV.ERROR, async (error) => {\n const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n if (cont)\n cont.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (isWindows && error.code === 'EPERM') {\n try {\n const fd = await open(path, 'r');\n await fd.close();\n broadcastErr(error);\n }\n catch (err) {\n // do nothing\n }\n }\n else {\n broadcastErr(error);\n }\n });\n cont = {\n listeners: listener,\n errHandlers: errHandler,\n rawEmitters: rawEmitter,\n watcher,\n };\n FsWatchInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // removes this instance's listeners and closes the underlying fs_watch\n // instance if there are no more listeners left\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_ERR, errHandler);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n // Check to protect against issue gh-730.\n // if (cont.watcherUnusable) {\n cont.watcher.close();\n // }\n FsWatchInstances.delete(fullPath);\n HANDLER_KEYS.forEach(clearItem(cont));\n // @ts-ignore\n cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n// fs_watchFile helpers\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path to be watched\n * @param fullPath absolute path\n * @param options options to be passed to fs_watchFile\n * @param handlers container for event listener functions\n * @returns closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n const { listener, rawEmitter } = handlers;\n let cont = FsWatchFileInstances.get(fullPath);\n // let listeners = new Set();\n // let rawEmitters = new Set();\n const copts = cont && cont.options;\n if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n // listeners = cont.listeners;\n // rawEmitters = cont.rawEmitters;\n unwatchFile(fullPath);\n cont = undefined;\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n // TODO\n // listeners.add(listener);\n // rawEmitters.add(rawEmitter);\n cont = {\n listeners: listener,\n rawEmitters: rawEmitter,\n options,\n watcher: watchFile(fullPath, options, (curr, prev) => {\n foreach(cont.rawEmitters, (rawEmitter) => {\n rawEmitter(EV.CHANGE, fullPath, { curr, prev });\n });\n const currmtime = curr.mtimeMs;\n if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n foreach(cont.listeners, (listener) => listener(path, curr));\n }\n }),\n };\n FsWatchFileInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // Removes this instance's listeners and closes the underlying fs_watchFile\n // instance if there are no more listeners left.\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n FsWatchFileInstances.delete(fullPath);\n unwatchFile(fullPath);\n cont.options = cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n/**\n * @mixin\n */\nexport class NodeFsHandler {\n fsw;\n _boundHandleError;\n constructor(fsW) {\n this.fsw = fsW;\n this._boundHandleError = (error) => fsW._handleError(error);\n }\n /**\n * Watch file for changes with fs_watchFile or fs_watch.\n * @param path to file or dir\n * @param listener on fs change\n * @returns closer for the watcher instance\n */\n _watchWithNodeFs(path, listener) {\n const opts = this.fsw.options;\n const directory = sp.dirname(path);\n const basename = sp.basename(path);\n const parent = this.fsw._getWatchedDir(directory);\n parent.add(basename);\n const absolutePath = sp.resolve(path);\n const options = {\n persistent: opts.persistent,\n };\n if (!listener)\n listener = EMPTY_FN;\n let closer;\n if (opts.usePolling) {\n const enableBin = opts.interval !== opts.binaryInterval;\n options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener,\n errHandler: this._boundHandleError,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n return closer;\n }\n /**\n * Watch a file and emit add event if warranted.\n * @returns closer for the watcher instance\n */\n _handleFile(file, stats, initialAdd) {\n if (this.fsw.closed) {\n return;\n }\n const dirname = sp.dirname(file);\n const basename = sp.basename(file);\n const parent = this.fsw._getWatchedDir(dirname);\n // stats is always present\n let prevStats = stats;\n // if the file is already being watched, do nothing\n if (parent.has(basename))\n return;\n const listener = async (path, newStats) => {\n if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))\n return;\n if (!newStats || newStats.mtimeMs === 0) {\n try {\n const newStats = await stat(file);\n if (this.fsw.closed)\n return;\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {\n this.fsw._closeFile(path);\n prevStats = newStats;\n const closer = this._watchWithNodeFs(file, listener);\n if (closer)\n this.fsw._addPathCloser(path, closer);\n }\n else {\n prevStats = newStats;\n }\n }\n catch (error) {\n // Fix issues where mtime is null but file is still present\n this.fsw._remove(dirname, basename);\n }\n // add is about to be emitted if file not already tracked in parent\n }\n else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n prevStats = newStats;\n }\n };\n // kick off the watcher\n const closer = this._watchWithNodeFs(file, listener);\n // emit an add event if we're supposed to\n if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n if (!this.fsw._throttle(EV.ADD, file, 0))\n return;\n this.fsw._emit(EV.ADD, file, stats);\n }\n return closer;\n }\n /**\n * Handle symlinks encountered while reading a dir.\n * @param entry returned by readdirp\n * @param directory path of dir being read\n * @param path of this item\n * @param item basename of this item\n * @returns true if no more processing is needed for this entry.\n */\n async _handleSymlink(entry, directory, path, item) {\n if (this.fsw.closed) {\n return;\n }\n const full = entry.fullPath;\n const dir = this.fsw._getWatchedDir(directory);\n if (!this.fsw.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this.fsw._incrReadyCount();\n let linkPath;\n try {\n linkPath = await fsrealpath(path);\n }\n catch (e) {\n this.fsw._emitReady();\n return true;\n }\n if (this.fsw.closed)\n return;\n if (dir.has(item)) {\n if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.CHANGE, path, entry.stats);\n }\n }\n else {\n dir.add(item);\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.ADD, path, entry.stats);\n }\n this.fsw._emitReady();\n return true;\n }\n // don't follow the same symlink more than once\n if (this.fsw._symlinkPaths.has(full)) {\n return true;\n }\n this.fsw._symlinkPaths.set(full, true);\n }\n _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n // Normalize the directory name on Windows\n directory = sp.join(directory, '');\n const throttleKey = target ? `${directory}:${target}` : directory;\n throttler = this.fsw._throttle('readdir', throttleKey, 1000);\n if (!throttler)\n return;\n const previous = this.fsw._getWatchedDir(wh.path);\n const current = new Set();\n let stream = this.fsw._readdirp(directory, {\n fileFilter: (entry) => wh.filterPath(entry),\n directoryFilter: (entry) => wh.filterDir(entry),\n });\n if (!stream)\n return;\n stream\n .on(STR_DATA, async (entry) => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const item = entry.path;\n let path = sp.join(directory, item);\n current.add(item);\n if (entry.stats.isSymbolicLink() &&\n (await this._handleSymlink(entry, directory, path, item))) {\n return;\n }\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || (!target && !previous.has(item))) {\n this.fsw._incrReadyCount();\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sp.join(dir, sp.relative(dir, path));\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n })\n .on(EV.ERROR, this._boundHandleError);\n return new Promise((resolve, reject) => {\n if (!stream)\n return reject();\n stream.once(STR_END, () => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const wasThrottled = throttler ? throttler.clear() : false;\n resolve(undefined);\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous\n .getChildren()\n .filter((item) => {\n return item !== directory && !current.has(item);\n })\n .forEach((item) => {\n this.fsw._remove(directory, item);\n });\n stream = undefined;\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled)\n this._handleRead(directory, false, wh, target, dir, depth, throttler);\n });\n });\n }\n /**\n * Read directory to add / remove files from `@watched` list and re-read it on change.\n * @param dir fs path\n * @param stats\n * @param initialAdd\n * @param depth relative to user-supplied path\n * @param target child path targeted for watch\n * @param wh Common watch helpers for this path\n * @param realpath\n * @returns closer for the watcher instance.\n */\n async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));\n const tracked = parentDir.has(sp.basename(dir));\n if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n this.fsw._emit(EV.ADD_DIR, dir, stats);\n }\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sp.basename(dir));\n this.fsw._getWatchedDir(dir);\n let throttler;\n let closer;\n const oDepth = this.fsw.options.depth;\n if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n if (!target) {\n await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n if (this.fsw.closed)\n return;\n }\n closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n // if current directory is removed, do nothing\n if (stats && stats.mtimeMs === 0)\n return;\n this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n });\n }\n return closer;\n }\n /**\n * Handle added file, directory, or glob pattern.\n * Delegates call to _handleFile / _handleDir after checks.\n * @param path to file or ir\n * @param initialAdd was the file added at watch instantiation?\n * @param priorWh depth relative to user-supplied path\n * @param depth Child path actually targeted for watch\n * @param target Child path actually targeted for watch\n */\n async _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n const ready = this.fsw._emitReady;\n if (this.fsw._isIgnored(path) || this.fsw.closed) {\n ready();\n return false;\n }\n const wh = this.fsw._getWatchHelpers(path);\n if (priorWh) {\n wh.filterPath = (entry) => priorWh.filterPath(entry);\n wh.filterDir = (entry) => priorWh.filterDir(entry);\n }\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed)\n return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n ready();\n return false;\n }\n const follow = this.fsw.options.followSymlinks;\n let closer;\n if (stats.isDirectory()) {\n const absPath = sp.resolve(path);\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (absPath !== targetPath && targetPath !== undefined) {\n this.fsw._symlinkPaths.set(absPath, targetPath);\n }\n }\n else if (stats.isSymbolicLink()) {\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n const parent = sp.dirname(wh.watchPath);\n this.fsw._getWatchedDir(parent).add(wh.watchPath);\n this.fsw._emit(EV.ADD, wh.watchPath, stats);\n closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (targetPath !== undefined) {\n this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);\n }\n }\n else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd);\n }\n ready();\n if (closer)\n this.fsw._addPathCloser(path, closer);\n return false;\n }\n catch (error) {\n if (this.fsw._handleError(error)) {\n ready();\n return path;\n }\n }\n }\n}\n","/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport { EventEmitter } from 'node:events';\nimport { stat as statcb, Stats } from 'node:fs';\nimport { readdir, stat } from 'node:fs/promises';\nimport * as sp from 'node:path';\nimport { readdirp, ReaddirpStream } from 'readdirp';\nimport { EMPTY_FN, EVENTS as EV, isIBMi, isWindows, NodeFsHandler, STR_CLOSE, STR_END, } from './handler.js';\nconst SLASH = '/';\nconst SLASH_SLASH = '//';\nconst ONE_DOT = '.';\nconst TWO_DOTS = '..';\nconst STRING_TYPE = 'string';\nconst BACK_SLASH_RE = /\\\\/g;\nconst DOUBLE_SLASH_RE = /\\/\\//g;\nconst DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nconst REPLACER_RE = /^\\.[/\\\\]/;\nfunction arrify(item) {\n return Array.isArray(item) ? item : [item];\n}\nconst isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);\nfunction createPattern(matcher) {\n if (typeof matcher === 'function')\n return matcher;\n if (typeof matcher === 'string')\n return (string) => matcher === string;\n if (matcher instanceof RegExp)\n return (string) => matcher.test(string);\n if (typeof matcher === 'object' && matcher !== null) {\n return (string) => {\n if (matcher.path === string)\n return true;\n if (matcher.recursive) {\n const relative = sp.relative(matcher.path, string);\n if (!relative) {\n return false;\n }\n return !relative.startsWith('..') && !sp.isAbsolute(relative);\n }\n return false;\n };\n }\n return () => false;\n}\nfunction normalizePath(path) {\n if (typeof path !== 'string')\n throw new Error('string expected');\n path = sp.normalize(path);\n path = path.replace(/\\\\/g, '/');\n let prepend = false;\n if (path.startsWith('//'))\n prepend = true;\n path = path.replace(DOUBLE_SLASH_RE, '/');\n if (prepend)\n path = '/' + path;\n return path;\n}\nfunction matchPatterns(patterns, testString, stats) {\n const path = normalizePath(testString);\n for (let index = 0; index < patterns.length; index++) {\n const pattern = patterns[index];\n if (pattern(path, stats)) {\n return true;\n }\n }\n return false;\n}\nfunction anymatch(matchers, testString) {\n if (matchers == null) {\n throw new TypeError('anymatch: specify first argument');\n }\n // Early cache for matchers.\n const matchersArray = arrify(matchers);\n const patterns = matchersArray.map((matcher) => createPattern(matcher));\n if (testString == null) {\n return (testString, stats) => {\n return matchPatterns(patterns, testString, stats);\n };\n }\n return matchPatterns(patterns, testString);\n}\nconst unifyPaths = (paths_) => {\n const paths = arrify(paths_).flat();\n if (!paths.every((p) => typeof p === STRING_TYPE)) {\n throw new TypeError(`Non-string provided as watch path: ${paths}`);\n }\n return paths.map(normalizePathToUnix);\n};\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n// because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n let str = string.replace(BACK_SLASH_RE, SLASH);\n let prepend = false;\n if (str.startsWith(SLASH_SLASH)) {\n prepend = true;\n }\n str = str.replace(DOUBLE_SLASH_RE, SLASH);\n if (prepend) {\n str = SLASH + str;\n }\n return str;\n};\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));\n// TODO: refactor\nconst normalizeIgnored = (cwd = '') => (path) => {\n if (typeof path === 'string') {\n return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));\n }\n else {\n return path;\n }\n};\nconst getAbsolutePath = (path, cwd) => {\n if (sp.isAbsolute(path)) {\n return path;\n }\n return sp.join(cwd, path);\n};\nconst EMPTY_SET = Object.freeze(new Set());\n/**\n * Directory entry.\n */\nclass DirEntry {\n path;\n _removeWatcher;\n items;\n constructor(dir, removeWatcher) {\n this.path = dir;\n this._removeWatcher = removeWatcher;\n this.items = new Set();\n }\n add(item) {\n const { items } = this;\n if (!items)\n return;\n if (item !== ONE_DOT && item !== TWO_DOTS)\n items.add(item);\n }\n async remove(item) {\n const { items } = this;\n if (!items)\n return;\n items.delete(item);\n if (items.size > 0)\n return;\n const dir = this.path;\n try {\n await readdir(dir);\n }\n catch (err) {\n if (this._removeWatcher) {\n this._removeWatcher(sp.dirname(dir), sp.basename(dir));\n }\n }\n }\n has(item) {\n const { items } = this;\n if (!items)\n return;\n return items.has(item);\n }\n getChildren() {\n const { items } = this;\n if (!items)\n return [];\n return [...items.values()];\n }\n dispose() {\n this.items.clear();\n this.path = '';\n this._removeWatcher = EMPTY_FN;\n this.items = EMPTY_SET;\n Object.freeze(this);\n }\n}\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nexport class WatchHelper {\n fsw;\n path;\n watchPath;\n fullWatchPath;\n dirParts;\n followSymlinks;\n statMethod;\n constructor(path, follow, fsw) {\n this.fsw = fsw;\n const watchPath = path;\n this.path = path = path.replace(REPLACER_RE, '');\n this.watchPath = watchPath;\n this.fullWatchPath = sp.resolve(watchPath);\n this.dirParts = [];\n this.dirParts.forEach((parts) => {\n if (parts.length > 1)\n parts.pop();\n });\n this.followSymlinks = follow;\n this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n }\n entryPath(entry) {\n return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));\n }\n filterPath(entry) {\n const { stats } = entry;\n if (stats && stats.isSymbolicLink())\n return this.filterDir(entry);\n const resolvedPath = this.entryPath(entry);\n // TODO: what if stats is undefined? remove !\n return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);\n }\n filterDir(entry) {\n return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n }\n}\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n * new FSWatcher()\n * .add(directories)\n * .on('add', path => log('File', path, 'was added'))\n */\nexport class FSWatcher extends EventEmitter {\n closed;\n options;\n _closers;\n _ignoredPaths;\n _throttled;\n _streams;\n _symlinkPaths;\n _watched;\n _pendingWrites;\n _pendingUnlinks;\n _readyCount;\n _emitReady;\n _closePromise;\n _userIgnored;\n _readyEmitted;\n _emitRaw;\n _boundRemove;\n _nodeFsHandler;\n // Not indenting methods for history sake; for now.\n constructor(_opts = {}) {\n super();\n this.closed = false;\n this._closers = new Map();\n this._ignoredPaths = new Set();\n this._throttled = new Map();\n this._streams = new Set();\n this._symlinkPaths = new Map();\n this._watched = new Map();\n this._pendingWrites = new Map();\n this._pendingUnlinks = new Map();\n this._readyCount = 0;\n this._readyEmitted = false;\n const awf = _opts.awaitWriteFinish;\n const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };\n const opts = {\n // Defaults\n persistent: true,\n ignoreInitial: false,\n ignorePermissionErrors: false,\n interval: 100,\n binaryInterval: 300,\n followSymlinks: true,\n usePolling: false,\n // useAsync: false,\n atomic: true, // NOTE: overwritten later (depends on usePolling)\n ..._opts,\n // Change format\n ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),\n awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,\n };\n // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n if (isIBMi)\n opts.usePolling = true;\n // Editor atomic write normalization enabled by default with fs.watch\n if (opts.atomic === undefined)\n opts.atomic = !opts.usePolling;\n // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;\n // Global override. Useful for developers, who need to force polling for all\n // instances of chokidar, regardless of usage / dependency depth\n const envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n const envLower = envPoll.toLowerCase();\n if (envLower === 'false' || envLower === '0')\n opts.usePolling = false;\n else if (envLower === 'true' || envLower === '1')\n opts.usePolling = true;\n else\n opts.usePolling = !!envLower;\n }\n const envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval)\n opts.interval = Number.parseInt(envInterval, 10);\n // This is done to emit ready only once, but each 'add' will increase that?\n let readyCalls = 0;\n this._emitReady = () => {\n readyCalls++;\n if (readyCalls >= this._readyCount) {\n this._emitReady = EMPTY_FN;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(() => this.emit(EV.READY));\n }\n };\n this._emitRaw = (...args) => this.emit(EV.RAW, ...args);\n this._boundRemove = this._remove.bind(this);\n this.options = opts;\n this._nodeFsHandler = new NodeFsHandler(this);\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n }\n _addIgnoredPath(matcher) {\n if (isMatcherObject(matcher)) {\n // return early if we already have a deeply equal matcher object\n for (const ignored of this._ignoredPaths) {\n if (isMatcherObject(ignored) &&\n ignored.path === matcher.path &&\n ignored.recursive === matcher.recursive) {\n return;\n }\n }\n }\n this._ignoredPaths.add(matcher);\n }\n _removeIgnoredPath(matcher) {\n this._ignoredPaths.delete(matcher);\n // now find any matcher objects with the matcher as path\n if (typeof matcher === 'string') {\n for (const ignored of this._ignoredPaths) {\n // TODO (43081j): make this more efficient.\n // probably just make a `this._ignoredDirectories` or some\n // such thing.\n if (isMatcherObject(ignored) && ignored.path === matcher) {\n this._ignoredPaths.delete(ignored);\n }\n }\n }\n }\n // Public methods\n /**\n * Adds paths to be watched on an existing FSWatcher instance.\n * @param paths_ file or file list. Other arguments are unused\n */\n add(paths_, _origAdd, _internal) {\n const { cwd } = this.options;\n this.closed = false;\n this._closePromise = undefined;\n let paths = unifyPaths(paths_);\n if (cwd) {\n paths = paths.map((path) => {\n const absPath = getAbsolutePath(path, cwd);\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n return absPath;\n });\n }\n paths.forEach((path) => {\n this._removeIgnoredPath(path);\n });\n this._userIgnored = undefined;\n if (!this._readyCount)\n this._readyCount = 0;\n this._readyCount += paths.length;\n Promise.all(paths.map(async (path) => {\n const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);\n if (res)\n this._emitReady();\n return res;\n })).then((results) => {\n if (this.closed)\n return;\n results.forEach((item) => {\n if (item)\n this.add(sp.dirname(item), sp.basename(_origAdd || item));\n });\n });\n return this;\n }\n /**\n * Close watchers or start ignoring events from specified paths.\n */\n unwatch(paths_) {\n if (this.closed)\n return this;\n const paths = unifyPaths(paths_);\n const { cwd } = this.options;\n paths.forEach((path) => {\n // convert to absolute path unless relative path already matches\n if (!sp.isAbsolute(path) && !this._closers.has(path)) {\n if (cwd)\n path = sp.join(cwd, path);\n path = sp.resolve(path);\n }\n this._closePath(path);\n this._addIgnoredPath(path);\n if (this._watched.has(path)) {\n this._addIgnoredPath({\n path,\n recursive: true,\n });\n }\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n });\n return this;\n }\n /**\n * Close watchers and remove all listeners from watched paths.\n */\n close() {\n if (this._closePromise) {\n return this._closePromise;\n }\n this.closed = true;\n // Memory management.\n this.removeAllListeners();\n const closers = [];\n this._closers.forEach((closerList) => closerList.forEach((closer) => {\n const promise = closer();\n if (promise instanceof Promise)\n closers.push(promise);\n }));\n this._streams.forEach((stream) => stream.destroy());\n this._userIgnored = undefined;\n this._readyCount = 0;\n this._readyEmitted = false;\n this._watched.forEach((dirent) => dirent.dispose());\n this._closers.clear();\n this._watched.clear();\n this._streams.clear();\n this._symlinkPaths.clear();\n this._throttled.clear();\n this._closePromise = closers.length\n ? Promise.all(closers).then(() => undefined)\n : Promise.resolve();\n return this._closePromise;\n }\n /**\n * Expose list of watched paths\n * @returns for chaining\n */\n getWatched() {\n const watchList = {};\n this._watched.forEach((entry, dir) => {\n const key = this.options.cwd ? sp.relative(this.options.cwd, dir) : dir;\n const index = key || ONE_DOT;\n watchList[index] = entry.getChildren().sort();\n });\n return watchList;\n }\n emitWithAll(event, args) {\n this.emit(event, ...args);\n if (event !== EV.ERROR)\n this.emit(EV.ALL, event, ...args);\n }\n // Common helpers\n // --------------\n /**\n * Normalize and emit events.\n * Calling _emit DOES NOT MEAN emit() would be called!\n * @param event Type of event\n * @param path File or directory path\n * @param stats arguments to be passed with event\n * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n async _emit(event, path, stats) {\n if (this.closed)\n return;\n const opts = this.options;\n if (isWindows)\n path = sp.normalize(path);\n if (opts.cwd)\n path = sp.relative(opts.cwd, path);\n const args = [path];\n if (stats != null)\n args.push(stats);\n const awf = opts.awaitWriteFinish;\n let pw;\n if (awf && (pw = this._pendingWrites.get(path))) {\n pw.lastChange = new Date();\n return this;\n }\n if (opts.atomic) {\n if (event === EV.UNLINK) {\n this._pendingUnlinks.set(path, [event, ...args]);\n setTimeout(() => {\n this._pendingUnlinks.forEach((entry, path) => {\n this.emit(...entry);\n this.emit(EV.ALL, ...entry);\n this._pendingUnlinks.delete(path);\n });\n }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n return this;\n }\n if (event === EV.ADD && this._pendingUnlinks.has(path)) {\n event = EV.CHANGE;\n this._pendingUnlinks.delete(path);\n }\n }\n if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {\n const awfEmit = (err, stats) => {\n if (err) {\n event = EV.ERROR;\n args[0] = err;\n this.emitWithAll(event, args);\n }\n else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 1) {\n args[1] = stats;\n }\n else {\n args.push(stats);\n }\n this.emitWithAll(event, args);\n }\n };\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n if (event === EV.CHANGE) {\n const isThrottled = !this._throttle(EV.CHANGE, path, 50);\n if (isThrottled)\n return this;\n }\n if (opts.alwaysStat &&\n stats === undefined &&\n (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {\n const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;\n let stats;\n try {\n stats = await stat(fullPath);\n }\n catch (err) {\n // do nothing\n }\n // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n if (!stats || this.closed)\n return;\n args.push(stats);\n }\n this.emitWithAll(event, args);\n return this;\n }\n /**\n * Common handler for errors\n * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n _handleError(error) {\n const code = error && error.code;\n if (error &&\n code !== 'ENOENT' &&\n code !== 'ENOTDIR' &&\n (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {\n this.emit(EV.ERROR, error);\n }\n return error || this.closed;\n }\n /**\n * Helper utility for throttling\n * @param actionType type being throttled\n * @param path being acted upon\n * @param timeout duration of time to suppress duplicate actions\n * @returns tracking object or false if action should be suppressed\n */\n _throttle(actionType, path, timeout) {\n if (!this._throttled.has(actionType)) {\n this._throttled.set(actionType, new Map());\n }\n const action = this._throttled.get(actionType);\n if (!action)\n throw new Error('invalid throttle');\n const actionPath = action.get(path);\n if (actionPath) {\n actionPath.count++;\n return false;\n }\n // eslint-disable-next-line prefer-const\n let timeoutObject;\n const clear = () => {\n const item = action.get(path);\n const count = item ? item.count : 0;\n action.delete(path);\n clearTimeout(timeoutObject);\n if (item)\n clearTimeout(item.timeoutObject);\n return count;\n };\n timeoutObject = setTimeout(clear, timeout);\n const thr = { timeoutObject, clear, count: 0 };\n action.set(path, thr);\n return thr;\n }\n _incrReadyCount() {\n return this._readyCount++;\n }\n /**\n * Awaits write operation to finish.\n * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n * @param path being acted upon\n * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n * @param event\n * @param awfEmit Callback to be called when ready for event to be emitted.\n */\n _awaitWriteFinish(path, threshold, event, awfEmit) {\n const awf = this.options.awaitWriteFinish;\n if (typeof awf !== 'object')\n return;\n const pollInterval = awf.pollInterval;\n let timeoutHandler;\n let fullPath = path;\n if (this.options.cwd && !sp.isAbsolute(path)) {\n fullPath = sp.join(this.options.cwd, path);\n }\n const now = new Date();\n const writes = this._pendingWrites;\n function awaitWriteFinishFn(prevStat) {\n statcb(fullPath, (err, curStat) => {\n if (err || !writes.has(path)) {\n if (err && err.code !== 'ENOENT')\n awfEmit(err);\n return;\n }\n const now = Number(new Date());\n if (prevStat && curStat.size !== prevStat.size) {\n writes.get(path).lastChange = now;\n }\n const pw = writes.get(path);\n const df = now - pw.lastChange;\n if (df >= threshold) {\n writes.delete(path);\n awfEmit(undefined, curStat);\n }\n else {\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);\n }\n });\n }\n if (!writes.has(path)) {\n writes.set(path, {\n lastChange: now,\n cancelWait: () => {\n writes.delete(path);\n clearTimeout(timeoutHandler);\n return event;\n },\n });\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);\n }\n }\n /**\n * Determines whether user has asked to ignore this path.\n */\n _isIgnored(path, stats) {\n if (this.options.atomic && DOT_RE.test(path))\n return true;\n if (!this._userIgnored) {\n const { cwd } = this.options;\n const ign = this.options.ignored;\n const ignored = (ign || []).map(normalizeIgnored(cwd));\n const ignoredPaths = [...this._ignoredPaths];\n const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];\n this._userIgnored = anymatch(list, undefined);\n }\n return this._userIgnored(path, stats);\n }\n _isntIgnored(path, stat) {\n return !this._isIgnored(path, stat);\n }\n /**\n * Provides a set of common helpers and properties relating to symlink handling.\n * @param path file or directory pattern being watched\n */\n _getWatchHelpers(path) {\n return new WatchHelper(path, this.options.followSymlinks, this);\n }\n // Directory helpers\n // -----------------\n /**\n * Provides directory tracking objects\n * @param directory path of the directory\n */\n _getWatchedDir(directory) {\n const dir = sp.resolve(directory);\n if (!this._watched.has(dir))\n this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n return this._watched.get(dir);\n }\n // File helpers\n // ------------\n /**\n * Check for read permissions: https://stackoverflow.com/a/11781404/1358405\n */\n _hasReadPermissions(stats) {\n if (this.options.ignorePermissionErrors)\n return true;\n return Boolean(Number(stats.mode) & 0o400);\n }\n /**\n * Handles emitting unlink events for\n * files and directories, and via recursion, for\n * files and directories within directories that are unlinked\n * @param directory within which the following item is located\n * @param item base path of item/directory\n */\n _remove(directory, item, isDirectory) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n const path = sp.join(directory, item);\n const fullPath = sp.resolve(path);\n isDirectory =\n isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100))\n return;\n // if the only watched file is removed, watch for its return\n if (!isDirectory && this._watched.size === 1) {\n this.add(directory, item, true);\n }\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n const wp = this._getWatchedDir(path);\n const nestedDirectoryChildren = wp.getChildren();\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));\n // Check if item was on the watched list and remove it\n const parent = this._getWatchedDir(directory);\n const wasTracked = parent.has(item);\n parent.remove(item);\n // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n // but never removed from the map in case the path was deleted.\n // This leads to an incorrect state if the path was recreated:\n // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n if (this._symlinkPaths.has(fullPath)) {\n this._symlinkPaths.delete(fullPath);\n }\n // If we wait for this file to be fully written, cancel the wait.\n let relPath = path;\n if (this.options.cwd)\n relPath = sp.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n const event = this._pendingWrites.get(relPath).cancelWait();\n if (event === EV.ADD)\n return;\n }\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n this._watched.delete(path);\n this._watched.delete(fullPath);\n const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;\n if (wasTracked && !this._isIgnored(path))\n this._emit(eventName, path);\n // Avoid conflicts if we later create another file with the same name\n this._closePath(path);\n }\n /**\n * Closes all watchers for a path\n */\n _closePath(path) {\n this._closeFile(path);\n const dir = sp.dirname(path);\n this._getWatchedDir(dir).remove(sp.basename(path));\n }\n /**\n * Closes only file-specific watchers\n */\n _closeFile(path) {\n const closers = this._closers.get(path);\n if (!closers)\n return;\n closers.forEach((closer) => closer());\n this._closers.delete(path);\n }\n _addPathCloser(path, closer) {\n if (!closer)\n return;\n let list = this._closers.get(path);\n if (!list) {\n list = [];\n this._closers.set(path, list);\n }\n list.push(closer);\n }\n _readdirp(root, opts) {\n if (this.closed)\n return;\n const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };\n let stream = readdirp(root, options);\n this._streams.add(stream);\n stream.once(STR_CLOSE, () => {\n stream = undefined;\n });\n stream.once(STR_END, () => {\n if (stream) {\n this._streams.delete(stream);\n stream = undefined;\n }\n });\n return stream;\n }\n}\n/**\n * Instantiates watcher with paths to be tracked.\n * @param paths file / directory paths\n * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others\n * @returns an instance of FSWatcher for chaining.\n * @example\n * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });\n * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })\n */\nexport function watch(paths, options = {}) {\n const watcher = new FSWatcher(options);\n watcher.add(paths);\n return watcher;\n}\nexport default { watch: watch, FSWatcher: FSWatcher };\n","/**\n * @typedef {import('@rockcarver/frodo-lib/types/ops/ScriptOps').ScriptFilter} LibScriptFilter\n * @typedef {import('@rockcarver/frodo-lib/types/ops/ScriptOps').ScriptFilterCondition} LibScriptFilterCondition\n * @typedef {import('@rockcarver/frodo-lib/types/ops/ScriptOps').ScriptFilterGroup} LibScriptFilterGroup\n */\n\nfunction normalizeFilterValue(value) {\n const normalizedValue = value?.trim();\n return normalizedValue ? normalizedValue : undefined;\n}\n\nexport function normalizeScriptFilters(filters = {}) {\n return {\n context: normalizeFilterValue(filters.context)\n ?.replace(/[\\s-]+/g, '_')\n .toUpperCase(),\n evaluatorVersion: normalizeFilterValue(filters.evaluatorVersion),\n language: normalizeFilterValue(filters.language)?.toUpperCase(),\n };\n}\n\nexport function hasScriptFilters(filters = {}) {\n return !!(filters.context || filters.evaluatorVersion || filters.language);\n}\n\nexport function matchesScriptFilters(script, filters = {}) {\n const normalizedFilters = normalizeScriptFilters(filters);\n return (\n (!normalizedFilters.context ||\n script.context === normalizedFilters.context) &&\n (!normalizedFilters.evaluatorVersion ||\n script.evaluatorVersion === normalizedFilters.evaluatorVersion) &&\n (!normalizedFilters.language ||\n script.language === normalizedFilters.language)\n );\n}\n\nexport function filterScripts(scripts, filters = {}) {\n if (!hasScriptFilters(filters)) return scripts;\n return scripts.filter((script) => matchesScriptFilters(script, filters));\n}\n\n/**\n * @param {{ context?: string, evaluatorVersion?: string, language?: string }} [filters={}]\n * @returns {LibScriptFilter | undefined}\n */\nexport function createScriptFilter(filters = {}) {\n const normalizedFilters = normalizeScriptFilters(filters);\n /** @type {LibScriptFilterCondition[]} */\n const filterConditions = [\n normalizedFilters.context && {\n field: 'context',\n value: normalizedFilters.context,\n },\n normalizedFilters.evaluatorVersion && {\n field: 'evaluatorVersion',\n value: normalizedFilters.evaluatorVersion,\n },\n normalizedFilters.language && {\n field: 'language',\n value: normalizedFilters.language,\n },\n ].filter(Boolean);\n if (filterConditions.length === 0) return undefined;\n if (filterConditions.length === 1) return filterConditions[0];\n return /** @type {LibScriptFilterGroup} */ ({\n operator: 'AND',\n filters: filterConditions,\n });\n}\n\nfunction getLibraryScriptNames(script) {\n if (!script.script) return [];\n const rawScript = Array.isArray(script.script)\n ? script.script.join('\\n')\n : script.script;\n return Array.from(rawScript.matchAll(/require\\((['\"])(.+?)\\1\\)/g)).map(\n (match) => match[2]\n );\n}\n\nexport function includeScriptDependencies(scripts, allScripts) {\n const scriptsByName = new Map(\n allScripts.map((script) => [script.name, script])\n );\n const includedScripts = new Map(\n scripts.map((script) => [script._id, script])\n );\n const queue = [...scripts];\n while (queue.length > 0) {\n const script = queue.shift();\n if (!script) continue;\n for (const libraryScriptName of getLibraryScriptNames(script)) {\n const libraryScript = scriptsByName.get(libraryScriptName);\n if (libraryScript && !includedScripts.has(libraryScript._id)) {\n includedScripts.set(libraryScript._id, libraryScript);\n queue.push(libraryScript);\n }\n }\n }\n return Array.from(includedScripts.values());\n}\n\nexport function filterScriptExport(\n scriptExport,\n filters = {},\n includeDependencies = false\n) {\n if (!hasScriptFilters(filters)) return scriptExport;\n const allScripts = Object.values(scriptExport.script);\n let filteredScripts = filterScripts(allScripts, filters);\n if (includeDependencies) {\n filteredScripts = includeScriptDependencies(filteredScripts, allScripts);\n }\n return {\n ...scriptExport,\n script: Object.fromEntries(\n filteredScripts.map((script) => [script._id, script])\n ),\n };\n}\n","import fs from 'fs';\nimport {\n frodo,\n FrodoError,\n state,\n type FullExportInterface,\n type ScriptExportInterface,\n type ScriptExportOptions,\n type ScriptImportOptions,\n type ScriptSkeleton,\n} from '@rockcarver/frodo-lib';\nimport chokidar from 'chokidar';\nimport c from '../utils/ColorTheme';\nimport {\n extractDataToFile,\n getExtractedData,\n getFullExportConfig,\n getIdLocations,\n} from '../utils/Config';\nimport {\n createKeyValueTable,\n createProgressIndicator,\n createTable,\n debugMessage,\n failSpinner,\n printError,\n printMessage,\n showSpinner,\n stopProgressIndicator,\n succeedSpinner,\n updateProgressIndicator,\n} from '../utils/Console';\nimport { errorHandler } from './utils/OpsUtils';\nimport {\n createScriptFilter,\n filterScriptExport,\n filterScripts,\n hasScriptFilters,\n} from './utils/ScriptFilters';\nimport wordwrap from './utils/Wordwrap';\n\nconst {\n getTypedFilename,\n isValidUrl,\n saveJsonToFile,\n titleCase,\n isBase64Encoded,\n getFilePath,\n getWorkingDirectory,\n saveToFile,\n decodeBase64,\n} = frodo.utils;\nconst {\n readScript,\n readScriptByName,\n readScripts,\n exportScript,\n exportScriptByName,\n exportScripts,\n importScripts,\n deleteScript,\n deleteScriptByName,\n deleteScripts,\n} = frodo.script;\nconst { readScriptBindings, readScriptTypes } = frodo.scriptType;\n\nconst langMap = { JAVASCRIPT: 'JavaScript', GROOVY: 'Groovy' };\n\nexport type ScriptFilters = {\n context?: string;\n evaluatorVersion?: string;\n language?: string;\n};\n\ntype SeparatedScripts = {\n realm: Record<string, { script: Record<string, ScriptSkeleton> }>;\n};\n\ntype ScriptLike = ScriptSkeleton & {\n _id: string;\n evaluatorVersion?: string;\n};\n\n/**\n * Pass filters through to newer frodo-lib versions when available.\n * Current frodo-lib releases ignore the extra argument, so callers still\n * apply local filtering as a compatibility fallback.\n */\nfunction readScriptsWithFilterPassthrough(\n filters: ScriptFilters = {}\n): Promise<ScriptLike[]> {\n const filter = createScriptFilter(filters);\n return (\n readScripts as unknown as (filter?: unknown) => Promise<ScriptLike[]>\n )(filter);\n}\n\n/**\n * Pass filters through to newer frodo-lib versions when available.\n * Current frodo-lib releases ignore the extra argument, so callers still\n * apply local filtering as a compatibility fallback.\n */\nfunction exportScriptsWithFilterPassthrough(\n options: ScriptExportOptions,\n filters: ScriptFilters = {}\n): Promise<ScriptExportInterface> {\n const filter = createScriptFilter(filters);\n const optionsWithFilter: ScriptExportOptions = filter\n ? { ...options, filter }\n : options;\n return exportScripts(optionsWithFilter, errorHandler);\n}\n\nasync function readFilteredScripts(\n filters: ScriptFilters = {}\n): Promise<ScriptLike[]> {\n return filterScripts(\n await readScriptsWithFilterPassthrough(filters),\n filters\n );\n}\n\nasync function readFilteredNonDefaultScripts(\n filters: ScriptFilters = {}\n): Promise<ScriptLike[]> {\n return (await readFilteredScripts(filters)).filter(\n (script) => !script.default\n );\n}\n\nfunction filterTypedScriptExport(\n scriptExport: ScriptExportInterface,\n filters: ScriptFilters = {},\n includeDependencies = false\n): ScriptExportInterface {\n return filterScriptExport(\n scriptExport as unknown as {\n script: Record<string, ScriptLike>;\n },\n filters,\n includeDependencies\n ) as ScriptExportInterface;\n}\n\n/**\n * Get a one-line description of the script object\n * @param {ScriptSkeleton} scriptObj script object to describe\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(scriptObj: ScriptSkeleton): string {\n const description = `[${c.heading(scriptObj._id)}] ${scriptObj.context} - ${scriptObj.name}`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Name | Language | Type | Id |\\n';\n markdown += '| ---- | -------- | ---- | ---|';\n return markdown;\n}\n\n/**\n * Get a one-line description of the script object in markdown\n * @param {TypesRaw.ScriptSkeleton} scriptObj script object to describe\n * @returns {string} markdown table row\n */\nexport function getTableRowMd(scriptObj: ScriptSkeleton): string {\n const description = `| ${scriptObj.name} | ${\n langMap[scriptObj.language]\n } | ${titleCase(scriptObj.context.split('_').join(' '))} | \\`${\n scriptObj._id\n }\\` |`;\n return description;\n}\n\n/**\n * List scripts\n * @param {boolean} long detail list\n * @param {boolean} usage display usage field\n * @param {String | null} file Optional filename to determine usage\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listScripts(\n long: boolean = false,\n usage: boolean = false,\n file: string | null = null,\n filters: ScriptFilters = {}\n): Promise<boolean> {\n let spinnerId: string;\n let scripts: ScriptSkeleton[];\n debugMessage(`Cli.ScriptOps.listScripts: start`);\n try {\n spinnerId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Reading scripts...`\n );\n scripts = await readFilteredScripts(filters);\n scripts.sort((a, b) => a.name.localeCompare(b.name));\n stopProgressIndicator(\n spinnerId,\n `Successfully read ${scripts.length} scripts.`,\n 'success'\n );\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error reading scripts`, 'fail');\n printError(error);\n return false;\n }\n if (!long && !usage) {\n scripts.forEach((script) => {\n printMessage(`${script.name}`, 'data');\n });\n debugMessage(`Cli.ScriptOps.listScripts: end`);\n return true;\n }\n let fullExport: FullExportInterface = null;\n let scriptExport: SeparatedScripts = null;\n const headers = long\n ? ['Name', 'UUID', 'Language', 'Context', 'Description']\n : ['Name'];\n if (usage) {\n try {\n fullExport = await getFullExportConfig(file);\n } catch (error) {\n printError(error);\n return false;\n }\n scriptExport = separateScriptsFromFullExport(fullExport);\n headers.push('Used');\n }\n const table = createTable(headers);\n scripts.forEach((script) => {\n const values = long\n ? [\n wordwrap(script.name, 25, ' '),\n script._id,\n langMap[script.language],\n wordwrap(titleCase(script.context.split('_').join(' ')), 25),\n wordwrap(script.description, 30),\n ]\n : [wordwrap(script.name, 25, ' ')];\n if (usage) {\n const locations = getIdLocations(fullExport, script._id, false).concat(\n getScriptLocations(scriptExport, script.name)\n );\n values.push(\n locations.length > 0\n ? `${c.positive('yes')} (${locations.length === 1 ? `at` : `${locations.length} uses, including:`} ${locations[0]})`\n : c.negative('no')\n );\n }\n table.push(values);\n });\n printMessage(table.toString(), 'data');\n debugMessage(`Cli.ScriptOps.listScripts: end`);\n return true;\n}\n\n/**\n * Describe a script\n * @param {string} scriptId script id\n * @param {string} scriptName script name\n * @param {string} file optional export file\n * @param {boolean} usage true to describe usage, false otherwise. Default: false\n * @param {boolean} json output description as json. Default: false\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function describeScript(\n scriptId: string,\n scriptName: string,\n file?: string,\n usage = false,\n json = false\n): Promise<boolean> {\n try {\n let script;\n if (scriptId) {\n script = (await readScript(scriptId)) as ScriptSkeleton & {\n locations: string[];\n };\n } else {\n script = (await readScriptByName(scriptName)) as ScriptSkeleton & {\n locations: string[];\n };\n }\n if (usage) {\n try {\n const fullExport = await getFullExportConfig(file);\n const scriptExport = separateScriptsFromFullExport(fullExport);\n script.locations = getIdLocations(fullExport, script._id, false).concat(\n getScriptLocations(scriptExport, script.name)\n );\n } catch (error) {\n printError(error);\n return false;\n }\n }\n if (json) {\n printMessage(script, 'data');\n } else {\n const table = createKeyValueTable();\n table.push([c.heading('Id'), script._id]);\n table.push([c.heading('Name'), script.name]);\n table.push([c.heading('Language'), langMap[script.language]]);\n table.push([\n c.heading('Context'),\n titleCase(script.context.split('_').join(' ')),\n ]);\n table.push([c.heading('Description'), script.description]);\n table.push([\n c.heading('Default'),\n script.default ? c.positive('true') : c.negative('false'),\n ]);\n table.push([c.heading('Evaluator Version'), script.evaluatorVersion]);\n const scriptWrapLength = 80;\n const wrapRegex = new RegExp(`.{1,${scriptWrapLength + 1}}`, 'g');\n const scriptParts = script.script.match(wrapRegex);\n table.push([c.heading('Script (Base 64)'), scriptParts[0]]);\n for (let i = 1; i < scriptParts.length; i++) {\n table.push(['', scriptParts[i]]);\n }\n if (usage) {\n table.push([\n c.heading(`Usage Locations (${script.locations.length} total)`),\n script.locations.length > 0 ? script.locations[0] : '',\n ]);\n for (let i = 1; i < script.locations.length; i++) {\n table.push(['', script.locations[i]]);\n }\n }\n printMessage(table.toString(), 'data');\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * List every scripting context, i.e. the valid `-c/--context` values for\n * `script type describe` (the context's own `_id`, e.g.\n * `SCRIPTED_DECISION_NODE`). Name only by default, one per line; `long`\n * prints a Name/Languages/Hidden table instead. A context marked hidden\n * (e.g. `NODE_DESIGNER`) is an internal one the platform doesn't surface in\n * its own UI, not one `describe` refuses to read -- included either way.\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete list, regardless of `long`\n * @param {boolean} long true to print a Name/Languages/Hidden table instead of just names\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listScriptTypes(\n json = false,\n long = false\n): Promise<boolean> {\n try {\n const types = await readScriptTypes();\n const sorted = types.slice().sort((a, b) => a._id.localeCompare(b._id));\n if (json) {\n printMessage(JSON.stringify(sorted, null, 2), 'data');\n return true;\n }\n if (!long) {\n sorted.forEach((type) => printMessage(type._id, 'data'));\n return true;\n }\n const table = createTable(['Name', 'Languages', 'Hidden']);\n sorted.forEach((type) => {\n table.push([\n type._id,\n (type.languages || []).join(', '),\n type.isHidden ? 'yes' : 'no',\n ]);\n });\n printMessage(table.toString(), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Describe the bindings (available objects/APIs) exposed to scripts running\n * in a given scripting context, e.g. what httpClient/idRepository/logger\n * methods a SCRIPTED_DECISION_NODE script can call.\n * @param {string} context scripting context id, e.g. SCRIPTED_DECISION_NODE\n * @param {boolean} json output the full binding definitions as JSON instead of a summary table\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function describeScriptBindings(\n context: string,\n json = false\n): Promise<boolean> {\n try {\n const bindings = await readScriptBindings(context);\n if (json) {\n printMessage(JSON.stringify(bindings, null, 2), 'data');\n return true;\n }\n const table = createTable(['Name', 'Java Class', 'Elements']);\n bindings\n .slice()\n .sort((a, b) => a.name.localeCompare(b.name))\n .forEach((binding) => {\n table.push([\n binding.name,\n binding.javaClass,\n String(binding.elements?.length ?? 0),\n ]);\n });\n printMessage(table.toString(), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export script by id to file\n * @param {string} scriptId script uuid\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {boolean} extract Extracts the scripts from the exports into separate files if true\n * @param {ScriptExportOptions} options Export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportScriptToFile(\n scriptId: string,\n file: string,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n extract: boolean = false,\n options: ScriptExportOptions\n): Promise<boolean> {\n debugMessage(`Cli.ScriptOps.exportScriptToFile: start`);\n try {\n const id = showSpinner(`Exporting script '${scriptId}'...`);\n let fileName = getTypedFilename(scriptId, 'script');\n if (file) {\n fileName = file;\n }\n const filePath = getFilePath(fileName, true);\n updateProgressIndicator(\n id,\n `Exporting script '${scriptId}' to '${filePath}'...`\n );\n const scriptExport = await exportScript(scriptId, options);\n if (extract) {\n extractScriptsToFiles(scriptExport, undefined, undefined, false);\n }\n saveJsonToFile(\n scriptExport,\n filePath,\n includeMeta,\n false,\n keepModifiedProperties\n );\n succeedSpinner(`Exported script '${scriptId}' to '${filePath}'.`);\n debugMessage(`Cli.ScriptOps.exportScriptToFile: end`);\n return true;\n } catch (error) {\n failSpinner(`Error exporting script '${scriptId}': ${error.message}`);\n printError(error);\n }\n return false;\n}\n\n/**\n * Export script by name to file\n * @param {string} name script name\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {boolean} extract Extracts the scripts from the exports into separate files if true\n * @param {ScriptExportOptions} options Export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportScriptByNameToFile(\n name: string,\n file: string,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n extract: boolean = false,\n options: ScriptExportOptions\n): Promise<boolean> {\n debugMessage(`Cli.ScriptOps.exportScriptByNameToFile: start`);\n try {\n const id = showSpinner(`Exporting script '${name}'...`);\n let fileName = getTypedFilename(name, 'script');\n if (file) {\n fileName = file;\n }\n const filePath = getFilePath(fileName, true);\n updateProgressIndicator(\n id,\n `Exporting script '${name}' to '${filePath}'...`\n );\n const scriptExport = await exportScriptByName(name, options);\n if (extract) extractScriptsToFiles(scriptExport);\n saveJsonToFile(\n scriptExport,\n filePath,\n includeMeta,\n false,\n keepModifiedProperties\n );\n succeedSpinner(`Exported script '${name}' to '${filePath}'.`);\n debugMessage(`Cli.ScriptOps.exportScriptByNameToFile: end`);\n return true;\n } catch (error) {\n failSpinner(`Error exporting script '${name}': ${error.message}`);\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all scripts to single file\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {ScriptExportOptions} options Export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportScriptsToFile(\n file: string,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n options: ScriptExportOptions,\n filters: ScriptFilters = {}\n): Promise<boolean> {\n debugMessage(`Cli.ScriptOps.exportScriptsToFile: start`);\n try {\n let fileName = getTypedFilename(\n `all${titleCase(state.getRealm())}Scripts`,\n 'script'\n );\n if (file) {\n fileName = file;\n }\n const scriptExport = filterTypedScriptExport(\n await exportScriptsWithFilterPassthrough(options, filters),\n filters,\n options.deps\n );\n saveJsonToFile(\n scriptExport,\n getFilePath(fileName, true),\n includeMeta,\n false,\n keepModifiedProperties\n );\n debugMessage(`Cli.ScriptOps.exportScriptsToFile: end`);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all scripts to individual files\n * @param {boolean} extract Extracts the scripts from the exports into separate files if true\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {ScriptExportOptions} options Export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportScriptsToFiles(\n extract: boolean = false,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n options: ScriptExportOptions,\n filters: ScriptFilters = {}\n): Promise<boolean> {\n debugMessage(`Cli.ScriptOps.exportScriptsToFiles: start`);\n const errors: Error[] = [];\n const scriptExport = filterTypedScriptExport(\n await exportScriptsWithFilterPassthrough(options, filters),\n filters,\n options.deps\n );\n const scriptList = Object.values(scriptExport.script);\n const barId = createProgressIndicator(\n 'determinate',\n scriptList.length,\n 'Exporting scripts to individual files...'\n );\n for (const script of scriptList) {\n const fileBarId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting script ${script.name}...`\n );\n try {\n const file = getFilePath(getTypedFilename(script.name, 'script'), true);\n if (extract) {\n extractScriptsToFiles({\n script: {\n [script._id]: script,\n },\n });\n }\n saveToFile(\n 'script',\n script,\n '_id',\n file,\n includeMeta,\n keepModifiedProperties\n );\n updateProgressIndicator(fileBarId, `Saving ${script.name} to ${file}.`);\n stopProgressIndicator(fileBarId, `${script.name} saved to ${file}.`);\n } catch (error) {\n stopProgressIndicator(\n fileBarId,\n `Error exporting ${script.name}`,\n 'fail'\n );\n errors.push(error);\n }\n updateProgressIndicator(barId, `Exported script ${script.name}`);\n }\n if (errors.length > 0) {\n throw new FrodoError(`Error exporting scripts`, errors);\n }\n stopProgressIndicator(\n barId,\n `Exported ${scriptList.length} scripts to individual files.`\n );\n debugMessage(`Cli.ScriptOps.exportScriptsToFiles: end`);\n return true;\n}\n\n/**\n * Extracts scripts from a script export into separate files.\n * @param {ScriptExportInterface} scriptExport The script export\n * @param {string} scriptId The script id to extract a specific script. If undefined, will extract all scripts.\n * @param {string} directory The directory within the base directory to save the script files\n * @param {boolean} useScriptNamesForFiles True to name files using script names, false to use id's instead. Default: true\n * @returns {boolean} true if successful, false otherwise\n */\nexport function extractScriptsToFiles(\n scriptExport: ScriptExportInterface,\n scriptId?: string,\n directory?: string,\n useScriptNamesForFiles: boolean = true\n): boolean {\n try {\n const scripts = scriptId\n ? [scriptExport.script[scriptId]]\n : Object.values(scriptExport.script);\n for (const script of scripts) {\n const fileExtension = script.language === 'JAVASCRIPT' ? 'js' : 'groovy';\n const scriptFileName = getTypedFilename(\n useScriptNamesForFiles ? script.name : script._id,\n 'script',\n fileExtension\n );\n const scriptText = Array.isArray(script.script)\n ? script.script.join('\\n')\n : script.script;\n script.script = extractDataToFile(scriptText, scriptFileName, directory);\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\nexport function isScriptExtracted(script: string | string[]): boolean {\n debugMessage(`Cli.ScriptOps.isScriptExtracted: start`);\n let extracted = false;\n if (Array.isArray(script)) {\n debugMessage(`Cli.ScriptOps.isScriptExtracted: script is string array`);\n extracted = false;\n } else if (isValidUrl(script as string)) {\n debugMessage(`Cli.ScriptOps.isScriptExtracted: script is extracted`);\n extracted = script.startsWith('file://');\n } else if (isBase64Encoded(script)) {\n debugMessage(`Cli.ScriptOps.isScriptExtracted: script is base64-encoded`);\n extracted = false;\n }\n debugMessage(`Cli.ScriptOps.isScriptExtracted: end [extracted=${extracted}]`);\n return extracted;\n}\n\n/**\n * Import script(s) from file\n * @param {string} id Optional id of script. If supplied, only the script of that id is imported. Takes priority over the name if both are provided.\n * @param {string} name Optional name of script. If supplied, only the script of that name is imported\n * @param {string} file file name\n * @param {ScriptImportOptions} options Script import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importScriptsFromFile(\n id: string = '',\n name: string = '',\n file: string,\n options: ScriptImportOptions = {\n deps: true,\n reUuid: false,\n includeDefault: false,\n }\n): Promise<boolean> {\n const filePath = getFilePath(file);\n debugMessage(`Cli.ScriptOps.importScriptsFromFile: start`);\n try {\n await handleScriptFileImport(id, name, filePath, options, false);\n debugMessage(`Cli.ScriptOps.importScriptsFromFile: end`);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Import extracted scripts.\n *\n * @param {boolean} watch whether or not to watch for file changes\n * @param {ScriptImportOptions} options Script import options\n * @param {boolean} validateScripts If true, validates Javascript scripts to ensure no errors exist in them. Default: false\n */\nexport async function importScriptsFromFiles(\n watch: boolean,\n options: ScriptImportOptions,\n validateScripts: boolean\n): Promise<void> {\n debugMessage(`Cli.ScriptOps.importScriptsFromFiles: start`);\n\n // If watch is true, it doesn't make sense to reUuid.\n options.reUuid = watch ? false : options.reUuid;\n\n let initialImport = true;\n // Generate mappings while importing to identify script files with their script ids and json files for use in watching.\n const scriptPathToJsonMapping = {};\n const scriptPathToIdMapping = {};\n\n /**\n * Run on file change detection, as well as on initial run.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async function onChange(path: string, _stats?: fs.Stats): Promise<void> {\n debugMessage(\n `Cli.ScriptOps.importScriptsFromFiles.onChange: start [initialImport=${initialImport}, path=${path}]`\n );\n try {\n if (initialImport && path.endsWith('.script.json')) {\n debugMessage(\n `Cli.ScriptOps.importScriptsFromFiles.onChange: initial import of ${path}`\n );\n if (watch) {\n scriptPathToJsonMapping[path] = path;\n for (const extracted of getExtractedPathsAndNames(path)) {\n scriptPathToJsonMapping[extracted.path] = path;\n scriptPathToIdMapping[extracted.path] = extracted.id;\n }\n } else {\n await handleScriptFileImport('', '', path, options, validateScripts);\n }\n } else if (!initialImport) {\n await handleScriptFileImport(\n scriptPathToIdMapping[path],\n '',\n scriptPathToJsonMapping[path],\n options,\n validateScripts\n );\n }\n } catch (error) {\n printError(error, `${path}`);\n }\n debugMessage(`Cli.ScriptOps.importScriptsFromFiles.onChange: end`);\n }\n\n // We watch json files and script files.\n const watcher = chokidar.watch(getWorkingDirectory(), {\n // ignored: (path, stats) =>\n // watch\n // ? // in watch mode, ignore everything but raw scripts\n // stats?.isFile() &&\n // !path?.endsWith('.script.js') &&\n // !path?.endsWith('.script.groovy')\n // : // in regular mode, ignore everything but frodo script exports\n // stats?.isFile() && !path?.endsWith('.script.json'),\n ignored: (path, stats) =>\n stats?.isFile() &&\n !path?.endsWith('.script.json') &&\n !path?.endsWith('.script.js') &&\n !path?.endsWith('.script.groovy'),\n persistent: watch,\n ignoreInitial: false,\n });\n\n watcher\n .on('add', onChange)\n .on('change', onChange)\n .on('error', (error) => {\n printError(error as Error, `Watcher error`);\n watcher.close();\n })\n .on('ready', async () => {\n debugMessage(\n `Cli.ScriptOps.importScriptsFromFiles: Watcher ready: ${JSON.stringify(watcher.getWatched())}`\n );\n if (watch) {\n initialImport = false;\n printMessage('Watching for changes...');\n } else {\n await watcher.close();\n }\n });\n\n debugMessage(`Cli.ScriptOps.importScriptsFromFiles: end`);\n}\n\n/**\n * Handle a script file import.\n * @param {string} id Optional id of script. If supplied, only the script of that id is imported. Takes priority over the name if both are provided.\n * @param {string} name Optional name of script. If supplied, only the script of that name is imported\n * @param {string} file The script json file\n * @param {ScriptImportOptions} options Script import options\n * @param {boolean} validateScripts If true, validates Javascript scripts to ensure no errors exist in them. Default: false\n */\nasync function handleScriptFileImport(\n id: string = '',\n name: string = '',\n file: string,\n options: ScriptImportOptions,\n validateScripts: boolean\n) {\n debugMessage(`Cli.ScriptOps.handleScriptFileImport: start`);\n const script = getScriptExportByScriptFile(file);\n const indicatorId = createProgressIndicator('determinate', 1, `${file}`);\n try {\n const scripts = await importScripts(\n id,\n name,\n script,\n options,\n validateScripts,\n errorHandler\n );\n let message;\n if (id || name) {\n message =\n scripts.length > 0\n ? `${file}: Imported ${id || name}.`\n : `${file}: Did not import ${id || name} since no changes were made.`;\n } else {\n message = `${file}: Imported ${scripts.length} scripts.`;\n }\n updateProgressIndicator(indicatorId, message);\n stopProgressIndicator(\n indicatorId,\n message,\n scripts.length ? 'success' : 'warn'\n );\n } catch (error) {\n stopProgressIndicator(indicatorId, `${file}: ${error}`, 'fail');\n }\n debugMessage(`Cli.ScriptOps.handleScriptFileImport: end`);\n}\n\n/**\n * Get a script export from a script file.\n *\n * @param scriptFile The path to the script file\n * @returns The script export\n */\nexport function getScriptExportByScriptFile(\n scriptFile: string\n): ScriptExportInterface {\n const scriptExport = getScriptExport(scriptFile);\n for (const script of Object.values(scriptExport.script)) {\n if (!isScriptExtracted(script.script)) {\n continue;\n }\n const scriptRaw = getExtractedData(\n script.script as string,\n scriptFile.substring(0, scriptFile.lastIndexOf('/'))\n );\n script.script = scriptRaw.split('\\n');\n }\n return scriptExport;\n}\n\n/**\n * Get a script export from a file.\n *\n * @param file The path to a script export file\n * @returns The script export\n */\nfunction getScriptExport(file: string): ScriptExportInterface {\n const scriptExportRaw = fs.readFileSync(file, 'utf8');\n return JSON.parse(scriptExportRaw) as ScriptExportInterface;\n}\n\n/**\n * Gets extracted file paths and script ids from json file\n *\n * @param file the json file\n * @returns The extracted file paths and script ids\n */\nfunction getExtractedPathsAndNames(\n file: string\n): { path: string; id: string }[] {\n const extractedFileNames = [];\n const scriptExport = getScriptExport(file);\n const directory =\n file.lastIndexOf('/') === -1\n ? ''\n : file.substring(0, file.lastIndexOf('/')) + '/';\n for (const script of Object.values(scriptExport.script)) {\n if (!isScriptExtracted(script.script)) {\n continue;\n }\n extractedFileNames.push({\n path: `${directory}${(script.script as string).replace('file://', '')}`,\n id: script._id,\n });\n }\n return extractedFileNames;\n}\n\n/**\n * Delete script by id\n * @param {String} id script id\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteScriptId(id: string): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${id}...`\n );\n try {\n await deleteScript(id);\n stopProgressIndicator(spinnerId, `Deleted ${id}.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete script by name\n * @param {String} name script name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteScriptName(name: string): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${name}...`\n );\n try {\n await deleteScriptByName(name);\n stopProgressIndicator(spinnerId, `Deleted ${name}.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete all non-default scripts\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteAllScripts(\n filters: ScriptFilters = {}\n): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting all non-default scripts...`\n );\n try {\n if (hasScriptFilters(filters)) {\n const scripts = await readFilteredNonDefaultScripts(filters);\n for (const script of scripts) {\n await deleteScript(script._id);\n }\n stopProgressIndicator(\n spinnerId,\n `Deleted ${scripts.length} matching non-default script${scripts.length === 1 ? '' : 's'}.`,\n 'success'\n );\n return true;\n }\n await deleteScripts(errorHandler);\n stopProgressIndicator(\n spinnerId,\n `Deleted all non-default scripts.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Helper that takes a full export and separates the scripts from it into their own export\n * @param {FullExportInterface} fullExport The full export\n * @returns {SeparatedScripts} The scripts separated from the fullExport\n */\nfunction separateScriptsFromFullExport(\n fullExport: FullExportInterface\n): SeparatedScripts {\n const scripts = { realm: {} };\n // Some live exports can omit realm content; treat that as no script usage data.\n if (!fullExport?.realm || typeof fullExport.realm !== 'object') {\n return scripts;\n }\n for (const [realm, realmExport] of Object.entries(fullExport.realm)) {\n if (!scripts.realm[realm]) {\n scripts.realm[realm] = {};\n }\n // Normalize missing per-realm script sections to an empty object to avoid traversal errors.\n scripts.realm[realm].script = realmExport?.script ?? {};\n if (realmExport && typeof realmExport === 'object') {\n delete realmExport.script;\n }\n }\n return scripts;\n}\n\n/**\n * Helper that finds all locations where a script is being used as a library in another script\n * @param {SeparatedScripts} configuration The scripts to search\n * @param {string} scriptName The name of the script being searched for\n */\nfunction getScriptLocations(\n configuration: SeparatedScripts,\n scriptName: string\n): string[] {\n const locations = [];\n const regex = new RegExp(`require\\\\(['|\"]${scriptName}['|\"]\\\\)`);\n // Guard against partially populated exports where realm or script objects are missing.\n for (const [realm, realmExport] of Object.entries(\n configuration?.realm ?? {}\n )) {\n for (const scriptData of Object.values(realmExport?.script ?? {})) {\n let scriptString = scriptData.script as string;\n if (Array.isArray(scriptData.script)) {\n scriptString = scriptData.script.join('\\n');\n } else if (isBase64Encoded(scriptData.script)) {\n scriptString = decodeBase64(scriptData.script);\n }\n if (regex.test(scriptString)) {\n locations.push(\n `realm.${realm}.script.${scriptData._id}(name: '${scriptData.name}').script`\n );\n }\n }\n }\n return locations;\n}\n","import fs from 'fs';\nimport {\n frodo,\n FrodoError,\n type ApprovalTask,\n type ScriptTask,\n type WorkflowExportInterface,\n type WorkflowExportOptions,\n type WorkflowExpression,\n type WorkflowGroup,\n type WorkflowImportOptions,\n} from '@rockcarver/frodo-lib';\nimport c from '../../../utils/ColorTheme';\nimport { extractDataToFile, getExtractedData } from '../../../utils/Config';\nimport {\n createKeyValueTable,\n createProgressIndicator,\n createTable,\n getTableRowsFromArray,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../../../utils/Console';\nimport * as EmailTemplate from '../../EmailTemplateOps';\nimport { isScriptExtracted } from '../../ScriptOps';\nimport { errorHandler } from '../../utils/OpsUtils';\n\nconst { getTypedFilename, saveJsonToFile, getFilePath, getWorkingDirectory } =\n frodo.utils;\nconst {\n publishWorkflow: _publishWorkflow,\n importWorkflows,\n readWorkflowGroups,\n exportWorkflow,\n exportWorkflows,\n deleteWorkflow: _deleteWorkflow,\n deleteWorkflows: _deleteWorkflows,\n} = frodo.cloud.iga.workflow;\n/**\n * List all the workflows\n * @param {boolean} long Long version, all the fields\n * @returns {Promise<boolean>} a promise resolving to true if successful, false otherwise\n */\nexport async function listWorkflows(long: boolean = false): Promise<boolean> {\n let workflows: WorkflowGroup[];\n try {\n workflows = await readWorkflowGroups();\n if (!long) {\n for (const workflow of workflows) {\n printMessage(\n `${workflow.published ? workflow.published.id : workflow.draft.id}`,\n 'data'\n );\n }\n return true;\n }\n const table = createTable([\n 'ID',\n 'Name',\n 'Drafted',\n 'Published',\n 'Mutable',\n ]);\n for (const workflowGroup of workflows) {\n const workflow = workflowGroup.published ?? workflowGroup.draft;\n table.push([\n `${workflow.id}`,\n workflow.name,\n workflowGroup.draft ? c.positive('true') : c.negative('false'),\n workflowGroup.published ? c.positive('true') : c.negative('false'),\n workflow.mutable ? c.positive('true') : c.negative('false'),\n ]);\n }\n printMessage(table.toString(), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Describe a workflow\n * @param {string} workflowId workflow id\n * @param {string} file the workflow export file\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function describeWorkflow(\n workflowId?: string,\n file?: string\n): Promise<boolean> {\n try {\n const workflowExport = file\n ? getWorkflowExportFromFile(getFilePath(file))\n : await exportWorkflow(workflowId, {\n deps: true,\n useStringArrays: false,\n coords: true,\n includeReadOnly: true,\n });\n if (!workflowId) {\n const ids = Object.keys(workflowExport.workflow);\n if (ids.length === 0)\n throw new FrodoError(`No workflows found in export file ${file}`);\n workflowId = ids[0];\n }\n // Workflow Details\n for (const workflow of [\n workflowExport.workflow[workflowId].draft,\n workflowExport.workflow[workflowId].published,\n ].filter((w) => w)) {\n printMessage(\n `${workflow.status.charAt(0).toUpperCase() + workflow.status.slice(1)} Workflow`,\n 'data'\n );\n const table = createKeyValueTable();\n table.push([c.heading('Id'), workflow.id]);\n table.push([c.heading('Name'), workflow.name]);\n table.push([c.heading('Display Name'), workflow.displayName]);\n table.push([c.heading('Description'), workflow.description]);\n if (workflow.type) table.push([c.heading('Type'), workflow.type]);\n table.push([c.heading('Status'), workflow.status]);\n table.push([\n c.heading('Mutable'),\n workflow.mutable ? c.positive('true') : c.negative('false'),\n ]);\n table.push([\n c.heading('ChildType'),\n workflow.childType ? c.positive('true') : c.negative('false'),\n ]);\n getTableRowsFromArray(\n table,\n `Steps (${workflow.steps.length})`,\n workflow.steps.map((s) => s.name)\n );\n printMessage(table.toString() + '\\n', 'data');\n }\n // Email Templates\n if (Object.entries(workflowExport.emailTemplate).length) {\n printMessage(\n `\\nEmail Templates (${\n Object.entries(workflowExport.emailTemplate).length\n }):`,\n 'data'\n );\n for (const templateData of Object.values(workflowExport.emailTemplate)) {\n printMessage(\n `- ${EmailTemplate.getOneLineDescription(templateData)}`,\n 'data'\n );\n }\n }\n // Events\n if (Object.entries(workflowExport.event).length) {\n printMessage(\n `\\nEvents (${Object.entries(workflowExport.event).length}):`,\n 'data'\n );\n for (const eventData of Object.values(workflowExport.event)) {\n printMessage(`- [${eventData.id}] ${eventData.name}`, 'data');\n }\n }\n // Request Forms\n if (Object.entries(workflowExport.requestForm).length) {\n printMessage(\n `\\nRequest Forms (${\n Object.entries(workflowExport.requestForm).length\n }):`,\n 'data'\n );\n for (const formData of Object.values(workflowExport.requestForm)) {\n printMessage(`- [${formData.id}] ${formData.name}`, 'data');\n }\n }\n // Request Types\n if (Object.entries(workflowExport.requestType).length) {\n printMessage(\n `\\nRequest Types (${\n Object.entries(workflowExport.requestType).length\n }):`,\n 'data'\n );\n for (const typeData of Object.values(workflowExport.requestType)) {\n printMessage(`- [${typeData.id}] ${typeData.displayName}`, 'data');\n }\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export workflow to file\n * @param {string} workflowId workflow id\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {boolean} extract extracts the scripts from the export into separate files if true. Default: false\n * @param {WorkflowExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportWorkflowToFile(\n workflowId: string,\n file: string,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n extract: boolean = false,\n options: WorkflowExportOptions = {\n deps: true,\n useStringArrays: true,\n coords: true,\n includeReadOnly: false,\n }\n): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${workflowId}...`\n );\n try {\n const exportData = await exportWorkflow(workflowId, options);\n if (!file) {\n file = getTypedFilename(workflowId, 'workflow');\n }\n const filePath = getFilePath(file, true);\n if (extract) extractWorkflowScriptsToFiles(exportData);\n updateProgressIndicator(\n indicatorId,\n `Saving ${workflowId} to ${filePath}...`\n );\n saveJsonToFile(\n exportData,\n filePath,\n includeMeta,\n false,\n keepModifiedProperties\n );\n stopProgressIndicator(\n indicatorId,\n `Exported workflow ${workflowId} to file`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error exporting workflow ${workflowId} to file`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all workflows to file\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {WorkflowExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportWorkflowsToFile(\n file: string,\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n options: WorkflowExportOptions = {\n deps: true,\n useStringArrays: true,\n coords: true,\n includeReadOnly: false,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportWorkflows(options, errorHandler);\n if (!file) {\n file = getTypedFilename(`allWorkflows`, 'workflow');\n }\n saveJsonToFile(\n exportData,\n getFilePath(file, true),\n includeMeta,\n false,\n keepModifiedProperties\n );\n return true;\n } catch (error) {\n printError(error, `Error exporting workflows to file`);\n }\n return false;\n}\n\n/**\n * Export all workflows to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} keepModifiedProperties true to keep modified properties, otherwise delete them. Default: false\n * @param {boolean} extract extracts the scripts from the exports into separate files if true. Default: false\n * @param {WorkflowExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportWorkflowsToFiles(\n includeMeta: boolean = true,\n keepModifiedProperties: boolean = false,\n extract: boolean = false,\n options: WorkflowExportOptions = {\n deps: true,\n useStringArrays: true,\n coords: true,\n includeReadOnly: false,\n }\n): Promise<boolean> {\n try {\n // We use the result callback here in order to ensure each saved file contains it's respective dependencies in the event options.deps is true\n await exportWorkflows(options, (e, workflowExport) => {\n if (e) {\n errorHandler(e);\n } else {\n if (extract) extractWorkflowScriptsToFiles(workflowExport);\n saveJsonToFile(\n workflowExport,\n getFilePath(\n getTypedFilename(\n Object.keys(workflowExport.workflow)[0],\n 'workflow'\n ),\n true\n ),\n includeMeta,\n false,\n keepModifiedProperties\n );\n }\n });\n return true;\n } catch (error) {\n printError(error, `Error exporting workflows to files`);\n }\n return false;\n}\n\n/**\n * Import a workflow from file\n * @param {string} workflowId workflow id\n * @param {string} file import file name\n * @param {WorkflowImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importWorkflowFromFile(\n workflowId: string,\n file: string,\n options: WorkflowImportOptions = {\n deps: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Importing workflow...'\n );\n const importData = getWorkflowExportFromFile(getFilePath(file));\n updateProgressIndicator(indicatorId, 'Importing workflow...');\n await importWorkflows(workflowId, importData, options);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported workflow ${workflowId}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing workflow ${workflowId}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Import workflows from file\n * @param {String} file file name\n * @param {WorkflowImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importWorkflowsFromFile(\n file: string,\n options: WorkflowImportOptions = {\n deps: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Importing workflows...'\n );\n const importData = getWorkflowExportFromFile(getFilePath(file));\n updateProgressIndicator(indicatorId, 'Importing workflows...');\n await importWorkflows(undefined, importData, options, errorHandler);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported workflow(s) from file ${file}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing workflow(s).`, 'fail');\n printError(error, `Error importing workflow(s) from file ${file}`);\n }\n return false;\n}\n\n/**\n * Import all workflows from separate files\n * @param {WorkflowImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importWorkflowsFromFiles(\n options: WorkflowImportOptions = {\n deps: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n const errors: Error[] = [];\n try {\n const names = fs.readdirSync(getWorkingDirectory());\n const workflowFiles = names.filter((name) =>\n name.toLowerCase().endsWith('.workflow.json')\n );\n indicatorId = createProgressIndicator(\n 'determinate',\n workflowFiles.length,\n 'Importing workflows...'\n );\n for (const file of workflowFiles) {\n try {\n updateProgressIndicator(\n indicatorId,\n `Importing workflows from file ${file}...`\n );\n await importWorkflowsFromFile(file, options);\n } catch (error) {\n errors.push(\n new FrodoError(`Error importing workflows from ${file}`, error)\n );\n }\n }\n if (errors.length > 0) {\n throw new FrodoError(`One or more errors importing workflows`, errors);\n }\n stopProgressIndicator(\n indicatorId,\n `Successfully imported workflows.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error(s) importing workflows.`, 'fail');\n printError(error, `Error importing workflows from files`);\n }\n return false;\n}\n\n/**\n * Import first workflow from file\n * @param {string} file import file name\n * @param {WorkflowImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importFirstWorkflowFromFile(\n file: string,\n options: WorkflowImportOptions = {\n deps: true,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Importing workflow...'\n );\n const importData = getWorkflowExportFromFile(getFilePath(file));\n const ids = Object.keys(importData.workflow);\n if (ids.length === 0)\n throw new FrodoError(`No workflows found in import data`);\n await importWorkflows(ids[0], importData, options);\n stopProgressIndicator(\n indicatorId,\n `Imported workflow from ${file}`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing workflow from ${file}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete workflow. If both deleteDraft and deletePublished are truthy or falsy, attempt to delete both, otherwise deletes only one of them.\n * @param {string} workflowId workflow id\n * @param {boolean} deleteDraft true to delete only the draft workflow, false otherwise\n * @param {boolean} deletePublished true to delete only the published workflow, false otherwise\n * @param {boolean} force true to forcefully delete the workflow, false otherwise\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteWorkflow(\n workflowId: string,\n deleteDraft?: boolean,\n deletePublished?: boolean,\n force?: boolean\n): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting workflow ${workflowId}...`\n );\n try {\n const result = await _deleteWorkflow(\n workflowId,\n deleteDraft || !deletePublished,\n deletePublished || !deleteDraft,\n { force },\n errorHandler\n );\n if (!result.draft && !result.published) {\n throw new FrodoError(`Failed to delete workflow ${workflowId}`);\n }\n stopProgressIndicator(\n spinnerId,\n `Deleted workflow ${workflowId}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete workflows. If both deleteDraft and deletePublished are truthy or falsy, attempt to delete all of both types, otherwise deletes only those of one type.\n * @param {boolean} deleteDraft true to delete only the draft workflows, false otherwise\n * @param {boolean} deletePublished true to delete only the published workflows, false otherwise\n * @param {boolean} force true to forcefully delete the workflow, false otherwise\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteWorkflows(\n deleteDraft?: boolean,\n deletePublished?: boolean,\n force?: boolean\n): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting workflows...`\n );\n try {\n await _deleteWorkflows(\n deleteDraft || !deletePublished,\n deletePublished || !deleteDraft,\n { force },\n errorHandler\n );\n stopProgressIndicator(spinnerId, `Deleted workflows.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n *\n * @param {string} workflowId workflow id\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function publishWorkflow(workflowId: string): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Publishing workflow ${workflowId}...`\n );\n try {\n await _publishWorkflow(workflowId);\n stopProgressIndicator(\n spinnerId,\n `Published workflow ${workflowId}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Get a workflow export from json file.\n *\n * @param file The path to the workflow export file\n * @returns The workflow export\n */\nexport function getWorkflowExportFromFile(\n file: string\n): WorkflowExportInterface {\n const exportData = JSON.parse(\n fs.readFileSync(file, 'utf8')\n ) as WorkflowExportInterface;\n for (const workflowGroup of Object.values(exportData.workflow)) {\n for (const workflow of [\n workflowGroup.draft,\n workflowGroup.published,\n ].filter((w) => w)) {\n for (const step of workflow.steps) {\n switch (step.type) {\n case 'approvalTask':\n case 'fulfillmentTask':\n case 'violationTask': {\n const actors = (step[step.type] as ApprovalTask)?.actors;\n if (\n !actors ||\n Array.isArray(actors) ||\n !actors.isExpression ||\n !isScriptExtracted(actors.value)\n )\n continue;\n const scriptRaw = getExtractedData(\n actors.value as string,\n file.substring(0, file.lastIndexOf('/'))\n );\n actors.value = scriptRaw;\n const uiConfigActors =\n workflow.staticNodes?.uiConfig?.[step.name]?.actors;\n if (\n !uiConfigActors ||\n Array.isArray(uiConfigActors) ||\n !uiConfigActors.isExpression ||\n !isScriptExtracted(uiConfigActors.value)\n )\n continue;\n uiConfigActors.value = scriptRaw;\n continue;\n }\n case 'scriptTask': {\n const scriptTask = step[step.type] as ScriptTask;\n if (!isScriptExtracted(scriptTask.script)) continue;\n const scriptRaw = getExtractedData(\n scriptTask.script as string,\n file.substring(0, file.lastIndexOf('/'))\n );\n scriptTask.script = scriptRaw;\n continue;\n }\n default:\n continue;\n }\n }\n }\n }\n return exportData;\n}\n\n/**\n * Extracts scripts from a workflow export into separate files.\n * @param {WorkflowExportInterface} exportData The workflow export\n * @param {string} workflowId The workflow id to extract a specific script from. If undefined, will extract scripts from all workflows.\n * @param {string} directory The directory within the base directory to save the script files\n * @returns {boolean} true if successful, false otherwise\n */\nexport function extractWorkflowScriptsToFiles(\n exportData: WorkflowExportInterface,\n workflowId?: string,\n directory?: string\n): boolean {\n try {\n const workflows = workflowId\n ? [exportData.workflow[workflowId]]\n : Object.values(exportData.workflow);\n for (const workflowGroup of workflows) {\n for (const workflow of [\n workflowGroup.draft,\n workflowGroup.published,\n ].filter((w) => w)) {\n for (const step of workflow.steps) {\n switch (step.type) {\n case 'approvalTask':\n case 'fulfillmentTask':\n case 'violationTask': {\n const actors = (step[step.type] as ApprovalTask)?.actors;\n if (!actors || Array.isArray(actors) || !actors.isExpression)\n continue;\n const scriptText = Array.isArray(actors.value)\n ? actors.value.join('\\n')\n : actors.value;\n const scriptFileName = getTypedFilename(\n step.name,\n 'workflow',\n 'js'\n );\n const extractedFile = extractDataToFile(\n scriptText,\n `${workflow.id}/${workflow.status}/${scriptFileName}`,\n directory\n );\n (\n (step[step.type] as ApprovalTask).actors as WorkflowExpression\n ).value = extractedFile;\n const uiConfigActors =\n workflow.staticNodes?.uiConfig?.[step.name]?.actors;\n if (\n !uiConfigActors ||\n Array.isArray(uiConfigActors) ||\n !uiConfigActors.isExpression\n )\n continue;\n (uiConfigActors as WorkflowExpression).value = extractedFile;\n continue;\n }\n case 'scriptTask': {\n const script = (step[step.type] as ScriptTask).script;\n const scriptText = Array.isArray(script)\n ? script.join('\\n')\n : script;\n const scriptFileName = getTypedFilename(\n step.name,\n 'workflow',\n (step[step.type] as ScriptTask).language === 'javascript'\n ? 'js'\n : 'unknown'\n );\n (step[step.type] as ScriptTask).script = extractDataToFile(\n scriptText,\n `${workflow.id}/${workflow.status}/${scriptFileName}`,\n directory\n );\n continue;\n }\n default:\n continue;\n }\n }\n }\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n","import { createPrompt, useState, useKeypress, isEnterKey, isTabKey, usePrefix, makeTheme, } from '@inquirer/core';\nimport { styleText } from 'node:util';\nconst confirmTheme = {\n keywords: {\n yes: 'Yes',\n no: 'No',\n error: ({ yes, no }) => `You must answer with \"${yes}\" or \"${no}\"`,\n },\n style: {\n confirmDefault: (text) => {\n const first = text[0] ?? '';\n if (first.toLowerCase() === first.toUpperCase()) {\n return styleText('cyan', text);\n }\n return first.toUpperCase() + text.slice(1);\n },\n },\n};\nexport default createPrompt((config, done) => {\n const [status, setStatus] = useState('idle');\n const [value, setValue] = useState('');\n const [errorMsg, setError] = useState();\n const theme = makeTheme(confirmTheme, config.theme);\n const prefix = usePrefix({ status, theme });\n const { yes, no } = theme.keywords;\n // The hint shows the first character of each label, lowercased; the default\n // side is then uppercased (or colored) by `confirmDefault`.\n const yesHint = (yes[0] ?? '').toLowerCase();\n const noHint = (no[0] ?? '').toLowerCase();\n const hint = config.default === false\n ? `${yesHint}/${theme.style.confirmDefault(noHint)}`\n : `${theme.style.confirmDefault(yesHint)}/${noHint}`;\n function boolToString(value) {\n return value ? yes : no;\n }\n const { transformer = boolToString } = config;\n // Note: the built-in English `y`/`n`/`yes`/`no` answers are always accepted,\n // whatever the localized keywords are; typing a single ASCII key is the\n // terminal muscle memory, even in non-Latin locales.\n function getBooleanValue(value) {\n const v = value.trim().toLowerCase();\n // Empty input selects the default answer (the one highlighted in the hint).\n if (v === '')\n return config.default !== false;\n if (yes.toLowerCase().startsWith(v))\n return true;\n if (no.toLowerCase().startsWith(v))\n return false;\n if ('yes'.startsWith(v))\n return true;\n if ('no'.startsWith(v))\n return false;\n // Unrecognized input is rejected by the caller (shows an error).\n return undefined;\n }\n useKeypress((key, rl) => {\n if (status !== 'idle')\n return;\n if (isEnterKey(key)) {\n const answer = getBooleanValue(value);\n if (answer === undefined) {\n // Reject unrecognized input instead of silently falling back on the\n // default. Restore the typed input (the line event cleared it).\n rl.write(value);\n setError(theme.keywords.error({ yes, no }));\n return;\n }\n setValue(transformer(answer));\n setStatus('done');\n done(answer);\n }\n else if (isTabKey(key)) {\n const answer = boolToString(!(getBooleanValue(value) ?? config.default !== false));\n rl.clearLine(0); // Remove the tab character.\n rl.write(answer);\n setValue(answer);\n }\n else {\n setValue(rl.line);\n setError(undefined);\n }\n });\n let formattedValue = value;\n let defaultValue = '';\n if (status === 'done') {\n formattedValue = theme.style.answer(value);\n }\n else {\n defaultValue = ` ${theme.style.defaultAnswer(hint)}`;\n }\n const message = theme.style.message(config.message, status);\n let error = '';\n if (errorMsg) {\n error = theme.style.error(errorMsg);\n }\n return [`${prefix} ${message}${defaultValue} ${formattedValue}`, error];\n});\n","import fs from 'fs';\nimport path from 'path';\nimport {\n frodo,\n FrodoError,\n type MappingExportInterface,\n type MappingExportOptions,\n type MappingImportOptions,\n type MappingSkeleton,\n type SyncSkeleton,\n} from '@rockcarver/frodo-lib';\nimport c from '../utils/ColorTheme';\nimport { extractDataToFile, getExtractedJsonData } from '../utils/Config';\nimport {\n createProgressIndicator,\n createTable,\n debugMessage,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../utils/Console';\nimport {\n findIdmScripts,\n getLastString,\n getObjectByPath,\n getObjectByPathExcludeLast,\n getTopString,\n resolveAllExtractedScriptsForImport,\n} from './IdmOps';\n\nconst {\n getTypedFilename,\n saveJsonToFile,\n saveToFile,\n getFilePath,\n getWorkingDirectory,\n readFiles,\n} = frodo.utils;\n\nconst {\n createMapping,\n readMapping,\n importFirstMapping,\n readMappings,\n exportMapping,\n exportMappings,\n importMapping,\n importMappings,\n updateMapping,\n isLegacyMapping,\n createMappingExportTemplate,\n} = frodo.idm.mapping;\n\n/**\n * List mappings\n * @param {boolean} [long=false] detailed list\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listMappings(long: boolean = false): Promise<boolean> {\n try {\n const mappings = await readMappings();\n if (long) {\n const table = createTable([\n 'Id',\n 'Display Name',\n 'Source',\n 'Target',\n 'Consent Required',\n 'Is Legacy',\n ]);\n for (const mapping of mappings) {\n table.push([\n mapping._id,\n mapping.displayName,\n mapping.source,\n mapping.target,\n mapping.consentRequired ? c.positive('yes') : c.negative('no'),\n isLegacyMapping(mapping._id) ? c.positive('yes') : c.negative('no'),\n ]);\n }\n printMessage(table.toString(), 'data');\n } else {\n mappings.forEach((mapping) => {\n printMessage(`${mapping._id}`, 'data');\n });\n }\n return true;\n } catch (error) {\n printError(error, `Error listing mappings`);\n }\n return false;\n}\n\n/**\n * Export mapping to file\n * @param {string} mappingId mapping id/name\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {MappingExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportMappingToFile(\n mappingId: string,\n file: string,\n includeMeta: boolean = true,\n extract: boolean = false,\n options: MappingExportOptions = {\n deps: true,\n useStringArrays: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportMapping(mappingId, options);\n const mappingName = getMappingNameFromId(mappingId);\n const mappingType = getMappingTypeFromId(mappingId);\n if (!extract) {\n const fileName = file || getTypedFilename(mappingName, mappingType);\n saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);\n return true;\n }\n writeMappingJsonToDirectory(\n mappingType === 'sync'\n ? exportData.sync.mappings[0]\n : exportData.mapping[mappingId],\n '.',\n includeMeta,\n extract\n );\n return true;\n } catch (error) {\n printError(error, `Error exporting mapping ${mappingId} to file`);\n }\n return false;\n}\n\n/**\n * Export all mappings to file\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {MappingExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportMappingsToFile(\n file: string,\n includeMeta: boolean = true,\n options: MappingExportOptions = {\n deps: true,\n useStringArrays: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportMappings(options);\n let fileName = getTypedFilename(`allMappings`, 'mapping');\n if (file) {\n fileName = file;\n }\n saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);\n return true;\n } catch (error) {\n printError(error, `Error exporting mappings to file`);\n }\n return false;\n}\n\n/**\n * Export all mappings to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {MappingExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportMappingsToFiles(\n includeMeta: boolean = true,\n extract: boolean,\n options: MappingExportOptions = {\n deps: true,\n useStringArrays: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportMappings(options);\n for (const mapping of Object.values(exportData.mapping)) {\n writeMappingJsonToDirectory(mapping, 'mapping', includeMeta, extract);\n }\n writeSyncJsonToDirectory(exportData.sync, 'sync', includeMeta, extract);\n return true;\n } catch (error) {\n printError(error, `Error exporting mappings to files`);\n }\n return false;\n}\n\n/**\n * Import a mapping from file\n * @param {string} mappingId mapping id/name\n * @param {string} file import file name\n * @param {MappingImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importMappingFromFile(\n mappingId: string,\n file: string,\n options: MappingImportOptions = { deps: true }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing mapping...'\n );\n const importData = getMappingImportDataFromFile(file);\n await importMapping(mappingId, importData, options);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported mapping ${mappingId}.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing mapping ${mappingId}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Import mappings from file\n * @param {String} file file name\n * @param {MappingImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importMappingsFromFile(\n file: string,\n options: MappingImportOptions = { deps: true }\n): Promise<boolean> {\n try {\n debugMessage(`importMappingsFromFile: start`);\n debugMessage(`importMappingsFromFile: importing ${file}`);\n const importData = getMappingImportDataFromFile(file);\n await importMappings(importData, options);\n debugMessage(`importMappingsFromFile: end`);\n return true;\n } catch (error) {\n printError(error, `Error importing mappings from file`);\n }\n return false;\n}\n\n/**\n * Import all mappings from separate files\n * @param {MappingImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importMappingsFromFiles(\n options: MappingImportOptions = { deps: true }\n): Promise<boolean> {\n try {\n const workingDirectory = getWorkingDirectory();\n const allMappingFiles = (await readFiles(workingDirectory)).filter(\n (f) =>\n f.path.endsWith('mapping.json') ||\n f.path.endsWith('sync.json') ||\n f.path.endsWith('sync.idm.json') ||\n f.path.endsWith('mapping.idm.json')\n );\n const mappingEntries: [string, MappingSkeleton][] = [];\n for (const f of allMappingFiles.filter((f) =>\n f.path.endsWith('mapping.json')\n )) {\n const parsed = parseAndResolveMappingFile(f);\n mappingEntries.push(...Object.entries(parsed));\n }\n const mapping = Object.fromEntries(mappingEntries) as Record<\n string,\n MappingSkeleton\n >;\n await importMappings(\n {\n mapping,\n sync: getLegacyMappingsFromFiles(allMappingFiles),\n } as MappingExportInterface,\n options\n );\n\n return true;\n } catch (error) {\n printError(error, `Error importing mappings from files`);\n }\n return false;\n}\n\n/**\n * Loads and resolves extracted scripts from a single mapping file.\n * @param file A file object with path and content (from readFiles)\n * @returns Record of mappings keyed by _id\n */\nexport function parseAndResolveMappingFile(file: {\n path: string;\n content: string;\n}): Record<string, MappingSkeleton> {\n const baseDir = path.dirname(file.path);\n const parsed = JSON.parse(file.content);\n const mappings = Object.values(parsed.mapping || {}) as MappingSkeleton[];\n\n const mappingRecord: Record<string, MappingSkeleton> = {};\n for (const mapping of mappings) {\n resolveAllExtractedScriptsForImport(mapping, baseDir);\n mappingRecord[mapping._id] = mapping;\n }\n return mappingRecord;\n}\n\n/**\n * Import first mapping from file\n * @param {string} file import file name\n * @param {MappingImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importFirstMappingFromFile(\n file: string,\n options: MappingImportOptions = { deps: true }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing mapping...'\n );\n const importData = getMappingImportDataFromFile(file);\n updateProgressIndicator(\n indicatorId,\n `Importing first mapping from ${file}...`\n );\n await importFirstMapping(importData, options);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported first mapping from ${file}.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing mapping from ${file}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete mapping\n * @param {string} mappingId mapping id/name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteMapping(mappingId: string): Promise<boolean> {\n try {\n await frodo.idm.mapping.deleteMapping(mappingId);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete mappings\n * @param {string} connectorId limit mappings to connector\n * @param {string} moType limit mappings to managed object type\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteMappings(\n connectorId?: string,\n moType?: string\n): Promise<boolean> {\n try {\n await frodo.idm.mapping.deleteMappings(connectorId, moType);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Rename mapping\n * @param {string} mappingId mapping id/name\n * @param {boolean} [legacy=false] true to rename from new to legacy naming scheme, false otherwise. Default: false\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function renameMapping(\n mappingId: string,\n legacy: boolean = false\n): Promise<boolean> {\n const name = getMappingNameFromId(mappingId);\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Renaming mapping ${name}...`\n );\n try {\n const oldId = `${legacy ? 'mapping' : 'sync'}/${name}`;\n const newId = `${legacy ? 'sync' : 'mapping'}/${name}`;\n const oldMapping = await readMapping(oldId);\n oldMapping._id = newId;\n // Not possible to determine where mapping should go in order, so just delete the property so default ordering is used\n delete oldMapping.syncAfter;\n await createMapping(newId, oldMapping);\n await frodo.idm.mapping.deleteMapping(oldId);\n stopProgressIndicator(\n spinnerId,\n `Successfully renamed ${name} to ${\n legacy ? 'legacy' : 'new'\n } naming scheme.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n spinnerId,\n error.response ? `Error renaming mapping ${name}` : error,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Rename all mappings\n * @param {boolean} [legacy=false] true to rename from new to legacy naming scheme, false otherwise. Default: false\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function renameMappings(\n legacy: boolean = false\n): Promise<boolean> {\n const mappings = await readMappings();\n const spinnerId = createProgressIndicator(\n 'determinate',\n mappings.length,\n `Renaming mappings...`\n );\n // Mappings should be ordered correctly by readMappings(), so we update the syncAfter properties to preserve order.\n const syncAfter = [];\n for (const mapping of mappings) {\n // slice() makes a copy of the array\n mapping.syncAfter = syncAfter.slice();\n syncAfter.push(mapping.name);\n const name = mapping.name;\n try {\n updateProgressIndicator(spinnerId, `Renaming mapping ${name}...`);\n const oldId = `${legacy ? 'mapping' : 'sync'}/${name}`;\n const newId = `${legacy ? 'sync' : 'mapping'}/${name}`;\n let oldMapping;\n try {\n oldMapping = await readMapping(oldId);\n oldMapping.syncAfter = mapping.syncAfter;\n } catch {\n // Old mapping doesn't exist, meaning the mapping is already new, so just update it with the new syncAfter property\n await updateMapping(newId, mapping);\n continue;\n }\n await createMapping(newId, oldMapping);\n await frodo.idm.mapping.deleteMapping(oldId);\n } catch (error) {\n stopProgressIndicator(\n spinnerId,\n error.response ? `Error renaming mapping ${name}` : error,\n 'fail'\n );\n printError(error);\n return false;\n }\n }\n stopProgressIndicator(\n spinnerId,\n `Successfully renamed ${mappings.length} mappings to ${\n legacy ? 'legacy' : 'new'\n } naming scheme.`,\n 'success'\n );\n return true;\n}\n\n/**\n * Helper that extracts mapping scripts from a mapping object\n * @param {MappingSkeleton} mapping The mapping object\n * @param {string} directory The directory to extract scripts to within the base directory\n * @returns {boolean} true if at least one script got extracted, false otherwise\n */\nexport function extractMappingScriptsToDirectory(\n mapping: MappingSkeleton,\n directory: string = mapping.name\n): boolean {\n const scripts = findIdmScripts(mapping);\n if (!scripts.length) return false;\n for (const script of scripts) {\n const objectSource = getObjectByPath(mapping, script.path);\n let fileName = script.path;\n if (getTopString(script.path) === 'policies') {\n const situation = getObjectByPathExcludeLast(\n mapping,\n script.path\n ).situation;\n fileName = `${situation}.${getLastString(script.path)}`;\n } else if (getTopString(script.path) === 'properties') {\n let source = getObjectByPathExcludeLast(mapping, script.path).source;\n if (!source) source = 'SOURCE';\n let target = getObjectByPathExcludeLast(mapping, script.path).target;\n if (!target) target = 'TARGET';\n fileName = `${source}.${target}.${getLastString(script.path)}`;\n }\n objectSource.source = extractDataToFile(\n script.source,\n `${fileName}.${script.type}`,\n directory\n );\n }\n return true;\n}\n\n/**\n * Helper that writes mappings in the sync IDM config entity to a directory\n * @param {SyncSkeleton} sync The sync IDM config entity\n * @param {string} directory The directory to save the entity to within the base directory\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n */\nexport function writeSyncJsonToDirectory(\n sync: SyncSkeleton,\n directory: string = 'sync',\n includeMeta: boolean = true,\n extract: boolean = false\n) {\n const mappingPaths = [];\n for (const mapping of sync.mappings) {\n if (!mapping) {\n // Skip null/malformed entries in the tenant's sync.json mappings array.\n continue;\n }\n const fileName = getTypedFilename(mapping.name, 'sync');\n if (\n extract &&\n extractMappingScriptsToDirectory(mapping, `${directory}/${mapping.name}`)\n ) {\n mappingPaths.push(\n extractDataToFile(mapping, `${mapping.name}/${fileName}`, directory)\n );\n } else {\n mappingPaths.push(extractDataToFile(mapping, fileName, directory));\n }\n }\n sync.mappings = mappingPaths;\n saveToFile(\n 'idm',\n sync,\n '_id',\n getFilePath(`${directory}/sync.idm.json`, true),\n includeMeta\n );\n}\n\n/**\n * Helper that writes a mapping IDM config entity to a directory\n * @param {MappingSkeleton} function The mapping IDM config entity\n * @param {string} directory The directory to save the entity to within the base directory\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n */\nexport function writeMappingJsonToDirectory(\n mapping: MappingSkeleton,\n directory: string = '.',\n includeMeta: boolean = true,\n extract: boolean = false\n) {\n const mappingType = getMappingTypeFromId(mapping._id);\n const fileName = getTypedFilename(mapping.name, mappingType);\n let filePath;\n if (\n extract &&\n extractMappingScriptsToDirectory(mapping, `${directory}/${mapping.name}`)\n ) {\n filePath = getFilePath(`${directory}/${mapping.name}/${fileName}`, true);\n } else {\n filePath = getFilePath(`${directory}/${fileName}`, true);\n }\n saveToFile(mappingType, mapping, '_id', filePath, includeMeta);\n}\n\n/**\n * Helper that reads the sync IDM config entity from files\n * @param {{ path: string; content: string }[]} files the files to read the sync IDM config entity object from\n * @returns {SyncSkeleton} the sync IDM config entity\n */\nexport function getLegacyMappingsFromFiles(\n files: { path: string; content: string }[]\n): SyncSkeleton {\n const syncFiles = files.filter((f) => f.path.endsWith('/sync.idm.json'));\n if (syncFiles.length > 1) {\n throw new FrodoError('Multiple sync.idm.json files found in idm directory');\n }\n const sync = {\n _id: 'sync',\n mappings: [],\n };\n if (syncFiles.length === 1) {\n const file = syncFiles[0];\n const jsonData = JSON.parse(file.content);\n const syncData = jsonData.sync ?? jsonData.idm?.sync;\n const syncJsonDir = path.dirname(file.path);\n if (syncData?.mappings) {\n for (const mapping of syncData.mappings) {\n let resolvedMapping: any;\n if (typeof mapping === 'string') {\n resolvedMapping = getExtractedJsonData(mapping, syncJsonDir);\n } else {\n resolvedMapping = mapping;\n }\n resolveAllExtractedScriptsForImport(\n resolvedMapping,\n `${syncJsonDir}/${resolvedMapping.name}`\n );\n sync.mappings.push(resolvedMapping);\n }\n }\n }\n return sync;\n}\n\n/**\n * Helper that reads mapping (non-legacy) config entities from files\n * @param {{ path: string; content: string }[]} mappingFiles the files to read the mapping (non-legacy) config entities from\n * @returns {Record<string, MappingSkeleton>} the mapping (non-legacy) config entities\n */\nexport function getNewMappingsFromFiles(\n mappingFiles: { path: string; content: string }[]\n): Record<string, MappingSkeleton> {\n const mappingEntries: [string, MappingSkeleton][] = [];\n for (const f of mappingFiles.filter((f) => f.path.endsWith('mapping.json'))) {\n const parsed = parseAndResolveMappingFile(f);\n mappingEntries.push(...Object.entries(parsed));\n }\n const mapping = Object.fromEntries(mappingEntries) as Record<\n string,\n MappingSkeleton\n >;\n return mapping;\n}\n\n/**\n * Helper that gets a mapping's type (either 'sync' or 'mapping') from it's id\n * @param {string} mappingId the mapping id\n * @returns {string} the mapping type\n */\nexport function getMappingTypeFromId(mappingId: string): string {\n return isLegacyMapping(mappingId) ? 'sync' : 'mapping';\n}\n\n/**\n * Helper that returns the mapping name given the mapping's id.\n * @param {string} mappingId the mapping id\n * @returns {string} the mapping name\n */\nexport function getMappingNameFromId(mappingId: string): string | undefined {\n if (!mappingId) {\n return undefined;\n }\n return mappingId.startsWith('mapping/') || mappingId.startsWith('sync/')\n ? mappingId.substring(mappingId.indexOf('/') + 1)\n : mappingId;\n}\n\n/**\n * Helper that returns mapping file data as import data\n *\n * @param {string} file the file path\n * @returns {MappingExportInterface} the import data\n */\nfunction getMappingImportDataFromFile(file: string): MappingExportInterface {\n const filePath = getFilePath(file);\n const data = fs.readFileSync(filePath, 'utf8');\n let importData = JSON.parse(data);\n const baseDir = path.dirname(filePath);\n // If importing from file not in export format, put it into export format\n if (!importData.sync && !importData.mapping) {\n const mapping = importData;\n importData = createMappingExportTemplate();\n\n if (mapping.idm) {\n importData.sync = getLegacyMappingsFromFiles([\n {\n path: `${filePath.substring(0, filePath.lastIndexOf('/'))}/sync.idm.json`,\n content: data,\n },\n ]);\n } else if (isLegacyMapping(mapping._id)) {\n resolveAllExtractedScriptsForImport(mapping, baseDir);\n importData.sync.mappings.push(mapping);\n } else {\n resolveAllExtractedScriptsForImport(mapping, baseDir);\n importData.mapping[mapping._id] = mapping;\n }\n } else {\n if (importData.mapping) {\n Object.values(importData.mapping).forEach((m) => {\n resolveAllExtractedScriptsForImport(m, baseDir);\n });\n }\n }\n if (!importData.sync && importData.mapping) {\n importData.sync = { id: 'sync', mappings: [] };\n } else if (importData.sync && !importData.mapping) {\n importData.mapping = {};\n }\n return importData;\n}\n","import fs from 'fs';\nimport path from 'path';\nimport confirm from '@inquirer/confirm';\nimport {\n buildManagedObjectSchemaRelationshipPropertyPayload as buildRelationshipPropertyPayload,\n buildManagedObjectSchemaPropertyPayload as buildSchemaPropertyPayload,\n extractManagedObjectSchemaRelationshipPropertyFields as extractRelationshipFields,\n extractManagedObjectSchemaPropertyFields as extractSchemaPropertyFields,\n frodo,\n FrodoError,\n inferManagedObjectSchemaRelationshipReverseIdentity as inferReverseIdentity,\n navigatePropertyPath,\n navigateToPropertyContainer,\n parseSubPropertyPath,\n setSchemaProperty,\n toManagedObjectSchemaRelationshipReverseFields as toReverseDescriptorFields,\n type ConfigEntityExportInterface,\n type IdObjectSkeletonInterface,\n type ManagedObjectSchema,\n type MappingSkeleton,\n type PropertyContainer,\n type ManagedObjectSchemaRelationshipPropertyFields as RelationshipPropertyFields,\n type ManagedObjectSchemaRelationshipReverseFields as RelationshipReverseCreateFields,\n type ManagedObjectSchemaPropertyFields as SchemaPropertyFields,\n type SyncSkeleton,\n} from '@rockcarver/frodo-lib';\nimport c from '../utils/ColorTheme';\nimport {\n extractDataToFile,\n getExtractedData,\n getExtractedJsonData,\n} from '../utils/Config';\nimport {\n createObjectTable,\n createProgressIndicator,\n createTable,\n printError,\n printMessage,\n stopProgressIndicator,\n} from '../utils/Console';\nimport {\n getLegacyMappingsFromFiles,\n writeMappingJsonToDirectory,\n writeSyncJsonToDirectory,\n} from './MappingOps';\nimport { errorHandler } from './utils/OpsUtils';\n\nconst {\n getFilePath,\n getTypedFilename,\n readFiles,\n getWorkingDirectory,\n saveJsonToFile,\n saveToFile,\n} = frodo.utils;\n\nconst {\n readConfigEntities,\n exportConfigEntity,\n exportConfigEntities,\n deleteConfigEntity,\n importConfigEntities,\n readSubConfigEntity,\n importSubConfigEntity,\n} = frodo.idm.config;\nconst { countManagedObjects: countManagedObjectsOfType } = frodo.idm.managed;\nconst {\n readManagedObjectSchema,\n updateManagedObjectSchemaProperty,\n createManagedObjectSchemaFlatProperty,\n updateManagedObjectSchemaFlatProperty,\n removeManagedObjectSchemaFlatProperty,\n createManagedObjectSchemaRelationshipProperty: createRelationshipPropertyLib,\n updateManagedObjectSchemaRelationshipProperty: updateRelationshipPropertyLib,\n removeManagedObjectSchemaRelationshipProperty: removeRelationshipPropertyLib,\n readManagedObjectSchemaRelationshipPropertyOrNull:\n tryReadRelationshipProperty,\n} = frodo.idm.managed.schema;\nconst { testConnectorServers } = frodo.idm.system;\n\ntype MatchResult = { path: string; source: string; type: string };\n\n/**\n * Warn about and list offline remote connector servers\n * @return {Promise<boolean>} a promise that resolves to true if a warning was printed, false otherwise\n */\nexport async function warnAboutOfflineConnectorServers(): Promise<boolean> {\n try {\n const all = await testConnectorServers();\n const offline = all\n .filter((status) => !status.ok)\n .map((status) => status.name);\n if (offline.length > 0) {\n printMessage(\n `\\nThe following connector server(s) are offline and their connectors and configuration unavailable:\\n${offline.join(\n '\\n'\n )}`,\n 'warn'\n );\n return true;\n }\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * List all IDM configuration objects\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function listAllConfigEntities(): Promise<boolean> {\n try {\n const configurations = await readConfigEntities();\n for (const configEntity of configurations) {\n printMessage(`${configEntity._id}`, 'data');\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\ntype ObjectSkeleton = IdObjectSkeletonInterface & {\n name: string;\n};\n\nexport type ManagedSkeleton = IdObjectSkeletonInterface & {\n objects: ObjectSkeleton[];\n};\n\ntype ManagedObjectTypeConfig = ObjectSkeleton & {\n schema?: ManagedObjectSchema;\n};\n\n/**\n * Export an IDM configuration object.\n * @param {string} id the desired configuration object\n * @param {string} file optional export file name (or directory name if exporting mappings separately)\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportConfigEntityToFile(\n id: string,\n file?: string,\n includeMeta: boolean = true,\n extract: boolean = false\n): Promise<boolean> {\n try {\n const exportData = await exportConfigEntity(id);\n if (!extract) {\n const fileName = file || getTypedFilename(`${id}`, 'idm');\n saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);\n return true;\n }\n if (id === 'sync') {\n writeSyncJsonToDirectory(\n exportData.idm[id] as SyncSkeleton,\n 'sync',\n includeMeta,\n extract\n );\n return true;\n }\n if (id === 'managed') {\n writeManagedJsonToDirectory(\n exportData.idm[id] as ManagedSkeleton,\n 'managed',\n includeMeta,\n extract\n );\n return true;\n }\n writeIdmObjectToDirectory(exportData.idm[id], '.', includeMeta, extract);\n return true;\n } catch (error) {\n printError(error, `Error exporting config entity ${id}`);\n }\n return false;\n}\n\n/**\n * Export an IDM configuration managed object.\n * @param {string} name the desired configuration object\n * @param {string} file optional export file name\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportManagedObjectToFile(\n name: string,\n file?: string,\n extract: boolean = false\n): Promise<boolean> {\n try {\n const exportData = (await readSubConfigEntity(\n 'managed',\n name\n )) as ObjectSkeleton;\n if (extract && extractManagedObjectScriptsToDirectory(exportData)) {\n const fileName = getTypedFilename(name, 'managed');\n saveJsonToFile(\n exportData,\n getFilePath(`${name}/${fileName}`, true),\n false\n );\n return true;\n }\n const fileName = file || getTypedFilename(name, 'managed');\n saveJsonToFile(exportData, getFilePath(fileName, true), false);\n return true;\n } catch (error) {\n printError(error, `Error exporting config managed object ${name}`);\n }\n return false;\n}\n\n/**\n * Export all IDM configuration objects\n * @param {string} file file to export to\n * @param {string} entitiesFile JSON file that specifies the config entities to export/import\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportAllConfigEntitiesToFile(\n file?: string,\n entitiesFile?: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n try {\n const options = getIdmImportExportOptions(entitiesFile);\n const exportData = await exportConfigEntities(\n {\n entitiesToExport: options.entitiesToExportOrImport,\n },\n errorHandler\n );\n let fileName = getTypedFilename(`all`, `idm`);\n if (file) {\n fileName = file;\n }\n saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);\n return true;\n } catch (error) {\n printError(error, `Error exporting idm config to file`);\n }\n return false;\n}\n\n/**\n * Export all IDM configuration objects to separate files\n * @param {string} entitiesFile JSON file that specifies the config entities to export/import\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportAllConfigEntitiesToFiles(\n entitiesFile?: string,\n includeMeta: boolean = true,\n extract: boolean = false\n): Promise<boolean> {\n const errors: Error[] = [];\n try {\n const options = getIdmImportExportOptions(entitiesFile);\n const exportData = await exportConfigEntities(\n {\n entitiesToExport: options.entitiesToExportOrImport,\n },\n errorHandler\n );\n for (const [id, obj] of Object.entries(exportData.idm)) {\n if (!obj) continue;\n try {\n if (!extract) {\n saveToFile(\n 'idm',\n obj,\n '_id',\n getFilePath(`${id}.idm.json`, true),\n includeMeta\n );\n continue;\n }\n if (id === 'sync') {\n writeSyncJsonToDirectory(\n obj as SyncSkeleton,\n 'sync',\n includeMeta,\n extract\n );\n continue;\n }\n if (id === 'managed') {\n writeManagedJsonToDirectory(\n obj as ManagedSkeleton,\n 'managed',\n includeMeta,\n extract\n );\n continue;\n }\n if (id.startsWith('mapping/')) {\n writeMappingJsonToDirectory(\n obj as MappingSkeleton,\n 'mapping',\n includeMeta,\n extract\n );\n continue;\n }\n writeIdmObjectToDirectory(obj, '.', includeMeta, extract);\n } catch (error) {\n errors.push(new FrodoError(`Error saving config entity ${id}`, error));\n }\n }\n if (errors.length > 0) {\n throw new FrodoError(`Error saving config entities`, errors);\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Import an IDM configuration object by id from file.\n * @param {string} entityId the configuration object to import\n * @param {string} file optional file to import\n * @param {boolean} validate True to validate script hooks. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importConfigEntityByIdFromFile(\n entityId: string,\n file?: string,\n validate: boolean = false\n): Promise<boolean> {\n try {\n if (!file) {\n file = getTypedFilename(entityId, 'idm');\n }\n const filePath = getFilePath(file);\n\n const fileData = fs.readFileSync(\n path.resolve(process.cwd(), filePath),\n 'utf8'\n );\n\n let importData;\n if (entityId === 'sync') {\n const syncData = getLegacyMappingsFromFiles([\n {\n content: fileData,\n path: `${filePath.substring(0, filePath.lastIndexOf('/'))}/sync.idm.json`,\n },\n ]);\n importData = { idm: { sync: syncData } };\n } else if (entityId === 'managed') {\n const managedData = getManagedObjectsFromFiles([\n {\n content: fileData,\n path: `${filePath.substring(0, filePath.lastIndexOf('/'))}/managed.idm.json`,\n },\n ]);\n importData = { idm: { managed: managedData } };\n } else {\n importData = JSON.parse(fileData);\n const entity = importData.idm?.[entityId];\n if (entity) {\n const baseDir = path.dirname(filePath);\n resolveAllExtractedScriptsForImport(entity, baseDir);\n importData.idm[entityId] = entity;\n }\n }\n\n await importConfigEntities(\n importData,\n entityId,\n {\n entitiesToImport: undefined,\n validate,\n },\n errorHandler\n );\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete IDM config Entity by id\n * @param {String} id saml entityId\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteConfigEntityById(\n entityId: string\n): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${entityId}...`\n );\n try {\n await deleteConfigEntity(entityId);\n stopProgressIndicator(spinnerId, `Deleted ${entityId}.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import first IDM configuration object from file.\n * @param {string} file optional file to import\n * @param {boolean} validate True to validate script hooks. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importFirstConfigEntityFromFile(\n file: string,\n validate: boolean = false\n): Promise<boolean> {\n const filePath = getFilePath(file);\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing ${filePath}...`\n );\n\n const fileData = fs.readFileSync(\n path.resolve(process.cwd(), filePath),\n 'utf8'\n );\n\n const parsed = JSON.parse(fileData);\n const allEntities = Object.entries(parsed.idm)\n .filter(([id]) => id !== 'meta')\n .map(([, val]) => val) as IdObjectSkeletonInterface[];\n\n if (allEntities.length === 0) {\n stopProgressIndicator(indicatorId, `No items to import.`, 'success');\n return true;\n }\n\n const entity = allEntities[0];\n const entityId = entity._id;\n\n const baseDir = path.dirname(filePath);\n resolveAllExtractedScriptsForImport(entity, baseDir);\n\n const importData: ConfigEntityExportInterface = {\n idm: { [entityId]: entity },\n };\n\n if (entityId === 'sync') {\n importData.idm.sync = getLegacyMappingsFromFiles([\n {\n content: fileData,\n path: `${baseDir}/sync.idm.json`,\n },\n ]);\n }\n\n if (entityId === 'managed') {\n importData.idm.managed = getManagedObjectsFromFiles([\n {\n content: fileData,\n path: `${baseDir}/managed.idm.json`,\n },\n ]);\n }\n\n await importConfigEntities(\n importData,\n entityId,\n {\n entitiesToImport: undefined,\n validate,\n },\n errorHandler\n );\n stopProgressIndicator(\n indicatorId,\n `Imported ${entityId} from ${filePath}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing ${filePath}.`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import all IDM configuration objects from a single file\n * @param {string} file the file with the configuration objects\n * @param {string} entitiesFile JSON file that specifies the config entities to export/import\n * @param {boolean} validate True to validate script hooks. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importAllConfigEntitiesFromFile(\n file: string,\n entitiesFile?: string,\n validate: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n let filePath;\n try {\n filePath = getFilePath(file);\n const baseDir = path.dirname(filePath);\n const importData = JSON.parse(fs.readFileSync(filePath, 'utf8'));\n resolveAllExtractedScriptsForImport(importData, baseDir);\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing config entities from ${filePath}...`\n );\n const options = getIdmImportExportOptions(entitiesFile);\n await importConfigEntities(\n importData as ConfigEntityExportInterface,\n undefined,\n {\n entitiesToImport: options.entitiesToExportOrImport,\n validate,\n },\n errorHandler\n );\n stopProgressIndicator(indicatorId, `Imported config entities`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing config entities from ${filePath}.`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Identifies which incoming managed-object type entries carry a schema\n * definition, to gate schema-bearing 'frodo idm schema object import'\n * calls behind an explicit confirmation before writing. Managed-object\n * CONFIGURATION (this command) is a superset of managed-object SCHEMA\n * (each object entry's own .schema key) — most configuration edits\n * (notifications, meta, etc.) don't touch schema at all, so this only\n * flags the subset of incoming objects that carry a schema.\n *\n * Deliberately does not compare against the live tenant's current schema\n * (which would need an extra read per type): a type carrying a schema key\n * is flagged whether or not that schema would actually change anything,\n * trading a small amount of false-positive friction for not depending on\n * an extra live read succeeding to make the correct safety call. Does not\n * read or write anything itself; pure/synchronous over the parsed import\n * data already in hand.\n * @param {{name: string; schema?: unknown}[]} objects incoming managed-object type entries about to be imported\n * @returns {string[]} the object type names that carry a schema definition\n */\nexport function getSchemaBearingObjectNames(\n objects: { name: string; schema?: unknown }[]\n): string[] {\n return objects.filter((object) => object.schema).map((object) => object.name);\n}\n\n/**\n * Import an individual managed object from a file\n * @param {string} file the file containing the managed object\n * @param {boolean} validate True to validate script hooks. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importManagedObjectFromFile(\n file: string,\n validate: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n let filePath: string;\n try {\n filePath = getFilePath(file);\n const fileData = fs.readFileSync(filePath, 'utf8');\n const importData = JSON.parse(fileData);\n const baseDir = path.dirname(filePath);\n resolveAllExtractedScriptsForImport(importData, baseDir);\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing config managed object from ${filePath}...`\n );\n const options = getIdmImportExportOptions(undefined);\n await importSubConfigEntity('managed', importData, {\n entitiesToImport: options.entitiesToExportOrImport,\n validate,\n });\n\n stopProgressIndicator(\n indicatorId,\n `Imported config managed object`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing config managed object from ${filePath}.`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Prints a warning and asks for confirmation before a schema-affecting\n * change, unless skipConfirmation is set. Refuses (rather than hanging on a\n * readline call with nowhere to read from) if stdin isn't an interactive\n * terminal and skipConfirmation wasn't passed. Mirrors the confirmation gate\n * `frodo idm schema object import` already uses.\n * @param {string} warning warning message printed before the prompt\n * @param {string} question the yes/no question to prompt\n * @param {boolean} skipConfirmation true to skip the prompt and proceed\n * @return {Promise<boolean>} a promise that resolves to true if the change should proceed\n */\nasync function confirmChange(\n warning: string,\n question: string,\n skipConfirmation: boolean\n): Promise<boolean> {\n printMessage(warning, 'warn');\n if (skipConfirmation) {\n return true;\n }\n if (!process.stdin.isTTY) {\n printMessage(\n '\\nRefusing to prompt for confirmation without an interactive terminal. Use -y/--yes to proceed non-interactively.',\n 'error'\n );\n return false;\n }\n return confirm({ message: question, default: false });\n}\n\n/** One row of a property table: `path` is the property's dot-path (just its own name, when not nested under --recursive). */\ntype PropertyTableRow = {\n path: string;\n type: string;\n title: string;\n nullable: 'yes' | 'no';\n required: 'yes' | 'no';\n searchable: 'yes' | 'no';\n userEditable: 'yes' | 'no';\n viewable: 'yes' | 'no';\n target: string;\n isRelationship: boolean;\n};\n\n/**\n * Renders a property's own JSON-Schema `type` as a table-friendly label,\n * applying the format substitution (date/time/datetime/duration). IDM\n * represents a nullable scalar as `type: [x, \"null\"]` rather than a plain\n * string; the nullability itself is surfaced separately via the NUL column\n * (see {@link isNullableProperty}) so this only ever returns the non-null\n * type name(s) -- joined with ` | ` in the unlikely case of more than one.\n */\nfunction describeCoreType(core: Record<string, unknown>): string {\n if (Array.isArray(core.type)) {\n const nonNull = core.type.filter((t) => t !== 'null').map(String);\n return nonNull.length > 0 ? nonNull.join(' | ') : 'null';\n }\n return core?.type === 'string' && typeof core.format === 'string'\n ? core.format\n : String(core?.type);\n}\n\n/** The property (or, for an array property, its item), unwrapped once so callers can inspect its own `type`/`resourceCollection`/etc. */\nfunction corePropertyDefinition(\n property: Record<string, unknown>\n): Record<string, unknown> {\n return (property.type === 'array' ? property.items : property) as Record<\n string,\n unknown\n >;\n}\n\n/** True if the property (or its item type, for an array property) is a relationship. */\nfunction isRelationshipProperty(property: Record<string, unknown>): boolean {\n return corePropertyDefinition(property)?.type === 'relationship';\n}\n\n/**\n * Renders a relationship property's cardinality as `<this>:<other>`, e.g.\n * `1:n` for a single-valued relationship whose reverse side is an array, or\n * `n:-` for an array-valued relationship with no reverse configured. Both\n * sides come straight from the property's own definition -- no extra read\n * of the target type's schema is needed, since IDM embeds the reverse\n * side's own shape directly at `resourceCollection[0].reverseProperty`.\n */\nfunction relationshipCardinality(property: Record<string, unknown>): string {\n const core = corePropertyDefinition(property);\n const thisSide = property.type === 'array' ? 'n' : '1';\n if (!core.reverseRelationship) {\n return `${thisSide}:-`;\n }\n const resourceCollection = core.resourceCollection as\n Array<{ reverseProperty?: { type?: string } }> | undefined;\n const reverseType = resourceCollection?.[0]?.reverseProperty?.type;\n const otherSide =\n reverseType === 'array' ? 'n' : reverseType === 'relationship' ? '1' : '-';\n return `${thisSide}:${otherSide}`;\n}\n\n/** Renders a property's Type-column value: a cardinality notation (e.g. `1:n`) for a relationship, its scalar type (e.g. `string`, `object[]`) otherwise. */\nfunction describePropertyType(property: Record<string, unknown>): string {\n if (isRelationshipProperty(property)) {\n return relationshipCardinality(property);\n }\n const array = property.type === 'array';\n const baseType = describeCoreType(corePropertyDefinition(property));\n return array ? `${baseType}[]` : baseType;\n}\n\n/** True if the property's own JSON-Schema `type` is IDM's nullable-scalar array form, `type: [x, \"null\"]`. */\nfunction isNullableProperty(property: Record<string, unknown>): boolean {\n const core = corePropertyDefinition(property);\n return Array.isArray(core?.type) && core.type.includes('null');\n}\n\n/** The target managed-object type of a relationship property, or '' if the property isn't a relationship. */\nfunction relationshipTarget(property: Record<string, unknown>): string {\n const core = corePropertyDefinition(property);\n if (core?.type !== 'relationship') {\n return '';\n }\n const resourceCollection = core.resourceCollection as\n Array<{ path?: string }> | undefined;\n return resourceCollection?.[0]?.path?.replace(/^managed\\//, '') || '';\n}\n\n/**\n * Flattens a property container into table rows, sorted by name. With\n * `recursive`, nested `type: object` properties are expanded inline\n * underneath their parent, using DOT-PATH names (e.g. `address.street`)\n * rather than indentation -- so a row's `path` is always a valid\n * `--sub-property` value.\n */\nfunction collectPropertyRows(\n properties: Record<string, Record<string, unknown>>,\n required: Set<string>,\n recursive: boolean,\n prefix = ''\n): PropertyTableRow[] {\n const rows: PropertyTableRow[] = [];\n Object.entries(properties || {})\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(([name, property]) => {\n const path = prefix ? `${prefix}.${name}` : name;\n rows.push({\n path,\n type: describePropertyType(property),\n title: (property.title as string) || '',\n nullable: isNullableProperty(property) ? 'yes' : 'no',\n required: required.has(name) ? 'yes' : 'no',\n searchable: property.searchable ? 'yes' : 'no',\n userEditable: property.userEditable ? 'yes' : 'no',\n viewable: property.viewable === false ? 'no' : 'yes',\n target: relationshipTarget(property),\n isRelationship: isRelationshipProperty(property),\n });\n const array = property.type === 'array';\n const core = (array ? property.items : property) as Record<\n string,\n unknown\n >;\n if (recursive && core?.type === 'object' && core.properties) {\n rows.push(\n ...collectPropertyRows(\n core.properties as Record<string, Record<string, unknown>>,\n new Set((core.required as string[]) || []),\n recursive,\n path\n )\n );\n }\n });\n return rows;\n}\n\n/**\n * Refines each relationship row's cardinality using IDM's dedicated v2\n * relationship-schema API, which embeds the reverse side's own shape at\n * `resourceCollection[0].reverseProperty` -- unlike the whole-type schema\n * read {@link collectPropertyRows} normally works from, which only knows a\n * reverse relationship exists (`reverseRelationship: true`), not its\n * cardinality. One extra read per top-level relationship row (parallelized,\n * skipped for a nested --sub-property row -- and for a nested relationship\n * row, if one somehow exists -- since the v2 API only addresses top-level\n * properties); a failed read (e.g. IDM too old for the v2 API) or a nested\n * row keeps that row's original, less-precise cardinality rather than\n * failing the whole describe.\n */\nasync function resolveRelationshipCardinalities(\n type: string,\n rows: PropertyTableRow[]\n): Promise<PropertyTableRow[]> {\n return Promise.all(\n rows.map(async (row) => {\n if (!row.isRelationship || row.path.includes('.')) {\n return row;\n }\n try {\n const property = await tryReadRelationshipProperty(type, row.path);\n return property\n ? { ...row, type: relationshipCardinality(property) }\n : row;\n } catch {\n return row;\n }\n })\n );\n}\n\n/** Column headers for a {@link PropertyTableRow} table -- the flag columns are abbreviated to keep the table narrow; see {@link PROPERTY_TABLE_KEY} for what they mean. */\nconst PROPERTY_TABLE_COLUMNS = [\n 'Name',\n 'Title',\n 'Target',\n 'Type',\n 'NUL',\n 'REQ',\n 'SRH',\n 'UED',\n 'VIW',\n];\n\n/**\n * {@link PROPERTY_TABLE_COLUMNS} without the Target column -- for `object\n * describe`'s Properties table (relationships get their own Relationships\n * table) and for `property describe`, which never shows Target even when\n * describing a relationship-typed property: Target is relationship-specific\n * and `relationship describe` is the dedicated command for that.\n */\nconst PROPERTY_ONLY_TABLE_COLUMNS = PROPERTY_TABLE_COLUMNS.filter(\n (column) => column !== 'Target'\n);\n\n/** Printed once below a {@link PROPERTY_TABLE_COLUMNS} table, spelling out its abbreviated flag columns. */\nconst PROPERTY_TABLE_KEY =\n 'NUL=Nullable, REQ=Required, SRH=Searchable, UED=User Editable, VIW=Viewable';\n\n/** Pushes {@link PropertyTableRow}s onto a table already headed with {@link PROPERTY_TABLE_COLUMNS} (from {@link createTable}); pass `includeTarget: false` for a table headed with {@link PROPERTY_ONLY_TABLE_COLUMNS} instead. */\nfunction flag(value: 'yes' | 'no'): string {\n return value === 'yes' ? c.positive(value) : c.negative(value);\n}\n\nfunction pushPropertyTableRows(\n table: ReturnType<typeof createTable>,\n rows: PropertyTableRow[],\n includeTarget: boolean = true\n): void {\n rows.forEach((row) => {\n const cells = [row.path, row.title];\n if (includeTarget) {\n cells.push(row.target);\n }\n cells.push(\n row.type,\n flag(row.nullable),\n flag(row.required),\n flag(row.searchable),\n flag(row.userEditable),\n flag(row.viewable)\n );\n table.push(cells);\n });\n}\n\n/**\n * List the schema properties of a managed object type -- or, if\n * `subProperty` is given (a dot-path, e.g. `\"profile.address\"`), the\n * immediate children of that nested `type: object` property instead. Name\n * only by default, one per line; `long` prints the full property table\n * instead (same columns/abbreviations as `property describe`).\n * @param {string} type managed object type, e.g. alpha_user\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete definitions, regardless of `long`\n * @param {boolean} long true to print the full property table instead of just names\n * @param {string} [subProperty] dot-path to a nested object property whose own children to list, instead of the type's top-level properties\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function listManagedObjectSchemaProperties(\n type: string,\n json: boolean = false,\n long: boolean = false,\n subProperty?: string\n): Promise<boolean> {\n try {\n const schema = await readManagedObjectSchema(type);\n const container = subProperty\n ? navigateToPropertyContainer(\n schema as unknown as PropertyContainer,\n parseSubPropertyPath(subProperty)\n )\n : (schema as unknown as PropertyContainer);\n if (json) {\n printMessage(JSON.stringify(container.properties, null, 2), 'data');\n return true;\n }\n if (!long) {\n Object.keys(container.properties || {})\n .sort()\n .forEach((name) => printMessage(name, 'data'));\n return true;\n }\n const rows = await resolveRelationshipCardinalities(\n type,\n collectPropertyRows(\n container.properties || {},\n new Set(container.required || []),\n false\n )\n );\n const table = createTable(PROPERTY_ONLY_TABLE_COLUMNS);\n pushPropertyTableRows(table, rows, false);\n printMessage(`${table.toString()}\\n\\n${PROPERTY_TABLE_KEY}`, 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Describe a single schema property of a managed object type -- or, with\n * `subProperty`, a nested property reached via that dot-path. Prints the\n * property's own fields first; then, if it's a `type: object` property with\n * any children, the same dot-path-rowed properties table `object describe`\n * uses (always, not gated behind a flag -- a `type: object` property's\n * children are exactly the useful part of describing it); then, if it's a\n * virtual property with an `onRetrieve`/`onStore` script, the script's\n * source printed verbatim rather than mangled into the generic field table\n * one line per row.\n *\n * Reads via the raw `managed` config entity (like `create`/`update`), not\n * the dedicated per-type schema endpoint `object describe`/`property list`\n * use -- confirmed live that the latter silently omits a virtual\n * property's `onRetrieve`/`onStore` script, so this is the one describe\n * path that can actually show it.\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete definition\n * @param {string} [subProperty] dot-path to a nested property beneath propertyName, e.g. \"address.street\"\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function describeManagedObjectSchemaProperty(\n type: string,\n propertyName: string,\n json: boolean = false,\n subProperty?: string\n): Promise<boolean> {\n try {\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n if (!typeConfig.schema) {\n throw new FrodoError(\n `Managed object type \"${type}\" has no schema definition.`\n );\n }\n const path = [propertyName, ...parseSubPropertyPath(subProperty)];\n const { container, propertyName: leafName } = navigatePropertyPath(\n typeConfig.schema as unknown as PropertyContainer,\n path\n );\n const property = container.properties?.[leafName];\n if (!property) {\n printError(\n new FrodoError(\n `Property \"${path.join('.')}\" not found on managed object type \"${type}\".`\n )\n );\n return false;\n }\n if (json) {\n printMessage(JSON.stringify(property, null, 2), 'data');\n return true;\n }\n const nameLabel = path.join('.');\n const header = c.heading(\n property.title ? `${property.title} (${nameLabel})` : nameLabel\n );\n const isObjectContainer = property.type === 'object' && property.properties;\n const scriptKeys = ['onRetrieve', 'onStore'].filter((key) => property[key]);\n const omit = [\n 'title',\n ...scriptKeys,\n ...(isObjectContainer ? ['properties', 'order', 'required'] : []),\n ];\n const displayFields = Object.fromEntries(\n Object.entries(property).filter(([key]) => !omit.includes(key))\n );\n const sections = [\n `${header}\\n\\n${createObjectTable(displayFields).toString()}`,\n ];\n if (isObjectContainer) {\n const childRows = await resolveRelationshipCardinalities(\n type,\n collectPropertyRows(\n property.properties as Record<string, Record<string, unknown>>,\n new Set((property.required as string[]) || []),\n true,\n nameLabel\n )\n );\n if (childRows.length > 0) {\n const table = createTable(PROPERTY_ONLY_TABLE_COLUMNS);\n pushPropertyTableRows(table, childRows, false);\n sections.push(\n `${c.heading('Properties')}\\n\\n${table.toString()}\\n\\n${PROPERTY_TABLE_KEY}`\n );\n }\n }\n if (scriptKeys.length > 0) {\n const scriptSections = scriptKeys.map((key) => {\n const script = property[key] as\n { type?: string; source?: string } | undefined;\n return `${c.heading(key)} (${script?.type || 'text/javascript'}):\\n\\n${(script?.source || '').trimEnd()}`;\n });\n sections.push(\n `${c.heading('Scripts')}\\n\\n${scriptSections.join('\\n\\n')}`\n );\n }\n printMessage(sections.join('\\n\\n'), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Create a new schema property on a managed object type -- or, with\n * `subProperty`, a nested property inside an existing `type: object`\n * property reached via that dot-path. Refuses if a property with that name\n * already exists at the target location (use update instead). Applies to\n * any deployment type — this reads and rewrites the whole type definition,\n * the same mechanism `frodo idm schema object export/import` already use.\n * These flags only cover a flat property definition; giving a new object\n * property its own nested sub-properties in one shot still needs the\n * file-based `property export`/`import` round trip.\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {SchemaPropertyFields} fields the property's field values\n * @param {string} [subProperty] dot-path to nest the new property under an existing object property beneath propertyName, e.g. \"address.street\"\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function createManagedObjectSchemaProperty(\n type: string,\n propertyName: string,\n fields: SchemaPropertyFields,\n subProperty?: string\n): Promise<boolean> {\n let indicatorId: string;\n const path = [propertyName, ...parseSubPropertyPath(subProperty)];\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Creating property \"${path.join('.')}\" on \"${type}\"...`\n );\n await createManagedObjectSchemaFlatProperty(\n type,\n propertyName,\n fields,\n subProperty\n );\n stopProgressIndicator(\n indicatorId,\n `Created property \"${path.join('.')}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error creating property \"${path.join('.')}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Update an existing schema property on a managed object type -- or, with\n * `subProperty`, a nested property reached via that dot-path. Refuses if\n * the property doesn't exist (use create instead). Only the fields whose\n * flags are passed change; everything else keeps its current value. Prints\n * a Current/Proposed diff and prompts for confirmation unless\n * skipConfirmation is set.\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {Partial<SchemaPropertyFields>} changedFields only the explicitly-passed field overrides\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @param {string} [subProperty] dot-path to a nested property beneath propertyName, e.g. \"address.street\"\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function updateManagedObjectSchemaPropertyCli(\n type: string,\n propertyName: string,\n changedFields: Partial<SchemaPropertyFields>,\n skipConfirmation: boolean = false,\n subProperty?: string\n): Promise<boolean> {\n let indicatorId: string;\n const path = [propertyName, ...parseSubPropertyPath(subProperty)];\n try {\n // A confirm-before-write diff needs the current/proposed definitions up\n // front, before frodo-lib's own read-modify-write runs -- so this reads\n // the type once here purely to build that preview (discarded after),\n // then lets updateManagedObjectSchemaFlatProperty do its own independent\n // read-modify-write for the actual change.\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n if (!typeConfig.schema) {\n throw new FrodoError(\n `Managed object type \"${type}\" has no schema definition.`\n );\n }\n const { container, propertyName: leafName } = navigatePropertyPath(\n typeConfig.schema as unknown as PropertyContainer,\n path\n );\n const current = container.properties?.[leafName];\n if (!current) {\n printError(\n new FrodoError(\n `Property \"${path.join('.')}\" not found on managed object type \"${type}\". Use create instead.`\n )\n );\n return false;\n }\n const overrides = pruneUndefined(changedFields);\n const mergedFields = {\n ...extractSchemaPropertyFields(current),\n ...overrides,\n };\n const propertyData = buildSchemaPropertyPayload(leafName, mergedFields);\n const warning = `Current:\\n${JSON.stringify(current, null, 2)}\\nProposed:\\n${JSON.stringify(propertyData, null, 2)}`;\n if (\n !(await confirmChange(\n warning,\n `Update property \"${path.join('.')}\" on managed object type \"${type}\"? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Update aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Updating property \"${path.join('.')}\" on \"${type}\"...`\n );\n await updateManagedObjectSchemaFlatProperty(\n type,\n propertyName,\n changedFields,\n subProperty\n );\n stopProgressIndicator(\n indicatorId,\n `Updated property \"${path.join('.')}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error updating property \"${path.join('.')}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Export a single schema property definition to a local file. Available on\n * any deployment type -- reads the whole type definition (via the raw\n * `managed` config entity, not the dedicated per-type schema endpoint,\n * which silently omits a virtual property's `onRetrieve`/`onStore` script)\n * and extracts the one property, the same mechanism `property\n * describe`/`create`/`update` already use.\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {string} [file] export file; defaults to a generated filename\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportManagedObjectSchemaPropertyToFile(\n type: string,\n propertyName: string,\n file?: string\n): Promise<boolean> {\n try {\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n const property = typeConfig.schema?.properties?.[propertyName];\n if (!property) {\n printError(\n new FrodoError(\n `Property \"${propertyName}\" not found on managed object type \"${type}\".`\n )\n );\n return false;\n }\n const fileName =\n file || getTypedFilename(`${type}-${propertyName}`, 'managed.property');\n saveJsonToFile(property, getFilePath(fileName, true), false);\n return true;\n } catch (error) {\n printError(\n error,\n `Error exporting property \"${propertyName}\" on \"${type}\"`\n );\n }\n return false;\n}\n\n/**\n * Import a single schema property definition from a local file, creating it\n * if it doesn't already exist or overwriting it (with confirmation, unless\n * skipConfirmation is set) if it does. The file's content is written\n * verbatim, unlike `create`/`update`, which build the definition from flags\n * -- this is the escape hatch for property shapes those flags can't express\n * (e.g. a `type: object` property with nested sub-properties).\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {string} file file containing the property definition to import\n * @param {boolean} skipConfirmation true to skip the confirmation prompt when overwriting an existing property\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importManagedObjectSchemaPropertyFromFile(\n type: string,\n propertyName: string,\n file: string,\n skipConfirmation: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n let filePath: string;\n try {\n filePath = getFilePath(file);\n const propertyData = JSON.parse(fs.readFileSync(filePath, 'utf8'));\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n if (!typeConfig.schema) {\n throw new FrodoError(\n `Managed object type \"${type}\" has no schema definition.`\n );\n }\n const current = typeConfig.schema.properties?.[propertyName];\n if (current) {\n const warning = `Current:\\n${JSON.stringify(current, null, 2)}\\nProposed:\\n${JSON.stringify(propertyData, null, 2)}`;\n if (\n !(await confirmChange(\n warning,\n `Import property \"${propertyName}\" on managed object type \"${type}\", overwriting its current definition? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Import aborted.', 'warn');\n return false;\n }\n }\n setSchemaProperty(\n typeConfig.schema as unknown as PropertyContainer,\n propertyName,\n propertyData\n );\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing property \"${propertyName}\" on \"${type}\" from ${filePath}...`\n );\n await importSubConfigEntity('managed', typeConfig, { validate: false });\n stopProgressIndicator(\n indicatorId,\n `Imported property \"${propertyName}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error importing property \"${propertyName}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete a schema property from a managed object type -- or, with\n * `subProperty`, a nested property reached via that dot-path. Prompts for\n * confirmation unless skipConfirmation is set.\n * @param {string} type managed object type, e.g. alpha_user\n * @param {string} propertyName schema property name, e.g. custom_merchantId\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @param {string} [subProperty] dot-path to a nested property beneath propertyName, e.g. \"address.street\"\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function deleteManagedObjectSchemaPropertyCli(\n type: string,\n propertyName: string,\n skipConfirmation: boolean = false,\n subProperty?: string\n): Promise<boolean> {\n let indicatorId: string;\n const path = [propertyName, ...parseSubPropertyPath(subProperty)];\n try {\n // See updateManagedObjectSchemaPropertyCli's comment: this read is only\n // to confirm the property exists before prompting, and is discarded --\n // removeManagedObjectSchemaFlatProperty does its own read-modify-write.\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n if (!typeConfig.schema) {\n throw new FrodoError(\n `Managed object type \"${type}\" has no schema definition.`\n );\n }\n const { container, propertyName: leafName } = navigatePropertyPath(\n typeConfig.schema as unknown as PropertyContainer,\n path\n );\n if (!container.properties?.[leafName]) {\n printError(\n new FrodoError(\n `Property \"${path.join('.')}\" not found on managed object type \"${type}\"`\n )\n );\n return false;\n }\n const warning = `This permanently deletes property \"${path.join('.')}\" from managed object type \"${type}\".`;\n if (\n !(await confirmChange(\n warning,\n `Delete property \"${path.join('.')}\" from managed object type \"${type}\"? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Delete aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Deleting property \"${path.join('.')}\" from \"${type}\"...`\n );\n await removeManagedObjectSchemaFlatProperty(\n type,\n propertyName,\n subProperty\n );\n stopProgressIndicator(\n indicatorId,\n `Deleted property \"${path.join('.')}\" from \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error deleting property \"${path.join('.')}\" from \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/** Drops keys whose value is `undefined`, so a partial CLI-flag object only overrides what was actually passed. */\nfunction pruneUndefined<T extends Record<string, unknown>>(obj: T): Partial<T> {\n const result: Partial<T> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n (result as Record<string, unknown>)[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Describe a single relationship schema property of a managed object type,\n * via the dedicated v2 API (requires IDM 7.5+; Cloud always qualifies). `withReverse` also reads and displays\n * the reverse side, inferred from the forward property's own definition.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {boolean} json true to print raw JSON instead of a table\n * @param {boolean} withReverse true to also read and display the reverse side\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function describeManagedObjectSchemaRelationshipProperty(\n type: string,\n propertyName: string,\n json: boolean = false,\n withReverse: boolean = false\n): Promise<boolean> {\n try {\n const property = await tryReadRelationshipProperty(type, propertyName);\n if (!property) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" not found on managed object type \"${type}\".`\n )\n );\n return false;\n }\n let reverse:\n | {\n type: string;\n propertyName: string;\n property: Record<string, unknown>;\n }\n | undefined;\n if (withReverse) {\n const identity = inferReverseIdentity(property);\n if (!identity) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" on managed object type \"${type}\" has no reverse relationship configured.`\n )\n );\n return false;\n }\n const reverseProperty = await tryReadRelationshipProperty(\n identity.type,\n identity.propertyName\n );\n if (!reverseProperty) {\n printError(\n new FrodoError(\n `Reverse relationship \"${identity.propertyName}\" not found on managed object type \"${identity.type}\".`\n )\n );\n return false;\n }\n reverse = { ...identity, property: reverseProperty };\n }\n if (json) {\n printMessage(\n JSON.stringify(\n reverse\n ? {\n [type]: { [propertyName]: property },\n [reverse.type]: { [reverse.propertyName]: reverse.property },\n }\n : property,\n null,\n 2\n ),\n 'data'\n );\n return true;\n }\n const describeRelationship = (\n name: string,\n relationshipProperty: Record<string, unknown>,\n suffix?: string\n ): string => {\n const title = relationshipProperty.title as string | undefined;\n const label =\n (title ? `${title} (${name})` : name) + (suffix ? ` ${suffix}` : '');\n const fields = Object.fromEntries(\n Object.entries(relationshipProperty).filter(([key]) => key !== 'title')\n );\n return `${c.heading(label)}\\n\\n${createObjectTable(fields).toString()}`;\n };\n const sections = [\n describeRelationship(`${type}.${propertyName}`, property),\n ];\n if (reverse) {\n sections.push(\n describeRelationship(\n `${reverse.type}.${reverse.propertyName}`,\n reverse.property,\n '(reverse)'\n )\n );\n }\n printMessage(sections.join('\\n\\n'), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Create a new relationship schema property, via IDM's dedicated v2 schema\n * API (requires IDM 7.5+; Cloud always qualifies). Refuses if a\n * property with that name already exists (use update\n * instead). When `reverse` is given, the reverse side on\n * `fields.targetObject` is auto-created by the server in the same write --\n * see {@link buildReversePropertyDescriptor} -- rather than through a\n * separate CLI-side write; live-confirmed to work for all four single/many\n * combinations on both sides. Note the server does not honor a custom\n * reverse title/description (it always uses the raw property name for\n * both), even though `--reverse-title`/`--reverse-description` are threaded\n * through in case that changes.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {RelationshipPropertyFields} fields the forward side's field values\n * @param {RelationshipReverseCreateFields} [reverse] the reverse side's field values, if creating both sides\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function createManagedObjectSchemaRelationshipProperty(\n type: string,\n propertyName: string,\n fields: RelationshipPropertyFields,\n reverse?: RelationshipReverseCreateFields\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n reverse\n ? `Creating relationship \"${propertyName}\" on \"${type}\", with reverse relationship \"${reverse.propertyName}\" on \"${fields.targetObject}\"...`\n : `Creating relationship \"${propertyName}\" on \"${type}\"...`\n );\n await createRelationshipPropertyLib(type, propertyName, fields, reverse);\n stopProgressIndicator(\n indicatorId,\n reverse\n ? `Created relationship \"${propertyName}\" on \"${type}\", with reverse relationship \"${reverse.propertyName}\" auto-created on \"${fields.targetObject}\".`\n : `Created relationship \"${propertyName}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error creating relationship \"${propertyName}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Update an existing relationship schema property, via IDM's dedicated v2\n * schema API (requires IDM 7.5+; Cloud always qualifies). Refuses\n * if the property doesn't exist (use create\n * instead). Only the fields present in `changedFields` change; everything\n * else keeps its current value. `withReverse` infers the reverse side from\n * the forward property's own current definition (no separate identity\n * flags needed) and applies the same explicit overrides to it too; no\n * automatic rollback if the reverse write fails after the forward side\n * already succeeded.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {Partial<RelationshipPropertyFields>} changedFields only the explicitly-passed field overrides\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @param {boolean} withReverse true to also update the inferred reverse side\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function updateManagedObjectSchemaRelationshipPropertyCli(\n type: string,\n propertyName: string,\n changedFields: Partial<RelationshipPropertyFields>,\n skipConfirmation: boolean = false,\n withReverse: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n // A confirm-before-write diff needs the current/proposed definition(s)\n // up front, before frodo-lib's own read-modify-write runs -- so this\n // preview is built here (and discarded), then\n // updateManagedObjectSchemaRelationshipProperty does its own\n // independent read-modify-write for the actual change (see the\n // analogous comment on updateManagedObjectSchemaPropertyCli).\n const current = await tryReadRelationshipProperty(type, propertyName);\n if (!current) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" not found on managed object type \"${type}\". Use create instead.`\n )\n );\n return false;\n }\n // A configured reverse side's descriptor must be re-supplied on every\n // write, not just when --with-reverse asks to also change its fields --\n // see toReverseDescriptorFields. So the reverse side is fetched whenever\n // one exists, regardless of --with-reverse.\n const reverseIdentity = inferReverseIdentity(current);\n if (withReverse && !reverseIdentity) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" on managed object type \"${type}\" has no reverse relationship configured; --with-reverse cannot be used.`\n )\n );\n return false;\n }\n let reverseCurrent: Record<string, unknown> | null = null;\n if (reverseIdentity) {\n reverseCurrent = await tryReadRelationshipProperty(\n reverseIdentity.type,\n reverseIdentity.propertyName\n );\n if (!reverseCurrent) {\n printError(\n new FrodoError(\n `Reverse relationship \"${reverseIdentity.propertyName}\" not found on managed object type \"${reverseIdentity.type}\".`\n )\n );\n return false;\n }\n }\n const overrides = pruneUndefined(changedFields);\n const mergedForwardFields = {\n ...extractRelationshipFields(current),\n ...overrides,\n };\n const mergedReverseFields =\n reverseCurrent && reverseIdentity\n ? withReverse\n ? { ...extractRelationshipFields(reverseCurrent), ...overrides }\n : extractRelationshipFields(reverseCurrent)\n : undefined;\n const forwardPayload = buildRelationshipPropertyPayload(\n propertyName,\n mergedForwardFields,\n mergedReverseFields && reverseIdentity\n ? toReverseDescriptorFields(\n reverseIdentity.propertyName,\n mergedReverseFields\n )\n : undefined\n );\n let warning = `Current (${type}.${propertyName}):\\n${JSON.stringify(current, null, 2)}\\nProposed:\\n${JSON.stringify(forwardPayload, null, 2)}`;\n if (withReverse && mergedReverseFields && reverseIdentity) {\n const reversePayload = buildRelationshipPropertyPayload(\n reverseIdentity.propertyName,\n mergedReverseFields,\n toReverseDescriptorFields(propertyName, mergedForwardFields)\n );\n warning += `\\nCurrent (${reverseIdentity.type}.${reverseIdentity.propertyName}, reverse):\\n${JSON.stringify(reverseCurrent, null, 2)}\\nProposed:\\n${JSON.stringify(reversePayload, null, 2)}`;\n }\n if (\n !(await confirmChange(\n warning,\n `Update relationship \"${propertyName}\" on managed object type \"${type}\"${withReverse ? ' and its reverse side' : ''}? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Update aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n withReverse\n ? `Updating relationship \"${propertyName}\" on \"${type}\" and its reverse side...`\n : `Updating relationship \"${propertyName}\" on \"${type}\"...`\n );\n await updateRelationshipPropertyLib(\n type,\n propertyName,\n changedFields,\n withReverse\n );\n stopProgressIndicator(\n indicatorId,\n `Updated relationship \"${propertyName}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error updating relationship \"${propertyName}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Export a single relationship schema property definition to a local file,\n * via IDM's dedicated v2 schema API (requires IDM 7.5+; Cloud always\n * qualifies). Exports the named side only -- the reverse side, if any, is\n * exported separately by naming it directly.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {string} [file] export file; defaults to a generated filename\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function exportManagedObjectSchemaRelationshipPropertyToFile(\n type: string,\n propertyName: string,\n file?: string\n): Promise<boolean> {\n try {\n const property = await tryReadRelationshipProperty(type, propertyName);\n if (!property) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" not found on managed object type \"${type}\".`\n )\n );\n return false;\n }\n const fileName =\n file ||\n getTypedFilename(`${type}-${propertyName}`, 'managed.relationship');\n saveJsonToFile(property, getFilePath(fileName, true), false);\n return true;\n } catch (error) {\n printError(\n error,\n `Error exporting relationship \"${propertyName}\" on \"${type}\"`\n );\n }\n return false;\n}\n\n/**\n * Import a single relationship schema property definition from a local\n * file, via IDM's dedicated v2 schema API (requires IDM 7.5+; Cloud always\n * qualifies), creating it if it doesn't already exist or overwriting it\n * (with confirmation, unless skipConfirmation is set) if it does. The\n * file's content is written verbatim, unlike `create`/`update`, which build\n * the definition from flags -- this is the escape hatch for relationship\n * shapes those flags can't express. Imports the named side only; the\n * reverse side, if any, needs its own separate import.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {string} file file containing the relationship property definition to import\n * @param {boolean} skipConfirmation true to skip the confirmation prompt when overwriting an existing relationship\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importManagedObjectSchemaRelationshipPropertyFromFile(\n type: string,\n propertyName: string,\n file: string,\n skipConfirmation: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n let filePath: string;\n try {\n filePath = getFilePath(file);\n const propertyData = JSON.parse(fs.readFileSync(filePath, 'utf8'));\n const current = await tryReadRelationshipProperty(type, propertyName);\n if (current) {\n const warning = `Current:\\n${JSON.stringify(current, null, 2)}\\nProposed:\\n${JSON.stringify(propertyData, null, 2)}`;\n if (\n !(await confirmChange(\n warning,\n `Import relationship \"${propertyName}\" on managed object type \"${type}\", overwriting its current definition? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Import aborted.', 'warn');\n return false;\n }\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing relationship \"${propertyName}\" on \"${type}\" from ${filePath}...`\n );\n await updateManagedObjectSchemaProperty(type, propertyName, propertyData);\n stopProgressIndicator(\n indicatorId,\n `Imported relationship \"${propertyName}\" on \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error importing relationship \"${propertyName}\" on \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete a relationship schema property, via IDM's dedicated v2 schema API\n * (requires IDM 7.5+; Cloud always qualifies). `withReverse`\n * infers the reverse side from the forward property's\n * own current definition (no separate identity flags needed) and deletes\n * it first, then the forward side, so a failed second delete leaves the\n * explicitly-named side as the one still consistently present.\n * @param {string} type managed object type, e.g. alpha_aiagentprivilege\n * @param {string} propertyName relationship property name, e.g. agent\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @param {boolean} withReverse true to also delete the inferred reverse side\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function deleteManagedObjectSchemaRelationshipPropertyCli(\n type: string,\n propertyName: string,\n skipConfirmation: boolean = false,\n withReverse: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n // See updateManagedObjectSchemaRelationshipPropertyCli's comment: this\n // preview is only to build the confirm warning, and is discarded --\n // removeManagedObjectSchemaRelationshipProperty does its own\n // independent read(s)/delete(s).\n const current = await tryReadRelationshipProperty(type, propertyName);\n if (!current) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" not found on managed object type \"${type}\"`\n )\n );\n return false;\n }\n let reverseIdentity: { type: string; propertyName: string } | null = null;\n let reverseCurrent: Record<string, unknown> | null = null;\n if (withReverse) {\n reverseIdentity = inferReverseIdentity(current);\n if (!reverseIdentity) {\n printError(\n new FrodoError(\n `Relationship \"${propertyName}\" on managed object type \"${type}\" has no reverse relationship configured; --with-reverse cannot be used.`\n )\n );\n return false;\n }\n reverseCurrent = await tryReadRelationshipProperty(\n reverseIdentity.type,\n reverseIdentity.propertyName\n );\n if (!reverseCurrent) {\n printError(\n new FrodoError(\n `Reverse relationship \"${reverseIdentity.propertyName}\" not found on managed object type \"${reverseIdentity.type}\".`\n )\n );\n return false;\n }\n }\n let warning = `This permanently removes the relationship \"${propertyName}\" from managed object type \"${type}\":\\n${JSON.stringify(current, null, 2)}`;\n if (withReverse && reverseCurrent && reverseIdentity) {\n warning += `\\n...and its reverse relationship, from managed object type \"${reverseIdentity.type}\":\\n${JSON.stringify(reverseCurrent, null, 2)}`;\n }\n warning += `\\nThis removes the relationship definition only.`;\n if (\n !(await confirmChange(\n warning,\n `Delete relationship \"${propertyName}\" from managed object type \"${type}\"${withReverse ? ' and its reverse side' : ''}? This affects every instance of that type. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Delete aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n withReverse\n ? `Deleting relationship \"${propertyName}\" from \"${type}\" and its reverse side...`\n : `Deleting relationship \"${propertyName}\" from \"${type}\"...`\n );\n await removeRelationshipPropertyLib(type, propertyName, withReverse);\n stopProgressIndicator(\n indicatorId,\n `Deleted relationship \"${propertyName}\" from \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error deleting relationship \"${propertyName}\" from \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Create a new managed object type. Refuses if a type with that name\n * already exists (use update instead). Prompts for confirmation, reusing\n * the same schema-change gate `frodo idm schema object import` already\n * uses, unless skipConfirmation is set.\n * @param {string} type managed object type, e.g. alpha_widget\n * @param {string} title display title for the new type\n * @param {string} [icon] display icon; defaults to a generic icon if not passed\n * @param {string} [description] display description; omitted from the definition if not passed\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function createManagedObjectType(\n type: string,\n title: string,\n icon: string | undefined,\n description: string | undefined,\n skipConfirmation: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n if (\n !(await confirmChange(\n `This creates the new managed object type \"${type}\".`,\n 'Schema changes affect every instance of this managed object type. Continue? (y|n):',\n skipConfirmation\n ))\n ) {\n printMessage('Create aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Creating managed object type \"${type}\"...`\n );\n await frodo.idm.managed.schema.createManagedObjectType(type, {\n title,\n icon,\n description,\n });\n stopProgressIndicator(\n indicatorId,\n `Created managed object type \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error creating managed object type \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Update an existing managed object type. Refuses if the type doesn't\n * exist (use create instead). Only the fields whose flags are passed\n * change; everything else keeps its current value. Prints a\n * current/proposed preview and prompts for confirmation, unless\n * skipConfirmation is set.\n * @param {string} type managed object type, e.g. alpha_widget\n * @param {{title?: string, icon?: string, description?: string}} changedFields only the explicitly-passed field overrides\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function updateManagedObjectTypeCli(\n type: string,\n changedFields: { title?: string; icon?: string; description?: string },\n skipConfirmation: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n // A confirm-before-write diff needs the current/proposed metadata up\n // front, before frodo-lib's own read-modify-write runs -- so this reads\n // the type once here purely to build that preview (discarded after),\n // then lets updateManagedObjectType do its own independent\n // read-modify-write for the actual change (see the analogous comment on\n // updateManagedObjectSchemaPropertyCli).\n const typeConfig = (await readSubConfigEntity(\n 'managed',\n type\n )) as ManagedObjectTypeConfig;\n if (!typeConfig.schema) {\n printError(\n new FrodoError(\n `Managed object type \"${type}\" not found. Use create instead.`\n )\n );\n return false;\n }\n const schemaRecord = typeConfig.schema as unknown as Record<\n string,\n unknown\n >;\n const current = {\n title: typeConfig.schema.title,\n icon: schemaRecord['mat-icon'] as string | undefined,\n description: schemaRecord.description as string | undefined,\n };\n const proposed = {\n title: changedFields.title ?? current.title,\n icon: changedFields.icon ?? current.icon,\n description: changedFields.description ?? current.description,\n };\n const warning = `This updates the managed object type \"${type}\".\\nCurrent:\\n${JSON.stringify(current, null, 2)}\\nProposed:\\n${JSON.stringify(proposed, null, 2)}`;\n if (\n !(await confirmChange(\n warning,\n 'Schema changes affect every instance of this managed object type. Continue? (y|n):',\n skipConfirmation\n ))\n ) {\n printMessage('Update aborted.', 'warn');\n return false;\n }\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Updating managed object type \"${type}\"...`\n );\n await frodo.idm.managed.schema.updateManagedObjectType(type, changedFields);\n stopProgressIndicator(\n indicatorId,\n `Updated managed object type \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error updating managed object type \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Describe a single managed object type: its own metadata (name/title/icon)\n * plus a Properties table and, if the type has any, a Relationships table\n * (which -- unlike Properties -- keeps the Target column). Flat by default\n * -- one row per top-level property; with `recursive`, nested `type: object`\n * properties expand inline, named by dot-path (e.g. `address.street`),\n * matching exactly what `--sub-property` on the property commands accepts.\n * @param {string} type managed object type, e.g. alpha_user or user\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete definition, regardless of `recursive`\n * @param {boolean} recursive true to expand nested object properties inline in the table\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function describeManagedObjectType(\n type: string,\n json: boolean = false,\n recursive: boolean = false\n): Promise<boolean> {\n try {\n const schema = await readManagedObjectSchema(type);\n if (json) {\n printMessage(JSON.stringify(schema, null, 2), 'data');\n return true;\n }\n const rows = await resolveRelationshipCardinalities(\n type,\n collectPropertyRows(\n (schema.properties || {}) as unknown as Record<\n string,\n Record<string, unknown>\n >,\n new Set(schema.required || []),\n recursive\n )\n );\n const propertyRows = rows.filter((row) => !row.isRelationship);\n const relationshipRows = rows.filter((row) => row.isRelationship);\n const matIcon = (schema as unknown as Record<string, unknown>)[\n 'mat-icon'\n ] as string | undefined;\n const sections = [\n c.heading(schema.title ? `${schema.title} (${type})` : type),\n matIcon ? `icon: ${matIcon}` : undefined,\n ].filter(Boolean);\n if (propertyRows.length > 0) {\n const propertiesTable = createTable(PROPERTY_ONLY_TABLE_COLUMNS);\n pushPropertyTableRows(propertiesTable, propertyRows, false);\n sections.push(\n `${c.heading('Properties')}\\n\\n${propertiesTable.toString()}`\n );\n }\n if (relationshipRows.length > 0) {\n const relationshipsTable = createTable(PROPERTY_TABLE_COLUMNS);\n pushPropertyTableRows(relationshipsTable, relationshipRows);\n sections.push(\n `${c.heading('Relationships')}\\n\\n${relationshipsTable.toString()}`\n );\n }\n sections.push(PROPERTY_TABLE_KEY);\n printMessage(sections.join('\\n\\n'), 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * List every managed object type defined on the tenant. A single read of\n * the whole `managed` config entity already contains every type's\n * `{name, schema}`, so no per-type follow-up read is needed -- Properties\n * and Relationships (each shown as `total/required`) are both counted from\n * that same local schema, no extra reads. Name only by default, one per\n * line; `long` prints a table (Name/Title/Icon/Properties/Relationships)\n * instead. Unlike `frodo idm count`, this never reflects actual record\n * counts.\n *\n * Known gap, accepted for staying on a single free read rather than one\n * read per type: the bulk `managed` config entity doesn't include IDM's\n * auto-injected `_meta`/`_notifications` relationship properties, which\n * only appear via the dedicated per-type schema read `object\n * describe`/`relationship list` use -- so a type's Properties/Relationships\n * counts here can undercount by up to 2 relative to those commands.\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete list, regardless of `long`\n * @param {boolean} long true to print the full table instead of just names\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function listManagedObjectTypes(\n json: boolean = false,\n long: boolean = false\n): Promise<boolean> {\n try {\n const managedConfig = (await frodo.idm.config.readConfigEntity(\n 'managed'\n )) as IdObjectSkeletonInterface & { objects?: ManagedObjectTypeConfig[] };\n const objects = managedConfig.objects || [];\n if (json) {\n printMessage(\n JSON.stringify(\n objects.map((object) => object.name),\n null,\n 2\n ),\n 'data'\n );\n return true;\n }\n const sorted = objects.slice().sort((a, b) => a.name.localeCompare(b.name));\n if (!long) {\n sorted.forEach((object) => printMessage(object.name, 'data'));\n return true;\n }\n const counts = sorted.map((object) => {\n const required = new Set(object.schema?.required || []);\n let propertyCount = 0;\n let requiredPropertyCount = 0;\n let relationshipCount = 0;\n let requiredRelationshipCount = 0;\n Object.entries(object.schema?.properties || {}).forEach(\n ([name, property]) => {\n if (\n isRelationshipProperty(\n property as unknown as Record<string, unknown>\n )\n ) {\n relationshipCount++;\n if (required.has(name)) {\n requiredRelationshipCount++;\n }\n } else {\n propertyCount++;\n if (required.has(name)) {\n requiredPropertyCount++;\n }\n }\n }\n );\n return {\n object,\n propertyCount,\n requiredPropertyCount,\n relationshipCount,\n requiredRelationshipCount,\n };\n });\n // Right-align just the numerator to the widest one in its column, so the \"/\" lines up across rows -- a plain right-aligned cell wouldn't, since it pads the whole \"total/required\" string as one block.\n const propertyWidth = Math.max(\n ...counts.map((c) => String(c.propertyCount).length)\n );\n const relationshipWidth = Math.max(\n ...counts.map((c) => String(c.relationshipCount).length)\n );\n const table = createTable([\n 'Name',\n 'Title',\n 'Icon',\n 'Properties',\n 'Relationships',\n ]);\n counts.forEach(\n ({\n object,\n propertyCount,\n requiredPropertyCount,\n relationshipCount,\n requiredRelationshipCount,\n }) => {\n table.push([\n object.name,\n object.schema?.title || '',\n ((object.schema as unknown as Record<string, unknown>)?.[\n 'mat-icon'\n ] as string) || '',\n `${String(propertyCount).padStart(propertyWidth)}/${requiredPropertyCount}`,\n `${String(relationshipCount).padStart(relationshipWidth)}/${requiredRelationshipCount}`,\n ]);\n }\n );\n printMessage(\n `${table.toString()}\\n\\nProperties/Relationships shown as total/required.`,\n 'data'\n );\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * List the relationship schema properties of a managed object type --\n * fills the gap noted when the dedicated v2 relationship-schema API was\n * first exposed via `frodo idm schema relationship`: that API is\n * single-property GET/PUT/DELETE only, no bulk listing, so this falls back\n * to the same whole-type schema read `property list` already uses,\n * filtered to relationship-typed properties. Name only by default, one per\n * line; `long` prints the full relationship table instead (same\n * columns/abbreviations, including cardinality, as `object describe`'s\n * Relationships table).\n * @param {string} type managed object type, e.g. alpha_user\n * @param {boolean} json true to print raw JSON instead of a table -- always the complete definitions, regardless of `long`\n * @param {boolean} long true to print the full relationship table instead of just names\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function listManagedObjectSchemaRelationshipProperties(\n type: string,\n json: boolean = false,\n long: boolean = false\n): Promise<boolean> {\n try {\n const schema = await readManagedObjectSchema(type);\n const entries = Object.entries(schema.properties || {}).filter(\n ([, property]) =>\n isRelationshipProperty(property as unknown as Record<string, unknown>)\n );\n if (json) {\n printMessage(\n JSON.stringify(Object.fromEntries(entries), null, 2),\n 'data'\n );\n return true;\n }\n if (!long) {\n entries\n .map(([name]) => name)\n .sort()\n .forEach((name) => printMessage(name, 'data'));\n return true;\n }\n const rows = await resolveRelationshipCardinalities(\n type,\n collectPropertyRows(\n Object.fromEntries(entries) as unknown as Record<\n string,\n Record<string, unknown>\n >,\n new Set(schema.required || []),\n false\n )\n );\n const table = createTable(PROPERTY_TABLE_COLUMNS);\n pushPropertyTableRows(table, rows);\n printMessage(`${table.toString()}\\n\\n${PROPERTY_TABLE_KEY}`, 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Counts the records of a managed object type. A 404 from the query\n * endpoint reliably means the type's collection was never provisioned —\n * i.e. confirmed zero records, not an unknown failure — so it resolves to\n * 0 rather than propagating. Any other failure (permission, timeout, etc.)\n * propagates, since that genuinely is an unknown count and must not be\n * silently treated as \"safe to proceed\" (the exact not-found-misclassification\n * anti-pattern the tracker flagged elsewhere).\n * @param {string} type managed object type\n * @return {Promise<number>} a promise that resolves to the record count\n */\nasync function countManagedObjectRecords(type: string): Promise<number> {\n try {\n return await countManagedObjectsOfType(type);\n } catch (error) {\n if ((error as FrodoError).httpStatus === 404) {\n return 0;\n }\n throw error;\n }\n}\n\n/**\n * Delete a managed object type entirely (schema included). Refuses if the\n * type has existing records, or if the record count couldn't be confirmed,\n * unless force is set — every existing record of that type becomes\n * orphaned by this operation, so an -F/--force override is required in\n * addition to skipConfirmation (matching `frodo iga workflow delete -F`'s\n * existing pattern in this codebase: a distinct override for a safety\n * check, not a bigger confirmation prompt). Otherwise prompts for\n * confirmation unless skipConfirmation is set.\n * @param {string} type managed object type to delete, e.g. alpha_customType\n * @param {boolean} skipConfirmation true to skip the confirmation prompt\n * @param {boolean} force true to proceed even if records exist or the record count is unknown\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function deleteManagedObjectTypeCli(\n type: string,\n skipConfirmation: boolean = false,\n force: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n try {\n let recordCount: number | undefined;\n try {\n recordCount = await countManagedObjectRecords(type);\n } catch {\n // count stays undefined; handled as \"unknown\" below\n }\n if (recordCount === undefined && !force) {\n printError(\n new FrodoError(\n `Unable to confirm number of existing \"${type}\" instances. Use -F/--force to delete.`\n )\n );\n return false;\n }\n if (recordCount !== undefined && recordCount > 0 && !force) {\n printError(\n new FrodoError(\n `${recordCount} existing \"${type}\" instance(s). Use -F/--force to delete.`\n )\n );\n return false;\n }\n if (\n !(await confirmChange(\n `This permanently deletes managed object type \"${type}\".`,\n `Delete managed object type \"${type}\"? This cannot be undone. Continue? (y|n):`,\n skipConfirmation\n ))\n ) {\n printMessage('Delete aborted.', 'warn');\n return false;\n }\n // No separate existence pre-check: removeManagedObjectType does its own\n // single read of the whole 'managed' config entity and throws its own\n // not-found error if the type is missing, so a second read here would\n // be a redundant round-trip.\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Deleting managed object type \"${type}\"...`\n );\n await frodo.idm.managed.schema.removeManagedObjectType(type);\n stopProgressIndicator(\n indicatorId,\n `Deleted managed object type \"${type}\".`,\n 'success'\n );\n return true;\n } catch (error) {\n if (indicatorId) {\n stopProgressIndicator(\n indicatorId,\n `Error deleting managed object type \"${type}\".`,\n 'fail'\n );\n }\n printError(error);\n }\n return false;\n}\n\n/**\n * Import all IDM configuration objects from working directory\n * @param {string} entitiesFile JSON file that specifies the config entities to export/import\n * @param {boolean} validate True to validate script hooks. Default: false\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function importAllConfigEntitiesFromFiles(\n entitiesFile?: string,\n validate: boolean = false\n): Promise<boolean> {\n let indicatorId: string;\n const baseDirectory = getWorkingDirectory();\n try {\n const importData = await getIdmImportDataFromIdmDirectory(baseDirectory);\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing config entities from ${baseDirectory}...`\n );\n const options = getIdmImportExportOptions(entitiesFile);\n await importConfigEntities(\n importData as ConfigEntityExportInterface,\n undefined,\n {\n entitiesToImport: options.entitiesToExportOrImport,\n validate,\n },\n errorHandler\n );\n stopProgressIndicator(indicatorId, `Imported config entities`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing config entities from ${baseDirectory}.`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Count number of managed objects of a given type\n * @param {String} type managed object type, e.g. alpha_user\n * @return {Promise<boolean>} a promise that resolves to true if successful, false otherwise\n */\nexport async function countManagedObjects(type: string): Promise<boolean> {\n try {\n const result = await countManagedObjectsOfType(type);\n printMessage(`${type}: ${result}`, 'data');\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Helper that reads all the idm config entity data from a directory\n * @param directory The directory of the idm config entities\n */\nexport async function getIdmImportDataFromIdmDirectory(\n directory: string\n): Promise<ConfigEntityExportInterface> {\n const importData = { idm: {} } as ConfigEntityExportInterface;\n const idmConfigFiles = await readFiles(directory);\n idmConfigFiles.forEach((f) => (f.path = f.path.replace(/\\/$/, '')));\n // Process sync mapping file(s)\n const sync = getLegacyMappingsFromFiles(idmConfigFiles);\n if (sync.mappings && sync.mappings.length > 0) {\n importData.idm.sync = sync;\n }\n const managed = getManagedObjectsFromFiles(idmConfigFiles);\n if (managed.objects && managed.objects.length > 0) {\n importData.idm.managed = managed;\n }\n // Process other files\n for (const f of idmConfigFiles.filter(\n (f) =>\n !f.path.endsWith('sync.idm.json') &&\n !f.path.endsWith('managed.idm.json') &&\n f.path.endsWith('.idm.json')\n )) {\n const baseDirOfThisJson = path.dirname(f.path);\n const entities = Object.values(\n JSON.parse(f.content).idm\n ) as unknown as IdObjectSkeletonInterface[];\n for (const entity of entities) {\n resolveAllExtractedScriptsForImport(entity, baseDirOfThisJson);\n importData.idm[entity._id] = entity;\n }\n }\n return importData;\n}\n\n/**\n * Recursive helper that reads in extracted scripts from IDM exports\n * @param {any} obj The object to read scripts in for\n * @param {string} baseDir The base directory where the extracted files are stored relative to\n * @param {WeakSet} visited The visited objects\n */\nexport function resolveAllExtractedScriptsForImport(\n obj: any,\n baseDir: string,\n visited = new WeakSet()\n) {\n if (obj === null || typeof obj !== 'object') {\n return;\n }\n if (visited.has(obj)) return;\n visited.add(obj);\n if (Array.isArray(obj)) {\n for (const item of obj) {\n resolveAllExtractedScriptsForImport(item, baseDir, visited);\n }\n return;\n }\n if (typeof obj.source === 'string' && obj.source.startsWith('file://')) {\n const fileContent = getExtractedData(obj.source, baseDir);\n if (fileContent !== null) {\n obj.source = fileContent;\n }\n }\n for (const key of Object.keys(obj)) {\n resolveAllExtractedScriptsForImport(obj[key], baseDir, visited);\n }\n}\n\n/**\n * Helper that returns options for exporting/importing IDM config entities\n * @param {string} entitiesFile JSON file that specifies the config entities to export/import\n * @return {ConfigEntityExportOptions} the config export options\n */\nexport function getIdmImportExportOptions(entitiesFile?: string): {\n entitiesToExportOrImport: string[];\n} {\n // read list of entities to export/import\n let entitiesToExportOrImport: string[] = [];\n if (entitiesFile) {\n const data = fs.readFileSync(entitiesFile, 'utf8');\n const entriesData = JSON.parse(data);\n entitiesToExportOrImport = entriesData.idm;\n }\n return {\n entitiesToExportOrImport,\n };\n}\n\n/**\n * Helper that writes objects in the managed IDM config entity to a directory\n * @param {ManagedSkeleton} managed The managed IDM config entity\n * @param {string} directory The directory to save the entity to within the base directory\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n */\nexport function writeManagedJsonToDirectory(\n managed: ManagedSkeleton,\n directory: string = 'managed',\n includeMeta: boolean = true,\n extract: boolean = false\n) {\n const objectPaths = [];\n for (const object of managed.objects) {\n if (!object) {\n // Skip null/malformed entries in the tenant's managed.json objects array.\n continue;\n }\n const fileName = getTypedFilename(object.name, 'managed');\n if (\n extract &&\n extractManagedObjectScriptsToDirectory(\n object,\n `${directory}/${object.name}`\n )\n ) {\n objectPaths.push(\n extractDataToFile(object, `${object.name}/${fileName}`, directory)\n );\n } else {\n objectPaths.push(extractDataToFile(object, fileName, directory));\n }\n }\n managed.objects = objectPaths;\n saveToFile(\n 'idm',\n managed,\n '_id',\n getFilePath(`${directory}/managed.idm.json`, true),\n includeMeta\n );\n}\n\n/**\n * Helper that extracts scripts from a managed object\n * @param {ObjectSkeleton} object The managed object\n * @param {string} directory The directory to extract scripts to within the base directory\n * @returns {boolean} true if at least one script got extracted, false otherwise\n */\nexport function extractManagedObjectScriptsToDirectory(\n object: ObjectSkeleton,\n directory: string = object.name\n): boolean {\n const scripts = findIdmScripts(object);\n if (!scripts.length) return false;\n for (const script of scripts) {\n const managedObjectPath = script.path\n .replace('schema.', '')\n .replaceAll('properties.', '');\n const sourceObj = getObjectByPath(object, script.path);\n const objectFileName = `${managedObjectPath}.${script.type}`;\n sourceObj.source = extractDataToFile(\n script.source,\n objectFileName,\n directory\n );\n }\n return true;\n}\n\n/**\n * Helper that writes an IDM config entity to a directory\n * @param {IdObjectSkeletonInterface} object The IDM config entity\n * @param {string} directory The directory to save the entity to within the base directory\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract true to extract idm scripts, false otherwise. Default: false\n */\nexport function writeIdmObjectToDirectory(\n object: IdObjectSkeletonInterface,\n directory: string = '.',\n includeMeta: boolean = true,\n extract: boolean = false\n) {\n let filePath;\n if (extract && extractIdmScriptsToDirectory(object, directory)) {\n filePath = getFilePath(\n `${directory}/${object._id}/${getTypedFilename(object._id.split('/').pop(), 'idm')}`,\n true\n );\n } else {\n filePath = getFilePath(`${directory}/${object._id}.idm.json`, true);\n }\n const directoryPath = path.dirname(filePath);\n if (!fs.existsSync(directoryPath))\n fs.mkdirSync(directoryPath, { recursive: true });\n saveToFile('idm', object, '_id', filePath, includeMeta);\n}\n\n/**\n * Helper that extracts scripts from an IDM entity\n * @param {ObjectSkeleton} object The IDM entity\n * @param {string} directory The directory to extract scripts to within the base directory\n * @returns {boolean} true if at least one script got extracted, false otherwise\n */\nexport function extractIdmScriptsToDirectory(\n object: IdObjectSkeletonInterface,\n directory: string\n): boolean {\n const scripts = findIdmScripts(object);\n if (!scripts.length) return false;\n for (const script of scripts) {\n let objectFileName;\n let sourceObject;\n if (!script.path) {\n objectFileName = `${object._id.split('/').pop()}.${script.type}`;\n sourceObject = object;\n } else {\n objectFileName = `${script.path}.${script.type}`;\n sourceObject = getObjectByPath(object, script.path);\n }\n sourceObject.source = extractDataToFile(\n script.source,\n objectFileName,\n `${directory}/${object._id}`\n );\n }\n return true;\n}\n\n/**\n * Helper that reads the managed IDM config entity from files\n * @param {{ path: string; content: string }[]} files the files to read the managed IDM config entity object from\n * @returns {ManagedSkeleton} the managed IDM config entity\n */\nexport function getManagedObjectsFromFiles(\n files: { path: string; content: string }[]\n): ManagedSkeleton {\n const managedFiles = files.filter((f) =>\n f.path.endsWith('/managed.idm.json')\n );\n if (managedFiles.length > 1) {\n throw new FrodoError(\n 'Multiple managed.idm.json files found in idm directory'\n );\n }\n const managed: ManagedSkeleton = {\n _id: 'managed',\n objects: [],\n };\n if (managedFiles.length === 1) {\n const jsonData = JSON.parse(managedFiles[0].content);\n const managedData = jsonData.managed ?? jsonData.idm?.managed;\n const managedJsonDir = managedFiles[0].path.substring(\n 0,\n managedFiles[0].path.indexOf('/managed.idm.json')\n );\n if (managedData?.objects) {\n for (const object of managedData.objects) {\n let resolvedObject: any;\n if (typeof object === 'string') {\n resolvedObject = getExtractedJsonData(object, managedJsonDir);\n } else {\n resolvedObject = object;\n }\n resolveAllExtractedScriptsForImport(\n resolvedObject,\n `${managedJsonDir}/${resolvedObject.name}`\n );\n managed.objects.push(resolvedObject);\n }\n }\n }\n return managed;\n}\n\n/**\n * Helper that returns the first object name in a path\n * @param {string} path The object path\n * @returns {string} The first name in the path\n */\nexport function getTopString(path: string): string {\n return path.split('.')[0];\n}\n\n/**\n * Helper that returns the first object in a path\n * @param {string} path The object path\n * @param {any} obj The parent object\n * @returns {any} The first object in the path\n */\nexport function getTopObject(path: string, obj: any): any {\n return obj[getTopString(path)];\n}\n\n/**\n * Helper that returns the last object name in a path\n * @param {string} path The object path\n * @returns {string} The last name in the path\n */\nexport function getLastString(path: string) {\n const parts = path.split('.');\n return parts[parts.length - 1];\n}\n\n/**\n * Helper that returns the object at the specified path\n * @param {string} path The object path\n * @param {any} obj The parent object\n * @returns {any} The object at the path\n */\nexport function getObjectByPath(obj: any, path: string): any {\n return path.split('.').reduce((acc, key) => {\n const realKey = /^\\d+$/.test(key) ? Number(key) : key;\n return acc?.[realKey];\n }, obj);\n}\n\n/**\n * Helper that returns the object at the second to last of the specified path\n * @param {string} path The object path\n * @param {any} obj The parent object\n * @returns {any} The object at the second to last of the path\n */\nexport function getObjectByPathExcludeLast(obj: any, path: string): any {\n const keys = path.split('.');\n keys.pop();\n return getObjectByPath(obj, keys.join('.'));\n}\n\n/**\n * Recursive helper that finds all IDM scripts within an object\n * @param {any} obj The object\n * @param {string} currentPath The current path to the object\n * @param {MatchResult[]} result the found IDM scripts so far\n * @returns {MatchResult[]} the found IDM scripts\n */\nexport function findIdmScripts(\n obj: any,\n currentPath: string = '',\n result: MatchResult[] = []\n): MatchResult[] {\n if (typeof obj !== 'object' || obj === null) return result;\n if ('source' in obj && 'type' in obj) {\n const normalizedSource = Array.isArray(obj.source)\n ? obj.source.join('\\n')\n : obj.source;\n const scriptType =\n obj.type === 'text/javascript'\n ? 'js'\n : obj.type === 'groovy'\n ? 'groovy'\n : 'unknown';\n result.push({\n path: currentPath,\n source: normalizedSource,\n type: scriptType,\n });\n }\n\n for (const key of Object.keys(obj)) {\n const newPath = currentPath ? `${currentPath}.${key}` : key;\n findIdmScripts(obj[key], newPath, result);\n }\n\n return result;\n}\n","import fs from 'fs';\nimport {\n frodo,\n FrodoError,\n type CustomNodeExportInterface,\n type CustomNodeExportOptions,\n type CustomNodeImportOptions,\n type CustomNodeSkeleton,\n type CustomNodeUsage,\n type InnerNodeRefSkeletonInterface,\n type NodeRefSkeletonInterface,\n type NodeSkeleton,\n} from '@rockcarver/frodo-lib';\nimport c from '../utils/ColorTheme';\nimport { extractDataToFile, getExtractedData } from '../utils/Config';\nimport {\n createKeyValueTable,\n createProgressIndicator,\n createTable,\n debugMessage,\n getTableRowsFromArray,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../utils/Console';\nimport { isScriptExtracted } from './ScriptOps';\nimport { errorHandler } from './utils/OpsUtils';\nimport wordwrap from './utils/Wordwrap';\n\nconst {\n readCustomNode,\n readCustomNodes,\n getCustomNodeUsage,\n exportCustomNode,\n exportCustomNodes,\n importCustomNodes,\n deleteCustomNode: _deleteCustomNode,\n deleteCustomNodes: _deleteCustomNodes,\n readNodeTypes,\n readNodeSchema,\n} = frodo.authn.node;\nconst {\n getTypedFilename,\n saveToFile,\n saveJsonToFile,\n getFilePath,\n getWorkingDirectory,\n} = frodo.utils;\n\nconst { stringify } = frodo.utils.json;\n\n/**\n * Get a one-line description of the node\n * @param {NodeSkeleton} nodeObj node object to describe\n * @param {NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface} nodeRef node reference object\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(\n nodeObj: NodeSkeleton,\n nodeRef?: NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface\n): string {\n const description = `[${c.heading(nodeObj._id)}] ${nodeObj._type._id}${\n nodeRef ? ' - ' + nodeRef?.displayName : ''\n }`;\n return description;\n}\n\n/**\n * Get a one-line description of the node in markdown\n * @param {NodeSkeleton} nodeObj node object to describe\n * @param {NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface} nodeRef node reference object\n * @returns {string} a one-line description in markdown\n */\nexport function getOneLineDescriptionMd(\n nodeObj: NodeSkeleton,\n nodeRef?: NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface\n): string {\n const description = `${nodeObj._id} ${nodeObj._type._id}${\n nodeRef ? ' - ' + nodeRef?.displayName : ''\n }`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Display Name | Type | Id |\\n';\n markdown += '| ------------ | ---- | -- |';\n return markdown;\n}\n\n/**\n * Get a table-row of the node in markdown\n * @param {NodeSkeleton} nodeObj node object to describe\n * @param {NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface} nodeRef node reference object\n * @returns {string} a table-row of the node in markdown\n */\nexport function getTableRowMd(\n nodeObj: NodeSkeleton,\n nodeRef?: NodeRefSkeletonInterface | InnerNodeRefSkeletonInterface\n): string {\n const row = `| ${nodeRef ? nodeRef.displayName : ''} | ${\n nodeObj._type._id\n } | \\`${nodeObj._id}\\` |`;\n return row;\n}\n\n/**\n * List custom nodes\n * @param {boolean} [long=false] detailed list\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listCustomNodes(long: boolean = false): Promise<boolean> {\n try {\n const nodes = await readCustomNodes();\n if (long) {\n const table = createTable([\n 'Display Name',\n 'Id (<Service Name>-1)',\n 'Journeys',\n 'Instances',\n 'Error Outcome',\n 'Description',\n ]);\n for (const node of nodes) {\n const usage = await getCustomNodeUsage(node._id);\n let numJourneys = 0;\n let numInstances = 0;\n for (const realmJourneys of Object.values(usage)) {\n for (const journeyInstances of Object.values(realmJourneys)) {\n numJourneys += 1;\n numInstances += journeyInstances.length;\n }\n }\n table.push([\n wordwrap(node.displayName, 25, ' '),\n node._id,\n numJourneys ? c.positive(String(numJourneys)) : c.negative('0'),\n numInstances ? c.positive(String(numInstances)) : c.negative('0'),\n node.errorOutcome ? c.positive('enabled') : c.negative('disabled'),\n wordwrap(node.description, 30),\n ]);\n }\n printMessage(table.toString(), 'data');\n } else {\n nodes.forEach((node) => {\n printMessage(`${node.displayName}`, 'data');\n });\n }\n return true;\n } catch (error) {\n printError(error, `Error listing custom nodes`);\n }\n return false;\n}\n\n/**\n * Describe a custom node\n * @param {string} nodeId custom node id\n * @param {string} nodeName custom node name\n * @param {boolean} json output description as json. Default: false\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function describeCustomNode(\n nodeId: string,\n nodeName: string,\n json = false\n): Promise<boolean> {\n try {\n const node = (await readCustomNode(\n nodeId,\n nodeName\n )) as CustomNodeSkeleton & {\n locations: CustomNodeUsage;\n };\n node.locations = await getCustomNodeUsage(node._id);\n if (json) {\n printMessage(node, 'data');\n return true;\n }\n const nodeTable = createKeyValueTable();\n nodeTable.push([c.heading('Id'), node._id]);\n nodeTable.push([c.heading('Service Name'), node.serviceName]);\n nodeTable.push([c.heading('Display Name'), node.displayName]);\n nodeTable.push([c.heading('Description'), node.description]);\n getTableRowsFromArray(nodeTable, 'Inputs', node.inputs);\n getTableRowsFromArray(nodeTable, 'Outputs', node.outputs);\n const outcomes = node.outcomes;\n if (node.errorOutcome) outcomes.push('Script Error');\n getTableRowsFromArray(nodeTable, 'Outcomes', outcomes);\n getTableRowsFromArray(nodeTable, 'Tags', node.tags);\n getTableRowsFromArray(\n nodeTable,\n 'Locations',\n buildTreeOutput(node.locations)\n );\n printMessage(nodeTable.toString(), 'data');\n printMessage('\\nProperties', 'data');\n for (const [name, prop] of Object.entries(node.properties)) {\n const propTable = createKeyValueTable();\n propTable.push([c.heading('Name'), name]);\n propTable.push([c.heading('Title'), prop.title]);\n propTable.push([c.heading('Description'), prop.description]);\n propTable.push([\n c.heading('Required'),\n prop.required ? c.positive('true') : c.negative('false'),\n ]);\n propTable.push([c.heading('Type'), prop.type]);\n propTable.push([\n c.heading('Multivalued'),\n prop.multivalued ? c.positive('true') : c.negative('false'),\n ]);\n if (prop.defaultValue) {\n getTableRowsFromArray(\n propTable,\n 'Default Value',\n stringify(prop.defaultValue).split('\\n')\n );\n }\n if (prop.options) {\n getTableRowsFromArray(\n propTable,\n 'Options',\n Object.entries(prop.options).map(([k, v]) => `${k} (${v})`)\n );\n }\n printMessage('\\n' + propTable.toString(), 'data');\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * List available node types\n * @param {boolean} [long=false] include versions/tags/help for each type\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listNodeTypes(long: boolean = false): Promise<boolean> {\n try {\n const types = await readNodeTypes();\n if (long) {\n const table = createTable(['Name', 'Versions', 'Tags']);\n for (const type of types) {\n table.push([\n type.name,\n (type.versions || []).join(', '),\n (type.tags || type.metadata?.tags || []).join(', '),\n ]);\n }\n printMessage(table.toString(), 'data');\n } else {\n types.forEach((type) => {\n printMessage(type.name, 'data');\n });\n }\n return true;\n } catch (error) {\n printError(error, `Error listing node types`);\n }\n return false;\n}\n\n/**\n * Describe a node type's configurable-property schema — either a standard\n * node type (by nodeType) or a custom node (by nodeId or nodeName, resolved\n * the same way describeCustomNode resolves them). Exactly one of nodeType\n * or nodeId/nodeName must be provided.\n * @param {string} nodeType standard node type, e.g. PasswordCollectorNode\n * @param {string} nodeTypeVersion standard node type version\n * @param {string} nodeId custom node id or service name\n * @param {string} nodeName custom node display name\n * @param {boolean} json true to print the raw schema as JSON, false for a summary table\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function describeNodeType(\n nodeType: string,\n nodeTypeVersion: string,\n nodeId: string,\n nodeName: string,\n json = false\n): Promise<boolean> {\n try {\n let properties: Record<string, any>;\n let label: string;\n if (nodeType) {\n const schema = await readNodeSchema(nodeType, nodeTypeVersion);\n properties = (schema as { properties?: Record<string, any> }).properties;\n label = nodeType;\n } else {\n const node = await readCustomNode(nodeId, nodeName);\n properties = node.properties;\n label = node.serviceName || node.displayName || node._id;\n }\n if (json) {\n printMessage({ properties }, 'data');\n return true;\n }\n printMessage(`\\nSchema for node type ${label}`, 'data');\n if (!properties || Object.keys(properties).length === 0) {\n printMessage('This node type has no configurable properties.', 'data');\n return true;\n }\n for (const [name, prop] of Object.entries(properties)) {\n const propTable = createKeyValueTable();\n propTable.push([c.heading('Name'), name]);\n if (prop.title) propTable.push([c.heading('Title'), prop.title]);\n if (prop.description)\n propTable.push([c.heading('Description'), prop.description]);\n if (prop.type) propTable.push([c.heading('Type'), prop.type]);\n if (prop.required !== undefined)\n propTable.push([\n c.heading('Required'),\n prop.required ? c.positive('true') : c.negative('false'),\n ]);\n if (prop.multivalued !== undefined)\n propTable.push([\n c.heading('Multivalued'),\n prop.multivalued ? c.positive('true') : c.negative('false'),\n ]);\n if (prop.defaultValue !== undefined)\n getTableRowsFromArray(\n propTable,\n 'Default Value',\n stringify(prop.defaultValue).split('\\n')\n );\n if (prop.options) {\n getTableRowsFromArray(\n propTable,\n 'Options',\n Object.entries(prop.options).map(([k, v]) => `${k} (${v})`)\n );\n }\n printMessage('\\n' + propTable.toString(), 'data');\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export custom node to file\n * @param {string} nodeId custom node id\n * @param {string} nodeName custom node name\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract extracts the scripts from the exports into separate files if true. Default: false\n * @param {CustomNodeExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportCustomNodeToFile(\n nodeId: string,\n nodeName: string,\n file: string,\n includeMeta: boolean = true,\n extract: boolean = false,\n options: CustomNodeExportOptions = {\n useStringArrays: true,\n }\n): Promise<boolean> {\n const name = nodeName ? nodeName : nodeId;\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${name}...`\n );\n try {\n const exportData = await exportCustomNode(nodeId, nodeName, options);\n if (!file) {\n file = getTypedFilename(nodeName ? nodeName : nodeId, 'nodeTypes');\n }\n const filePath = getFilePath(file, true);\n if (extract)\n extractCustomNodeScriptsToFiles(\n exportData,\n undefined,\n undefined,\n !!nodeName\n );\n updateProgressIndicator(indicatorId, `Saving ${name} to ${filePath}...`);\n saveJsonToFile(exportData, filePath, includeMeta);\n stopProgressIndicator(\n indicatorId,\n `Exported custom node ${name} to file`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error exporting custom node ${name} to file`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all custom nodes to file\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {CustomNodeExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportCustomNodesToFile(\n file: string,\n includeMeta: boolean = true,\n options: CustomNodeExportOptions = {\n useStringArrays: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportCustomNodes(options);\n if (!file) {\n file = getTypedFilename(`allCustomNodes`, 'nodeTypes');\n }\n saveJsonToFile(exportData, getFilePath(file, true), includeMeta);\n return true;\n } catch (error) {\n printError(error, `Error exporting custom nodes to file`);\n }\n return false;\n}\n\n/**\n * Export all custom nodes to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract extracts the scripts from the exports into separate files if true. Default: false\n * @param {CustomNodeExportOptions} options export options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportCustomNodesToFiles(\n includeMeta: boolean = true,\n extract: boolean = false,\n options: CustomNodeExportOptions = {\n useStringArrays: true,\n }\n): Promise<boolean> {\n try {\n const exportData = await exportCustomNodes(options);\n if (extract) extractCustomNodeScriptsToFiles(exportData);\n for (const customNode of Object.values(exportData.nodeTypes)) {\n saveToFile(\n 'nodeTypes',\n customNode,\n '_id',\n getFilePath(\n getTypedFilename(customNode.displayName, 'nodeTypes'),\n true\n ),\n includeMeta\n );\n }\n return true;\n } catch (error) {\n printError(error, `Error exporting custom nodes to files`);\n }\n return false;\n}\n\n/**\n * Import a custom node from file\n * @param {string} nodeId custom node id\n * @param {string} nodeName custom node name\n * @param {string} file import file name\n * @param {CustomNodeImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importCustomNodeFromFile(\n nodeId: string,\n nodeName: string,\n file: string,\n options: CustomNodeImportOptions = {\n reUuid: false,\n wait: false,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Reading custom node...'\n );\n const importData = getCustomNodeExportFromFile(getFilePath(file));\n updateProgressIndicator(indicatorId, 'Importing custom node...');\n await importCustomNodes(\n nodeId,\n nodeName,\n importData,\n options,\n errorHandler\n );\n stopProgressIndicator(\n indicatorId,\n `Successfully imported custom node ${nodeName ? nodeName : nodeId}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing custom node ${nodeName ? nodeName : nodeId}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Import custom nodes from file\n * @param {String} file file name\n * @param {CustomNodeImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importCustomNodesFromFile(\n file: string,\n options: CustomNodeImportOptions = {\n reUuid: false,\n wait: false,\n }\n): Promise<boolean> {\n try {\n debugMessage(`importCustomNodesFromFile: start`);\n debugMessage(`importCustomNodesFromFile: importing ${file}`);\n const importData = getCustomNodeExportFromFile(getFilePath(file));\n await importCustomNodes(\n undefined,\n undefined,\n importData,\n options,\n errorHandler\n );\n debugMessage(`importCustomNodesFromFile: end`);\n return true;\n } catch (error) {\n printError(error, `Error importing custom nodes from file`);\n }\n return false;\n}\n\n/**\n * Import all custom nodes from separate files\n * @param {CustomNodeImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importCustomNodesFromFiles(\n options: CustomNodeImportOptions = {\n reUuid: false,\n wait: false,\n }\n): Promise<boolean> {\n const errors: Error[] = [];\n try {\n const names = fs.readdirSync(getWorkingDirectory());\n const customNodeFiles = names.filter((name) =>\n name.toLowerCase().endsWith('.nodetypes.json')\n );\n for (const file of customNodeFiles) {\n try {\n await importCustomNodesFromFile(file, options);\n } catch (error) {\n errors.push(\n new FrodoError(`Error importing custom nodes from ${file}`, error)\n );\n }\n }\n if (errors.length > 0) {\n throw new FrodoError(`One or more errors importing custom nodes`, errors);\n }\n return true;\n } catch (error) {\n printError(error, `Error importing custom nodes from files`);\n }\n return false;\n}\n\n/**\n * Import first custom node from file\n * @param {string} file import file name\n * @param {CustomNodeImportOptions} options import options\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importFirstCustomNodeFromFile(\n file: string,\n options: CustomNodeImportOptions = {\n reUuid: false,\n wait: false,\n }\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n 'Importing custom node...'\n );\n const importData = getCustomNodeExportFromFile(getFilePath(file));\n const ids = Object.keys(importData.nodeTypes);\n if (ids.length === 0)\n throw new FrodoError(`No custom nodes found in import data`);\n const firstNode = importData.nodeTypes[ids[0]];\n await importCustomNodes(\n firstNode._id,\n firstNode.displayName,\n importData,\n options,\n errorHandler\n );\n stopProgressIndicator(\n indicatorId,\n `Imported custom node from ${file}`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error importing custom node from ${file}`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete custom node\n * @param {string} nodeId custom node id\n * @param {string} nodeName custom node name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteCustomNode(\n nodeId: string,\n nodeName: string\n): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${nodeName ? nodeName : nodeId}...`\n );\n try {\n await _deleteCustomNode(nodeId, nodeName);\n stopProgressIndicator(\n spinnerId,\n `Deleted ${nodeName ? nodeName : nodeId}.`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete custom nodes\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteCustomNodes(): Promise<boolean> {\n const spinnerId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting custom nodes...`\n );\n try {\n await _deleteCustomNodes(errorHandler);\n stopProgressIndicator(spinnerId, `Deleted custom nodes.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(spinnerId, `Error: ${error.message}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Get a custom node export from json file.\n *\n * @param file The path to the custom node export file\n * @returns The custom node export\n */\nexport function getCustomNodeExportFromFile(\n file: string\n): CustomNodeExportInterface {\n const exportData = JSON.parse(\n fs.readFileSync(file, 'utf8')\n ) as CustomNodeExportInterface;\n for (const node of Object.values(exportData.nodeTypes)) {\n if (!isScriptExtracted(node.script)) {\n continue;\n }\n const scriptRaw = getExtractedData(\n node.script as string,\n file.substring(0, file.lastIndexOf('/'))\n );\n node.script = scriptRaw.split('\\n');\n }\n return exportData;\n}\n\n/**\n * Extracts scripts from a custom node export into separate files.\n * @param {CustomNodeExportInterface} exportData The script export\n * @param {string} nodeId The custom node id to extract a specific script from. If undefined, will extract scripts from all custom nodes.\n * @param {string} directory The directory within the base directory to save the script files\n * @param {boolean} useNameForFiles True to name files using custom node display names, false to use id's instead. Default: true\n * @returns {boolean} true if successful, false otherwise\n */\nexport function extractCustomNodeScriptsToFiles(\n exportData: CustomNodeExportInterface,\n nodeId?: string,\n directory?: string,\n useNameForFiles: boolean = true\n): boolean {\n try {\n const nodes = nodeId\n ? [exportData.nodeTypes[nodeId]]\n : Object.values(exportData.nodeTypes);\n for (const node of nodes) {\n const scriptFileName = getTypedFilename(\n useNameForFiles ? node.displayName : node.serviceName,\n 'nodeTypes',\n 'js'\n );\n const scriptText = Array.isArray(node.script)\n ? node.script.join('\\n')\n : node.script;\n node.script = extractDataToFile(scriptText, scriptFileName, directory);\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Helper that builds an array of lines to print a tree to the console\n */\nfunction buildTreeOutput(\n data: string | object,\n prefix = '',\n isFirst = true\n): string[] {\n if (typeof data !== 'object' || data === null) return [prefix + String(data)];\n if (\n Array.isArray(data) &&\n data.every((v) => typeof v !== 'object' || v === null)\n ) {\n return Object.values(data).map((v, i, arr) => {\n const isLast = i === arr.length - 1;\n return prefix + (isLast ? '└── ' : '├── ') + String(v);\n });\n }\n return Object.entries(data).flatMap(([k, v], i, arr) => {\n const isLast = i === arr.length - 1;\n return [\n ...[isFirst ? k : prefix + (isLast ? '└── ' : '├── ') + k],\n ...buildTreeOutput(\n v,\n isFirst ? '' : prefix + (isLast ? ' ' : '│ '),\n false\n ),\n ];\n });\n}\n","import * as fs from 'fs';\nimport {\n frodo,\n type ThemeExportInterface,\n type ThemeSkeleton,\n} from '@rockcarver/frodo-lib';\nimport { v4 as uuidv4 } from 'uuid';\nimport c from '../utils/ColorTheme';\nimport { extractDataToFile, getExtractedData } from '../utils/Config';\nimport {\n createProgressIndicator,\n createTable,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../utils/Console';\n\nconst {\n getRealmString,\n getTypedFilename,\n saveJsonToFile,\n saveToFile,\n getFilePath,\n getWorkingDirectory,\n} = frodo.utils;\nconst {\n readThemes,\n readThemeByName,\n readTheme,\n updateThemeByName,\n updateTheme,\n importThemes,\n exportThemes,\n deleteTheme: _deleteTheme,\n deleteThemeByName: _deleteThemeByName,\n deleteThemes: _deleteThemes,\n} = frodo.theme;\n\nconst THEME_HTML_PROPERTIES = [\n 'accountFooter',\n 'journeyFooter',\n 'journeyHeader',\n 'journeyJustifiedContent',\n 'accountFooterScriptTag',\n 'journeyFooterScriptTag',\n];\n\n/**\n * Get a one-line description of the theme\n * @param {ThemeSkeleton} themeObj theme object to describe\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(themeObj: ThemeSkeleton): string {\n const description = `[${c.heading(themeObj._id)}] ${themeObj.name}${\n themeObj.linkedTrees\n ? ' (' + c.heading(themeObj.linkedTrees.join(', ')) + ')'\n : ''\n }`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Name | Linked Journey(s) | Id |\\n';\n markdown += '| ---- | ----------------- | ---|';\n return markdown;\n}\n\n/**\n * Get a table-row of the theme in markdown\n * @param {ThemeSkeleton} themeObj theme object to describe\n * @returns {string} a table-row of the theme in markdown\n */\nexport function getTableRowMd(themeObj: ThemeSkeleton): string {\n const row = `| ${themeObj.name} | ${\n themeObj.linkedTrees ? themeObj.linkedTrees.join(', ') : ''\n } | \\`${themeObj._id}\\` |`;\n return row;\n}\n\n/**\n * List all the themes\n * @param {boolean} long Long version, more fields\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function listThemes(long: boolean = false): Promise<boolean> {\n try {\n const themeList = await readThemes();\n themeList.sort((a, b) => a.name.localeCompare(b.name));\n if (!long) {\n themeList.forEach((theme) => {\n printMessage(\n `${theme.isDefault ? c.heading(theme.name) : theme.name}`,\n 'data'\n );\n });\n } else {\n const table = createTable([\n c.heading('Name'),\n c.heading('Id'),\n c.heading('Default'),\n ]);\n themeList.forEach((theme) => {\n table.push([\n `${theme.name}`,\n `${theme._id}`,\n `${theme.isDefault ? c.positive('Yes') : ''}`,\n ]);\n });\n printMessage(table.toString(), 'data');\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export theme by name to file\n * @param {string} name theme name\n * @param {string} file optional export file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract extracts HTML into separate files if true. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportThemeByName(\n name: string,\n file: string,\n includeMeta: boolean = true,\n extract: boolean = true\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${name}`\n );\n const themeData = await readThemeByName(name);\n if (!themeData._id) themeData._id = uuidv4();\n let fileName = getTypedFilename(name, 'theme');\n if (extract) {\n extractThemeHTMLToFiles(\n { theme: { [themeData._id]: themeData } },\n themeData._id,\n name\n );\n fileName = `${name}/${fileName}`;\n } else if (file) {\n fileName = file;\n }\n const filePath = getFilePath(fileName, true);\n updateProgressIndicator(indicatorId, `Writing JSON file to ${filePath}`);\n saveToFile('theme', [themeData], '_id', filePath, includeMeta);\n stopProgressIndicator(indicatorId, `Successfully exported theme ${name}.`);\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error exporting theme ${name}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Export theme by uuid to file\n * @param {String} id theme uuid\n * @param {String} file optional export file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract extracts HTML into separate files if true. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportThemeById(\n id: string,\n file: string,\n includeMeta: boolean = true,\n extract: boolean = true\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator('determinate', 1, `Exporting ${id}`);\n const themeData = await readTheme(id);\n let fileName = getTypedFilename(id, 'theme');\n if (extract) {\n extractThemeHTMLToFiles({ theme: { [id]: themeData } }, id, id);\n fileName = `${id}/${fileName}`;\n } else if (file) {\n fileName = file;\n }\n const filePath = getFilePath(fileName, true);\n updateProgressIndicator(indicatorId, `Writing JSON file to ${filePath}`);\n saveToFile('theme', [themeData], '_id', filePath, includeMeta);\n stopProgressIndicator(indicatorId, `Successfully exported theme ${id}.`);\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error exporting theme ${id}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all themes to file\n * @param {String} file optional export file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportThemesToFile(\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n try {\n let fileName = getTypedFilename(`all${getRealmString()}Themes`, 'theme');\n if (file) {\n fileName = file;\n }\n const filePath = getFilePath(fileName, true);\n const exportData = await exportThemes();\n saveJsonToFile(exportData, filePath, includeMeta);\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all themes to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @param {boolean} extract extracts HTML into separate files if true. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportThemesToFiles(\n includeMeta: boolean = true,\n extract: boolean = true\n) {\n let barId: string;\n try {\n const themes = await readThemes();\n barId = createProgressIndicator(\n 'determinate',\n themes.length,\n 'Exporting themes'\n );\n\n for (const theme of themes) {\n if (!theme._id) theme._id = uuidv4();\n\n const fileBarId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting theme ${theme.name}...`\n );\n\n updateProgressIndicator(barId, `Exporting theme ${theme.name}`);\n\n let fileName = getTypedFilename(theme.name, 'theme');\n\n if (extract) {\n extractThemeHTMLToFiles(\n { theme: { [theme._id]: theme } },\n theme._id,\n theme.name\n );\n fileName = `${theme.name}/${fileName}`;\n }\n\n const file = getFilePath(fileName, true);\n\n saveToFile('theme', theme, '_id', file, includeMeta);\n\n updateProgressIndicator(fileBarId, `${theme.name} saved to ${file}`);\n stopProgressIndicator(fileBarId, `${theme.name} saved to ${file}.`);\n }\n\n return true;\n } catch (error) {\n stopProgressIndicator(barId, `Error exporting themes`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import theme by name from file\n * @param {string} name theme name\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importThemeByName(\n name: string,\n file: string\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing theme...'\n );\n const themeExport = getThemeExportFromFile(getFilePath(file));\n for (const id of Object.keys(themeExport.theme)) {\n if (themeExport.theme[id].name === name) {\n updateProgressIndicator(\n indicatorId,\n `Importing ${themeExport.theme[id].name}`\n );\n await updateThemeByName(name, themeExport.theme[id]);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported theme ${name}.`\n );\n return true;\n }\n }\n stopProgressIndicator(indicatorId, `Theme ${name} not found!`, 'fail');\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing theme ${name}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import theme by uuid from file\n * @param {string} id theme uuid\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importThemeById(\n id: string,\n file: string\n): Promise<boolean> {\n let indicatorId: string;\n try {\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing theme...'\n );\n const themeExport = getThemeExportFromFile(getFilePath(file));\n for (const themeId of Object.keys(themeExport.theme)) {\n if (themeId === id) {\n updateProgressIndicator(\n indicatorId,\n `Importing ${themeExport.theme[themeId]._id}`\n );\n await updateTheme(themeId, themeExport.theme[themeId]);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported theme ${id}.`\n );\n return true;\n }\n }\n stopProgressIndicator(indicatorId, `Theme ${id} not found!`, 'fail');\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing theme ${id}`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import all themes from single file\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importThemesFromFile(file: string): Promise<boolean> {\n let indicatorId: string;\n try {\n const filePath = getFilePath(file);\n indicatorId = createProgressIndicator(\n 'indeterminate',\n 0,\n `Importing themes from ${filePath}...`\n );\n const themeExport = getThemeExportFromFile(filePath);\n await importThemes(themeExport);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported ${Object.keys(themeExport.theme).length} themes from ${filePath}.`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing themes`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import themes from separate files\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importThemesFromFiles(): Promise<boolean> {\n let indicatorId: string;\n try {\n const names = fs.readdirSync(getWorkingDirectory());\n const jsonFiles: string[] = [];\n for (const name of names) {\n const filePath = getFilePath(name);\n if (\n fs.statSync(filePath).isFile() &&\n name.toLowerCase().endsWith('.theme.json')\n ) {\n jsonFiles.push(name);\n continue;\n }\n if (fs.statSync(filePath).isDirectory()) {\n const files = fs.readdirSync(filePath);\n const themeFile = files.find(\n (file) =>\n fs.statSync(`${filePath}/${file}`).isFile() &&\n file.toLowerCase().endsWith('.theme.json')\n );\n if (themeFile) {\n jsonFiles.push(`${name}/${themeFile}`);\n }\n }\n }\n indicatorId = createProgressIndicator(\n 'determinate',\n jsonFiles.length,\n 'Importing themes...'\n );\n let numFiles = 0;\n for (const file of jsonFiles) {\n const success = await importThemesFromFile(file);\n if (!success) continue;\n numFiles += 1;\n updateProgressIndicator(indicatorId, `Imported theme(s) from ${file}`);\n }\n stopProgressIndicator(\n indicatorId,\n `Finished importing themes from ${numFiles} file(s).`\n );\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing themes`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import first theme from file\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importFirstThemeFromFile(file: string): Promise<boolean> {\n let indicatorId: string;\n try {\n const themeExport = getThemeExportFromFile(getFilePath(file));\n indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing theme...'\n );\n for (const id of Object.keys(themeExport.theme)) {\n updateProgressIndicator(\n indicatorId,\n `Importing ${themeExport.theme[id].name}`\n );\n await updateTheme(id, themeExport.theme[id]);\n stopProgressIndicator(\n indicatorId,\n `Successfully imported theme ${themeExport.theme[id].name}`\n );\n return true;\n }\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing first theme`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete theme by id\n * @param {string} id theme id\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteTheme(id: string): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${id}...`\n );\n try {\n await _deleteTheme(id);\n stopProgressIndicator(indicatorId, `Deleted ${id}.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error deleting theme`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Delete theme by name\n * @param {string} name theme name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteThemeByName(name: string): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting ${name}...`\n );\n try {\n await _deleteThemeByName(name);\n stopProgressIndicator(indicatorId, `Deleted ${name}.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error: ${error.message}`, 'fail');\n }\n return false;\n}\n\n/**\n * Delete all themes\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function deleteThemes(): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'indeterminate',\n undefined,\n `Deleting all realm themes...`\n );\n try {\n await _deleteThemes();\n stopProgressIndicator(indicatorId, `Deleted all realm themes.`, 'success');\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error: ${error.message}`, 'fail');\n }\n return false;\n}\n\n/**\n * Extract a theme HTML property to a file\n * @param {ThemeSkeleton} theme theme object containing the property\n * @param {string} property theme property to extract\n * @param {string} directory directory within the base directory to save the HTML file\n */\nfunction extractHTMLToFile(\n theme: ThemeSkeleton,\n property: string,\n directory?: string\n): void {\n const htmlData = theme[property];\n if (!htmlData) return;\n\n if (typeof htmlData === 'object') {\n for (const [language, html] of Object.entries(htmlData)) {\n htmlData[language] = extractDataToFile(\n html,\n `${property}/${getTypedFilename(language, 'theme', 'html')}`,\n directory\n );\n }\n } else {\n theme[property] = extractDataToFile(\n htmlData,\n getTypedFilename(property, 'theme', 'html'),\n directory\n );\n }\n}\n\n/**\n * Extracts HTML from a theme export into separate files\n * @param {ThemeExportInterface} exportData theme export\n * @param {string} themeId theme id to extract a specific theme from. If undefined, extracts HTML from all themes\n * @param {string} directory directory within the base directory to save the HTML files\n * @returns {boolean} true if successful, false otherwise\n */\nexport function extractThemeHTMLToFiles(\n exportData: ThemeExportInterface,\n themeId?: string,\n directory?: string\n): boolean {\n try {\n const themes = themeId\n ? [exportData.theme[themeId]]\n : Object.values(exportData.theme);\n for (const theme of themes) {\n for (const property of THEME_HTML_PROPERTIES) {\n extractHTMLToFile(theme, property, directory);\n }\n }\n return true;\n } catch (error) {\n printError(error);\n }\n return false;\n}\n\n/**\n * Read an extracted theme HTML property from a file\n * @param {ThemeSkeleton} theme theme object containing the property\n * @param {string} property theme property to read\n * @param {string} [directory] directory containing the extracted HTML file\n */\nfunction readHTMLFromFile(\n theme: ThemeSkeleton,\n property: string,\n directory?: string\n): void {\n if (!theme[property]) return;\n\n if (typeof theme[property] === 'object') {\n for (const [language, filePath] of Object.entries(theme[property])) {\n const fileContent = getExtractedData(filePath, directory);\n if (fileContent !== null) {\n theme[property][language] = fileContent;\n }\n }\n } else {\n const fileContent = getExtractedData(theme[property] as string, directory);\n if (fileContent !== null) {\n theme[property] = fileContent;\n }\n }\n}\n\n/**\n * Get a theme export from json file\n * @param {string} file path to the theme export file\n * @returns {ThemeExportInterface} theme export\n */\nexport function getThemeExportFromFile(file: string): ThemeExportInterface {\n const exportData = JSON.parse(\n fs.readFileSync(file, 'utf8')\n ) as ThemeExportInterface;\n\n const directory = file.substring(0, file.lastIndexOf('/'));\n\n for (const theme of Object.values(exportData.theme)) {\n for (const property of THEME_HTML_PROPERTIES) {\n readHTMLFromFile(theme, property, directory);\n }\n }\n\n return exportData;\n}\n","import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport {\n frodo,\n state,\n type ExportMetaData,\n type FullExportInterface,\n type FullGlobalExportInterface,\n type FullRealmExportInterface,\n type IdObjectSkeletonInterface,\n} from '@rockcarver/frodo-lib';\nimport { readServersFromFiles } from '../ops/classic/ServerOps';\nimport { getWorkflowExportFromFile } from '../ops/cloud/iga/IgaWorkflowOps';\nimport {\n getManagedObjectsFromFiles,\n resolveAllExtractedScriptsForImport,\n} from '../ops/IdmOps';\nimport {\n getLegacyMappingsFromFiles,\n getNewMappingsFromFiles,\n} from '../ops/MappingOps';\nimport { getCustomNodeExportFromFile } from '../ops/NodeOps';\nimport { getScriptExportByScriptFile } from '../ops/ScriptOps';\nimport { getThemeExportFromFile } from '../ops/ThemeOps';\nimport { errorHandler } from '../ops/utils/OpsUtils';\nimport { printMessage } from './Console';\n\nconst { getFilePath, readFiles, saveTextToFile, saveJsonToFile } = frodo.utils;\n\nconst { exportFullConfiguration } = frodo.config;\n\nconst { getDefaultNoiseFilter } = frodo.cloud.log;\n\nexport const FRODO_CONFIG_PATH_KEY = 'FRODO_CONFIG_PATH';\nexport const FRODO_LOG_NOISEFILTER_FILENAME = 'LoggingNoiseFilter.json';\n\nexport function getConfigPath(): string {\n return process.env[FRODO_CONFIG_PATH_KEY] || `${os.homedir()}/.frodo`;\n}\n\nfunction getCustomNoiseFilters(): Array<string> {\n const filename = `${getConfigPath()}/${FRODO_LOG_NOISEFILTER_FILENAME}`;\n let noiseFilter = [];\n try {\n const data = fs.readFileSync(filename, 'utf8');\n noiseFilter = JSON.parse(data);\n } catch (e) {\n printMessage(`Error reading ${filename} (${e.message})`, 'error');\n }\n return noiseFilter;\n}\n\nexport function getNoiseFilters(defaults: boolean): Array<string> {\n const filename = `${getConfigPath()}/${FRODO_LOG_NOISEFILTER_FILENAME}`;\n if (defaults) {\n printMessage(`Using default logging noise filters.`, 'info');\n return getDefaultNoiseFilter();\n }\n let noiseFilter = getCustomNoiseFilters();\n if (noiseFilter.length == 0) {\n printMessage(`No custom noise filters defined. Using defaults.`, 'info');\n noiseFilter = getDefaultNoiseFilter();\n try {\n fs.writeFileSync(filename, JSON.stringify(noiseFilter, null, 2));\n printMessage(\n `The default filters were saved in ${filename}. You can change the filters as needed.`,\n 'info'\n );\n } catch {\n printMessage(\n `Error creating noise filter configuration with default values.`,\n 'error'\n );\n }\n }\n return noiseFilter;\n}\n\n/**\n * Gets the full export config from one of three locations:\n * 1. The file passed into the function if one is provided.\n * 2. The working directory if it exists (provided by the user)\n * 3. From deployment (e.g. cloud) if the exports are not locally provided\n * @param file The optional file path\n * @returns The full export config\n */\nexport async function getFullExportConfig(\n file: string | null = null\n): Promise<FullExportInterface> {\n // Get export from file if it exists\n if (file) {\n return JSON.parse(fs.readFileSync(getFilePath(file), 'utf8'));\n }\n // If working directory doesn't exist, export from the cloud\n const workingDirectory = state.getDirectory();\n if (!workingDirectory) {\n return await exportFullConfiguration(\n {\n useStringArrays: true,\n noDecode: false,\n coords: true,\n includeDefault: true,\n includeActiveValues: false,\n target: '',\n includeReadOnly: true,\n onlyCustom: false,\n onlyRealm: false,\n onlyGlobal: false,\n },\n errorHandler\n );\n }\n // Go through files in the working directory and reconstruct the full export\n return await getFullExportConfigFromDirectory(workingDirectory);\n}\n\n/**\n * Reconstructs the full export config from files in the given directory\n * @param directory The directory\n * @return The full export config\n */\nexport async function getFullExportConfigFromDirectory(\n directory: string\n): Promise<FullExportInterface> {\n const realmDir = directory + '/realm';\n const realms = fs.existsSync(realmDir) ? fs.readdirSync(realmDir) : [];\n const fullExportConfig: FullExportInterface = {\n meta: {} as ExportMetaData,\n global: {} as unknown as FullGlobalExportInterface,\n realm: Object.fromEntries(\n realms.map((r) => [r, {} as FullRealmExportInterface])\n ),\n } as FullExportInterface;\n // Get global\n await getConfig(fullExportConfig.global, undefined, directory + '/global');\n // Get realms\n for (const realm of realms) {\n await getConfig(\n fullExportConfig.realm[realm],\n undefined,\n `${realmDir}/${realm}`\n );\n }\n return fullExportConfig;\n}\n\n/**\n * Helper method that gets all the config from a directory or file.\n * @param exportConfig The export object to store the config in\n * @param file The file to get config from\n * @param directory The directory to get config from\n */\nexport async function getConfig(\n exportConfig: FullGlobalExportInterface | FullRealmExportInterface,\n file?: string,\n directory?: string\n): Promise<void> {\n if (!file && !directory) {\n return;\n }\n if (!directory && file) {\n directory = file.substring(0, file.lastIndexOf('/'));\n }\n if (!fs.existsSync(directory)) return;\n const fileName = file ? file.substring(file.lastIndexOf('/') + 1) : undefined;\n const files = (await readFiles(directory)).filter(\n (f) => !fileName || f.path.endsWith(fileName)\n );\n const jsonFiles = files.filter((f) => f.path.endsWith('.json'));\n const samlFiles = jsonFiles.filter((f) => f.path.endsWith('.saml.json'));\n const scriptFiles = jsonFiles.filter((f) => f.path.endsWith('.script.json'));\n const mappingFiles = jsonFiles.filter((f) =>\n f.path.endsWith('.mapping.json')\n );\n const customNodefiles = jsonFiles.filter((f) =>\n f.path.endsWith('.nodeTypes.json')\n );\n const themeFiles = jsonFiles.filter((f) => f.path.endsWith('.theme.json'));\n const workflowFiles = jsonFiles.filter((f) =>\n f.path.endsWith('.workflow.json')\n );\n const serverFiles = jsonFiles.filter(\n (f) =>\n f.path.endsWith('.server.json') &&\n !f.path.endsWith('.properties.server.json')\n );\n const idmFiles = jsonFiles.filter(\n (f) =>\n f.path.endsWith('idm.json') &&\n !f.path.endsWith('/sync.idm.json') &&\n !f.path.endsWith('sync.json') &&\n !f.path.endsWith('/managed.idm.json') &&\n !f.path.endsWith('managed.json') &&\n !f.path.endsWith('mapping.idm.json')\n );\n\n const allOtherFiles = jsonFiles.filter(\n (f) =>\n !f.path.endsWith('.saml.json') &&\n !f.path.endsWith('.script.json') &&\n !f.path.endsWith('.nodeTypes.json') &&\n !f.path.endsWith('.server.json') &&\n !f.path.endsWith('/sync.idm.json') &&\n !f.path.endsWith('sync.json') &&\n !f.path.endsWith('/managed.idm.json') &&\n !f.path.endsWith('managed.json') &&\n !f.path.endsWith('idm.json')\n );\n // Handle all other json files\n for (const f of allOtherFiles) {\n for (const [id, value] of Object.entries(\n JSON.parse(f.content) as Record<string, Record<string, object>>\n )) {\n if (id === 'meta') {\n continue;\n }\n if (!exportConfig[id]) {\n exportConfig[id] = value;\n } else {\n Object.entries(value).forEach(([key, val]) => {\n exportConfig[id][key] = val;\n });\n }\n }\n }\n for (const f of idmFiles) {\n const baseDirOfThisJson = path.dirname(f.path);\n const parsed = JSON.parse(f.content);\n if (!parsed.idm) continue;\n const entities = Object.values(\n parsed.idm\n ) as unknown as IdObjectSkeletonInterface[];\n for (const entity of entities) {\n resolveAllExtractedScriptsForImport(entity, baseDirOfThisJson);\n if (!(exportConfig as FullGlobalExportInterface).idm) {\n (exportConfig as FullGlobalExportInterface).idm = {};\n }\n (exportConfig as FullGlobalExportInterface).idm[entity._id] = entity;\n }\n }\n // Handle sync files\n const sync = await getLegacyMappingsFromFiles(jsonFiles);\n if (sync.mappings.length > 0) {\n (exportConfig as FullGlobalExportInterface).sync = sync;\n }\n if (mappingFiles.length > 0) {\n const mapping = await getNewMappingsFromFiles(mappingFiles);\n (exportConfig as FullGlobalExportInterface).mapping = mapping;\n }\n const managed = await getManagedObjectsFromFiles(jsonFiles);\n if (managed.objects.length > 0) {\n (exportConfig as FullGlobalExportInterface).idm.managed = managed;\n }\n // Handle saml files\n if (\n samlFiles.length > 0 &&\n !(exportConfig as FullRealmExportInterface).saml\n ) {\n (exportConfig as FullRealmExportInterface).saml = {\n hosted: {},\n remote: {},\n metadata: {},\n cot: {},\n };\n }\n for (const f of samlFiles) {\n let content = JSON.parse(f.content);\n content = content.saml;\n if (!(exportConfig as FullRealmExportInterface).saml) {\n (exportConfig as FullRealmExportInterface).saml = {\n hosted: {},\n remote: {},\n metadata: {},\n cot: {},\n };\n }\n for (const [id, value] of Object.entries(\n content as Record<string, object>\n )) {\n if (!(exportConfig as FullRealmExportInterface).saml[id]) {\n (exportConfig as FullRealmExportInterface).saml[id] = value;\n } else {\n Object.entries(value).forEach(\n ([key, val]) =>\n ((exportConfig as FullRealmExportInterface).saml[id][key] = val)\n );\n }\n }\n }\n // Handle server files\n (exportConfig as FullGlobalExportInterface).server =\n readServersFromFiles(serverFiles);\n // Handle extracted scripts\n if (\n scriptFiles.length > 0 &&\n !(exportConfig as FullRealmExportInterface).script\n ) {\n (exportConfig as FullRealmExportInterface).script = {};\n }\n for (const f of scriptFiles) {\n const scriptExport = getScriptExportByScriptFile(f.path);\n Object.entries(scriptExport.script).forEach(([id, script]) => {\n (exportConfig as FullRealmExportInterface).script[id] = script;\n });\n }\n // Handle extracted custom node scripts\n if (\n customNodefiles.length > 0 &&\n !(exportConfig as FullGlobalExportInterface).nodeTypes\n ) {\n (exportConfig as FullGlobalExportInterface).nodeTypes = {};\n }\n for (const f of customNodefiles) {\n const nodeExport = getCustomNodeExportFromFile(f.path);\n Object.entries(nodeExport.nodeTypes).forEach(([id, node]) => {\n (exportConfig as FullGlobalExportInterface).nodeTypes[id] = node;\n });\n }\n // Handle extracted theme HTML\n if (\n themeFiles.length > 0 &&\n !(exportConfig as FullRealmExportInterface).theme\n ) {\n (exportConfig as FullRealmExportInterface).theme = {};\n }\n for (const f of themeFiles) {\n const themeExport = getThemeExportFromFile(f.path);\n Object.entries(themeExport.theme).forEach(([id, theme]) => {\n (exportConfig as FullRealmExportInterface).theme[id] = theme;\n });\n }\n // Handle extracted workflow scripts\n if (\n workflowFiles.length > 0 &&\n !(exportConfig as FullGlobalExportInterface).workflow\n ) {\n (exportConfig as FullGlobalExportInterface).workflow = {};\n }\n for (const f of workflowFiles) {\n const workflowExport = getWorkflowExportFromFile(f.path);\n Object.entries(workflowExport.workflow).forEach(([id, workflow]) => {\n (exportConfig as FullGlobalExportInterface).workflow[id] = workflow;\n });\n }\n}\n\n/**\n * Extracts data to a file\n * @param {any} data The data to extract\n * @param {string} file The relative file path to the directory\n * @param {string} directory The directory within the base directory to start. If not provided, defaults to base directory.\n * @returns the extracted file path\n */\nexport function extractDataToFile(\n data: any,\n file: string,\n directory?: string\n): string {\n const filePath = getFilePath((directory ? `${directory}/` : '') + file, true);\n if (typeof data === 'object') {\n saveJsonToFile(data, filePath, false);\n } else {\n saveTextToFile(String(data), filePath);\n }\n return `file://${file}`;\n}\n\nexport function extractFrConfigDataToFile(\n data: any,\n file: string,\n directory?: string\n): { file: string } {\n const filePath = getFilePath((directory ? `${directory}/` : '') + file, true);\n if (typeof data === 'object') {\n saveJsonToFile(data, filePath, false);\n } else {\n saveTextToFile(String(data), filePath);\n }\n return {\n file,\n };\n}\n\n/**\n * Gets extracted data from a file as a string\n * @param extractedPath The file path where data was extracted\n * @param directory The directory where the extractedPath is located\n * @returns The extracted data as a string\n */\nexport function getExtractedData(\n extractedPath: string,\n directory?: string\n): string {\n if (\n typeof extractedPath === 'string' &&\n extractedPath.startsWith('file://')\n ) {\n const filePath = `${directory || '.'}/${extractedPath.replace('file://', '')}`;\n return fs.readFileSync(filePath, 'utf8');\n }\n return null;\n}\n\n/**\n * Gets extracted data from a file as a JSON object\n * @param extractedPath The file path where data was extracted\n * @param directory The directory where the extractedPath is located\n * @returns The extracted data as a JSON object\n */\nexport function getExtractedJsonData(\n extractedPath: string,\n directory: string\n): object {\n return JSON.parse(getExtractedData(extractedPath, directory));\n}\n\n/**\n * Determines all locations where a string id is being used anywhere within the given configuration object\n * @param {object} configuration The configuration object\n * @param {string} id The id being searched for\n * @param {boolean} isEsv Whether the id corresponds to an ESV or not\n * @returns {string[]} an array of locations where the id is being used\n */\nexport function getIdLocations(\n configuration: object,\n id: string,\n isEsv: boolean\n): string[] {\n return getIdLocationsRecurse(\n configuration,\n isEsv\n ? // For ESV ids, they contain either letters, numbers, dashes, or underscores. The dashes get replaced with periods (escaped with a \\ for the regex)\n // since anywhere they are being used they will be used with periods, not dashes. Note that the (?:[^a-z0-9._]|$) expressions at the beginning and\n // end are meant to ensure that the id found is not a substring of some other id (i.e. the id found must either be at the beginning or end of the\n // string, or if in the middle of a string, is not preceded or followed by a character that would be part of another id).\n new RegExp(\n `(?:[^a-z0-9._]|^)${id.replaceAll('-', '\\\\.')}(?:[^a-z0-9._]|$)`\n )\n : // For normal ids, they contain only letters, numbers, or dashes.\n new RegExp(`(?:[^a-z0-9-]|^)${id}(?:[^a-z0-9-]|$)`)\n );\n}\n\n/**\n * Recursive helper for getIdLocations that finds locations of any strings contained in the configuration that pass the regex\n * @param {any} configuration The configuration (could be anything)\n * @param {RegExp} regex The regex test\n * @returns {string[]} an array of locations where the id is found\n */\nfunction getIdLocationsRecurse(configuration: any, regex: RegExp): string[] {\n let locations = [];\n const type = typeof configuration;\n if (type === 'object' && configuration !== null) {\n for (const [id, value] of Object.entries(\n configuration as Record<string, any>\n )) {\n const usedLocations = getIdLocationsRecurse(value, regex);\n // Updates the relative locations of each place the id is used\n const updatedLocations = usedLocations.map(\n (loc) =>\n id +\n (value.name ? `(name: '${value.name}')` : '') +\n (loc === '' ? '' : '.') +\n loc\n );\n locations = locations.concat(updatedLocations);\n }\n }\n // This if statement determines whether or not the id is used in this configuration. If it is, return an empty string for its relative location.\n else if (type === 'string' && regex.test(configuration)) {\n locations.push('');\n }\n return locations;\n}\n","import fs from 'fs';\nimport path from 'path';\nimport {\n detectTerminalBackgroundRgb,\n FRODO_COLOR_THEME_ENV_KEY,\n matchBackgroundPreset,\n state,\n type BackgroundPreset,\n} from '@rockcarver/frodo-lib';\nimport { applyCustomThemeOverrides, HUE_NAME_TO_FUNCTION } from './ColorTheme';\nimport { getConfigPath } from './Config';\nimport { printMessage } from './Console';\n\nexport const FRODO_THEME_ACTIVE_FILENAME = 'Theme.json';\nexport const FRODO_THEME_DEFINITIONS_DIRNAME = 'themes';\n\nexport type ThemeDefinition = {\n name: string;\n description: string;\n mode: 'dark' | 'light';\n colors: Record<string, string>;\n};\n\n/**\n * The two independent preferences a theme is built from.\n *\n * `Background` is frodo-cli's own concept -- which background color a\n * theme is tuned for (`dark`, `light`, and any number of specific hues\n * beyond that, like `blue`/`yellow`). It's deliberately a different idea\n * from frodo-lib's `mode`: frodo-lib only knows `'dark' | 'light'` (its\n * own small built-in palette, used by a handful of print calls inside\n * frodo-lib itself, e.g. `AuthenticateOps.ts`/`curlirize.ts`), so every\n * `Background` still carries a `mode` (see `ThemeDefinition` above) saying\n * which of frodo-lib's two palettes is the closer fit -- `blue` and\n * `yellow` both currently map to `mode: 'light'`. Widening frodo-lib's own\n * `mode` concept to match would be a change to that package's public API,\n * not something layered on from here.\n *\n * `ContrastTier` is how colorful a background's theme is willing to be:\n * `high-contrast` always clears strict WCAG AA (4.5:1 normal text / 3:1\n * bold), `regular` relaxes that floor for a more colorful (but still\n * reasonably legible) result, and `vibrant` goes further still, aiming to\n * be the most colorful option a background can support. Every background\n * gets all three -- see `themeName`/`parseThemeName` for how they combine\n * into one of the file names in `~/.frodo/themes/`.\n */\nexport type Background = 'dark' | 'light' | 'blue' | 'yellow';\nexport type ContrastTier = 'high-contrast' | 'regular' | 'vibrant';\n\nexport const BACKGROUNDS: Background[] = ['dark', 'light', 'blue', 'yellow'];\nexport const CONTRAST_TIERS: ContrastTier[] = [\n 'high-contrast',\n 'regular',\n 'vibrant',\n];\n\n/**\n * The file/theme name for a (background, contrast) pair -- `high-contrast`\n * is unsuffixed (`dark`, `blue`, ...) since it's the baseline every\n * background starts from; `regular`/`vibrant` append their tier\n * (`dark-regular`, `blue-vibrant`, ...). Inverse of `parseThemeName`.\n */\nexport function themeName(\n background: Background,\n contrast: ContrastTier\n): string {\n return contrast === 'high-contrast'\n ? background\n : `${background}-${contrast}`;\n}\n\n/**\n * Parses a theme name back into its (background, contrast) pair, or\n * `null` if it doesn't match the convention -- e.g. a hand-authored custom\n * theme with an arbitrary name. Inverse of `themeName`.\n */\nexport function parseThemeName(\n name: string\n): { background: Background; contrast: ContrastTier } | null {\n for (const background of BACKGROUNDS) {\n for (const contrast of CONTRAST_TIERS) {\n if (themeName(background, contrast) === name)\n return { background, contrast };\n }\n }\n return null;\n}\n\n// Illustrative reference content only -- these are what gets written to\n// disk so a user has a real, forkable starting point to copy and edit, not\n// the live source of truth for the `dark`/`light` built-ins. Selecting\n// `dark`/`light` always resolves via ColorTheme.ts's own code (guaranteed,\n// via TerminalContrastFilter, to be readable), regardless of whether these\n// files exist, were deleted, or were hand-edited -- only a *different*\n// (genuinely custom) theme name is ever actually read from disk. This is\n// the one asymmetry in an otherwise uniform (background, contrast) model:\n// only `dark`/`light`'s high-contrast tier gets this \"unbreakable\"\n// treatment, matching the two hardcoded defaults from before this session\n// added any other backgrounds -- `blue`/`yellow` are fully file-driven at\n// every tier, including their own high-contrast one.\nconst BUILT_IN_REFERENCE_DEFINITIONS: Record<\n 'dark' | 'light',\n ThemeDefinition\n> = {\n dark: {\n name: 'dark',\n description:\n 'High-contrast, optimized for dark-background terminals. This file is a reference copy -- editing it has no effect; copy it to a new file with a different name to make a custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellowBright',\n command: 'cyanBright',\n emphasis: 'magentaBright',\n heading: 'blueBright',\n positive: 'greenBright',\n negative: 'redBright',\n muted: 'blackBright',\n debug: 'white',\n },\n },\n light: {\n name: 'light',\n description:\n 'High-contrast, optimized for light-background terminals. This file is a reference copy -- editing it has no effect; copy it to a new file with a different name to make a custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'magentaBright',\n negative: 'red',\n muted: 'blackBright',\n debug: 'magentaBright',\n },\n },\n};\n\n/**\n * Every other bundled theme -- all genuinely file-driven (see\n * `getActiveThemeDefinition`), materialized to `~/.frodo/themes/` on first\n * use and safe to hand-edit, at the same trust level as a theme a user\n * writes themselves.\n *\n * `dark-regular`/`light-regular` (renamed from `-relaxed`): a relaxed\n * contrast floor rather than strict WCAG AA, for a more colorful but still\n * reasonably legible result. `light-regular` exists because the light\n * background is the real casualty of strict AA: only 5 of the 16 standard\n * ANSI colors clear 4.5:1 on white at all, so `light`'s `positive` has no\n * color whatsoever. Relaxed to a ~2:1 floor, `green` (2.16:1) becomes\n * reachable -- nothing else does; yellow (1.70) and cyan (1.98) stay well\n * under 2:1 no matter how far the threshold is pushed, since their own\n * luminance is close to white's. `dark-regular` doesn't have a scarcity\n * problem to solve (`dark` already uses the full *Bright palette, all\n * comfortably clearing 4.5:1 on black) -- it exists for a different, more\n * muted aesthetic, using each intent's plain (non-Bright) counterpart\n * wherever that still clears a ~4:1 floor. `error` stays `redBright`:\n * plain `red` is only 3.60:1 on black, too low to use at any reasonable\n * floor.\n *\n * `dark-vibrant`/`light-vibrant`: the most colorful tier, built to be more\n * colorful than what's already bundled, not to chase a lower contrast\n * floor for its own sake. Each starts from the theme already closest to\n * \"as colorful as it gets\" (`dark` itself, and `light-regular` for light)\n * and fills in the one remaining flat spot each has: both previously\n * aliased `negative` to `error`'s exact color, which reads as \"correct but\n * not actually distinct.\" `dark-vibrant` also gives `debug` a real hue\n * (plain `magenta`, 4.48:1) instead of leaving it plain `white`. `muted`\n * stays gray in both -- giving it a hue would defeat its actual job (quiet,\n * secondary content), so \"more colorful\" doesn't mean \"everything is\n * colored.\"\n *\n * `blue` (reference RGB 34,78,189 -- macOS Terminal's built-in \"Ocean\"\n * profile, HSB 223°/82%/74%) is a fairly saturated, dark-leaning blue\n * (relative luminance ~0.095, far closer to black than white), so unlike\n * `yellow` below it needs a `mode: 'dark'` (bright-foreground) treatment,\n * not a light one -- an earlier version of this preset guessed a pale\n * pastel blue instead, which auto-detection then couldn't actually match\n * to real blue terminals at all (nearest neighbor preferred plain `dark`).\n * `blue` also turns out to be unusually constrained even as a dark\n * background: no red-family hue clears 4.5:1 at all against it (red and\n * blue sit close enough in luminance that even `redBright` only reaches\n * 1.82:1), and `white`/`whiteBright` (5.76:1 / 7.26:1) are the Ocean\n * profile's own default foreground -- numerically the best contrast, but\n * indistinguishable from unstyled text in practice, the same trap\n * `whiteBright` was on `dark` before that got fixed earlier this session.\n * That leaves only `yellowBright` (6.76:1), `cyanBright` (5.79:1), and\n * `greenBright` (5.29:1) as genuinely usable accents:\n * - `blue` (high-contrast): `warning: 'yellowBright'`, `command:\n * 'cyanBright'`, `positive: 'greenBright'` all cleanly clear AA.\n * `error: 'redBright'` (1.82:1) is a deliberate, documented exception --\n * abandoning red for \"this is an error\" felt like a worse outcome than\n * a low-contrast red, given nothing red-family clears AA here at all.\n * `emphasis` aliases `command`'s cyan (no 4th distinct AA hue survives);\n * `muted`/`debug` use plain `black` (2.89:1) -- computed to actually\n * beat `blackBright` (1.81:1) here, since this background is dark\n * enough that true black stands out more than mid-gray. `heading` stays\n * bold-only -- nothing clears even the relaxed bold threshold.\n * - `blue-regular`: same, but `emphasis` gets its own `magentaBright`\n * (2.31:1) instead of aliasing `command`.\n * - `blue-vibrant`: same as regular, plus `debug` gets `blackBright`\n * (1.81:1) instead of aliasing `muted`'s `black` -- the last bit of\n * differentiation this background can support. `heading` still has no\n * viable color at any tier -- an honest constraint of this specific\n * background, not a gap left unaddressed.\n *\n * `yellow` (reference RGB 255,245,156 -- macOS Terminal's built-in \"Man\n * Page\" profile, HSB 54°/39%/100%) is a genuinely mustard-toned yellow,\n * not a pale pastel (an earlier version of this preset guessed the latter,\n * CSS \"lightyellow\" at 255,255,224 -- close enough to white that\n * auto-detection couldn't actually distinguish it from `light` in\n * practice). Its high relative luminance (~0.89) confirms `mode: 'light'`\n * is still the right direction (dark text, matching the real profile), but\n * it's meaningfully more constrained than pure white: `light`'s `warning`/\n * `command` picks (`magenta`/`blueBright`) fall just short of 4.5:1 here\n * (4.20:1 / 4.24:1 -- close enough that using them anyway is a minor,\n * documented exception, not the dramatic compromise `blue`'s `error`\n * needed), and `light`'s `heading` pick (`magentaBright`) drops to 2.81:1,\n * below even the relaxed bold threshold, so `heading` uses `blackBright`\n * (3.58:1) instead -- clearly distinct from this profile's own black\n * default foreground, unlike plain `black` would be.\n * - `yellow` (high-contrast): `error: 'red'` (5.23:1), `emphasis: 'blue'`\n * (8.41:1), `warning: 'magenta'`, `command: 'blueBright'` (both ~4.2:1,\n * the documented near-AA exception above), `heading: 'blackBright'`.\n * `muted`/`debug` also use `blackBright` -- no room for further\n * distinction at this floor.\n * - `yellow-regular`: adds `positive: 'green'` (1.93:1, a deliberately\n * low-floor addition, matching the same aggressive relaxation\n * `light-regular`'s own `positive: 'green'` (2.16:1) already accepts).\n * - `yellow-vibrant`: adds `negative: 'redBright'` (3.58:1) instead of\n * aliasing `error`'s `red`.\n */\nconst BUNDLED_DEFINITIONS: Record<string, ThemeDefinition> = {\n 'dark-regular': {\n name: 'dark-regular',\n description:\n 'A more muted alternative to \"dark\" for dark-background terminals, at a relaxed (~4:1) contrast floor instead of strict WCAG AA -- same intents, plain (non-Bright) hues wherever that contrast allows. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellow',\n command: 'cyan',\n emphasis: 'magenta',\n heading: 'bold',\n positive: 'green',\n negative: 'redBright',\n muted: 'blackBright',\n debug: 'white',\n },\n },\n 'light-regular': {\n name: 'light-regular',\n description:\n 'A relaxed-contrast (~2:1 floor) alternative to \"light\" for light-background terminals, adding a color for positive/active values that the stricter WCAG AA floor can\\'t fit. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'magentaBright',\n positive: 'green',\n negative: 'red',\n muted: 'blackBright',\n debug: 'magentaBright',\n },\n },\n 'dark-vibrant': {\n name: 'dark-vibrant',\n description:\n 'The most colorful dark-background theme -- same as \"dark\", plus a genuinely distinct color for negative/inactive values and for debug output instead of leaving them uncolored or aliased to another intent. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellowBright',\n command: 'cyanBright',\n emphasis: 'magentaBright',\n heading: 'blueBright',\n positive: 'greenBright',\n negative: 'red',\n muted: 'blackBright',\n debug: 'magenta',\n },\n },\n 'light-vibrant': {\n name: 'light-vibrant',\n description:\n 'The most colorful light-background theme -- same as \"light-regular\", plus a genuinely distinct color for negative/inactive values instead of aliasing \"error\". This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'magentaBright',\n positive: 'green',\n negative: 'redBright',\n muted: 'blackBright',\n debug: 'magentaBright',\n },\n },\n blue: {\n name: 'blue',\n description:\n 'High-contrast (strict WCAG AA), tuned for a saturated, dark-leaning blue terminal background (reference: macOS Terminal\\'s built-in \"Ocean\" profile). `error` is the one deliberate exception to strict AA here -- no red-family hue clears it against this specific background at all, and a low-contrast red felt better than abandoning \"red means error\" outright. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellowBright',\n command: 'cyanBright',\n emphasis: 'cyanBright',\n heading: 'bold',\n positive: 'greenBright',\n negative: 'redBright',\n muted: 'black',\n debug: 'black',\n },\n },\n 'blue-regular': {\n name: 'blue-regular',\n description:\n 'A relaxed-contrast alternative to \"blue\" for the same saturated blue terminal background, giving `emphasis` its own color instead of aliasing `command`. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellowBright',\n command: 'cyanBright',\n emphasis: 'magentaBright',\n heading: 'bold',\n positive: 'greenBright',\n negative: 'redBright',\n muted: 'black',\n debug: 'black',\n },\n },\n 'blue-vibrant': {\n name: 'blue-vibrant',\n description:\n 'The most colorful theme for this saturated blue terminal background -- same as \"blue-regular\", plus a genuinely distinct color for debug output instead of aliasing `muted`. `heading` still has no viable color on this background at any tier -- an honest constraint, not a gap left unaddressed. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'dark',\n colors: {\n error: 'redBright',\n warning: 'yellowBright',\n command: 'cyanBright',\n emphasis: 'magentaBright',\n heading: 'bold',\n positive: 'greenBright',\n negative: 'redBright',\n muted: 'black',\n debug: 'blackBright',\n },\n },\n yellow: {\n name: 'yellow',\n description:\n 'High-contrast (strict WCAG AA), tuned for a mustard-toned yellow terminal background (reference: macOS Terminal\\'s built-in \"Man Page\" profile). `warning`/`command` are a minor, documented near-AA exception here (~4.2:1 against this specific background, just short of 4.5:1) -- close enough that keeping \"light\"\\'s intuitive hue choices felt better than reassigning them. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'blackBright',\n negative: 'red',\n muted: 'blackBright',\n debug: 'blackBright',\n },\n },\n 'yellow-regular': {\n name: 'yellow-regular',\n description:\n 'A relaxed-contrast alternative to \"yellow\" for the same mustard-toned yellow terminal background, adding a color for positive/active values that the stricter WCAG AA floor can\\'t fit. This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'blackBright',\n positive: 'green',\n negative: 'red',\n muted: 'blackBright',\n debug: 'blackBright',\n },\n },\n 'yellow-vibrant': {\n name: 'yellow-vibrant',\n description:\n 'The most colorful theme for this mustard-toned yellow terminal background -- same as \"yellow-regular\", plus a genuinely distinct color for negative/inactive values instead of aliasing \"error\". This file is a starting point: editing it changes this theme\\'s colors; copy it to a new file with a different name instead to make a separate custom theme.',\n mode: 'light',\n colors: {\n error: 'red',\n warning: 'magenta',\n command: 'blueBright',\n emphasis: 'blue',\n heading: 'blackBright',\n positive: 'green',\n negative: 'redBright',\n muted: 'blackBright',\n debug: 'blackBright',\n },\n },\n};\n\n/**\n * Reference backgrounds `ensureThemeDetectedIfNeeded` matches a detected\n * terminal background RGB against (see `matchBackgroundPreset`). Plain\n * black/white are included as real candidates here, not just as the\n * distance-based fallback -- without them, a genuinely near-white\n * background had nothing closer to compete against `yellow` (only ~31 RGB\n * units away from pure white) and matched it by default, even though it's\n * a poor match. With black/white in the running, a near-white background\n * correctly matches `light` (distance ~0) instead.\n */\nconst BACKGROUND_PRESETS: BackgroundPreset[] = [\n { themeName: 'dark', referenceRgb: [0, 0, 0] },\n { themeName: 'light', referenceRgb: [255, 255, 255] },\n { themeName: 'blue', referenceRgb: [34, 78, 189] },\n { themeName: 'yellow', referenceRgb: [255, 245, 156] },\n];\n\nfunction getThemesDir(): string {\n return path.join(getConfigPath(), FRODO_THEME_DEFINITIONS_DIRNAME);\n}\n\nfunction getActiveThemeFilePath(): string {\n return path.join(getConfigPath(), FRODO_THEME_ACTIVE_FILENAME);\n}\n\n/**\n * Writes the built-in themes' reference files to ~/.frodo/themes/ if they\n * aren't already there, so `frodo settings theme list`/`show` (and anyone\n * browsing the directory directly) have something real to discover, copy,\n * and edit into a custom theme -- per \"keep settings in separate,\n * discoverable files\" rather than a single opaque settings blob.\n */\nexport function ensureBuiltInThemeFiles(): void {\n const dir = getThemesDir();\n try {\n fs.mkdirSync(dir, { recursive: true });\n const allBundled = [\n ...Object.values(BUILT_IN_REFERENCE_DEFINITIONS),\n ...Object.values(BUNDLED_DEFINITIONS),\n ];\n for (const def of allBundled) {\n const filePath = path.join(dir, `${def.name}.json`);\n if (!fs.existsSync(filePath)) {\n fs.writeFileSync(filePath, JSON.stringify(def, null, 2));\n }\n }\n } catch (e) {\n printMessage(\n `Error creating default theme files in ${dir} (${e.message})`,\n 'error'\n );\n }\n}\n\nfunction isValidThemeDefinition(value: unknown): value is ThemeDefinition {\n if (!value || typeof value !== 'object') return false;\n const def = value as Partial<ThemeDefinition>;\n if (typeof def.name !== 'string') return false;\n if (def.mode !== 'dark' && def.mode !== 'light') return false;\n if (!def.colors || typeof def.colors !== 'object') return false;\n return Object.values(def.colors).every(\n (hueName) => typeof hueName === 'string' && hueName in HUE_NAME_TO_FUNCTION\n );\n}\n\n/**\n * Every theme definition found in ~/.frodo/themes/ -- both the built-in\n * reference files and any custom ones a user has added. Malformed files\n * are skipped with a warning rather than failing the whole listing.\n *\n * Results are cached and revalidated against each file's mtime+size, so\n * repeated calls within one process (the FrodoStubCommand constructor\n * calls activatePersistedTheme, and every color resolution re-reads\n * settings) don't re-read the whole directory -- ~5,600 redundant file\n * reads / ~200 ms of startup on the first `frodo -v` without this.\n * Editing a theme file still takes effect immediately (mtime changes).\n */\ntype DirCacheEntry = {\n signature: Map<string, { mtimeMs: number; size: number }>;\n definitions: ThemeDefinition[];\n};\nlet dirCache: DirCacheEntry | undefined;\n\nfunction currentDirSignature(\n dir: string,\n filenames: string[]\n): Map<string, { mtimeMs: number; size: number }> {\n const signature = new Map<string, { mtimeMs: number; size: number }>();\n for (const filename of filenames) {\n try {\n const st = fs.statSync(path.join(dir, filename));\n signature.set(filename, { mtimeMs: st.mtimeMs, size: st.size });\n } catch {\n // unreadable/ vanished between readdir and stat -- treated as absent\n }\n }\n return signature;\n}\n\nfunction sameSignature(\n a: Map<string, { mtimeMs: number; size: number }>,\n b: Map<string, { mtimeMs: number; size: number }>\n): boolean {\n if (a.size !== b.size) return false;\n for (const [name, stat] of a) {\n const other = b.get(name);\n if (!other || other.mtimeMs !== stat.mtimeMs || other.size !== stat.size) {\n return false;\n }\n }\n return true;\n}\n\nexport function listThemeDefinitions(): ThemeDefinition[] {\n const dir = getThemesDir();\n let filenames: string[];\n try {\n filenames = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));\n } catch {\n dirCache = undefined;\n return [];\n }\n const signature = currentDirSignature(dir, filenames);\n if (dirCache && sameSignature(dirCache.signature, signature)) {\n return dirCache.definitions;\n }\n const definitions: ThemeDefinition[] = [];\n for (const filename of filenames) {\n try {\n const raw = fs.readFileSync(path.join(dir, filename), 'utf8');\n const parsed = JSON.parse(raw);\n if (isValidThemeDefinition(parsed)) {\n definitions.push(parsed);\n } else {\n printMessage(\n `Skipping malformed theme file ${filename}: doesn't match the expected {name, mode, colors} shape.`,\n 'warn'\n );\n }\n } catch (e) {\n printMessage(\n `Skipping unreadable theme file ${filename} (${e.message})`,\n 'warn'\n );\n }\n }\n dirCache = { signature, definitions };\n return definitions;\n}\n\ntype ThemeSettings = {\n background?: Background;\n contrast?: ContrastTier;\n // A literal, unparsed theme name -- used only when `set <name>` is given\n // something that isn't a recognized (background, contrast) combination\n // (e.g. a hand-authored custom theme). Takes precedence over\n // `background`/`contrast` whenever present; cleared by\n // `setActiveBackground`/`setActiveContrast`/a `set` that does parse.\n customActive?: string;\n autoDetect?: boolean;\n};\n\n// Old shape, from before background/contrast became two separate\n// preferences -- `active` was a single flat theme name. Migrated\n// in-memory on read (see `readThemeSettings`); the next write upgrades the\n// file on disk to the new shape naturally, no separate migration step.\ntype LegacyThemeSettings = { active?: string; autoDetect?: boolean };\n\n// Cache for `readThemeSettings`, revalidated against Theme.json's mtime+size.\n// The color getters resolve live on every access by design (theme edits take\n// effect immediately), but resolution must not cost three sync file reads per\n// access -- `getActiveThemeName` alone reads it three times.\nlet settingsCache:\n { mtimeMs: number; size: number; settings: ThemeSettings } | undefined;\n\nfunction readThemeSettings(): ThemeSettings {\n const file = getActiveThemeFilePath();\n try {\n const st = fs.statSync(file);\n if (\n settingsCache &&\n settingsCache.mtimeMs === st.mtimeMs &&\n settingsCache.size === st.size\n ) {\n return settingsCache.settings;\n }\n const parsed: unknown = JSON.parse(fs.readFileSync(file, 'utf8'));\n if (typeof parsed !== 'object' || !parsed) return {};\n const settings = parsed as ThemeSettings & LegacyThemeSettings;\n let result: ThemeSettings;\n if (settings.background || settings.customActive) {\n result = settings;\n } else if (typeof settings.active === 'string') {\n const legacyParsed = parseThemeName(settings.active);\n result = legacyParsed\n ? { ...legacyParsed, autoDetect: settings.autoDetect }\n : { customActive: settings.active, autoDetect: settings.autoDetect };\n } else {\n result = settings;\n }\n settingsCache = { mtimeMs: st.mtimeMs, size: st.size, settings: result };\n return result;\n } catch {\n return {};\n }\n}\n\nfunction writeThemeSettings(settings: ThemeSettings): void {\n try {\n // A fresh system has no ~/.frodo yet, and this can be its first write\n // (first-run auto-detection persists a background before anything else\n // creates the directory -- app.ts runs detection before\n // `activatePersistedTheme`/`ensureBuiltInThemeFiles` and long before\n // frodo-lib's own `initConnectionProfiles`/`initTokenCache`). Create the\n // directory so a first-ever write can't crash with a raw ENOENT.\n fs.mkdirSync(getConfigPath(), { recursive: true });\n fs.writeFileSync(\n getActiveThemeFilePath(),\n JSON.stringify(settings, null, 2)\n );\n settingsCache = undefined;\n } catch (e) {\n // Losing a theme preference is not fatal: report it and let startup\n // continue with the defaults (matching `ensureBuiltInThemeFiles`).\n printMessage(\n `Error saving theme settings to ${getActiveThemeFilePath()} (${e.message})`,\n 'error'\n );\n }\n}\n\nexport function getActiveBackground(): Background {\n const { background } = readThemeSettings();\n return background && BACKGROUNDS.includes(background) ? background : 'dark';\n}\n\nexport function getActiveContrast(): ContrastTier {\n const { contrast } = readThemeSettings();\n return contrast && CONTRAST_TIERS.includes(contrast) ? contrast : 'vibrant';\n}\n\nexport function setActiveBackground(background: Background): void {\n writeThemeSettings({\n ...readThemeSettings(),\n background,\n customActive: undefined,\n });\n}\n\nexport function setActiveContrast(contrast: ContrastTier): void {\n writeThemeSettings({\n ...readThemeSettings(),\n contrast,\n customActive: undefined,\n });\n}\n\n/**\n * The name of the resolved active theme. Normally derived from the\n * `background`/`contrast` preferences (see `themeName`); a `customActive`\n * literal (set by `set <name>` for a name that isn't a recognized\n * (background, contrast) combination) takes precedence when present.\n * Does not consider the `FRODO_COLOR_THEME` env var -- that's a separate,\n * higher-precedence override handled by frodo-lib's own `resolveThemeMode`.\n */\nexport function getActiveThemeName(): string {\n const { customActive } = readThemeSettings();\n if (typeof customActive === 'string') return customActive;\n return themeName(getActiveBackground(), getActiveContrast());\n}\n\n/**\n * Sets the active theme by name. A name matching the (background,\n * contrast) convention (see `parseThemeName`) updates those two\n * preferences directly, keeping them and the active theme in sync; any\n * other name (a hand-authored custom theme) is stored as a literal\n * `customActive` override instead.\n */\nexport function setActiveThemeName(name: string): void {\n const parsed = parseThemeName(name);\n if (parsed) {\n writeThemeSettings({\n ...readThemeSettings(),\n background: parsed.background,\n contrast: parsed.contrast,\n customActive: undefined,\n });\n } else {\n writeThemeSettings({ ...readThemeSettings(), customActive: name });\n }\n}\n\n/**\n * Whether a theme has ever actually been chosen -- manually, or by a\n * previous successful auto-detection -- as opposed to `getActiveThemeName`\n * quietly deriving one from defaults. Used to gate `ensureThemeDetectedIfNeeded`\n * so detection only ever runs before the first real choice exists, never\n * overriding one.\n */\nfunction hasPersistedThemeChoice(): boolean {\n const { background, customActive } = readThemeSettings();\n return typeof background === 'string' || typeof customActive === 'string';\n}\n\n/**\n * Whether terminal-background auto-detection is allowed to run at all.\n * Defaults to enabled -- a user who's never touched this setting still\n * benefits from a one-time detection on first run (see\n * `ensureThemeDetectedIfNeeded`), but can turn it off entirely via\n * `frodo settings theme autodetect off` to always fall through to the\n * `dark` default instead.\n */\nexport function isAutoDetectEnabled(): boolean {\n const { autoDetect } = readThemeSettings();\n return autoDetect !== false;\n}\n\nexport function setAutoDetectEnabled(enabled: boolean): void {\n writeThemeSettings({ ...readThemeSettings(), autoDetect: enabled });\n}\n\n/**\n * Resolves the active theme's full definition. `dark`/`light` always\n * resolve to the code-driven built-in (never read from disk, even if a\n * same-named file exists or was edited) -- anything else is looked up\n * among the discovered files, falling back to `dark` if not found.\n */\nexport function getActiveThemeDefinition(): ThemeDefinition {\n const activeName = getActiveThemeName();\n if (activeName === 'dark' || activeName === 'light') {\n return BUILT_IN_REFERENCE_DEFINITIONS[activeName];\n }\n const found = listThemeDefinitions().find((def) => def.name === activeName);\n return found ?? BUILT_IN_REFERENCE_DEFINITIONS.dark;\n}\n\n/**\n * Applies the persisted active theme at process startup: sets the base\n * dark/light mode, and, only for a genuinely custom (non-built-in) theme,\n * layers its color overrides on top. Built-in `dark`/`light` deliberately\n * never touch the override path, even though their reference files'\n * `colors` would (today) produce the same result -- going through\n * ColorTheme.ts's own code keeps the built-ins correct-by-construction if\n * that code ever changes, rather than silently drifting from a stale copy\n * on disk. Call once, before any output happens (see `app.ts`/`shell.ts`).\n *\n * `FRODO_COLOR_THEME`, if set, wins over anything persisted here -- this\n * function leaves `state`'s override unset in that case, so frodo-lib's own\n * `resolveThemeMode` falls through to the env var exactly as it would with\n * no persisted preference at all. A custom (non-built-in) theme's *color*\n * overrides, however, aren't a mode choice the env var has any way to\n * express, so those still apply even when the env var is picking the mode.\n */\nexport function activatePersistedTheme(): void {\n ensureBuiltInThemeFiles();\n const activeName = getActiveThemeName();\n const envMode = process.env[FRODO_COLOR_THEME_ENV_KEY];\n const envOverridesMode = envMode === 'dark' || envMode === 'light';\n\n if (activeName === 'dark' || activeName === 'light') {\n if (!envOverridesMode) state.setColorTheme(activeName);\n return;\n }\n const def = listThemeDefinitions().find((d) => d.name === activeName);\n if (def) {\n if (!envOverridesMode) state.setColorTheme(def.mode);\n applyCustomThemeOverrides(def.colors);\n } else if (!envOverridesMode) {\n state.setColorTheme('dark');\n }\n}\n\n/**\n * Queries the terminal's actual background color and, if it responds,\n * matches it against `BACKGROUND_PRESETS` and persists the result as the\n * `background` preference -- unconditionally, regardless of whether a\n * background was already chosen, and without touching the separate\n * `contrast` preference at all. Returns the background it persisted, or\n * `null` if the terminal never responded (non-TTY, or an interactive\n * terminal that doesn't support the query). Exported for\n * `frodo settings theme detect`'s explicit, user-triggered re-detection;\n * `ensureThemeDetectedIfNeeded` below is the gated, automatic-on-first-run\n * caller most code should use instead.\n */\nexport async function detectAndPersistTheme(): Promise<Background | null> {\n const rgb = await detectTerminalBackgroundRgb();\n if (!rgb) return null;\n const matched = matchBackgroundPreset(\n rgb,\n BACKGROUND_PRESETS,\n 'dark',\n 'light'\n ) as Background;\n setActiveBackground(matched);\n return matched;\n}\n\nlet detectionAttemptedThisProcess = false;\n\n/**\n * Best-effort, one-time terminal-background auto-detection: if no theme\n * has ever actually been chosen yet (see `hasPersistedThemeChoice`) and\n * auto-detection isn't disabled, runs `detectAndPersistTheme` -- so every\n * future invocation, this process included, skips detection entirely from\n * then on.\n *\n * Deliberately does *not* run on every invocation: `detectTerminalBackgroundRgb`\n * already resolves instantly with no query attempted on a non-TTY (piped/\n * scripted/CI) invocation, but a genuine interactive terminal that simply\n * doesn't respond still costs up to its ~500ms timeout, which a persisted\n * choice (successful or explicit) avoids paying again. Guarded by an\n * in-process flag too, since `activatePersistedTheme` is called multiple\n * times per process (once per command in the interactive shell) -- this\n * only ever attempts the query once per process, not once per call.\n *\n * Call explicitly, awaited, from a genuine top-level entry point (see\n * `app.ts`) -- unlike `activatePersistedTheme`, this is async (the OSC 11\n * query is inherently a round-trip) and must run, and settle, before that\n * synchronous call so a freshly-detected theme takes effect immediately\n * rather than one command late.\n */\nexport async function ensureThemeDetectedIfNeeded(): Promise<void> {\n if (detectionAttemptedThisProcess) return;\n detectionAttemptedThisProcess = true;\n if (hasPersistedThemeChoice() || !isAutoDetectEnabled()) return;\n await detectAndPersistTheme();\n}\n","import fs from 'fs';\nimport {\n frodo,\n FrodoError,\n state,\n type RetryStrategy,\n} from '@rockcarver/frodo-lib';\nimport { AddHelpTextContext, Argument, Command, Help, Option } from 'commander';\nimport propertiesReader from 'properties-reader';\nimport {\n setCredentialOverride,\n setForceLoginAsUser,\n setOpenBrowser,\n setUseDeviceFlow,\n} from '../ops/AuthenticateOps.js';\nimport {\n cleanupProgressIndicators,\n createProgressIndicator,\n curlirizeMessage,\n debugMessage,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n verboseMessage,\n} from '../utils/Console.js';\nimport { flushAuthoringPrint } from '../utils/interactive/AuthoringPrintState.js';\n// Type-only: the credential vocabulary lives in the interactive layer\n// (see docs/INTERACTIVE-COMMANDS.md, layering).\nimport type { CredentialOverrideType } from '../utils/interactive/ConnectionProfilePickers';\nimport { getEntityPicks } from '../utils/interactive/EntityPickers.js';\nimport {\n escapableSelect,\n ESCAPE,\n RIGHT,\n} from '../utils/interactive/EscapableSelectPrompt.js';\nimport { EXIT_ALL, EXIT_ALL_SIGNAL } from '../utils/interactive/ExitAll.js';\nimport { canPrompt, setNeverPrompt } from '../utils/interactive/PromptGate.js';\nimport { activatePersistedTheme } from '../utils/ThemeConfig.js';\nimport {\n deferMissingMandatoryOption,\n deferOneOfGroups,\n getOneOfGroups,\n resolveInteractiveInputs,\n setActiveActionCommand,\n type OptionRequirementSpec,\n} from './ResolveInteractiveInputs.js';\n\n// Frodo constants\nconst constants = frodo.utils.constants;\nconst {\n DEFAULT_REALM_KEY,\n DEPLOYMENT_TYPES,\n RETRY_STRATEGIES,\n RETRY_NOTHING_KEY,\n} = constants;\nconst { convertPrivateKeyToPem } = frodo.utils.crypto;\n\n// Default heading for grouped subcommands.\nconst COMMANDS_HEADING = 'Commands:';\n// Heading for command-specific options that do not declare a group.\nconst COMMAND_OPTIONS_HEADING = 'Options:';\n// Group for connection and deployment endpoint settings.\nconst CONNECTION_OPTIONS_HEADING = 'Connection Options:';\n// Group for login and credential-related settings.\nexport const AUTHENTICATION_OPTIONS_HEADING = 'Authentication Options:';\n// Group for runtime behavior controls.\nconst RUNTIME_OPTIONS_HEADING = 'Runtime Options:';\n// Group for output and diagnostics controls.\nconst OUTPUT_OPTIONS_HEADING = 'Output Options:';\n// Help flags intentionally use the same visible label as command options to keep a single\n// \"Options:\" section in help output while still preserving a separate semantic bucket.\nconst HELP_OPTIONS_HEADING = 'Options:';\n// Top-level env var section for host/realm/endpoint values.\nconst CONNECTION_ENVIRONMENT_VARIABLES_HEADING = 'Connection:';\n// Top-level env var section for auth and credentials.\nconst AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING = 'Authentication:';\n// Top-level env var section for runtime behavior.\nconst RUNTIME_ENVIRONMENT_VARIABLES_HEADING = 'Runtime:';\n// Top-level env var section for output and debug toggles.\nconst OUTPUT_ENVIRONMENT_VARIABLES_HEADING = 'Output:';\n\n/**\n * Stable identity for what kind of option this is, independent of which\n * heading it renders under. Headings are purely cosmetic (renamed or\n * reorganized freely for display); category is the semantic identity that\n * drives bulk-omission decisions (e.g. `{ local: true }` dropping every\n * Authentication/Connection option from a command that never calls\n * getTokens()), so that reorganizing display headings can never silently\n * change which options a command gets.\n */\nexport enum OptionCategory {\n Command = 'command',\n Connection = 'connection',\n Authentication = 'authentication',\n Runtime = 'runtime',\n Output = 'output',\n}\n// Short flag alias for --help-more; triggers level-2 help showing all option groups.\nconst HELP_MORE_SHORT_FLAG = '-hh';\n// Level-2 help flag: shows all option groups (Connection, Authentication, Runtime, Output)\n// that are hidden from basic -h output, including stability badges. Does not include env vars.\nconst HELP_MORE_FLAG = '--help-more';\n// Short flag alias for --help-all; triggers level-3 help showing everything.\nconst HELP_ALL_SHORT_FLAG = '-hhh';\n// Level-3 help flag: shows all option groups plus environment variable sections.\n// Superset of --help-more output. Stability badges appear at all levels.\nconst HELP_ALL_FLAG = '--help-all';\n// Fallback help text width used when the terminal width cannot be determined.\nconst DEFAULT_HELP_WIDTH = 100;\n// Absolute minimum help text width; applied at all help levels regardless of terminal width.\nconst MINIMUM_HELP_WIDTH = 60;\n// Padding between option flags and their descriptions in help output.\nconst ENVIRONMENT_VARIABLE_NAME_INDENT = 4;\n// Padding between environment variable descriptions and their group headings in help output.\nconst ENVIRONMENT_VARIABLE_DESCRIPTION_PADDING = 2;\n// Property key used to attach stability metadata to Commander objects (commands, options,\n// arguments). The double-underscore prefix avoids collision with Commander's own property\n// namespace. Typed `as const` so TypeScript treats it as a literal type for type-safe\n// indexed access via the `StabilityAnnotated` interface.\nconst STABILITY_METADATA_KEY = '__frodoStabilityMetadata' as const;\nconst SUPPRESS_STABILITY_WARNING_KEY =\n '__frodoSuppressStabilityWarning' as const;\n\nexport type StabilityIndicator =\n 'stable' | 'preview' | 'experimental' | 'deprecated';\n\nexport type StabilityGateMode = 'option-or-env' | 'option-only' | 'env-only';\n\nexport type StabilityGateConfig = {\n requiredOptIn?: boolean;\n optionName?: string;\n envVarName?: string;\n helpText?: string;\n mode?: StabilityGateMode;\n};\n\ntype StabilityMetadata = {\n level: StabilityIndicator;\n gate?: StabilityGateConfig;\n};\n\nconst stabilityLevelPriority: Record<StabilityIndicator, number> = {\n stable: 0,\n preview: 1,\n experimental: 2,\n deprecated: 3,\n};\n\ntype StabilityAnnotated = {\n [STABILITY_METADATA_KEY]?: StabilityMetadata;\n [SUPPRESS_STABILITY_WARNING_KEY]?: boolean;\n};\n\n/**\n * Logical scope used for deployment-constrained help sub-sections.\n *\n * Keep this in sync with deployment type constants and with\n * `getScopeForDeploymentType()` / `getDeploymentTypeForScope()`.\n */\ntype DeploymentScope = 'classic-only' | 'cloud-only' | 'forgeops-only';\n\n/**\n * Optional per-command variants for a single environment variable.\n *\n * Use this when a variable has different override rules depending on the\n * command (for example `frodo conn save` versus `frodo log`).\n */\ntype VariantDescriptor = {\n description: string;\n appliesTo?: string;\n commandNames?: string[];\n include?: (command: FrodoCommand) => boolean;\n};\n\n/**\n * Metadata for environment variable help generation.\n *\n * How to add a new env var entry:\n * 1) Add an object to `environmentVariables` with `name`, `description`, and `group`.\n * 2) Add `include` when the variable should only appear if a default arg/option exists.\n * 3) Add `appliesToTypes` and/or `scope` when deployment visibility is constrained.\n * 4) Add `variants` when the override description differs by command.\n */\ntype EnvironmentVariableDescriptor = {\n name: string;\n description: string;\n group: string;\n appliesToTypes?: string[];\n scope?: DeploymentScope;\n commandNames?: string[];\n include?: (command: FrodoCommand) => boolean;\n variants?: VariantDescriptor[];\n};\n\n/**\n * Order of top-level environment variable groups.\n *\n * Add new headings here if you introduce new env var categories and want\n * deterministic output ordering in full help (`-hhh`).\n */\nconst environmentVariableGroupOrder = [\n CONNECTION_ENVIRONMENT_VARIABLES_HEADING,\n AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n OUTPUT_ENVIRONMENT_VARIABLES_HEADING,\n];\n\n/**\n * Rendering order for scoped deployment sub-sections.\n *\n * This controls the order of inline labels such as `(Classic-only):`\n * in options, env vars, and command lists.\n */\nconst environmentVariableScopeOrder: DeploymentScope[] = [\n 'classic-only',\n 'cloud-only',\n 'forgeops-only',\n];\n\n// Property key used to attach category metadata to Option objects, mirroring\n// STABILITY_METADATA_KEY's double-underscore-prefixed convention to avoid\n// collision with Commander's own property namespace.\nconst OPTION_CATEGORY_KEY = '__frodoOptionCategory' as const;\n\ntype CategoryAnnotated = {\n [OPTION_CATEGORY_KEY]?: OptionCategory;\n};\n\nfunction setOptionCategory(option: Option, category: OptionCategory): void {\n (option as unknown as CategoryAnnotated)[OPTION_CATEGORY_KEY] = category;\n}\n\n/**\n * Reads an option's category, as assigned via `withHelpGroup(...)`.\n * @param option Annotated option.\n * @returns The option's category, or undefined for options that never went\n * through `withHelpGroup(...)` (e.g. help flags added directly).\n */\nfunction getOptionCategory(option: Option): OptionCategory | undefined {\n return (option as unknown as CategoryAnnotated)[OPTION_CATEGORY_KEY];\n}\n\nfunction withHelpGroup(\n option: Option,\n group: string,\n category: OptionCategory\n): Option {\n option.helpGroup(group);\n setOptionCategory(option, category);\n return option;\n}\n\n/**\n * Annotates an option with stability metadata for help rendering.\n * @param option Option to annotate.\n * @param level Stability level to apply.\n * @returns Same option for chaining.\n */\nexport function withOptionStability(\n option: Option,\n level: StabilityIndicator,\n gate?: StabilityGateConfig\n): Option {\n const metadata = getStabilityMetadata(option);\n setStabilityMetadata(option, {\n ...metadata,\n level,\n gate: gate || metadata.gate,\n });\n return option;\n}\n\n/**\n * Annotates an argument with stability metadata for help rendering.\n * @param argument Argument to annotate.\n * @param level Stability level to apply.\n * @returns Same argument for chaining.\n */\nexport function withArgumentStability(\n argument: Argument,\n level: StabilityIndicator,\n gate?: StabilityGateConfig\n): Argument {\n const metadata = getStabilityMetadata(argument);\n setStabilityMetadata(argument, {\n ...metadata,\n level,\n gate: gate || metadata.gate,\n });\n return argument;\n}\n\n/**\n * Stores stability metadata on Commander objects.\n * @param target Annotated command, option, or argument.\n * @param metadata Stability metadata to persist.\n */\nfunction setStabilityMetadata(\n target: Command | Option | Argument,\n metadata: StabilityMetadata\n) {\n (target as unknown as StabilityAnnotated)[STABILITY_METADATA_KEY] = metadata;\n}\n\n/**\n * Reads raw stability metadata as explicitly configured on the target.\n * @param target Annotated command, option, or argument.\n * @returns Explicit metadata if present, otherwise undefined.\n */\nfunction getRawStabilityMetadata(\n target: Command | Option | Argument\n): StabilityMetadata | undefined {\n return (target as unknown as StabilityAnnotated)[STABILITY_METADATA_KEY];\n}\n\n/**\n * Reads stability metadata from Commander objects.\n * @param target Annotated command, option, or argument.\n * @returns Stability metadata, defaulting to stable.\n */\nfunction getStabilityMetadata(\n target: Command | Option | Argument\n): StabilityMetadata {\n const metadata = getRawStabilityMetadata(target);\n return metadata || { level: 'stable' };\n}\n\n/**\n * Resolves effective stability for a command by walking up parent commands.\n *\n * Behavior:\n * - level: strongest level found in the command ancestry\n * - gate: nearest required opt-in gate found in the ancestry\n *\n * This allows declaring stability once at a stub command (command tree root)\n * and having it apply to all descendants.\n * @param command Command to evaluate.\n * @returns Effective stability metadata for runtime and help rendering.\n */\nfunction getEffectiveCommandStabilityMetadata(\n command: Command\n): StabilityMetadata {\n let level: StabilityIndicator = 'stable';\n let gate: StabilityGateConfig | undefined;\n\n let current: Command | null = command;\n while (current) {\n const metadata = getRawStabilityMetadata(current);\n if (metadata) {\n if (\n stabilityLevelPriority[metadata.level] > stabilityLevelPriority[level]\n ) {\n level = metadata.level;\n }\n\n if (!gate && metadata.gate?.requiredOptIn) {\n gate = metadata.gate;\n }\n }\n current = current.parent || null;\n }\n\n return gate ? { level, gate } : { level };\n}\n\n/**\n * Formats stability level labels for display in help text and warnings.\n * @param level Stability level.\n * @returns Human-readable label.\n */\nfunction formatStabilityLevel(level: StabilityIndicator): string {\n switch (level) {\n case 'preview':\n return 'Preview';\n case 'experimental':\n return 'Experimental';\n case 'deprecated':\n return 'Deprecated';\n default:\n return 'Stable';\n }\n}\n\n/**\n * Determines whether colored stability badges should be emitted.\n * @returns True when color output is supported and not explicitly disabled.\n */\nfunction shouldUseStabilityColors(): boolean {\n return !!process.stdout.isTTY && !process.env.NO_COLOR;\n}\n\n/**\n * Applies ANSI color to stability and opt-in badges.\n * @param text Badge text to colorize.\n * @param level Stability level used for color selection.\n * @param isOptInBadge True for opt-in badge coloring.\n * @returns Colored or plain badge text.\n */\nfunction colorizeStabilityBadge(\n text: string,\n level: StabilityIndicator,\n isOptInBadge = false\n): string {\n if (!shouldUseStabilityColors()) {\n return text;\n }\n\n const reset = '\\x1b[0m';\n if (isOptInBadge) {\n return `\\x1b[36m${text}${reset}`;\n }\n\n switch (level) {\n case 'preview':\n return `\\x1b[1;93m${text}${reset}`;\n case 'experimental':\n return `\\x1b[1;31m${text}${reset}`;\n case 'deprecated':\n return `\\x1b[1;90m${text}${reset}`;\n default:\n return `\\x1b[32m${text}${reset}`;\n }\n}\n\n/**\n * Appends stability and optional opt-in badges to a description.\n * @param description Existing description text.\n * @param target Annotated command, option, or argument.\n * @returns Decorated description.\n */\n/**\n * ANSI color for deployment-scope badges ([Cloud-only] etc.). Magenta is the\n * one free hue that clears normal-text AA (4.5:1) on both dark and light\n * terminal backgrounds without bolding, and it reads as an informational\n * qualifier rather than a status: the stability palette already claims\n * yellow (preview), red (experimental), gray (deprecated), green (stable),\n * and cyan (opt-in).\n */\nconst DEPLOYMENT_BADGE_COLOR = '\\x1b[35m';\n\n/**\n * Returns the deployment badge text for a command, or undefined when the\n * command supports more than one deployment type (or none are declared).\n * Mirrors getSingleTypeScopeForCommand but keeps the display label instead\n * of the scope token.\n */\nfunction getDeploymentBadge(command: Command): string | undefined {\n const typedCommand = command as CommandWithTypes;\n if (!typedCommand.types || typedCommand.types.length !== 1) {\n return undefined;\n }\n return `[${toDeploymentOnlyLabel(typedCommand.types[0])}]`;\n}\n\n/**\n * Colorizes a deployment badge. Same TTY/NO_COLOR gating as the stability\n * badges.\n */\nfunction colorizeDeploymentBadge(text: string): string {\n if (!shouldUseStabilityColors()) {\n return text;\n }\n return `${DEPLOYMENT_BADGE_COLOR}${text}\\x1b[0m`;\n}\n\nfunction decorateDescriptionWithStability(\n description: string,\n target: Command | Option | Argument\n): string {\n const metadata =\n target instanceof Command\n ? getEffectiveCommandStabilityMetadata(target)\n : getStabilityMetadata(target);\n\n const badges: string[] = [];\n\n // Stability badges first — a property of the command itself — then the\n // deployment badge, a property of the environment the command runs\n // against.\n if (metadata.level !== 'stable') {\n badges.push(\n colorizeStabilityBadge(\n `[${formatStabilityLevel(metadata.level)}]`,\n metadata.level\n )\n );\n if (metadata.gate?.requiredOptIn) {\n badges.push(\n colorizeStabilityBadge('[Opt-in required]', metadata.level, true)\n );\n }\n }\n\n // Deployment badge: commands only (options/arguments never carry types),\n // and only when the command is single-deployment-type. The direct lookup\n // on the target (not the parent chain) is correct here: the Help overrides\n // call this for the exact command being listed, and getEffectiveCommand-\n // StabilityMetadata has already resolved inherited stability above.\n if (target instanceof Command) {\n const deploymentBadge = getDeploymentBadge(target);\n if (deploymentBadge) {\n badges.push(colorizeDeploymentBadge(deploymentBadge));\n }\n }\n\n if (badges.length === 0) {\n return description;\n }\n\n return description ? `${badges.join(' ')} ${description}` : badges.join(' ');\n}\n\n/**\n * Creates a detached copy of an option so command-level mutations do not\n * affect shared defaults.\n * @param option Source option definition.\n * @returns Cloned option instance.\n */\nfunction cloneOption(option: Option): Option {\n const cloned = Object.assign(new Option(option.flags, option.description), {\n defaultValue: option.defaultValue,\n defaultValueDescription: option.defaultValueDescription,\n presetArg: option.presetArg,\n envVar: option.envVar,\n parseArg: option.parseArg,\n hidden: option.hidden,\n mandatory: option.mandatory,\n argChoices: option.argChoices ? [...option.argChoices] : option.argChoices,\n helpGroupHeading: option.helpGroupHeading,\n });\n\n setStabilityMetadata(cloned, getStabilityMetadata(option));\n const category = getOptionCategory(option);\n if (category) setOptionCategory(cloned, category);\n return cloned;\n}\n\n/**\n * Creates a detached copy of an argument so command-level mutations do not\n * affect shared defaults.\n * @param argument Source argument definition.\n * @returns Cloned argument instance.\n */\nfunction cloneArgument(argument: Argument): Argument {\n const bracketOpen = argument.required ? '<' : '[';\n const bracketClose = argument.required ? '>' : ']';\n const spec = `${bracketOpen}${argument.name()}${argument.variadic ? '...' : ''}${bracketClose}`;\n\n const cloned = Object.assign(new Argument(spec, argument.description), {\n defaultValue: argument.defaultValue,\n defaultValueDescription: argument.defaultValueDescription,\n parseArg: argument.parseArg,\n argChoices: argument.argChoices\n ? [...argument.argChoices]\n : argument.argChoices,\n });\n\n setStabilityMetadata(cloned, getStabilityMetadata(argument));\n return cloned;\n}\n\n/**\n * Option that collects repeated values into an array.\n */\nexport class ListOption extends Option {\n constructor(flags: string, description?: string) {\n super(flags, description);\n this.argParser((value: string, previous: string[] = []) => {\n previous.push(value);\n return previous;\n }).default([]);\n }\n}\n\n/**\n * Option that collects repeated values into an object using dot notation\n */\nexport class ObjectOption extends Option {\n constructor(flags: string, description?: string) {\n super(flags, description);\n this.expandArguments();\n this.argParser((input: string, previous: Record<string, any> = {}) => {\n const equalsIdx = input.indexOf('=');\n if (equalsIdx === -1) {\n this.setPath(previous, input, true);\n } else {\n this.setPath(\n previous,\n input.slice(0, equalsIdx),\n input.slice(equalsIdx + 1)\n );\n }\n return previous;\n });\n }\n\n /**\n * Helper that sets an object value at a specific path for an ObjectOption\n * @param obj The object to set\n * @param path The path to set in the object\n * @param value The value to set in the object\n */\n setPath(obj: Record<string, any>, path: string, value: string | true): void {\n const keys = path.split('.');\n let current = obj;\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n if (typeof current[key] !== 'object' || current[key] === null)\n current[key] = {};\n current = current[key];\n }\n const lastKey = keys[keys.length - 1];\n if (!current[lastKey]) {\n current[lastKey] = value;\n return;\n }\n if (!Array.isArray(current[lastKey])) {\n current[lastKey] = [current[lastKey]];\n }\n current[lastKey].push(value);\n }\n\n /**\n * Helper that \"expands\" arguments from dot notation into <key>=<value> notation that the option argParser can then use to easily parse the object\n */\n expandArguments(): void {\n // This pattern ends up looking something like this to match the flags: `^(-M|--metadata)\\\\.(.+)$`\n const pattern = new RegExp(\n `^(${[this.short, this.long]\n .filter((o) => o)\n // This escapes characters in the flags for the regex\n .map((f) => f.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('|')})\\\\.(.+)$`\n );\n const expandedArgv: string[] = [];\n for (let i = 0; i < process.argv.length; i++) {\n const token = process.argv[i];\n const match = token.match(pattern);\n if (!match) {\n expandedArgv.push(token);\n continue;\n }\n const [, baseFlag, path] = match;\n const equalsIdx = path.indexOf('=');\n if (equalsIdx !== -1) {\n expandedArgv.push(baseFlag, path);\n } else if (\n process.argv[i + 1] !== undefined &&\n // Check that the next argument is not a flag\n !/^-{1,2}.*/.test(process.argv[i + 1])\n ) {\n expandedArgv.push(baseFlag, `${path}=${process.argv[++i]}`);\n } else {\n expandedArgv.push(baseFlag, path);\n }\n }\n process.argv = expandedArgv;\n }\n}\n\nexport const hostArgument = new Argument(\n '[host]',\n 'AM base URL, e.g.: https://cdk.iam.example.com/am. To use a connection profile, just specify a unique substring or alias.'\n);\n\nconst realmArgument = new Argument(\n '[realm]',\n \"Realm. Specify realm as '/' for the root realm or 'realm' or '/parent/child' otherwise.\"\n).default(\n // must check for FRODO_REALM env variable here because otherwise cli will overwrite realm with default value\n process.env.FRODO_REALM || DEFAULT_REALM_KEY,\n '\"alpha\" for Identity Cloud tenants, \"/\" otherwise.'\n);\n\nconst usernameArgument = new Argument(\n '[username]',\n \"Username to login with. Must be an admin user with appropriate rights to manage authentication journeys/trees. If given without a password, and it matches the username already stored in the connection profile for the target host, frodo uses that profile's stored password instead of requiring it on the command line.\"\n);\n\nconst passwordArgument = new Argument('[password]', 'Password.');\n\nconst idmHostOption = withHelpGroup(\n new Option(\n '--idm-host <idm-host>',\n 'IDM base URL, e.g.: https://cdk.idm.example.com/myidm. Use only if your IDM installation resides in a different domain and/or if the base path differs from the default \"/openidm\".'\n ),\n CONNECTION_OPTIONS_HEADING,\n OptionCategory.Connection\n);\n\nconst loginClientId = withHelpGroup(\n new Option(\n '--login-client-id <client-id>',\n 'Specify a custom OAuth2 client id. Mandatory with --browser and deployment types \"forgeops\" and \"classic\", optional for cloud.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst loginRedirectUri = withHelpGroup(\n new Option(\n '--login-redirect-uri <redirect-uri>',\n 'Specify a redirect URI for your custom OAuth2 client. When used with --browser, its port binds the local loopback listener, and the URI itself is sent to your OAuth2 provider verbatim.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\n// Experimental: the device-flow bug tracked in the browser-login plan doc\n// is still open, and cloud defaults to piggy-backing on Ping's own\n// AICMCPClient/AICMCPExchangeClient rather than a Frodo-owned OAuth2\n// client — see that plan's item 19 for the full rationale. Help-text badge\n// only (via withOptionStability()); no runtime warning is wired up yet,\n// since --browser/--device are global options usable on any command, and\n// where a runtime signal should live is still an open design question.\nconst browserLoginOption = withOptionStability(\n withHelpGroup(\n new Option(\n '--browser',\n 'Authenticate via an interactive browser login instead of providing a username/password on the command line.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n ),\n 'experimental'\n);\n\nconst deviceFlowOption = withOptionStability(\n withHelpGroup(\n new Option(\n '--device',\n 'Use the OAuth2 Device Authorization Grant. Useful for headless/SSH sessions with no local browser to launch.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n ),\n 'experimental'\n);\n\nconst noOpenOption = withHelpGroup(\n new Option(\n '--no-open',\n 'Print the browser-login URL instead of launching a local browser. Ignored without --browser.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\n// A connection profile can hold more than one configured credential at once\n// (e.g. both a service account and a plain username/password, or a cached\n// browser-login session alongside either) — without this, an implicit\n// command's credential resolution always follows a fixed priority order\n// (cached browser session if nothing else is requested, then service\n// account, then plain user, then Amster) with no way to override it for\n// one invocation. An absolute override: wins even over a saved\n// --preferred-credential preference. 'browser' means \"use my cached\n// browser-login session, and fail clearly rather than fall back to\n// something else if none is valid\" — it never launches a fresh interactive\n// login itself; that's what --browser/--device are for.\nconst credentialOption = withHelpGroup(\n new Option(\n '--credential <type>',\n \"Force this one invocation to use a specific configured credential, overriding ambient browser-session reuse and any saved --preferred-credential preference. 'browser' reuses a cached browser-login session (fails clearly if none is valid; never starts a fresh interactive login).\"\n ).choices(['user', 'svcacct', 'amster', 'browser']),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\n// Explicit, persisted preference for which credential type later implicit\n// commands against this profile should use — replaces the old\n// --default-credential entirely (it couldn't express \"prefer browser\",\n// since browser-login persistence was a separate, ambient-state-derived\n// mechanism — see AuthenticateOps.ts's/ConnectionProfileOps.ts's\n// preferredCredential remarks for the full history). Unlike --credential\n// above (a one-shot per-invocation override), this is durable: it applies\n// to every future implicit command against this host, not just one\n// invocation. Only added explicitly by the commands that persist a\n// profile (conn-save.ts, login.ts) — not part of defaultOpts, since it's\n// meaningless without --save.\nexport const preferredCredentialOption = withHelpGroup(\n new Option(\n '--preferred-credential <type>',\n \"Explicit, persisted preference for which credential type later implicit commands against this host should use — 'browser' means always launch/reuse an interactive browser login; the other three narrow a profile with more than one non-interactive credential configured. Unlike --credential, applies to every future implicit command against this host, not just one invocation.\"\n ).choices(['user', 'svcacct', 'amster', 'browser']),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\n// Deprecated in favor of the more general --credential above (equivalent to\n// --credential user) — kept working for backward compatibility, planned for\n// removal at the next major release.\nconst forceLoginAsUserOption = withOptionStability(\n withHelpGroup(\n new Option(\n '--force-login-as-user',\n 'Force a plain username/password login even if the resolved connection profile also has a service account or Amster credential configured. Deprecated: use --credential user instead.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n ),\n 'deprecated'\n);\n\nconst serviceAccountIdOption = withHelpGroup(\n new Option('--sa-id <sa-id>', 'Service account id.'),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst serviceAccountJwkFileOption = withHelpGroup(\n new Option(\n '--sa-jwk-file <file>',\n 'File containing the JSON Web Key (JWK) associated with the the service account.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst amsterPrivateKeyPassphraseOption = withHelpGroup(\n new Option(\n '--passphrase <passphrase>',\n 'The passphrase for the Amster private key if it is encrypted.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst amsterPrivateKeyFileOption = withHelpGroup(\n new Option(\n '--private-key <file>',\n 'File containing the private key for authenticating with Amster. Supported formats include PEM (both PKCS#1 and PKCS#8 variants), OpenSSH, DNSSEC, and JWK.'\n ),\n AUTHENTICATION_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst deploymentOption = withHelpGroup(\n new Option(\n '-m, --type <type>',\n 'Override auto-detected deployment type. Valid values for type: \\n\\\nclassic: A classic Access Management-only deployment with custom layout and configuration. \\n\\\ncloud: A ForgeRock Identity Cloud environment. \\n\\\nforgeops: A ForgeOps CDK or CDM deployment. \\n\\\nThe detected or provided deployment type controls certain behavior like obtaining an Identity \\\nManagement admin token or not and whether to export/import referenced email templates or how \\\nto walk through the tenant admin login flow of Identity Cloud and handle MFA'\n ).choices(DEPLOYMENT_TYPES),\n CONNECTION_OPTIONS_HEADING,\n OptionCategory.Connection\n);\n\nconst directoryOption = withHelpGroup(\n new Option(\n '-D, --directory <directory>',\n 'Set the working directory.'\n ).default(undefined, 'undefined'),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\nconst envOption = withHelpGroup(\n new ListOption(\n '-E, --env <key=value>',\n 'Set an environment variable for placeholder resolution. May be specified multiple times. Overrides values from --env-file.'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\nconst envFileOption = withHelpGroup(\n new ListOption(\n '--env-file <file>',\n 'Read environment variables from a file for placeholder resolution. May be specified multiple times; later files override earlier ones.'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\nconst forceUpdateOption = withHelpGroup(\n new Option(\n '-F, --force-update',\n 'When used, will force imports/updates to occur even if there are no changes made. Supported commands: authz, esv, script, config for configurations of the previous commands, and the config-manager equivalents of previous commands.'\n ).default(false),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\n// The prompting switch (see docs/INTERACTIVE-COMMANDS.md):\n// commander's dual negation pair -- TWO options sharing the `prompt`\n// attribute: --prompt sets it true (and, per the resolver, marks the\n// session explicitly interactive: the flow runs even when nothing is\n// missing, opening the options editor), --no-prompt sets it false (the\n// opt-out: fail with the classic errors instead of prompting, even on a\n// TTY). Unset (undefined) = prompting allowed when input is missing, as\n// since the interactive layer landed. FRODO_NO_PROMPT is honored process-wide alongside (see\n// PromptGate).\n// Do NOT chain .default(false) here -- that would read as \"prompting\n// disabled by default\" and disable the whole feature (caught in review\n// of the first cut).\nconst promptOption = withHelpGroup(\n new Option(\n '--prompt',\n 'Run the interactive flow even when nothing is missing: open the options editor for this invocation (unset options keep their defaults).'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\nconst noPromptOption = withHelpGroup(\n new Option(\n '--no-prompt',\n 'Never prompt for missing input; fail with the usual errors instead (same as setting FRODO_NO_PROMPT).'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\n// Persistent per-command defaults (docs/INTERACTIVE-COMMANDS.md):\n// pairs with --prompt -- after the options editor commits values, they\n// are saved to ~/.frodo/Defaults.json under this command's path and\n// become the starting values for FUTURE runs (precedence: an explicit\n// flag or env var on a later invocation still wins). A no-op without\n// the editor (--prompt or guided mode) -- there is nothing to save.\nconst saveDefaultsOption = withHelpGroup(\n new Option(\n '--save-defaults',\n \"With --prompt: save the options you commit in the editor as this command's defaults for future runs (~/.frodo/Defaults.json).\"\n ).default(false),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\n// --edit RETIRED: the invocation editor now triggers on\n// an explicit --prompt (or the persisted guided-mode toggle,\n// `frodo settings guided`) instead of its own flag. commander rejects\n// --edit as an unknown option on its own; the 'edit' entries in the\n// editor/serializer machinery lists (EditableOptions, CommandPreview)\n// stay as defense-in-depth.\n\nconst insecureOption = withHelpGroup(\n new Option(\n '-k, --insecure',\n 'Allow insecure connections when using SSL/TLS, including expired certificates.'\n ).default(false, \"Don't allow insecure connections\"),\n CONNECTION_OPTIONS_HEADING,\n OptionCategory.Connection\n);\n\nconst verboseOption = withHelpGroup(\n new Option(\n '--verbose',\n 'Verbose output during command execution. If specified, may or may not produce additional output.'\n ),\n OUTPUT_OPTIONS_HEADING,\n OptionCategory.Output\n);\n\nconst debugOption = withHelpGroup(\n new Option(\n '--debug',\n 'Debug output during command execution. If specified, may or may not produce additional output helpful for troubleshooting.'\n ),\n OUTPUT_OPTIONS_HEADING,\n OptionCategory.Output\n);\n\nconst curlirizeOption = withHelpGroup(\n new Option('--curlirize', 'Output all network calls in curl format.'),\n OUTPUT_OPTIONS_HEADING,\n OptionCategory.Output\n);\n\n// Categorized as Authentication (not Runtime, despite rendering under\n// \"Runtime Options:\") since it only means anything relative to a token\n// cache — `{ local: true }` commands that never call getTokens() have\n// nothing to flush/disable, so this should be omitted alongside the rest of\n// Authentication, not kept just because its heading differs.\nconst noCacheOption = withHelpGroup(\n new Option('--no-cache', 'Disable token cache for this operation.'),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst useRealmPrefixOnManagedObjects = withHelpGroup(\n new Option(\n '--use-realm-prefix-on-managed-objects',\n 'Set to true if you want to use the realm name as a prefix on managed object configuration, e.g. managed/alpha_user,\\\n managed/alpha_application or managed/bravo_organization. When false, the default behaviour of using managed/user \\\n etc. is retained. \\\n This option is ignored when the deployment type is \"cloud\".'\n ),\n CONNECTION_OPTIONS_HEADING,\n OptionCategory.Connection\n);\n\n// See noCacheOption's comment above — same reasoning applies here.\nconst flushCacheOption = withHelpGroup(\n new Option('--flush-cache', 'Flush token cache.'),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Authentication\n);\n\nconst retryOption = withHelpGroup(\n new Option(\n '--retry <strategy>',\n `Retry failed operations. Valid values for strategy: \\n\\\neverything: Retry all failed operations. \\n\\\nnetwork: Retry only network-related failed operations. \\n\\\nnothing: Do not retry failed operations. \\n\\\nThe selected retry strategy controls how the CLI handles failures.`\n )\n .choices(RETRY_STRATEGIES)\n .default(`${RETRY_NOTHING_KEY}`, `Do not retry failed operations.`),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n);\n\n/**\n * Default positional arguments added to every `FrodoCommand` unless omitted.\n *\n * To add a new global/default argument:\n * 1) Define it near other `Argument` declarations.\n * 2) Add it to this array.\n * 3) Add state behavior in `stateMap` if needed.\n * 4) Add env var metadata in `environmentVariables` if there is an override.\n */\nconst defaultArgs = [\n hostArgument,\n realmArgument,\n usernameArgument,\n passwordArgument,\n];\n\n/**\n * Default options added to every `FrodoCommand` unless explicitly omitted.\n *\n * To add a new global/default option:\n * 1) Define the `Option` above and assign a help group and category via\n * `withHelpGroup(option, heading, category)`. The category decides\n * whether `{ local: true }` commands (see FrodoCommand's constructor)\n * get it or not — pick Authentication/Connection deliberately, not just\n * whichever heading looks right for display.\n * 2) Add it to this array.\n * 3) Add its behavior to `stateMap` if it should update shared runtime state.\n * 4) Add corresponding env var metadata in `environmentVariables` if applicable.\n * 5) If deployment-specific, add mapping in `getOptionAppliesToTypes(...)`.\n */\nconst defaultOpts = [\n idmHostOption,\n loginClientId,\n loginRedirectUri,\n browserLoginOption,\n deviceFlowOption,\n noOpenOption,\n credentialOption,\n forceLoginAsUserOption,\n serviceAccountIdOption,\n serviceAccountJwkFileOption,\n amsterPrivateKeyPassphraseOption,\n amsterPrivateKeyFileOption,\n deploymentOption,\n directoryOption,\n insecureOption,\n verboseOption,\n debugOption,\n curlirizeOption,\n noCacheOption,\n flushCacheOption,\n retryOption,\n useRealmPrefixOnManagedObjects,\n envOption,\n envFileOption,\n forceUpdateOption,\n promptOption,\n noPromptOption,\n saveDefaultsOption,\n];\n\n/**\n * Maps default argument/option names to state mutators.\n *\n * This is the central place to wire runtime side effects for default CLI\n * arguments and options. When introducing a new default argument/option,\n * add an entry here if it needs to mutate shared state.\n */\nconst stateMap = {\n [hostArgument.name()]: (host: string) => state.setHost(host),\n [realmArgument.name()]: (realm: string) => state.setRealm(realm),\n [usernameArgument.name()]: (username: string) => state.setUsername(username),\n [passwordArgument.name()]: (password: string) => state.setPassword(password),\n [idmHostOption.attributeName()]: (idmHost: string) =>\n state.setIdmHost(idmHost),\n [loginClientId.attributeName()]: (clientId: string) =>\n state.setAdminClientId(clientId),\n [loginRedirectUri.attributeName()]: (redirectUri: string) =>\n state.setAdminClientRedirectUri(redirectUri),\n [browserLoginOption.attributeName()]: (useBrowser: boolean) => {\n if (useBrowser) state.setAuthMode('interactive');\n },\n [deviceFlowOption.attributeName()]: (useDevice: boolean) => {\n if (useDevice) {\n state.setAuthMode('interactive');\n setUseDeviceFlow(true);\n }\n },\n [noOpenOption.attributeName()]: (open: boolean) => {\n if (!open) setOpenBrowser(false);\n },\n [forceLoginAsUserOption.attributeName()]: (force: boolean) => {\n if (force) setForceLoginAsUser(true);\n },\n [credentialOption.attributeName()]: (type: CredentialOverrideType) =>\n setCredentialOverride(type),\n [serviceAccountIdOption.attributeName()]: (saId: string) =>\n state.setServiceAccountId(saId),\n [serviceAccountJwkFileOption.attributeName()]: (file: string) => {\n try {\n const data = fs.readFileSync(file);\n const jwk = JSON.parse(data.toString());\n state.setServiceAccountJwk(jwk);\n } catch (error) {\n printMessage(\n `Error parsing JWK from file ${file}: ${error.message}`,\n 'error'\n );\n }\n },\n [amsterPrivateKeyPassphraseOption.attributeName()]: (passphrase: string) => {\n // This is needed in the case the passphrase is an option, but the private key is an environment variable.\n process.env.FRODO_AMSTER_PASSPHRASE = passphrase;\n },\n [amsterPrivateKeyFileOption.attributeName()]: (\n file: string,\n options: Record<string, string | boolean>\n ) => {\n const passphrase =\n (options[amsterPrivateKeyPassphraseOption.attributeName()] as string) ||\n process.env.FRODO_AMSTER_PASSPHRASE;\n try {\n // Store as PEM format (PKCS#8 variant specifically) since Jose supports PEM and since PKCS#8 supports more algorithms than PKCS#1\n state.setAmsterPrivateKey(\n convertPrivateKeyToPem(\n fs.readFileSync(file, 'utf8'),\n passphrase,\n file\n .replaceAll('\\\\', '/')\n .substring(file.replaceAll('\\\\', '/').lastIndexOf('/') + 1)\n )\n );\n } catch (error) {\n printMessage(\n `Error parsing private key from file ${file}: ${error.message}`,\n 'error'\n );\n }\n },\n [deploymentOption.attributeName()]: (type: string) =>\n state.setDeploymentType(type),\n [directoryOption.attributeName()]: (directory: string) =>\n state.setDirectory(directory.replaceAll('\\\\', '/').replaceAll('C:', '')),\n [insecureOption.attributeName()]: (insecure: boolean) =>\n state.setAllowInsecureConnection(insecure),\n [verboseOption.attributeName()]: (verbose: boolean) =>\n state.setVerbose(verbose),\n [debugOption.attributeName()]: (debug: boolean) => state.setDebug(debug),\n [curlirizeOption.attributeName()]: (curlirize: boolean) =>\n state.setCurlirize(curlirize),\n [noCacheOption.attributeName()]: (cache: boolean) =>\n state.setUseTokenCache(cache),\n [useRealmPrefixOnManagedObjects.attributeName()]: () =>\n state.setUseRealmPrefixOnManagedObjects(true),\n [flushCacheOption.attributeName()]: (flush: boolean) => {\n if (flush) frodo.cache.flush();\n },\n [retryOption.attributeName()]: (strategy: RetryStrategy) => {\n state.setAxiosRetryStrategy(strategy);\n },\n [envFileOption.attributeName()]: (files: string[]) => {\n for (const filePath of files) {\n try {\n propertiesReader({ sourceFile: filePath }).each(\n (key: string, value: number | boolean | string) => {\n // env-file values are strings by definition; coerce the reader's\n // numeric/boolean guesses back (properties-reader v3 widened the\n // .each callback's value type to `Value`).\n state.setEnv(key, String(value));\n }\n );\n } catch (error) {\n throw new FrodoError(`Error parsing env file ${filePath}`, error);\n }\n }\n },\n [envOption.attributeName()]: (envs: string[]) => {\n for (const env of envs) {\n const separatorIndex = env.indexOf('=');\n if (separatorIndex < 0) {\n throw new FrodoError(\n `Invalid env format; expected \"key=value\" but got \"${env}\"`\n );\n }\n state.setEnv(\n env.substring(0, separatorIndex),\n env.substring(separatorIndex + 1)\n );\n }\n },\n [forceUpdateOption.attributeName()]: (forceUpdate: boolean) =>\n state.setForceUpdate(forceUpdate),\n};\n\n/**\n * Re-applies the stateMap handlers for the options the invocation\n * editor committed AFTER the action body's own\n * handleDefaultArgsAndOpts copy ran -- the editor can open from inside\n * getTokens (a picker's -> key), which is after that copy, so options\n * like --curlirize/--debug/--verbose committed there reached the\n * command object but never frodo-lib's state (user report 2026-10-13:\n * --curlirize selected in the editor produced no curl output). Called\n * from the resolution pass (lazy import -- the cycle resolver ->\n * FrodoCommand is otherwise static). Only options carrying a\n * user-authored value (source 'cli') replay; the host/realm/user/\n * password entries are SKIPPED -- the resolver owns connection state\n * and re-feeding those would clobber a resolved connection.\n */\nexport function replayEditorOptionStates(command: Command): void {\n const skip = new Set(['host', 'realm', 'username', 'password']);\n for (const option of command.options) {\n const name = option.attributeName();\n if (skip.has(name)) continue;\n if (Object.keys(stateMap).includes(name)) {\n const value = command.getOptionValue(name);\n if (value === undefined || value === false || value === '') continue;\n if (command.getOptionValueSource(name) !== 'cli') continue;\n const handler: any = stateMap[name];\n handler(value, command.opts());\n }\n }\n}\n\n/**\n * Registry of environment variables shown in `-hhh` help.\n *\n * This list drives display only; runtime behavior is still controlled by\n * command handlers and `stateMap`. Keep descriptions in sync with the\n * corresponding option/argument override semantics.\n */\nconst environmentVariables: EnvironmentVariableDescriptor[] = [\n {\n name: 'FRODO_HOST',\n description: \"AM base URL. Overridden by 'host' argument.\",\n group: CONNECTION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) => command.hasDefaultArgument('host'),\n },\n {\n name: 'FRODO_IDM_HOST',\n description: \"IDM base URL. Overridden by '--idm-host' option.\",\n group: CONNECTION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(idmHostOption.attributeName()),\n },\n {\n name: 'FRODO_REALM',\n description: \"Realm. Overridden by 'realm' argument.\",\n group: CONNECTION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) => command.hasDefaultArgument('realm'),\n },\n {\n name: 'FRODO_USERNAME',\n description: \"Username. Overridden by 'username' argument.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) => command.hasDefaultArgument('username'),\n },\n {\n name: 'FRODO_PASSWORD',\n description: \"Password. Overridden by 'password' argument.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) => command.hasDefaultArgument('password'),\n },\n {\n name: 'FRODO_LOGIN_CLIENT_ID',\n description:\n \"OAuth2 client id for IDM API calls, and (mandatory on forgeops/classic) for --browser login. Overridden by '--login-client-id' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n appliesToTypes: [\n constants.CLOUD_DEPLOYMENT_TYPE_KEY,\n constants.FORGEOPS_DEPLOYMENT_TYPE_KEY,\n ],\n include: (command) =>\n command.hasDefaultOption(loginClientId.attributeName()),\n },\n {\n name: 'FRODO_LOGIN_REDIRECT_URI',\n description:\n \"Redirect URI for your custom OAuth2 client, shared by the synthetic IDM-scoped login flow (default: '<host>/platform/appAuthHelperRedirect.html') and --browser login (default: an OS-assigned ephemeral port). Overridden by '--login-redirect-uri' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n appliesToTypes: [\n constants.CLOUD_DEPLOYMENT_TYPE_KEY,\n constants.FORGEOPS_DEPLOYMENT_TYPE_KEY,\n ],\n include: (command) =>\n command.hasDefaultOption(loginRedirectUri.attributeName()),\n },\n {\n name: 'FRODO_BROWSER_LOGIN',\n description:\n \"Authenticate via an interactive browser login instead of a username/password. Overridden by '--browser' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(browserLoginOption.attributeName()),\n },\n {\n name: 'FRODO_LOGIN_DEVICE_FLOW',\n description:\n \"Use the OAuth2 Device Authorization Grant for browser login. Overridden by '--device' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(deviceFlowOption.attributeName()),\n },\n {\n name: 'FRODO_BROWSER_LOGIN_NO_OPEN',\n description:\n \"Print the browser-login URL instead of launching a local browser. Overridden by '--no-open' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(noOpenOption.attributeName()),\n },\n {\n name: 'FRODO_CREDENTIAL',\n description:\n \"Force this one invocation to use a specific configured credential ('user', 'svcacct', 'amster', or 'browser'). Overridden by '--credential' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(credentialOption.attributeName()),\n },\n {\n name: 'FRODO_FORCE_LOGIN_AS_USER',\n description:\n \"Deprecated: use FRODO_CREDENTIAL=user instead. Force a plain username/password login even if the resolved connection profile also has a service account or Amster credential configured. Overridden by '--force-login-as-user' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(forceLoginAsUserOption.attributeName()),\n },\n {\n name: 'FRODO_SA_ID',\n description: \"Service account uuid. Overridden by '--sa-id' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'cloud-only',\n include: (command) =>\n command.hasDefaultOption(serviceAccountIdOption.attributeName()),\n },\n {\n name: 'FRODO_SA_JWK',\n description:\n \"Service account JWK. Overridden by '--sa-jwk-file' option but takes the actual JWK as a value, not a file name.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'cloud-only',\n include: (command) =>\n command.hasDefaultOption(serviceAccountJwkFileOption.attributeName()),\n },\n {\n name: 'FRODO_AMSTER_PASSPHRASE',\n description:\n \"Passphrase for the Amster private key if it is encrypted. Overridden by '--passphrase' option.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'classic-only',\n include: (command) =>\n command.hasDefaultOption(\n amsterPrivateKeyPassphraseOption.attributeName()\n ),\n },\n {\n name: 'FRODO_AMSTER_PRIVATE_KEY',\n description:\n \"Amster private key. Overridden by '--private-key' option but takes the actual private key as a value (i.e. the file contents), not a file name. Supported formats include PEM (both PKCS#1 and PKCS#8 variants), OpenSSH, DNSSEC, and JWK.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'classic-only',\n include: (command) =>\n command.hasDefaultOption(amsterPrivateKeyFileOption.attributeName()),\n },\n {\n name: 'FRODO_NO_CACHE',\n description: \"Disable token cache. Same as '--no-cache' option.\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) =>\n command.hasDefaultOption(noCacheOption.attributeName()),\n },\n {\n name: 'FRODO_TOKEN_CACHE_PATH',\n description:\n \"Use this token cache file instead of '~/.frodo/TokenCache.json'.\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_CONNECTION_PROFILES_PATH',\n description:\n \"Use this connection profiles file instead of '~/.frodo/Connections.json'.\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_AUTHENTICATION_SERVICE',\n description:\n \"Name of a login journey to use. When using an Amster private key, specifies which journey to use for Amster authentication as opposed to the default 'amsterService' journey.\",\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_AUTHENTICATION_HEADER_OVERRIDES',\n description:\n 'Map of headers: \\'{\"host\":\"am.example.com:8081\"}\\'. These headers are sent with all requests and can be used to override default behavior, for example to set a custom host header for Proxy Connect-protected PingOne Advanced Identity Cloud environments.',\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_CONFIGURATION_HEADER_OVERRIDES',\n description:\n 'Map of headers: \\'{\"X-Configuration-Type\":\"mutable\"}\\'. These headers are sent with all configuration requests and can be used to override default behavior, for example to set a custom configuration header for mutable PingOne Advanced Identity Cloud environments.',\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_DEBUG',\n description: \"Set to any value to enable debug output. Same as '--debug'.\",\n group: OUTPUT_ENVIRONMENT_VARIABLES_HEADING,\n include: (command) => command.hasDefaultOption(debugOption.attributeName()),\n },\n {\n name: 'FRODO_IGA',\n description:\n 'Set to \"true\" to enable IGA (Identity Governance) endpoints for cloud deployments, or \"false\" to disable them, overriding auto-detected value.',\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'cloud-only' as DeploymentScope,\n },\n {\n name: 'FRODO_MASTER_KEY_PATH',\n description:\n \"Use this master key file instead of '~/.frodo/masterkey.key' file.\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_MASTER_KEY',\n description:\n \"Use this master key instead of what's in '~/.frodo/masterkey.key'. Takes precedence over FRODO_MASTER_KEY_PATH.\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_NO_PROMPT',\n description:\n \"Never prompt for missing input; fail with the usual errors instead (same as '--no-prompt').\",\n group: RUNTIME_ENVIRONMENT_VARIABLES_HEADING,\n },\n {\n name: 'FRODO_LOG_KEY',\n description: 'Log API key.',\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'cloud-only',\n variants: [\n {\n description: \"Overridden by '--log-api-key' option.\",\n appliesTo: '`frodo conn save`',\n commandNames: ['frodo conn save'],\n },\n {\n description: \"Overridden by 'username' argument.\",\n appliesTo: '`frodo log` commands',\n include: (command) => command.name().startsWith('frodo log'),\n },\n ],\n },\n {\n name: 'FRODO_LOG_SECRET',\n description: 'Log API secret.',\n group: AUTHENTICATION_ENVIRONMENT_VARIABLES_HEADING,\n scope: 'cloud-only',\n variants: [\n {\n description: \"Overridden by '--log-api-secret' option.\",\n appliesTo: '`frodo conn save`',\n commandNames: ['frodo conn save'],\n },\n {\n description: \"Overridden by 'password' argument.\",\n appliesTo: '`frodo log` commands',\n include: (command) => command.name().startsWith('frodo log'),\n },\n ],\n },\n];\n\nconst longestEnvironmentVariableNameLength = Math.max(\n ...environmentVariables.map(({ name }) => name.length)\n);\nconst environmentVariableDescriptionColumn =\n ENVIRONMENT_VARIABLE_NAME_INDENT +\n longestEnvironmentVariableNameLength +\n ENVIRONMENT_VARIABLE_DESCRIPTION_PADDING;\n\n/**\n * Checks whether a variant line applies to the current command.\n * @param variant Variant metadata under an env var descriptor.\n * @param command Command being rendered.\n * @returns True when variant should be included.\n */\nfunction matchesEnvironmentVariableVariant(\n variant: VariantDescriptor,\n command: FrodoCommand\n) {\n if (variant.commandNames && !variant.commandNames.includes(command.name())) {\n return false;\n }\n\n if (variant.include) {\n return variant.include(command);\n }\n\n return true;\n}\n\n/**\n * Checks whether an environment variable descriptor applies to the current\n * command.\n * @param entry Environment variable descriptor.\n * @param command Command being rendered.\n * @returns True when descriptor should be included.\n */\nfunction matchesEnvironmentVariableEntry(\n entry: EnvironmentVariableDescriptor,\n command: FrodoCommand\n) {\n if (entry.commandNames && !entry.commandNames.includes(command.name())) {\n return false;\n }\n\n if (entry.include) {\n return entry.include(command);\n }\n\n return true;\n}\n\n/**\n * Computes effective wrapping width for help output.\n * @returns Terminal-aware text width with sane minimum fallback.\n */\nfunction getHelpTextWidth() {\n const envWidth = Number.parseInt(process.env.COLUMNS || '', 10);\n const terminalWidth = Number.isNaN(envWidth)\n ? process.stdout.columns\n : envWidth;\n\n return Math.max(terminalWidth || DEFAULT_HELP_WIDTH, MINIMUM_HELP_WIDTH);\n}\n\n/**\n * Wraps a help description preserving hanging indentation.\n * @param prefix Prefix for first line and width anchor for continuation lines.\n * @param text Description text to wrap.\n * @returns Wrapped lines ready to join with newlines.\n */\nfunction wrapHelpText(prefix: string, text: string) {\n if (!text) {\n return [prefix.trimEnd()];\n }\n\n const continuationPrefix = ' '.repeat(prefix.length);\n const availableWidth = Math.max(20, getHelpTextWidth() - prefix.length);\n const words = text.split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n const candidate = currentLine ? `${currentLine} ${word}` : word;\n\n if (currentLine && candidate.length > availableWidth) {\n lines.push(currentLine);\n currentLine = word;\n continue;\n }\n\n currentLine = candidate;\n }\n\n if (currentLine) {\n lines.push(currentLine);\n }\n\n return lines.map(\n (line, index) => `${index === 0 ? prefix : continuationPrefix}${line}`\n );\n}\n\n/**\n * Builds aligned prefix for environment variable name column.\n * @param name Environment variable name.\n * @param extraIndent Additional left indentation.\n * @returns Formatted prefix including spacing before description column.\n */\nfunction formatEnvironmentVariablePrefix(name: string, extraIndent = 0) {\n const nameIndent = ENVIRONMENT_VARIABLE_NAME_INDENT + extraIndent;\n const trailingPadding = Math.max(\n 1,\n environmentVariableDescriptionColumn - nameIndent - name.length\n );\n\n return `${' '.repeat(nameIndent)}${name}${' '.repeat(trailingPadding)}`;\n}\n\n/**\n * Builds prefix for env var variant bullet lines.\n * @param extraIndent Additional left indentation.\n * @returns Prefix aligned with env var description column.\n */\nfunction formatEnvironmentVariableVariantPrefix(extraIndent = 0) {\n return `${' '.repeat(formatEnvironmentVariablePrefix('', extraIndent).length)}- `;\n}\n\n/**\n * Formats one env var entry and optional variant lines into wrapped output.\n * @param entry Env var descriptor.\n * @param variants Variant rows to render.\n * @param extraIndent Additional left indentation.\n * @returns Rendered text lines.\n */\nfunction formatEnvironmentVariableEntry(\n entry: EnvironmentVariableDescriptor,\n variants: VariantDescriptor[],\n extraIndent = 0\n) {\n if (!variants.length) {\n return wrapHelpText(\n formatEnvironmentVariablePrefix(entry.name, extraIndent),\n entry.description\n );\n }\n\n const variantLines = variants.map((variant) => {\n const appliesToPrefix = variant.appliesTo ? `(${variant.appliesTo}) ` : '';\n return wrapHelpText(\n formatEnvironmentVariableVariantPrefix(extraIndent),\n `${appliesToPrefix}${variant.description}`\n );\n });\n\n return [\n ...wrapHelpText(\n formatEnvironmentVariablePrefix(entry.name, extraIndent),\n entry.description\n ),\n ...variantLines.flat(),\n ];\n}\n\ntype GroupData = {\n unscoped: string[];\n scoped: Map<string, string[]>;\n};\n\ntype OptionGroupData = {\n unscoped: Option[];\n scoped: Map<DeploymentScope, Option[]>;\n};\ntype CommandWithTypes = Command & { types?: string[] };\n\n/**\n * Converts a rendering scope (e.g. `cloud-only`) back to canonical\n * deployment type key (e.g. `cloud`).\n * @param scope Scoped token used by help renderer.\n * @returns Canonical deployment type key.\n */\nfunction getDeploymentTypeForScope(scope: DeploymentScope): string {\n switch (scope) {\n case 'classic-only':\n return constants.CLASSIC_DEPLOYMENT_TYPE_KEY;\n case 'cloud-only':\n return constants.CLOUD_DEPLOYMENT_TYPE_KEY;\n case 'forgeops-only':\n return constants.FORGEOPS_DEPLOYMENT_TYPE_KEY;\n }\n}\n\n/**\n * Returns whether a scoped env var/section should be rendered for the\n * current command's supported deployment types.\n * @param scope Deployment scope being evaluated.\n * @param supportedTypes Command-supported deployment types.\n * @returns True when scope is compatible.\n */\nfunction isScopeSupported(\n scope: DeploymentScope,\n supportedTypes?: string[]\n): boolean {\n if (!supportedTypes || supportedTypes.length === 0) {\n return true;\n }\n return supportedTypes.includes(getDeploymentTypeForScope(scope));\n}\n\n/**\n * Returns whether an env var entry is generally compatible with command\n * deployment types based on `appliesToTypes` metadata.\n * @param entry Env var descriptor.\n * @param supportedTypes Command-supported deployment types.\n * @returns True when entry should be considered for rendering.\n */\nfunction isEntrySupportedByTypes(\n entry: EnvironmentVariableDescriptor,\n supportedTypes?: string[]\n): boolean {\n if (!supportedTypes || supportedTypes.length === 0) {\n return true;\n }\n\n if (!entry.appliesToTypes || entry.appliesToTypes.length === 0) {\n return true;\n }\n\n return entry.appliesToTypes.some((type) => supportedTypes.includes(type));\n}\n\n/**\n * Helper used to switch between flat output (single deployment type) and\n * scoped sub-sections (mixed deployment types).\n * @param types Deployment type list.\n * @returns True when exactly one deployment type is supported.\n */\nfunction isSingleDeploymentType(types?: string[]): boolean {\n return !!types && types.length === 1;\n}\n\n/**\n * Collects env var lines grouped by top-level section and optional\n * deployment scope.\n *\n * Extension guidance:\n * - Prefer adding metadata to `environmentVariables` instead of custom logic.\n * - Only add conditional code here when metadata cannot express the behavior.\n * @param command Command context for include predicates.\n * @param includeAll When true, bypass command include filters.\n * @param supportedTypes Deployment types for stub/global rendering.\n * @returns Grouped env var lines by top-level group and deployment scope.\n */\nfunction collectEnvironmentVariableGroups(\n command?: FrodoCommand,\n includeAll = false,\n supportedTypes?: string[]\n) {\n const groupedEntries = new Map<string, GroupData>();\n const effectiveTypes = command?.types || supportedTypes;\n\n function getOrCreate(group: string): GroupData {\n let data = groupedEntries.get(group);\n if (!data) {\n data = { unscoped: [], scoped: new Map() };\n groupedEntries.set(group, data);\n }\n return data;\n }\n\n for (const entry of environmentVariables) {\n if (!isEntrySupportedByTypes(entry, effectiveTypes)) {\n continue;\n }\n\n if (entry.scope && !isScopeSupported(entry.scope, effectiveTypes)) {\n continue;\n }\n\n // Scoped entries are rendered as top-level deployment-prefixed groups,\n // so no extra indentation is needed.\n const extraIndent = 0;\n\n if (entry.variants) {\n const matchingVariants =\n includeAll || !command\n ? entry.variants\n : entry.variants.filter((variant) =>\n matchesEnvironmentVariableVariant(variant, command)\n );\n\n if (!matchingVariants.length) {\n continue;\n }\n\n const groupData = getOrCreate(entry.group);\n const formatted = formatEnvironmentVariableEntry(\n entry,\n matchingVariants,\n extraIndent\n );\n\n if (entry.scope) {\n const scopeEntries = groupData.scoped.get(entry.scope) || [];\n scopeEntries.push(...formatted);\n groupData.scoped.set(entry.scope, scopeEntries);\n } else {\n groupData.unscoped.push(...formatted);\n }\n continue;\n }\n\n if (\n command &&\n !includeAll &&\n !matchesEnvironmentVariableEntry(entry, command)\n ) {\n continue;\n }\n\n const groupData = getOrCreate(entry.group);\n const formatted = formatEnvironmentVariableEntry(entry, [], extraIndent);\n\n if (entry.scope) {\n const scopeEntries = groupData.scoped.get(entry.scope) || [];\n scopeEntries.push(...formatted);\n groupData.scoped.set(entry.scope, scopeEntries);\n } else {\n groupData.unscoped.push(...formatted);\n }\n }\n\n return groupedEntries;\n}\n\n/**\n * Renders environment variable help with:\n * - deterministic top-level group ordering\n * - inline deployment labels for mixed deployment commands\n * - flat output for single deployment commands\n * @param groupedEntries Output of `collectEnvironmentVariableGroups`.\n * @param command Command context used for type resolution.\n * @param supportedTypes Deployment types used for stub/global rendering.\n * @returns Fully rendered environment variable section (or empty string).\n */\nfunction renderEnvironmentVariableGroups(\n groupedEntries: Map<string, GroupData>,\n command?: FrodoCommand,\n supportedTypes?: string[]\n) {\n const effectiveTypes = command?.types || supportedTypes;\n const isSingleType = isSingleDeploymentType(effectiveTypes);\n\n const sections = environmentVariableGroupOrder.flatMap((group) => {\n const groupData = groupedEntries.get(group);\n if (!groupData) {\n return [];\n }\n\n const baseLines: string[] = [...groupData.unscoped];\n if (isSingleType) {\n for (const scope of environmentVariableScopeOrder) {\n const scopeEntries = groupData.scoped.get(scope);\n if (!scopeEntries || scopeEntries.length === 0) {\n continue;\n }\n baseLines.push(...scopeEntries);\n }\n } else {\n for (const scope of environmentVariableScopeOrder) {\n const scopeEntries = groupData.scoped.get(scope);\n if (!scopeEntries || scopeEntries.length === 0) {\n continue;\n }\n\n const deploymentType = getDeploymentTypeForScope(scope);\n baseLines.push('');\n baseLines.push(` (${toDeploymentOnlyLabel(deploymentType)}):`);\n baseLines.push(...scopeEntries);\n }\n }\n\n if (!baseLines.length) {\n return [];\n }\n\n return ['', ` ${group}`, ...baseLines];\n });\n\n if (!sections.length) {\n return '';\n }\n\n while (sections[0] === '') {\n sections.shift();\n }\n\n return `\\nEnvironment Variables:\\n\\n${sections.join('\\n')}\\n`;\n}\n\n/**\n * Generates a deployment type label for single-deployment-type commands.\n * @param command The command to check.\n * @returns Label like `Cloud-only` for single-type commands, otherwise empty.\n */\nfunction getDeploymentTypeLabel(command?: CommandWithTypes): string {\n if (!command || !command.types || command.types.length === 0) {\n return '';\n }\n\n if (command.types.length === 1) {\n return toDeploymentOnlyLabel(command.types[0]);\n }\n\n return '';\n}\n\n/**\n * Converts deployment keys to display labels.\n *\n * Use this to preserve canonical casing for known values (e.g. `ForgeOps`)\n * while still producing reasonable labels for future camelCase values.\n * @param type Canonical deployment type key.\n * @returns Human-friendly deployment display label.\n */\nfunction getDeploymentTypeDisplayLabel(type: string): string {\n switch (type) {\n case constants.CLASSIC_DEPLOYMENT_TYPE_KEY:\n return 'Classic';\n case constants.CLOUD_DEPLOYMENT_TYPE_KEY:\n return 'Cloud';\n case constants.FORGEOPS_DEPLOYMENT_TYPE_KEY:\n return 'ForgeOps';\n default:\n // Preserve existing camelCase/PascalCase beyond the first character.\n return `${type.charAt(0).toUpperCase()}${type.slice(1)}`;\n }\n}\n\n/**\n * Produces standardized deployment labels used in help output such as\n * `Cloud-only`, `Classic-only`, or `ForgeOps-only`.\n * @param type Canonical deployment type key.\n * @returns `Type-only` label for help rendering.\n */\nfunction toDeploymentOnlyLabel(type: string): string {\n return `${getDeploymentTypeDisplayLabel(type)}-only`;\n}\n\n/**\n * Maps deployment type keys to the corresponding scoped section token.\n * @param type Canonical deployment type key.\n * @returns Matching scope token or undefined when unsupported.\n */\nfunction getScopeForDeploymentType(type: string): DeploymentScope | undefined {\n switch (type) {\n case constants.CLASSIC_DEPLOYMENT_TYPE_KEY:\n return 'classic-only';\n case constants.CLOUD_DEPLOYMENT_TYPE_KEY:\n return 'cloud-only';\n case constants.FORGEOPS_DEPLOYMENT_TYPE_KEY:\n return 'forgeops-only';\n default:\n return undefined;\n }\n}\n\n/**\n * Determines whether an option should be rendered in a deployment-scoped\n * sub-section when a command supports multiple deployment types.\n * @param option Option to classify.\n * @param commandTypes Deployment types supported by the command.\n * @returns Scope token when option is single-type constrained.\n */\nfunction getSingleTypeScopeForOption(\n option: Option,\n commandTypes?: string[]\n): DeploymentScope | undefined {\n if (!commandTypes || commandTypes.length <= 1) {\n return undefined;\n }\n\n const appliesToTypes = getOptionAppliesToTypes(option);\n if (!appliesToTypes || appliesToTypes.length !== 1) {\n return undefined;\n }\n\n const onlyType = appliesToTypes[0];\n if (!commandTypes.includes(onlyType)) {\n return undefined;\n }\n\n return getScopeForDeploymentType(onlyType);\n}\n\n/**\n * Splits option list into unscoped and scoped subsets for inline help\n * rendering in `formatHelp`.\n * @param options Option list for one heading.\n * @param commandTypes Deployment types supported by the command.\n * @returns Option groups partitioned by scope.\n */\nfunction collectOptionGroupsByScope(\n options: Option[],\n commandTypes?: string[]\n): OptionGroupData {\n const grouped: OptionGroupData = {\n unscoped: [],\n scoped: new Map<DeploymentScope, Option[]>(),\n };\n\n for (const option of options) {\n const scope = getSingleTypeScopeForOption(option, commandTypes);\n if (!scope) {\n grouped.unscoped.push(option);\n continue;\n }\n\n const entries = grouped.scoped.get(scope) || [];\n entries.push(option);\n grouped.scoped.set(scope, entries);\n }\n\n return grouped;\n}\n\n/**\n * Determines whether a subcommand belongs to a single deployment-only\n * section in stub command help.\n * @param command Subcommand to classify.\n * @returns Scope token when subcommand is single-type constrained.\n */\n\n/**\n * Declares which deployment types each default option applies to.\n *\n * Update this when adding deployment-constrained default options so mixed\n * deployment help can render scoped sub-labels correctly.\n * @param option Default/global option.\n * @returns Deployment types for the option, or undefined when unscoped.\n */\nfunction getOptionAppliesToTypes(option: Option): string[] | undefined {\n // Keep this mapping aligned with option semantics. It is used only for help\n // rendering to decide when options should appear under scoped sub-labels.\n switch (option.name()) {\n case loginClientId.name():\n case loginRedirectUri.name():\n return [\n constants.CLOUD_DEPLOYMENT_TYPE_KEY,\n constants.FORGEOPS_DEPLOYMENT_TYPE_KEY,\n ];\n case serviceAccountIdOption.name():\n case serviceAccountJwkFileOption.name():\n return [constants.CLOUD_DEPLOYMENT_TYPE_KEY];\n case amsterPrivateKeyPassphraseOption.name():\n case amsterPrivateKeyFileOption.name():\n return [constants.CLASSIC_DEPLOYMENT_TYPE_KEY];\n default:\n return undefined;\n }\n}\n\n/**\n * Generates command-scoped environment variable help for leaf commands.\n * @param command Command being rendered.\n * @param includeAll When true, bypass command include filters.\n * @returns Rendered environment variable section.\n */\nfunction formatEnvironmentVariables(command: FrodoCommand, includeAll = false) {\n const groupedEntries = collectEnvironmentVariableGroups(\n command,\n includeAll,\n command.types\n );\n\n return renderEnvironmentVariableGroups(\n groupedEntries,\n command,\n command.types\n );\n}\n\n/**\n * Generates environment variable help for stub commands that aggregate\n * deployment support from their children.\n * @param supportedTypes Deployment types supported by child commands.\n * @returns Rendered environment variable section.\n */\nexport function formatGlobalEnvironmentVariables(supportedTypes?: string[]) {\n // Global help always shows scope headings (no specific command context)\n return renderEnvironmentVariableGroups(\n collectEnvironmentVariableGroups(undefined, false, supportedTypes),\n undefined,\n supportedTypes\n );\n}\n\nfunction getHelpLevel(argv: string[] = process.argv): 1 | 2 | 3 {\n if (argv.includes(HELP_ALL_SHORT_FLAG) || argv.includes(HELP_ALL_FLAG))\n return 3;\n if (argv.includes(HELP_MORE_SHORT_FLAG) || argv.includes(HELP_MORE_FLAG))\n return 2;\n return 1;\n}\n\nexport function isExpandedHelpRequested(argv: string[] = process.argv) {\n return getHelpLevel(argv) >= 2;\n}\n\nexport function isFullHelpRequested(argv: string[] = process.argv) {\n return getHelpLevel(argv) >= 3;\n}\n\nexport function normalizeExpandedHelpArgv(argv: string[] = process.argv) {\n const normalizedArgv: string[] = [];\n\n for (const token of argv) {\n if (token === HELP_ALL_SHORT_FLAG) {\n normalizedArgv.push(HELP_ALL_FLAG, '--help');\n } else if (token === HELP_MORE_SHORT_FLAG) {\n normalizedArgv.push(HELP_MORE_FLAG, '--help');\n } else {\n normalizedArgv.push(token);\n }\n }\n\n return normalizedArgv;\n}\n\nconst warnedStabilityCommands = new Set<string>();\n// Leaf commands whose interactive input resolution already ran (or is\n// running) this process. The preAction hook is registered on every\n// FrodoCommand in the ancestry and all receive the same actionCommand, so\n// without this the resolution would run once per ancestor. Also guards\n// against a re-entrant double-run if a hook ever fires twice for the same\n// command instance.\nconst resolvedActionCommands = new WeakSet<Command>();\nconst warnedStabilityOptions = new Set<string>();\n\n/**\n * Builds a user-facing command path for warnings/errors.\n * @param command Command instance.\n * @returns Command path, e.g. `frodo shell`.\n */\nfunction getCommandPath(command: Command): string {\n const names: string[] = [];\n let current: Command | null = command;\n while (current) {\n if (current.name()) {\n names.unshift(current.name());\n }\n current = current.parent || null;\n }\n return names.join(' ');\n}\n\n/**\n * Returns a user-facing identifier for an option.\n * @param option Option metadata.\n * @returns Preferred long flag or raw flags string.\n */\nfunction getOptionLabel(option: Option): string {\n return option.long || option.flags;\n}\n\n/**\n * Converts option name (`enable-preview`) into Commander attribute name.\n * @param optionName Dashed option name.\n * @returns CamelCase attribute key.\n */\nfunction toOptionAttributeName(optionName: string): string {\n return optionName.replace(/-([a-z])/g, (_m, c: string) => c.toUpperCase());\n}\n\n/**\n * Returns true if value is treated as enabled for opt-in checks.\n * @param value Value to evaluate.\n * @returns Truthy opt-in interpretation.\n */\nfunction isTruthyOptInValue(value: unknown): boolean {\n if (typeof value === 'boolean') {\n return value;\n }\n if (typeof value === 'string') {\n return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());\n }\n return false;\n}\n\n/**\n * Checks whether an opt-in gate has been satisfied.\n * @param command Command being executed.\n * @param gate Gate configuration.\n * @returns True when execution is allowed.\n */\nfunction isStabilityGateSatisfied(\n command: Command,\n gate: StabilityGateConfig\n): boolean {\n const mode = gate.mode || 'option-or-env';\n const optionName = gate.optionName || 'enable-preview';\n const envVarName = gate.envVarName || 'FRODO_ENABLE_PREVIEW';\n\n const options = command.optsWithGlobals<Record<string, unknown>>();\n const optionKey = toOptionAttributeName(optionName);\n const optionEnabled = isTruthyOptInValue(options?.[optionKey]);\n const envEnabled = isTruthyOptInValue(process.env[envVarName]);\n\n switch (mode) {\n case 'option-only':\n return optionEnabled;\n case 'env-only':\n return envEnabled;\n default:\n return optionEnabled || envEnabled;\n }\n}\n\n/**\n * Returns whether an option was explicitly supplied or otherwise set from a\n * non-default source.\n * @param command Command being executed.\n * @param option Option to inspect.\n * @returns True when option value source is non-default.\n */\nfunction isOptionUsed(command: Command, option: Option): boolean {\n const source = command.getOptionValueSourceWithGlobals(\n option.attributeName()\n );\n return !!source && source !== 'default';\n}\n\n/**\n * Enforces stability gate and prints warnings for non-stable options that were\n * actually used.\n * @param actionCommand Concrete command being executed.\n */\nfunction enforceOptionStabilityAndWarn(actionCommand: Command): void {\n for (const option of actionCommand.options) {\n const metadata = getStabilityMetadata(option);\n if (metadata.level === 'stable' || !isOptionUsed(actionCommand, option)) {\n continue;\n }\n\n const commandPath = getCommandPath(actionCommand);\n const optionLabel = getOptionLabel(option);\n const warningKey = `${commandPath}::${optionLabel}`;\n\n if (metadata.gate?.requiredOptIn) {\n const gate = metadata.gate;\n if (!isStabilityGateSatisfied(actionCommand, gate)) {\n const optionName = gate.optionName || 'enable-preview';\n const envVarName = gate.envVarName || 'FRODO_ENABLE_PREVIEW';\n const mode = gate.mode || 'option-or-env';\n const guidance =\n mode === 'option-only'\n ? `Use '--${optionName}'.`\n : mode === 'env-only'\n ? `Set '${envVarName}=true'.`\n : `Use '--${optionName}' or set '${envVarName}=true'.`;\n throw new FrodoError(\n `${formatStabilityLevel(metadata.level)} option '${optionLabel}' on command '${commandPath}' requires explicit opt-in. ${guidance}`\n );\n }\n }\n\n if (!warnedStabilityOptions.has(warningKey)) {\n const suffix = metadata.gate?.requiredOptIn\n ? metadata.level === 'deprecated'\n ? ' This option is opt-in, deprecated, and may be removed in a future release.'\n : ' This option is opt-in and may change without notice.'\n : metadata.level === 'deprecated'\n ? ' This option is deprecated and may be removed in a future release.'\n : ' This option may change without notice.';\n printMessage(\n `${formatStabilityLevel(metadata.level)} option in use: '${optionLabel}' on command '${commandPath}'.${suffix}`,\n 'warn'\n );\n warnedStabilityOptions.add(warningKey);\n }\n }\n}\n\n/**\n * Enforces stability gate and prints warnings for non-stable commands.\n * @param actionCommand Concrete command being executed.\n */\nfunction enforceStabilityAndWarn(actionCommand: Command): void {\n const metadata = getEffectiveCommandStabilityMetadata(actionCommand);\n if (metadata.level === 'stable') {\n return;\n }\n\n const commandPath = getCommandPath(actionCommand);\n\n if (metadata.gate?.requiredOptIn) {\n const gate = metadata.gate;\n if (!isStabilityGateSatisfied(actionCommand, gate)) {\n const optionName = gate.optionName || 'enable-preview';\n const envVarName = gate.envVarName || 'FRODO_ENABLE_PREVIEW';\n const mode = gate.mode || 'option-or-env';\n const guidance =\n mode === 'option-only'\n ? `Use '--${optionName}'.`\n : mode === 'env-only'\n ? `Set '${envVarName}=true'.`\n : `Use '--${optionName}' or set '${envVarName}=true'.`;\n throw new FrodoError(\n `${formatStabilityLevel(metadata.level)} command '${commandPath}' requires explicit opt-in. ${guidance}`\n );\n }\n }\n\n if (!warnedStabilityCommands.has(commandPath)) {\n const gateSuffix = metadata.gate?.requiredOptIn\n ? metadata.level === 'deprecated'\n ? ' This command is opt-in, deprecated, and may be removed in a future release.'\n : ' This feature is opt-in and may change without notice.'\n : metadata.level === 'deprecated'\n ? ' This command is deprecated and may be removed in a future release.'\n : ' This feature may change without notice.';\n if (\n !(actionCommand as Command & StabilityAnnotated)[\n SUPPRESS_STABILITY_WARNING_KEY\n ]\n ) {\n printMessage(\n `${formatStabilityLevel(metadata.level)} feature in use: '${commandPath}'.${gateSuffix}`,\n 'warn'\n );\n }\n warnedStabilityCommands.add(commandPath);\n }\n\n enforceOptionStabilityAndWarn(actionCommand);\n}\n\n/**\n * Command with default options\n */\n/**\n * Commander internals this file relies on: public at runtime (verified\n * against commander's lib/command.js -- note visibility is `_hidden`,\n * set via addCommand's `hidden` option, not a `hidden` property), absent\n * from its typings. One declaration instead of scattered inline casts.\n */\ninterface CommandInternal extends Command {\n _actionHandler: ((...args: unknown[]) => unknown) | null;\n _getHelpCommand: () => Command | undefined;\n _parseCommand: (operands: string[], unknown: string[]) => unknown;\n _hidden: boolean;\n}\n\n/**\n * Splits the raw `_parseCommand(operands, unknown)` argument lists into\n * the leading positional words (\"this command's arguments in intent\") and\n * everything else. The parent's parseOptions cannot classify command\n * words -- `frodo journey` reaches the root with everything in `unknown`\n * -- so the bare-invocation check re-classifies here: words before the\n * first option-looking token (`-x`, `--long`, `--long=value`, or a lone\n * `--` separator) are positional; that first token and the rest are\n * options/option-values/sub-command options and stay out of the count.\n */\nfunction splitPositionalArgs(\n operands: string[],\n unknown: string[]\n): { positional: string[] } {\n const positional = [...operands];\n for (const arg of unknown) {\n if (arg === '--' || /^-{1,2}[^-]/.test(arg)) break;\n positional.push(arg);\n }\n return { positional };\n}\n\n/**\n * Options the bare-stub sub-command picker must not swallow -- when one\n * of these is present the interception falls through to commander's own\n * parse:\n *\n * - the help family and version make commander act and EXIT where they\n * appear, and the picker replaces parseOptions wholesale, so\n * intercepting around them would never fire them (`frodo -v` and\n * `frodo -h` on a TTY would show the picker instead of their own\n * output);\n * - `--no-prompt` is the explicit prompting opt-out -- showing a prompt\n * against it would defeat its meaning (its value is only read during\n * parseOptions, which the picker bypasses, and in a stub's bare\n * invocation no preAction runs to set the gate).\n *\n * Other pass-down options (--verbose, --debug, ...) keep the picker and\n * re-parse in the picked sub-command's context as designed.\n */\nconst BARE_PICKER_BLOCKING_OPTION_TOKENS = new Set([\n '-h',\n '--help',\n HELP_MORE_FLAG,\n HELP_MORE_SHORT_FLAG,\n HELP_ALL_FLAG,\n HELP_ALL_SHORT_FLAG,\n '-v',\n '--version',\n '--no-prompt',\n]);\n\nfunction isBarePickerBlockingOptionToken(token: string): boolean {\n return BARE_PICKER_BLOCKING_OPTION_TOKENS.has(token);\n}\n\n/**\n * commander's own _parseCommand implementation, captured from the\n * Command.prototype ONCE at module load -- before any subclass shadows\n * it. Reaching it via prototype walking is wrong: a 2-level walk lands\n * on FrodoStubCommand.prototype (this override itself) for FrodoCommand\n * (leaf) instances -- FrodoCommand extends FrodoStubCommand extends\n * Command -- causing infinite recursion (observed live as \"Maximum call\n * stack size exceeded\" when a picked sub-command dispatched).\n */\nconst commanderParseCommand = (Command.prototype as unknown as CommandInternal)\n ._parseCommand as (\n this: Command,\n operands: string[],\n unknown: string[]\n) => unknown;\n\n/**\n * Thrown by a nested sub-command picker when its user pressed ESC (see\n * pickAndDispatchSubCommand's tree-climb loop): the PARENT's picker\n * catches it and re-opens, so ESC climbs one command-tree level instead\n * of leaving the session. Escapes commander's dispatch (which awaits\n * _parseCommand results) as a plain exception; every catch site\n * re-throws anything that is not this symbol.\n */\nconst STEP_BACK = Symbol('interactive:stepBack');\n\n/**\n * Thrown by an ACTION-BEARING stub's bare action (conn, settings) when\n * its own interactive mode was DECLINED (ESC / gate-blocked / esc×2):\n * the framework's picker machinery catches it and re-opens the stub's\n * sub-command picker (the Run row) -- bare-invocation interactive modes\n * are one level of the navigable command tree, not session endpoints.\n * Exported so command files can throw it from their actions; catching\n * lives exclusively in pickAndDispatchSubCommand.\n */\nexport const STEP_BACK_FROM_ACTION = STEP_BACK;\n\n/**\n * The sub-command picker's synthetic \"run this stub's own action\" row\n * (action-bearing stubs only, first row): distinct from any real\n * sub-command name so it can't collide with one.\n */\nconst RUN_ROW_VALUE = Symbol('interactive:runOwnAction');\n\n/**\n * The stub prompting pair (user decision 2026-10-12 -- stubs list ONLY\n * these, never the live commands' full option set), registered LAZILY\n * on ACTION-BEARING stubs only (conn, settings; plus the root's own\n * picker machinery): --prompt shows the sub-command picker instead of\n * the action (browse mode); --no-prompt makes the bare action\n * gate-respecting (declines). Pure containers never carry the pair --\n * registering it there would let an ANCESTOR consume a flag a\n * descendant leaf also declares (commander's parse assigns the value to\n * the first command in the chain that declares it, verified live: with\n * --prompt on both, `frodo esv secret list --prompt` landed on the ESV\n * stub and left the leaf's getOptionValue('prompt') undefined, so the\n * resolver skipped the editor). FrodoCommand leaves get the pair from\n * defaultOpts with live semantics; the defaultOpts loop's replace\n * branch exists for the same reason and now never fires (stubs no\n * longer pre-register), but is kept as a safety net.\n */\nfunction stubPromptPair(): Option[] {\n return [\n withHelpGroup(\n new Option(\n '--prompt',\n 'Show the interactive sub-command selector instead of running this command.'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n ),\n withHelpGroup(\n new Option(\n '--no-prompt',\n 'Never prompt interactively (same as setting FRODO_NO_PROMPT).'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n ),\n ];\n}\n\nexport class FrodoStubCommand extends Command {\n /**\n * Command stability metadata. Defaults to stable.\n */\n [STABILITY_METADATA_KEY]?: StabilityMetadata;\n\n types?: string[];\n\n /**\n * Creates a new FrodoCommand instance\n * @param name Name of the command\n * @param types Deployment types this command supports. When omitted, the\n * command starts untyped and inherits types from its sub-commands via\n * addCommand's type-merge — but an untyped or multi-type parent drops out\n * of the scoped (Cloud-only etc.) help grouping, so single-type families\n * should declare their type here explicitly.\n */\n constructor(name: string, types?: string[]) {\n super(name);\n\n if (types && types.length > 0) {\n this.types = [...new Set(types)];\n }\n\n if (!process.listenerCount('unhandledRejection')) {\n process.on('unhandledRejection', (error: any) => {\n printError(\n new FrodoError(\n `Please report this unhandled error here: https://github.com/rockcarver/frodo-cli/issues`,\n error\n )\n );\n process.exitCode = 1;\n });\n }\n\n // other default settings\n this.helpOption('-h, --help', 'Help');\n this.addOption(\n withHelpGroup(\n new Option(HELP_MORE_FLAG, 'Help with all options.'),\n HELP_OPTIONS_HEADING,\n OptionCategory.Command\n )\n );\n this.addOption(\n withHelpGroup(\n new Option(\n HELP_ALL_FLAG,\n 'Help with all options, environment variables, and usage examples.'\n ),\n HELP_OPTIONS_HEADING,\n OptionCategory.Command\n )\n );\n this.showHelpAfterError();\n this.configureHelp({\n sortSubcommands: true,\n sortOptions: true,\n });\n // The stub prompting pair (user decision 2026-10-12 -- stubs list\n // ONLY these, never the live commands' full option set), registered\n // LAZILY by the help/pick machinery (see registerPromptingPair)\n // rather than here: registering in the CONSTRUCTOR would put the\n // pair on EVERY stub, and commander's parse lets an ANCESTOR\n // consume a flag the leaf also declares (verified live: with --prompt\n // on both, `frodo esv secret list --prompt` assigned the value to\n // the ESV stub and left the leaf's getOptionValue('prompt')\n // undefined -- the resolver then saw prompt!==true and skipped the\n // editor). Pure containers must NOT carry the pair at all; only\n // action-bearing stubs (conn, settings) and the root do.\n this.options\n .find((option) => option.name() === 'help')\n ?.helpGroup(HELP_OPTIONS_HEADING);\n this.addHelpText('after', () => {\n if (!isFullHelpRequested()) {\n return '';\n }\n\n // FrodoCommand appends its own scoped env reference.\n if (this instanceof FrodoCommand) {\n return '';\n }\n\n // Root help wiring in app.ts already handles its own expanded env section.\n if (this.name() === 'frodo') {\n return '';\n }\n\n return formatGlobalEnvironmentVariables(this.types);\n });\n\n // register default handlers\n state.setPrintHandler(printMessage);\n state.setVerboseHandler(verboseMessage);\n state.setDebugHandler(debugMessage);\n state.setCurlirizeHandler(curlirizeMessage);\n state.setCreateProgressHandler(createProgressIndicator);\n state.setUpdateProgressHandler(updateProgressIndicator);\n state.setStopProgressHandler(stopProgressIndicator);\n activatePersistedTheme();\n\n // shutdown handlers\n\n this.hook('postAction', (thisCommand, actionCommand) => {\n debugMessage(\n `FrodoCommand: running postAction hook: this command: ${thisCommand.name()}, action command: ${actionCommand.name()}`\n );\n cleanupProgressIndicators();\n // The deferred authoring print: the only point where\n // nothing can change the command anymore -- resolution pass, realm\n // pick, entity picks, and the action's output have all concluded.\n // Flushed LAST so the printed command is the final line of the run,\n // adjacent to the next shell prompt. Flows that never reach the\n // action (cancelled pickers, missing-input throws) skip this hook:\n // an abandoned authoring session leaves nothing behind. No-op when\n // the session never armed (no prompts, not explicitly interactive).\n flushAuthoringPrint();\n });\n\n // Async preAction hook: commander's hook chain awaits returned\n // promises (_chainOrCall), so the action handler below only starts\n // after interactive input resolution finished. The hook is registered\n // on every FrodoCommand in the ancestry and all receive the same\n // actionCommand, so dedupe on the executing command.\n this.hook('preAction', (_thisCommand, actionCommand) => {\n enforceStabilityAndWarn(actionCommand);\n // The prompting switch is a dual option pair sharing the `prompt`\n // attribute (undefined = prompting allowed when input is missing);\n // --no-prompt sets it false. Set once per process, before the\n // resolution hook below (hook order = registration order).\n if (\n actionCommand.getOptionValue(promptOption.attributeName()) === false\n ) {\n setNeverPrompt();\n }\n });\n\n this.hook('preAction', async (_thisCommand, actionCommand) => {\n // Only leaf FrodoCommands get the resolution pass. Stub commands'\n // own bare actions (conn, settings, login -- all already\n // interactive by design) must not run it, or they would\n // double-prompt.\n if (!(actionCommand instanceof FrodoCommand)) return;\n if (resolvedActionCommands.has(actionCommand)) return;\n resolvedActionCommands.add(actionCommand);\n setActiveActionCommand(actionCommand);\n await resolveInteractiveInputs(actionCommand);\n });\n }\n\n /**\n * Commander calls this during parsing, BEFORE the preAction hook chain,\n * when a `makeOptionMandatory()` option is missing. Reimplemented here\n * (verbatim from commander's own implementation, whose typings omit the\n * method -- so an override below cannot `super` into it) as the shared\n * declaration point both subclasses control: stub commands keep this\n * verbatim throw (today's behavior, unchanged), and FrodoCommand\n * replaces it with deferral (see ResolveInteractiveInputs) so the\n * preAction resolution pass can prompt for the value on an interactive\n * session, or re-throw this exact error on a non-interactive one. That\n * is what makes all existing `makeOptionMandatory()` call sites\n * prompt-capable with zero syntax change.\n * @param option The mandatory option that is missing.\n */\n missingMandatoryOptionValue(option: Option): void {\n this.error(`error: required option '${option.flags}' not specified`, {\n code: 'commander.missingMandatoryOptionValue',\n });\n }\n\n /**\n * Marks a command stability level and optionally requires explicit opt-in.\n * Stable is the default and requires no call sites.\n * @param level Stability indicator.\n * @param gate Optional gate configuration for high-risk features.\n * @returns This command for chaining.\n */\n withStability(level: StabilityIndicator, gate?: StabilityGateConfig): this {\n const normalizedGate = gate?.requiredOptIn\n ? {\n requiredOptIn: true,\n optionName: gate.optionName || 'enable-preview',\n envVarName: gate.envVarName || 'FRODO_ENABLE_PREVIEW',\n helpText: gate.helpText,\n mode: gate.mode || 'option-or-env',\n }\n : gate;\n\n setStabilityMetadata(this, { level, gate: normalizedGate });\n\n if (normalizedGate?.requiredOptIn) {\n const optionName = normalizedGate.optionName || 'enable-preview';\n const optionExists = this.options.some(\n (option) =>\n option.name() === optionName || option.attributeName() === optionName\n );\n\n if (!optionExists) {\n const envVarName = normalizedGate.envVarName || 'FRODO_ENABLE_PREVIEW';\n const helpText =\n normalizedGate.helpText ||\n `Opt in to ${level} feature execution. You can also set ${envVarName}=true.`;\n this.addOption(\n withHelpGroup(\n new Option(`--${optionName}`, helpText),\n HELP_OPTIONS_HEADING,\n OptionCategory.Command\n )\n );\n }\n }\n\n return this;\n }\n\n /**\n * Suppresses the process-level stability warning for commands that report\n * the same notice through their own protocol-aware output channel.\n */\n suppressStabilityWarning(): this {\n this[SUPPRESS_STABILITY_WARNING_KEY] = true;\n return this;\n }\n\n /**\n * Declares that this command needs AT LEAST ONE of the named options --\n * the declarative replacement for the `Unrecognized combination of\n * options or no options...` dead-ends that 113 command action bodies\n * enforce only AFTER authenticating. Evaluated in the preAction\n * resolution pass (ResolveInteractiveInputs): on an interactive session\n * the user is prompted for a member and its value; otherwise commander's\n * own error+help+exit-1 fires with code `frodo.oneOfUnsatisfied`.\n *\n * Unlike makeOptionMandatory (which commander checks during parsing),\n * this runs later -- after connection-arg gap-fill -- so a command\n * whose one-of members need tenant context first still prompts\n * sensibly. Option names are long names without dashes (`agentId`,\n * `all`), matching commander's attributeName.\n *\n * @param groups One or more group specs.\n * @returns This command for chaining.\n */\n requireOneOf(\n ...groups: [OptionRequirementSpec, ...OptionRequirementSpec[]]\n ): this {\n deferOneOfGroups(\n this,\n groups.map((group) => ({ ...group, all: false }))\n );\n return this;\n }\n\n /**\n * Declares that this command needs ALL of the named options together --\n * the pairwise-required shape (e.g. esv secret version activate needs\n * `-i` AND `-v`; either alone dead-ended with `Unrecognized\n * combination`). Same evaluation, prompting, and error semantics as\n * requireOneOf (see that method), with the all-members check and an\n * \"all of ... are required\" error message.\n *\n * @param groups One or more group specs.\n * @returns This command for chaining.\n */\n requireAllOf(\n ...groups: [OptionRequirementSpec, ...OptionRequirementSpec[]]\n ): this {\n deferOneOfGroups(\n this,\n groups.map((group) => ({ ...group, all: true }))\n );\n return this;\n }\n\n override addCommand(\n command: Command,\n opts?: Parameters<Command['addCommand']>[1]\n ) {\n const typedCommand = command as CommandWithTypes;\n if (typedCommand.types && typedCommand.types.length > 0) {\n const currentTypes = this.types || [];\n this.types = [...new Set([...currentTypes, ...typedCommand.types])];\n }\n\n if (!command.helpGroup()) {\n command.helpGroup(COMMANDS_HEADING);\n }\n\n return super.addCommand(command, opts);\n }\n\n override addHelpText(\n position: 'beforeAll' | 'before' | 'after' | 'afterAll',\n text: string | ((context: AddHelpTextContext) => string)\n ): this {\n if (position === 'after' && typeof text === 'string') {\n return super.addHelpText(position, () =>\n isFullHelpRequested() ? text : ''\n );\n }\n if (typeof text === 'string') {\n return super.addHelpText(position, text);\n }\n return super.addHelpText(position, text);\n }\n\n createHelp() {\n return Object.assign(new FrodoStubHelp(), this.configureHelp());\n }\n\n /**\n * When a stub command with\n * sub-commands is invoked BARE (no sub-command word, no operands) on an\n * interactive session, offer the sub-commands in a picker and dispatch\n * to the picked one -- e.g. `frodo journey <enter>` proposes all journey\n * sub-commands. A stub with a single child auto-descends to it\n * (announced under --verbose), mirroring the single-saved-profile skip\n * in the resolver.\n *\n * Backing out of the picker (Escape, or prompting disallowed) falls\n * through to commander's own bare-stub behavior (`help({ error: true })`\n * inside _parseCommand), so every existing path is byte-identical\n * off-interactive.\n *\n * Implemented as an override rather than any hook because there is no\n * hook at this point: commander calls `_parseCommand` directly on the\n * stub and help-exits before any hook or action runs. Stubs that\n * already have their own bare action (conn, settings, login, shell)\n * never reach the interception -- their `_actionHandler` short-circuits\n * the fallthrough in commander's _parseCommand, exactly as before. Per\n * plan decision there is NO skip list beyond that: mcp, log, and every\n * other stub get the picker (\"the guided path through complex commands\n * is the feature's purpose\").\n *\n * `super._parseCommand` is re-entered with the picked name as the only\n * operand, so commander dispatches normally: options in `unknown`\n * (--no-prompt, --verbose, ...) re-parse in the sub-command's context\n * exactly as if the user had typed them. Returning the promise is safe:\n * the parent's dispatch wraps `_parseCommand` in `_chainOrCall`, which\n * awaits results.\n *\n * Entry contract (verified against commander 15.0.0 lib/command.js and\n * a live harness): `_parseCommand(operands, unknown)` receives raw\n * split argv -- operand words the PARENT didn't consume arrive in\n * `unknown` (the parent's parseOptions can't classify them; e.g.\n * `frodo journey` calls the root's _parseCommand with operands=[] and\n * unknown=['journey']). This override therefore classifies the leading\n * words itself: everything before the first option-looking token is\n * this command's positional operands; the bare-invocation case is\n * \"no operands AND nothing that classifies as a sub-command word\".\n *\n * commander's typings omit `_parseCommand` entirely, so this is NOT\n * marked `override` (TS4113 -- the modifier requires a declared base\n * member) and the base implementation is reached through the prototype\n * (baseParseCommand below) rather than `super` (TS2339 for the same\n * reason). Runtime commander version: 15.0.0, verified against\n * lib/command.js.\n */\n _parseCommand(\n operands: string[],\n unknown: string[]\n ): Promise<unknown> | undefined {\n const self = this as unknown as CommandInternal;\n const { positional } = splitPositionalArgs(operands, unknown);\n // Action-bearing stubs own the prompting pair (see\n // registerPromptingPair): ensure it exists before any parse of this\n // command so --prompt/--no-prompt parse onto it.\n this.registerPromptingPair();\n // An action-bearing stub (conn, settings) intercepted with --prompt\n // routes to the sub-command picker INSTEAD of running its action:\n // --prompt means \"show me the tree\" on these, while bare (no --prompt)\n // keeps the command's own interactive mode. The action stub's picker\n // carries a Run row to re-enter it (see pickAndDispatchSubCommand).\n const promptAsBrowse =\n self._actionHandler !== null &&\n unknown.some(\n (token) =>\n token === '--prompt' ||\n token === `${promptOption.attributeName()}=true`\n );\n if (\n (self._actionHandler === null || promptAsBrowse) &&\n positional.length === 0 &&\n this.commands.length > 0 &&\n // Root-exiting options (help family, version) must reach\n // commander's own parse: the picker replaces parseOptions\n // wholesale, so intercepting around them would turn `frodo -v` and\n // `frodo -h` into the sub-command picker instead of their own\n // output. Pass-down options (--verbose, --no-prompt, ...) don't\n // exit and re-parse in the picked sub-command's context, so they\n // keep the picker.\n !unknown.some(isBarePickerBlockingOptionToken)\n ) {\n return this.pickAndDispatchSubCommand(unknown);\n }\n // PURE stub + --no-prompt: the user's legacy escape hatch (user\n // decision 2026-10-12). The option is deliberately NOT registered on\n // pure containers (an ancestor registration would consume the token\n // a descendant leaf also declares, silently defeating the leaf's\n // own --no-prompt), so commander would reject it as unknown --\n // handle it HERE as the legacy bare-stub behavior instead: print\n // this command's help and exit 0 (no picker, no action).\n if (\n self._actionHandler === null &&\n positional.length === 0 &&\n unknown.some((token) => token === '--no-prompt')\n ) {\n this.outputHelp();\n process.exit(0);\n }\n // Action path (bare invocation of an action-bearing stub): the\n // action may throw STEP_BACK (its interactive mode was DECLINED) --\n // route that into the sub-command picker, exactly like ESC out of a\n // nested picker. Everything else propagates (errors, exits). The\n // result may be a promise (async actions) -- chain the STEP_BACK\n // recovery onto it rather than awaiting (this method is sync, like\n // commander's own _parseCommand).\n try {\n const result = this.baseParseCommand(operands, unknown);\n if (result instanceof Promise) {\n return result.catch((error) => {\n if (error === STEP_BACK) {\n return this.pickAndDispatchSubCommand(unknown);\n }\n throw error;\n });\n }\n return result;\n } catch (error) {\n if (error === STEP_BACK) return this.pickAndDispatchSubCommand(unknown);\n throw error;\n }\n }\n\n /**\n * Registers the stub prompting pair (--prompt/--no-prompt) on this\n * command when it is an ACTION-BEARING STUB (has its own action, is\n * not a live FrodoCommand -- leaves get the pair from defaultOpts\n * with live semantics). Idempotent; called from _parseCommand (before\n * any parse of this command) and from the help renderer (so the\n * stub's -h lists the pair even when parse never ran, e.g.\n * `frodo conn -h`). Never called for pure containers: an ancestor\n * registration would consume the flag a descendant leaf also\n * declares (see stubPromptPair's doc).\n */\n registerPromptingPair(): void {\n const self = this as unknown as CommandInternal;\n if (self._actionHandler === null) return; // pure container\n if (this instanceof FrodoCommand) return; // live leaf: defaultOpts\n for (const opt of stubPromptPair()) {\n if (!this.options.some((option) => option.name() === opt.name())) {\n this.addOption(opt);\n }\n }\n }\n\n /**\n * commander's _parseCommand, reached through the prototype chain (see\n * the _parseCommand override above for why not `super`).\n */\n private baseParseCommand(\n operands: string[],\n unknown: string[]\n ): Promise<unknown> | undefined {\n return commanderParseCommand.call(this, operands, unknown) as\n Promise<unknown> | undefined;\n }\n /**\n * Offers this command's sub-commands (skipping the synthetic help\n * command) in the escape-as-back picker and re-enters the parser for\n * the pick. Resolves to the super result -- a promise when the picked\n * sub-command's action is async.\n */\n private async pickAndDispatchSubCommand(unknown: string[]): Promise<unknown> {\n const self = this as unknown as CommandInternal;\n const candidates = this.commands.filter(\n (command) =>\n command !== self._getHelpCommand() &&\n !(command as unknown as CommandInternal)._hidden\n );\n if (candidates.length === 0) {\n // Nothing pickable: fall through with the ORIGINAL arguments --\n // unknown may still carry --help/-h or options commander must see\n // (discarding them would turn `frodo x --help` into a bare help\n // dump with exit 1 instead of a clean help exit).\n return this.baseParseCommand([], unknown);\n }\n\n if (candidates.length === 1) {\n // Single child: no menu -- mirror the single-saved-profile\n // convention (announced only under --verbose, this runs inside an\n // otherwise-quiet command). Prompting disallowed (FRODO_TEST,\n // --no-prompt, non-TTY): fall through to commander's own bare-stub\n // help-exit -- auto-descend is an interactive affordance, and\n // snapshot/help tests assert the command's OWN help text here.\n if (!canPrompt()) {\n return this.baseParseCommand([], unknown);\n }\n verboseMessage(\n `No sub-command given; using the only one available: ${candidates[0].name()}`\n );\n return this.baseParseCommand([candidates[0].name()], unknown);\n }\n\n if (!canPrompt()) {\n return this.baseParseCommand([], unknown);\n }\n\n // Tree-climb loop (user feedback 2026-10-12: ESC in a nested\n // picker exited the session instead of stepping back one command\n // level -- \"frodo\" > config-manager > push > ESC should re-offer\n // config-manager's picker, not leave frodo): ESC from a CHILD\n // picker surfaces here as STEP_BACK, this picker re-opens, and the\n // user picks another branch. Only the ROOT picker's ESC leaves the\n // session (nothing above it).\n //\n // The Run row (user decision 2026-10-12): a stub with its OWN\n // action (conn, settings) lists that action FIRST -- \"Run 'conn'\n // (its own description)\" -- so bare `frodo conn --prompt` shows the\n // tree AND the action stays reachable, and ESC from the action\n // climbs here (navigation restored; the pre-Run-row behavior\n // exited the session). The row is synthetic: it dispatches by\n // re-entering the parser with NO sub-command operand, which falls\n // through to the stub's own action.\n const runRow = self._actionHandler\n ? [\n {\n value: RUN_ROW_VALUE as unknown as string,\n name: `Run '${this.name()}'${this.description() ? ` -- ${this.description().split('\\n')[0]}` : ''}`,\n },\n ]\n : [];\n for (;;) {\n const choice = await escapableSelect<string>({\n message: `Choose a sub-command for '${this.name()}':`,\n choices: [\n ...runRow,\n ...candidates.map((command) => ({\n value: command.name(),\n name: command.summary()\n ? `${command.name()} -- ${command.summary()}`\n : command.name(),\n })),\n ],\n });\n if (choice === RIGHT) {\n // Unreachable (no hint), kept for the widened type.\n return this.baseParseCommand([], unknown);\n }\n if (choice === EXIT_ALL) {\n // From any depth: THROW the exit-all signal (docs/\n // INTERACTIVE-COMMANDS.md: \"lands straight back at the shell\")\n // -- app.ts's top-level handler ends the session cleanly.\n throw EXIT_ALL_SIGNAL;\n }\n if (choice === ESCAPE) {\n if (this.parent) {\n // One level up: re-open the PARENT's sub-command picker.\n throw STEP_BACK;\n }\n // Root picker: ESC exits as it always has.\n return this.baseParseCommand([], unknown);\n }\n if (choice === (RUN_ROW_VALUE as unknown as string)) {\n // Re-enter the parser with NO sub-command operand: the stub's\n // own action runs. The action may throw STEP_BACK (it DECLINED\n // its interactive mode -- ESC / --no-prompt / esc×2): catch and\n // LOOP, re-offering this picker (Run row first), so the bare\n // mode is one level of the navigable tree, not a dead end.\n try {\n return await this.baseParseCommand([], unknown);\n } catch (error) {\n if (error === STEP_BACK) continue;\n throw error;\n }\n }\n // Descend: the child's own dispatch may throw STEP_BACK (its\n // picker's ESC) -- catch it and LOOP, re-offering this level's\n // picker. Everything else propagates.\n try {\n return await this.baseParseCommand([choice], unknown);\n } catch (error) {\n if (error === STEP_BACK) continue;\n throw error;\n }\n }\n }\n}\n\nclass FrodoStubHelp extends Help {\n private readonly helpOptionOrder: Record<string, number> = {\n help: 0,\n 'help-more': 1,\n 'help-all': 2,\n };\n\n /**\n * The command currently being rendered (set by formatHelp). The entity\n * pick annotation in optionDescription reads the pick registry off it.\n */\n private renderedCommand?: Command;\n\n /**\n * Custom help renderer that extends Commander output with deployment-aware\n * inline sub-sections for options and subcommands.\n *\n * If you add new default option groups or deployment scopes, update helper\n * functions (`collectOptionGroupsByScope`, `environmentVariableScopeOrder`,\n * and related mappings) rather than editing rendering loops directly.\n * @param cmd Command being rendered.\n * @param helper Commander help helper instance.\n * @returns Fully rendered help text for the command.\n */\n override formatHelp(cmd: Command, helper: Help): string {\n // optionDescription is called from inside formatHelp with no command\n // context of its own -- remember which command is being rendered so\n // the entity-pick annotation can consult that command's registry.\n this.renderedCommand = cmd;\n // Action-bearing stubs list the prompting pair even when parse never\n // ran (`frodo conn -h` help-exits without parsing options) -- see\n // registerPromptingPair's doc. Idempotent.\n if (cmd instanceof FrodoStubCommand) {\n (cmd as FrodoStubCommand).registerPromptingPair();\n }\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80;\n\n function callFormatItem(term: string, description: string) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth\n ),\n '',\n ]);\n }\n\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument))\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper)\n );\n\n // Add deployment type indicator after Usage/Description/Arguments for single-type commands.\n const typedCmd = cmd as CommandWithTypes;\n const typeLabel = getDeploymentTypeLabel(typedCmd);\n if (typeLabel) {\n output.push(`Deployment: ${typeLabel}`, '');\n }\n\n // --prompt/--no-prompt per class (user decision 2026-10-12):\n // - PURE container stub: --no-prompt only (legacy help-exit;\n // --prompt is a no-op there and is hidden). The option is NOT\n // registered (an ancestor registration would consume the token a\n // descendant leaf also declares), so formatHelp renders it\n // VIRTUALLY from the shared stub wording.\n // - Action-bearing stub: both, registered (registerPromptingPair).\n // Both are ALSO rendered virtually: at help level 1 visibleOptions()\n // filters out everything under Runtime Options: (stub pair included),\n // so the registered pair would vanish from -h -- the very surface\n // that must advertise it (caught by the user on `frodo conn -h`).\n // - Live commands: both via defaultOpts, live wording; at level 1 the\n // runtime groups stay hidden (deliberate - machinery, not contract).\n // A stub's pair IS its contract (bare invocation behavior), hence\n // the virtual render there and only there.\n // FrodoCommand EXTENDS FrodoStubCommand, so instanceof alone also\n // matches live leaves -- a leaf's pair comes from defaultOpts and stays\n // under the level-1 runtime filter (machinery, not contract). Only the\n // two STUB classes take the virtual render.\n const isStub =\n cmd instanceof FrodoStubCommand && !(cmd instanceof FrodoCommand);\n const isActionStub =\n isStub && (cmd as unknown as CommandInternal)._actionHandler !== null;\n const isPureStub = isStub && !isActionStub;\n const virtualOptions = isPureStub\n ? [\n // Pure stub: --no-prompt only (as before). Wording must stay in\n // sync with stubPromptPair.\n withHelpGroup(\n new Option(\n '--no-prompt',\n 'Never prompt interactively (same as setting FRODO_NO_PROMPT).'\n ),\n RUNTIME_OPTIONS_HEADING,\n OptionCategory.Runtime\n ),\n ]\n : isActionStub\n ? [\n // Action stub: the pair, registered AND virtually rendered\n // (identical instances would double-list through groupItems'\n // all+visible split, so render from fresh copies; the wording\n // must stay in sync with stubPromptPair).\n ...stubPromptPair(),\n ]\n : [];\n const visibleOptions = helper.visibleOptions(cmd).filter(\n (option) =>\n !(isPureStub && option.name() === 'prompt') &&\n // The action stub's registered pair renders virtually (level-1\n // runtime filter would drop it) -- dedupe against the copies.\n !(\n isActionStub &&\n (option.name() === 'prompt' || option.name() === 'no-prompt')\n )\n );\n const optionGroups = this.groupItems(\n [...cmd.options, ...virtualOptions],\n [...visibleOptions, ...virtualOptions],\n (option) => option.helpGroupHeading ?? 'Options:'\n );\n const orderedOptionGroups = [...optionGroups.entries()].sort(\n ([leftGroup], [rightGroup]) => {\n if (leftGroup === COMMAND_OPTIONS_HEADING) {\n return -1;\n }\n\n if (rightGroup === COMMAND_OPTIONS_HEADING) {\n return 1;\n }\n\n return leftGroup.localeCompare(rightGroup, undefined, {\n sensitivity: 'base',\n });\n }\n );\n\n orderedOptionGroups.forEach(([group, options]) => {\n const scopedGroups = collectOptionGroupsByScope(options, typedCmd.types);\n const optionLines = scopedGroups.unscoped.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option))\n );\n });\n\n for (const scope of environmentVariableScopeOrder) {\n const scopedOptions = scopedGroups.scoped.get(scope);\n if (!scopedOptions || scopedOptions.length === 0) {\n continue;\n }\n\n const deploymentType = getDeploymentTypeForScope(scope);\n optionLines.push('');\n optionLines.push(` (${toDeploymentOnlyLabel(deploymentType)}):`);\n optionLines.push(\n ...scopedOptions.map((option) =>\n callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option))\n )\n )\n );\n }\n\n output = output.concat(this.formatItemList(group, optionLines, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option))\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper)\n );\n }\n\n // Option-requiredness rules (requireOneOf/requireAllOf) declared on\n // this command, rendered after the option lists: the declarative\n // replacement for the old \"Unrecognized combination\" dead-ends, so\n // help now says the rule the action body used to reveal only after\n // authenticating.\n for (const group of getOneOfGroups(cmd)) {\n const members = group.options\n .map((name) => {\n const option = cmd.options.find(\n (candidate) => candidate.attributeName() === name\n );\n return option ? option.flags : `--${name}`;\n })\n .join(group.all ? ' + ' : ' | ');\n const ruleText = group.all\n ? `all of ${members} are required together`\n : `one of ${members} is required`;\n output = output.concat(\n this.formatItemList(\n 'Rule:',\n [ruleText + (group.purpose ? ` -- choose ${group.purpose}` : '')]\n .map((line) => ` ${line}`)\n .concat(''),\n helper\n )\n );\n }\n\n const commandGroups = this.groupItems(\n [...cmd.commands],\n [...helper.visibleCommands(cmd)],\n (sub) =>\n sub.helpGroup() ||\n // Commander's implicit help command is created lazily, too late for\n // an explicit helpGroup assignment at registration — route it to\n // Utilities here, matching the README's placement.\n (sub.name() === 'help' ? 'Utilities:' : 'Commands:')\n );\n commandGroups.forEach((commands, group) => {\n // Single-deployment-type commands stay inline with their group, marked\n // by a [Cloud-only]-style badge in their description (see\n // decorateDescriptionWithStability). The former (<Type>-only):\n // sub-sections are gone — they broke alphabetical order and mixed\n // grouping concepts.\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub))\n );\n });\n\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n // The bare-invocation marker (user decision 2026-10-12): PURE\n // containers (stubs without their own action) get the framework's\n // standard line -- bare invocation enters the sub-command picker.\n // Action-bearing stubs (conn, settings) are full commands of their\n // own and declare the bare behavior in their DESCRIPTION instead\n // (their -h shows no marker line).\n const isActionBearingStub =\n (cmd as unknown as CommandInternal)._actionHandler !== null &&\n !(cmd instanceof FrodoCommand);\n if (\n cmd instanceof FrodoStubCommand &&\n !(cmd instanceof FrodoCommand) &&\n !isActionBearingStub &&\n helper.visibleCommands(cmd).length > 0\n ) {\n output = output.concat([\n '',\n 'Run without a sub-command to enter interactive mode.',\n ]);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Decorates command description with stability badges.\n * @param cmd Command being rendered.\n * @returns Possibly decorated description.\n */\n override commandDescription(cmd: Command): string {\n return decorateDescriptionWithStability(super.commandDescription(cmd), cmd);\n }\n\n /**\n * Decorates subcommand description with stability badges.\n * @param cmd Subcommand being rendered.\n * @returns Possibly decorated description.\n */\n override subcommandDescription(cmd: Command): string {\n return decorateDescriptionWithStability(\n super.subcommandDescription(cmd),\n cmd\n );\n }\n\n /**\n * Decorates argument description with stability badges.\n * @param argument Argument being rendered.\n * @returns Possibly decorated description.\n */\n override argumentDescription(argument: Argument): string {\n return decorateDescriptionWithStability(\n super.argumentDescription(argument),\n argument\n );\n }\n\n /**\n * Decorates option description with stability badges.\n * @param option Option being rendered.\n * @returns Possibly decorated description.\n */\n override optionDescription(option: Option): string {\n // \"(prompts if missing)\": option mandatory-ness deferred to the\n // resolution pass means the CLI prompts for it on an interactive\n // session -- worth saying in help, where today mandatory-ness shows\n // only as an error after the fact. Plain makeOptionMandatory has the\n // same prompt behavior (FrodoCommand defers it too), so the\n // annotation keys on the flag itself.\n const description = decorateDescriptionWithStability(\n super.optionDescription(option),\n option\n );\n // \"(pick from <kind>)\": the option has an entity picker registered\n // (deferEntityPicks), so an interactive session offers a dropdown of\n // the live system's entities for it.\n const pick = (\n this.renderedCommand ? getEntityPicks(this.renderedCommand) : []\n ).find((candidate) => candidate.name === option.attributeName());\n const pickSuffix = pick ? ` (pick from ${pick.kind})` : '';\n const mandatorySuffix = option.mandatory ? ' (prompts if missing)' : '';\n return `${description}${pickSuffix}${mandatorySuffix}`;\n }\n\n /**\n * Reorders options so help flags are always shown at the end.\n * @param options Visible options for a help section.\n * @returns Reordered options.\n */\n private orderHelpOptions(options: Option[]): Option[] {\n const indexed = options.map((option, index) => ({ option, index }));\n\n indexed.sort((left, right) => {\n const leftPriority = this.helpOptionOrder[left.option.name()];\n const rightPriority = this.helpOptionOrder[right.option.name()];\n const leftIsHelp = leftPriority !== undefined;\n const rightIsHelp = rightPriority !== undefined;\n\n if (leftIsHelp && rightIsHelp) {\n return leftPriority - rightPriority;\n }\n\n if (leftIsHelp) {\n return 1;\n }\n\n if (rightIsHelp) {\n return -1;\n }\n\n return left.index - right.index;\n });\n\n return indexed.map(({ option }) => option);\n }\n\n /**\n * Renders compact aliases for custom help flags.\n * @param option Option being rendered.\n * @returns Display term for the option.\n */\n override optionTerm(option: Option) {\n if (option.long === HELP_MORE_FLAG) {\n return `${HELP_MORE_SHORT_FLAG}, ${HELP_MORE_FLAG}`;\n }\n\n if (option.long === HELP_ALL_FLAG) {\n return `${HELP_ALL_SHORT_FLAG}, ${HELP_ALL_FLAG}`;\n }\n\n return super.optionTerm(option);\n }\n\n /**\n * Filters and orders visible options by help level.\n * @param cmd Command being rendered.\n * @returns Visible options for current help level.\n */\n override visibleOptions(cmd: Command): Option[] {\n // Base help (`-h`) intentionally hides advanced default option groups,\n // while expanded help (`-hh` / `-hhh`) shows everything. A command can\n // opt specific options out of a heading entirely (folding them into the\n // always-visible \"Options:\" section instead) via\n // `FrodoCommand.mergeHeadingIntoOptions()` — see `login`, whose\n // authentication options aren't \"advanced\", they're the whole point of\n // the command. That changes an option's `helpGroupHeading` directly, so\n // it requires no special-casing here.\n const allVisible = super.visibleOptions(cmd);\n\n if (getHelpLevel() >= 2) {\n return this.orderHelpOptions(allVisible);\n }\n\n return this.orderHelpOptions(\n allVisible.filter(\n (opt) =>\n opt.helpGroupHeading !== CONNECTION_OPTIONS_HEADING &&\n opt.helpGroupHeading !== AUTHENTICATION_OPTIONS_HEADING &&\n opt.helpGroupHeading !== RUNTIME_OPTIONS_HEADING &&\n opt.helpGroupHeading !== OUTPUT_OPTIONS_HEADING\n )\n );\n }\n\n /**\n * Uses visible-item ordering to keep dynamic scoped sections stable.\n * @param _unsortedItems Commander-provided original list (unused intentionally).\n * @param visibleItems Visible list after filtering.\n * @param getGroup Grouping selector.\n * @returns Group map with stable visible ordering.\n */\n override groupItems<T extends Command | Option>(\n _unsortedItems: T[],\n visibleItems: T[],\n getGroup: (item: T) => string\n ): Map<string, T[]> {\n // Seed group order from visible items so filtered and transformed sections\n // keep stable ordering with custom help rendering.\n const grouped = super.groupItems(visibleItems, visibleItems, getGroup);\n\n // Root command groups render in the README's table order (the help\n // grouping mirrors the docs): Commands, then Utilities, then Continuous\n // integration — NOT first-member registration order, which would put\n // Utilities first (admin registers before agent).\n if (visibleItems.length > 0 && visibleItems[0] instanceof Command) {\n const preferred = ['Commands:', 'Utilities:', 'Continuous integration:'];\n for (const heading of preferred.reverse()) {\n if (!grouped.has(heading)) {\n continue;\n }\n const items = grouped.get(heading);\n grouped.delete(heading);\n if (items) {\n const rebuilt = new Map([[heading, items], ...grouped]);\n grouped.clear();\n for (const [k, v] of rebuilt) {\n grouped.set(k, v);\n }\n }\n }\n }\n\n return grouped;\n }\n\n /**\n * Renders subcommand term with first alias, if present.\n * @param cmd Subcommand.\n * @returns Display label for command list row.\n */\n subcommandTerm(cmd: Command) {\n const aliases = cmd.aliases();\n return cmd.name() + (aliases[0] ? '|' + aliases[0] : '');\n }\n}\n\n/**\n * Command with default options\n */\nexport class FrodoCommand extends FrodoStubCommand {\n /**\n * Explicit deployment types for this concrete command instance.\n */\n types: string[];\n\n /**\n * Deferred mandatory handling (see FrodoStubCommand's implementation\n * for the verbatim-commander default): record the violation instead of\n * throwing, so the preAction resolution pass can prompt for the value\n * on an interactive session, or re-throw this exact error on a\n * non-interactive one.\n * @param option The mandatory option that is missing.\n */\n missingMandatoryOptionValue(option: Option): void {\n deferMissingMandatoryOption(this, option.flags);\n }\n\n /**\n * Creates a new FrodoCommand instance\n * @param name Name of the command\n * @param omits Array of default argument names and default option names that should not be added to this command\n * @param types Array of deployment types this command supports\n * @param options.local Set for a command that never calls getTokens() (e.g. `conn list`, `session delete`) — omits every default option categorized as Authentication or Connection, in addition to whatever `omits` already lists. Default arguments (host/realm/username/password) are unaffected — categories only apply to options — so still list those explicitly in `omits` if this command has no use for them either.\n */\n constructor(\n name: string,\n omits: string[] = [],\n types: string[] = DEPLOYMENT_TYPES,\n options: { local?: boolean } = {}\n ) {\n super(name);\n\n this.types = types;\n this.allowExcessArguments();\n const commandOmits = new Set(omits);\n const supportsCloud = types.includes(constants.CLOUD_DEPLOYMENT_TYPE_KEY);\n const supportsForgeops = types.includes(\n constants.FORGEOPS_DEPLOYMENT_TYPE_KEY\n );\n const supportsClassic = types.includes(\n constants.CLASSIC_DEPLOYMENT_TYPE_KEY\n );\n\n // A command that never calls getTokens() has no use for any\n // Authentication or Connection option, regardless of how many more get\n // added to those categories in the future — this reads category, not\n // heading, so reorganizing display headings can never silently change\n // what a `local` command gets.\n if (options.local) {\n for (const opt of defaultOpts) {\n const category = getOptionCategory(opt);\n if (\n category === OptionCategory.Authentication ||\n category === OptionCategory.Connection\n ) {\n commandOmits.add(opt.name());\n }\n }\n }\n\n // Cloud-only commands do not need Amster private key defaults.\n if (\n types.length === 1 &&\n types[0] === constants.CLOUD_DEPLOYMENT_TYPE_KEY\n ) {\n commandOmits.add(amsterPrivateKeyPassphraseOption.name());\n commandOmits.add(amsterPrivateKeyFileOption.name());\n }\n\n // Service account options are only applicable for cloud-supporting commands.\n if (!supportsCloud) {\n commandOmits.add(serviceAccountIdOption.name());\n commandOmits.add(serviceAccountJwkFileOption.name());\n }\n\n // Login client options are applicable only when cloud, forgeops, or classic is supported.\n if (!supportsCloud && !supportsForgeops && !supportsClassic) {\n commandOmits.add(loginClientId.name());\n commandOmits.add(loginRedirectUri.name());\n }\n\n // register default arguments\n // This is the primary extension point for adding CLI-wide arguments.\n for (const arg of defaultArgs) {\n if (!commandOmits.has(arg.name())) this.addArgument(arg);\n }\n\n // register default options\n // This is the primary extension point for adding CLI-wide options.\n // The --prompt/--no-prompt pair needs special care: the STUB base\n // class registered them first (stub wording), but a live command's\n // semantics differ (--prompt opens the options editor), so the\n // singleton is REPLACED in place rather than skipped (commander\n // throws on re-registration; direct array replacement keeps the\n // parse-time lookup working). Every other option: existence-guarded\n // skip (none overlap today, the guard is for future safety).\n for (const opt of defaultOpts) {\n const existingIndex = this.options.findIndex(\n (option) =>\n option.name() === opt.name() ||\n option.flags === opt.flags ||\n // BOTH defined before comparing: undefined === undefined would\n // match EVERY short-less option (verified live -- it made the\n // replace branch clobber the array's first option).\n (opt.short !== undefined &&\n opt.short !== null &&\n option.short === opt.short)\n );\n if (commandOmits.has(opt.name())) continue;\n if (existingIndex === -1) {\n this.addOption(opt);\n } else if (\n (opt === promptOption || opt === noPromptOption) &&\n this.options[existingIndex] !== opt\n ) {\n // commander's .options is readonly-TYPED but a plain array at\n // runtime (verified: direct splice keeps the parse-time lookup\n // working).\n (this.options as Option[]).splice(existingIndex, 1, opt);\n }\n }\n\n this.options\n .find((option) => option.name() === 'help')\n ?.helpGroup(HELP_OPTIONS_HEADING);\n\n // additional help\n this.addHelpText('after', () =>\n isFullHelpRequested() ? formatEnvironmentVariables(this) : ''\n );\n }\n\n /**\n * Adds and normalizes an option before registration.\n * @param option Option to add.\n * @returns This command for chaining.\n */\n override addOption(option: Option) {\n // Clone to avoid mutating shared default option instances.\n const commandOption = cloneOption(option);\n\n if (!commandOption.helpGroupHeading) {\n commandOption.helpGroup(COMMAND_OPTIONS_HEADING);\n }\n\n return super.addOption(commandOption);\n }\n\n /**\n * Moves every currently-registered option under the given heading(s) into\n * the plain \"Options:\" section instead, for this command instance only.\n * Every other command adding the same shared default option (e.g.\n * `--browser`, `--sa-id`) keeps it under its usual heading — this\n * mutates only this instance's own cloned copies (see `addOption()`\n * above). Use it when a heading distinction that makes sense globally is\n * redundant for one specific command (e.g. `login`, where every option\n * already IS an authentication option, so a separate \"Authentication\n * Options:\" section adds a heading without adding information). Call\n * after every `addOption()`/default-option registration is done, since it\n * only sees options already on the command.\n * @param headings Heading(s) whose options should be reassigned.\n * @returns This command for chaining.\n */\n mergeHeadingIntoOptions(...headings: string[]) {\n for (const option of this.options) {\n if (headings.includes(option.helpGroupHeading)) {\n option.helpGroup(COMMAND_OPTIONS_HEADING);\n }\n }\n return this;\n }\n\n /**\n * Adds a cloned argument to avoid mutating shared definitions.\n * @param argument Argument to add.\n * @returns This command for chaining.\n */\n override addArgument(argument: Argument) {\n // Clone to avoid mutating shared default argument instances.\n return super.addArgument(cloneArgument(argument));\n }\n\n /**\n * Used by env var include predicates to detect whether a default argument\n * is currently present on this command.\n * @param argumentName Argument name to test.\n * @returns True when argument is present.\n */\n hasDefaultArgument(argumentName: string) {\n return this.registeredArguments.some(\n (argument) => argument.name() === argumentName\n );\n }\n\n /**\n * Used by env var include predicates to detect whether a default option\n * is currently present on this command.\n * @param optionName Option attribute/name to test.\n * @returns True when option is present.\n */\n hasDefaultOption(optionName: string) {\n return this.options.some(\n (option) =>\n option.attributeName() === optionName || option.name() === optionName\n );\n }\n\n /**\n * Applies shared default argument/option handlers to runtime state and then\n * invokes command-specific handler logic.\n * @param args Commander action arguments where trailing values are options and command.\n * @returns Promise from command action flow.\n */\n\n handleDefaultArgsAndOpts(...args: any) {\n const command = args.pop();\n const options = args.pop();\n\n // handle arguments first\n for (const [i, v] of command.args.entries()) {\n if (!command._args[i]) {\n printMessage(\n `${command.args.length} arguments supplied but command only supports ${command._args.length}.`,\n 'warn'\n );\n break;\n }\n const arg = command._args[i].name();\n // handle only default arguments\n if (Object.keys(stateMap).includes(arg)) {\n debugMessage(\n `FrodoCommand.handleDefaultArgsAndOpts: Handling default argument '${arg}'.`\n );\n\n const handler: any = stateMap[arg];\n handler(v);\n } else {\n debugMessage(\n `FrodoCommand.handleDefaultArgsAndOpts: Ignoring non-default argument '${arg}'.`\n );\n }\n }\n\n // handle options\n for (const [k, v] of Object.entries(options).sort(([k1], [k2]) => {\n if (k1 === envFileOption.attributeName()) return -1;\n if (k2 === envFileOption.attributeName()) return 1;\n if (k1 === envOption.attributeName()) return -1;\n if (k2 === envOption.attributeName()) return 1;\n return 0;\n })) {\n // handle only default options\n if (Object.keys(stateMap).includes(k)) {\n debugMessage(\n `FrodoCommand.handleDefaultArgsAndOpts: Handling default option '${k}'.`\n );\n\n const handler: any = stateMap[k];\n handler(v, options);\n } else {\n debugMessage(\n `FrodoCommand.handleDefaultArgsAndOpts: Ignoring non-default option '${k}'.`\n );\n }\n }\n\n // fail fast if an incompatible deployment type option (-m or --type) was provided\n if (\n state.getDeploymentType() &&\n !this.types.includes(state.getDeploymentType())\n ) {\n throw new FrodoError(\n `Command does not support deployment type '${state.getDeploymentType()}'`\n );\n }\n\n // Deliberately no fail-fast check here for --browser/--device without an\n // explicit --type: this runs synchronously, before any connection\n // profile can be consulted, so it can't tell \"genuinely unknown\" apart\n // from \"resolvable from a saved profile for this host\" — the exact case\n // a bare `frodo login <alias> --browser` needs to work without a\n // redundant --type. getTokensInteractive() (frodo-lib) now resolves\n // deploymentType from the profile itself when one isn't already known,\n // and throws its own clear error if it's still unresolvable there.\n }\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,46,47,48,52],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAa,iBAAb,cAAoC,MAAM;;;;;;;CAOxC,YAAY,UAAU,MAAM,SAAS;EACnC,MAAM,OAAO;EAEb,MAAM,kBAAkB,MAAM,KAAK,WAAW;EAC9C,KAAK,OAAO,KAAK,YAAY;EAC7B,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,cAAc,KAAA;CACrB;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,eAAe;;;;;CAKvD,YAAY,SAAS;EACnB,MAAM,GAAG,6BAA6B,OAAO;EAE7C,MAAM,kBAAkB,MAAM,KAAK,WAAW;EAC9C,KAAK,OAAO,KAAK,YAAY;CAC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;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,MAAM;EACJ,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,QAAQ;EACN,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,MAAM;EACN,QAAQ;GACN,OAAO;GACP,SAAS;GACT,SAAS;GACT,UAAU;GACV,SAAS;GACT,UAAU;GACV,UAAU;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,MAAM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