@highflame/overwatch 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +337 -0
  2. package/bin/overwatch +12 -0
  3. package/dist/auth/cli-oauth.d.ts +13 -0
  4. package/dist/auth/cli-oauth.d.ts.map +1 -0
  5. package/dist/auth/html-utils.d.ts +20 -0
  6. package/dist/auth/html-utils.d.ts.map +1 -0
  7. package/dist/auth/index.d.ts +10 -0
  8. package/dist/auth/index.d.ts.map +1 -0
  9. package/dist/auth/oauth.d.ts +81 -0
  10. package/dist/auth/oauth.d.ts.map +1 -0
  11. package/dist/auth/pkce.d.ts +26 -0
  12. package/dist/auth/pkce.d.ts.map +1 -0
  13. package/dist/auth/token-store.d.ts +44 -0
  14. package/dist/auth/token-store.d.ts.map +1 -0
  15. package/dist/bin/overwatch +12 -0
  16. package/dist/cli.d.ts +6 -0
  17. package/dist/cli.d.ts.map +1 -0
  18. package/dist/cli.js +5449 -0
  19. package/dist/cli.js.map +7 -0
  20. package/dist/config/index.d.ts +5 -0
  21. package/dist/config/index.d.ts.map +1 -0
  22. package/dist/config/manager.d.ts +54 -0
  23. package/dist/config/manager.d.ts.map +1 -0
  24. package/dist/daemon.d.ts +11 -0
  25. package/dist/daemon.d.ts.map +1 -0
  26. package/dist/daemon.js +6004 -0
  27. package/dist/daemon.js.map +7 -0
  28. package/dist/data/ingestor.d.ts +31 -0
  29. package/dist/data/ingestor.d.ts.map +1 -0
  30. package/dist/data/processor.d.ts +96 -0
  31. package/dist/data/processor.d.ts.map +1 -0
  32. package/dist/data/reader.d.ts +24 -0
  33. package/dist/data/reader.d.ts.map +1 -0
  34. package/dist/data/recorder.d.ts +12 -0
  35. package/dist/data/recorder.d.ts.map +1 -0
  36. package/dist/engines/cedar.d.ts +41 -0
  37. package/dist/engines/cedar.d.ts.map +1 -0
  38. package/dist/engines/remote.d.ts +21 -0
  39. package/dist/engines/remote.d.ts.map +1 -0
  40. package/dist/engines/yara.d.ts +12 -0
  41. package/dist/engines/yara.d.ts.map +1 -0
  42. package/dist/handlers/dashboard-handler.d.ts +7 -0
  43. package/dist/handlers/dashboard-handler.d.ts.map +1 -0
  44. package/dist/handlers/hook-handler.d.ts +23 -0
  45. package/dist/handlers/hook-handler.d.ts.map +1 -0
  46. package/dist/handlers/oauth-handler.d.ts +12 -0
  47. package/dist/handlers/oauth-handler.d.ts.map +1 -0
  48. package/dist/handlers/scan-handler.d.ts +13 -0
  49. package/dist/handlers/scan-handler.d.ts.map +1 -0
  50. package/dist/handlers/utils.d.ts +11 -0
  51. package/dist/handlers/utils.d.ts.map +1 -0
  52. package/dist/hooks/claudecode/hooks.json.template +20 -0
  53. package/dist/hooks/cursor/hooks.json.template +74 -0
  54. package/dist/hooks/universal-hook.sh +36 -0
  55. package/dist/http/server.d.ts +38 -0
  56. package/dist/http/server.d.ts.map +1 -0
  57. package/dist/index.d.ts +8 -0
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +5941 -0
  60. package/dist/index.js.map +7 -0
  61. package/dist/installer.d.ts +25 -0
  62. package/dist/installer.d.ts.map +1 -0
  63. package/dist/javelin/admin-client.d.ts +75 -0
  64. package/dist/javelin/admin-client.d.ts.map +1 -0
  65. package/dist/javelin/client.d.ts +30 -0
  66. package/dist/javelin/client.d.ts.map +1 -0
  67. package/dist/javelin/config-reader.d.ts +70 -0
  68. package/dist/javelin/config-reader.d.ts.map +1 -0
  69. package/dist/javelin/index.d.ts +5 -0
  70. package/dist/javelin/index.d.ts.map +1 -0
  71. package/dist/javelin/types.d.ts +81 -0
  72. package/dist/javelin/types.d.ts.map +1 -0
  73. package/dist/lib/policy-engine.d.ts +34 -0
  74. package/dist/lib/policy-engine.d.ts.map +1 -0
  75. package/dist/lib/policy-manager.d.ts +86 -0
  76. package/dist/lib/policy-manager.d.ts.map +1 -0
  77. package/dist/module.d.ts +52 -0
  78. package/dist/module.d.ts.map +1 -0
  79. package/dist/pipeline/context-mapper.d.ts +16 -0
  80. package/dist/pipeline/context-mapper.d.ts.map +1 -0
  81. package/dist/pipeline/extractors/claude-extractor.d.ts +48 -0
  82. package/dist/pipeline/extractors/claude-extractor.d.ts.map +1 -0
  83. package/dist/pipeline/extractors/cursor-extractor.d.ts +44 -0
  84. package/dist/pipeline/extractors/cursor-extractor.d.ts.map +1 -0
  85. package/dist/pipeline/extractors/github-copilot-extractor.d.ts +49 -0
  86. package/dist/pipeline/extractors/github-copilot-extractor.d.ts.map +1 -0
  87. package/dist/pipeline/extractors/index.d.ts +47 -0
  88. package/dist/pipeline/extractors/index.d.ts.map +1 -0
  89. package/dist/pipeline/extractors/registry.d.ts +38 -0
  90. package/dist/pipeline/extractors/registry.d.ts.map +1 -0
  91. package/dist/pipeline/hook-pipeline.d.ts +25 -0
  92. package/dist/pipeline/hook-pipeline.d.ts.map +1 -0
  93. package/dist/policy.cedar +783 -0
  94. package/dist/rules/pre/command_injection.yar +60 -0
  95. package/dist/rules/pre/cross_origin_escalation.yar +106 -0
  96. package/dist/rules/pre/mcp_config_risk.yar +35 -0
  97. package/dist/rules/pre/path_traversal.yar +50 -0
  98. package/dist/rules/pre/prompt_injection.yar +101 -0
  99. package/dist/rules/pre/secrets_leakage.yar +100 -0
  100. package/dist/rules/pre/sql_injection.yar +65 -0
  101. package/dist/scanner.d.ts +80 -0
  102. package/dist/scanner.d.ts.map +1 -0
  103. package/dist/service.d.ts +18 -0
  104. package/dist/service.d.ts.map +1 -0
  105. package/dist/services/interface.d.ts +11 -0
  106. package/dist/services/interface.d.ts.map +1 -0
  107. package/dist/services/launchd.d.ts +12 -0
  108. package/dist/services/launchd.d.ts.map +1 -0
  109. package/dist/services/systemd.d.ts +12 -0
  110. package/dist/services/systemd.d.ts.map +1 -0
  111. package/dist/services/windows.d.ts +7 -0
  112. package/dist/services/windows.d.ts.map +1 -0
  113. package/dist/skills/index.d.ts +7 -0
  114. package/dist/skills/index.d.ts.map +1 -0
  115. package/dist/skills/scanner.d.ts +44 -0
  116. package/dist/skills/scanner.d.ts.map +1 -0
  117. package/dist/skills/types.d.ts +29 -0
  118. package/dist/skills/types.d.ts.map +1 -0
  119. package/dist/types/config.d.ts +165 -0
  120. package/dist/types/config.d.ts.map +1 -0
  121. package/dist/types/events.d.ts +225 -0
  122. package/dist/types/events.d.ts.map +1 -0
  123. package/dist/types/index.d.ts +6 -0
  124. package/dist/types/index.d.ts.map +1 -0
  125. package/dist/types/remote-policy.d.ts +129 -0
  126. package/dist/types/remote-policy.d.ts.map +1 -0
  127. package/dist/types/requests.d.ts +45 -0
  128. package/dist/types/requests.d.ts.map +1 -0
  129. package/dist/types/responses.d.ts +60 -0
  130. package/dist/types/responses.d.ts.map +1 -0
  131. package/dist/ui/images/highflame-mono.png +0 -0
  132. package/dist/ui/views/dashboard.ejs +301 -0
  133. package/dist/ui/views/dashboard.js +785 -0
  134. package/dist/ui/views/partials/commands-table.ejs +54 -0
  135. package/dist/ui/views/partials/events-table.ejs +36 -0
  136. package/dist/ui/views/partials/filter-dropdown.ejs +12 -0
  137. package/dist/ui/views/partials/overview-charts.ejs +149 -0
  138. package/dist/ui/views/partials/scans-table.ejs +136 -0
  139. package/dist/ui/views/partials/sessions-table.ejs +50 -0
  140. package/dist/ui/views/partials/stats-grid.ejs +23 -0
  141. package/dist/ui/views/partials/threats-table.ejs +60 -0
  142. package/dist/utils/index.d.ts +3 -0
  143. package/dist/utils/index.d.ts.map +1 -0
  144. package/dist/utils/logger.d.ts +28 -0
  145. package/dist/utils/logger.d.ts.map +1 -0
  146. package/dist/utils/performance.d.ts +26 -0
  147. package/dist/utils/performance.d.ts.map +1 -0
  148. package/dist/utils/port-manager.d.ts +6 -0
  149. package/dist/utils/port-manager.d.ts.map +1 -0
  150. package/dist/yara/engine.d.ts +58 -0
  151. package/dist/yara/engine.d.ts.map +1 -0
  152. package/dist/yara/index.d.ts +5 -0
  153. package/dist/yara/index.d.ts.map +1 -0
  154. package/lib/platform-loader.js +210 -0
  155. package/package.json +63 -0
  156. package/scripts/postinstall.js +121 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "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", "../src/auth/pkce.ts", "../src/auth/oauth.ts", "../src/utils/logger.ts", "../src/utils/performance.ts", "../src/utils/index.ts", "../src/skills/types.ts", "../src/skills/scanner.ts", "../src/skills/index.ts", "../node_modules/commander/esm.mjs", "../src/installer.ts", "../src/handlers/utils.ts", "../src/services/launchd.ts", "../src/services/systemd.ts", "../src/services/windows.ts", "../src/service.ts", "../src/auth/index.ts", "../src/auth/cli-oauth.ts", "../node_modules/open/index.js", "../node_modules/wsl-utils/index.js", "../node_modules/is-wsl/index.js", "../node_modules/is-inside-container/index.js", "../node_modules/is-docker/index.js", "../node_modules/powershell-utils/index.js", "../node_modules/wsl-utils/utilities.js", "../node_modules/define-lazy-prop/index.js", "../node_modules/default-browser/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/is-in-ssh/index.js", "../src/auth/token-store.ts", "../src/auth/html-utils.ts", "../src/config/manager.ts", "../src/types/config.ts", "../src/types/remote-policy.ts", "../src/cli.ts"],
4
+ "sourcesContent": ["/**\n * CommanderError class\n * @class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @constructor\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 * @class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n * @constructor\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @api private\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\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 * @api private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required\n ? '<' + nameOutput + '>'\n : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);\n if (cmd._hasImplicitHelpCommand()) {\n // Create a command matching the implicit help command.\n const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);\n const helpCommand = cmd.createCommand(helpName)\n .helpOption(false);\n helpCommand.description(cmd._helpCommandDescription);\n if (helpArgs) helpCommand.arguments(helpArgs);\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: 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 ? option.short.replace(/^-/, '') : 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 // Implicit help\n const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);\n const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);\n if (showShortHelpFlag || showLongHelpFlag) {\n let helpOption;\n if (!showShortHelpFlag) {\n helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);\n } else if (!showLongHelpFlag) {\n helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);\n } else {\n helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);\n }\n visibleOptions.push(helpOption);\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 (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {\n const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);\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 = 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.map(arg => humanReadableArgName(arg)).join(' ');\n return 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 * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {\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: 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: 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 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 = option.required || option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(helper.optionTerm(option), helper.optionDescription(option));\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {\n return formatItem(helper.optionTerm(option), helper.optionDescription(option));\n });\n if (globalOptionList.length > 0) {\n output = output.concat(['Global Options:', formatList(globalOptionList), '']);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper)\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents = ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(`\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');\n const lines = columnText.match(regex) || [];\n return leadingStr + lines.map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return ((i > 0) ? indentString : '') + line.trimEnd();\n }).join('\\n');\n }\n}\n\nexports.Help = Help;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {string | string[]} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {Object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @api private\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n * @api private\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @api private\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 * @api private\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach(option => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = (preset !== undefined) ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @api 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 * @api private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.splitOptionFlags = splitOptionFlags;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map(candidate => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map(candidate => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('events').EventEmitter;\nconst childProcess = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\nconst process = require('process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, splitOptionFlags, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {boolean | string} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str)\n };\n\n this._hidden = false;\n this._hasHelpOption = true;\n this._helpFlags = '-h, --help';\n this._helpDescription = 'display help for command';\n this._helpShortFlag = '-h';\n this._helpLongFlag = '--help';\n this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false\n this._helpCommandName = 'help';\n this._helpCommandnameAndArgs = 'help [command]';\n this._helpCommandDescription = 'display help for command';\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._hasHelpOption = sourceCommand._hasHelpOption;\n this._helpFlags = sourceCommand._helpFlags;\n this._helpDescription = sourceCommand._helpDescription;\n this._helpShortFlag = sourceCommand._helpShortFlag;\n this._helpLongFlag = sourceCommand._helpLongFlag;\n this._helpCommandName = sourceCommand._helpCommandName;\n this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;\n this._helpCommandDescription = sourceCommand._helpCommandDescription;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue = 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 * @api private\n */\n\n _getCommandAndAncestors() {\n const result = [];\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.commands.push(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {Object} [configuration] - configuration options\n * @return {Command|Object} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {Object} [configuration] - configuration options\n * @return {Command|Object} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {boolean|string} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {Object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this.commands.push(cmd);\n cmd.parent = this;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {Function|*} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names.trim().split(/ +/).forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);\n }\n if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {\n throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Override default decision whether to add implicit help command.\n *\n * addHelpCommand() // force on\n * addHelpCommand(false); // force off\n * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details\n *\n * @return {Command} `this` command for chaining\n */\n\n addHelpCommand(enableOrNameAndArgs, description) {\n if (enableOrNameAndArgs === false) {\n this._addImplicitHelpCommand = false;\n } else {\n this._addImplicitHelpCommand = true;\n if (typeof enableOrNameAndArgs === 'string') {\n this._helpCommandName = enableOrNameAndArgs.split(' ')[0];\n this._helpCommandnameAndArgs = enableOrNameAndArgs;\n }\n this._helpCommandDescription = description || this._helpCommandDescription;\n }\n return this;\n }\n\n /**\n * @return {boolean}\n * @api private\n */\n\n _hasImplicitHelpCommand() {\n if (this._addImplicitHelpCommand === undefined) {\n return this.commands.length && !this._actionHandler && !this._findCommand('help');\n }\n return this._addImplicitHelpCommand;\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 * @api 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 * @api 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 * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // register the option\n this.options.push(option);\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @api private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {Function|*} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {Function|*} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);\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=true] - if `true` or omitted, an optional value can be specified directly after the flag.\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=true] - if `true` or omitted, no error will be thrown\n * for unknown options.\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=true] - if `true` or omitted, no error will be thrown\n * for excess arguments.\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=true]\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=true]\n * for unknown options.\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {\n throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');\n }\n return this;\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('call .storeOptionsAsProperties() before setting option values');\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 * @api 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 // Default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n // @ts-ignore: unknown property\n if (process.versions && process.versions.electron) {\n parseOptions.from = 'electron';\n }\n }\n this.rawArgs = argv.slice();\n\n // make it a little easier for callers by supporting various argv conventions\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: 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 default:\n throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath) 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 * The default expectation is that the arguments are from node and have the application as argv[0]\n * and the script being run in argv[1], with user parameters after that.\n *\n * @example\n * program.parse(process.argv);\n * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.\n *\n * The default expectation is that the arguments are from node and have the application as argv[0]\n * and the script being run in argv[1], with user parameters after that.\n *\n * @example\n * await program.parseAsync(process.argv);\n * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {Object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @api private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));\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 = subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);\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(this._scriptPath, path.extname(this._scriptPath));\n if (legacyName !== this._name) {\n localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) { // 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 // @ts-ignore\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!\n const exitCallback = this._exitCallback;\n if (!exitCallback) {\n proc.on('close', process.exit.bind(process));\n } else {\n proc.on('close', () => {\n exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));\n });\n }\n proc.on('error', (err) => {\n // @ts-ignore\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore\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(1, 'commander.executeSubCommandAsync', '(error)');\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 * @api private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');\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 * @api 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(subcommandName, [], [\n this._helpLongFlag || this._helpShortFlag\n ]);\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @api 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 (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {\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 * @api 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(argument, value, previous, invalidValueMessage);\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 * @api private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {Promise|undefined} promise\n * @param {string} event\n * @return {Promise|undefined}\n * @api 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 * @api 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 * @api 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 (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);\n }\n if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n outputHelpIfRequested(this, 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, () => this._actionHandler(this.processedArgs));\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) { // 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 * @api private\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @api private\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 * @api 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 (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {\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 * @api private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter(\n (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\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 * @api private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {String[]} argv\n * @return {{operands: String[], unknown: String[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else { // 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 (option.required || (option.optional && this._combineFlagAndOptionalValue)) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {Object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] = 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(`${message}\\n`, this._outputConfiguration.writeErr);\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 * @api 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 (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {\n if (option.required || option.optional) { // 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 { // 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 * @api private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));\n };\n this.options\n .filter(option => (option.implied !== undefined) &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))\n .forEach((option) => {\n Object.keys(option.implied)\n .filter(impliedKey => !hasCustomOptionValue(impliedKey))\n .forEach(impliedKey => {\n this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @api 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 * @api 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 * @api 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 * @api 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(target => target.negate && optionKey === target.attributeName());\n const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());\n if (negativeOption && (\n (negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined && 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 * @api 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 let command = this;\n do {\n const moreFlags = command.createHelp().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 * @api private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = (expected === 1) ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @api 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().visibleCommands(this).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(); // [sic] not defined in constructor, partly legacy, partly only needed at root\n this.options.push(versionOption);\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) 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 let command = this;\n if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {\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) throw new Error('Command alias can\\'t be the same as its name');\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 [].concat(\n (this.options.length || this._hasHelpOption ? '[options]' : []),\n (this.commands.length ? '[command]' : []),\n (this.registeredArguments.length ? args : [])\n ).join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {string|Command}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {string|null|Command}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @api private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors().reverse().forEach(command => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._helpLongFlag) {\n this.emit(this._helpLongFlag); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));\n }\n\n /**\n * You can pass in flags and a description to override the help\n * flags and help description for your command. Pass in false to\n * disable the built-in help option.\n *\n * @param {string | boolean} [flags]\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n if (typeof flags === 'boolean') {\n this._hasHelpOption = flags;\n return this;\n }\n this._helpFlags = flags || this._helpFlags;\n this._helpDescription = description || this._helpDescription;\n\n const helpFlags = splitOptionFlags(this._helpFlags);\n this._helpShortFlag = helpFlags.shortFlag;\n this._helpLongFlag = helpFlags.longFlag;\n\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {string | Function} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n}\n\n/**\n * Output help information if help flags specified\n *\n * @param {Command} cmd - command to output help for\n * @param {Array} args - array of options to search for help flags\n * @api private\n */\n\nfunction outputHelpIfRequested(cmd, args) {\n const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);\n if (helpOption) {\n cmd.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');\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 * @api 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 ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {\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 ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\n/**\n * Expose the root command.\n */\n\nexports = module.exports = new Command();\nexports.program = exports; // More explicit access to global command.\n// createArgument, createCommand, and createOption are implicitly available as they are methods on program.\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "/**\n * PKCE (Proof Key for Code Exchange) utilities\n * Used for secure OAuth 2.0 flow without client_secret (public client)\n * RFC 7636: https://tools.ietf.org/html/rfc7636\n */\n\nimport * as crypto from \"crypto\";\n\n/**\n * Base64 URL encoding (no padding, URL-safe characters)\n * Per RFC 7636 Appendix A\n */\nfunction base64URLEncode(buffer: Buffer): string {\n return buffer\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n\n/**\n * Generate a cryptographically random code verifier\n * Per RFC 7636: 43-128 characters, using unreserved characters\n * [A-Z] / [a-z] / [0-9] / \"-\" / \".\" / \"_\" / \"~\"\n *\n * We use 32 random bytes \u2192 43 base64url characters\n */\nexport function generateCodeVerifier(): string {\n const buffer = crypto.randomBytes(32);\n return base64URLEncode(buffer);\n}\n\n/**\n * Generate code challenge from verifier using S256 method\n * challenge = BASE64URL(SHA256(verifier))\n *\n * S256 is more secure than plain method and required by most OAuth providers\n */\nexport function generateCodeChallenge(verifier: string): string {\n const hash = crypto.createHash(\"sha256\").update(verifier).digest();\n return base64URLEncode(hash);\n}\n\n/**\n * Generate random state parameter for CSRF protection\n * Returns 32-character hex string (16 random bytes)\n */\nexport function generateState(): string {\n return crypto.randomBytes(16).toString(\"hex\");\n}\n", "/**\n * OAuth 2.0 flow manager for Highflame authentication\n * Uses PKCE for secure public client authentication\n */\n\nimport { generateCodeVerifier, generateState } from \"./pkce\";\n\n/**\n * OAuth configuration for Highflame Studio\n */\nexport const OAUTH_CONFIG = {\n authUrl: \"https://studio.api-dev.highflame.dev/cli-auth\",\n tokenUrl: \"https://studio.api-dev.highflame.dev/api/cli-auth/token\",\n clientId: \"overwatch-cli\",\n scopes: [\"account:read\", \"gateway:read\"],\n};\n\n/**\n * Token expiry: 90 days in seconds\n */\nexport const TOKEN_EXPIRY_SECONDS = 90 * 24 * 60 * 60; // 7,776,000 seconds\n\n/**\n * Pending OAuth flow state\n */\nexport interface OAuthState {\n state: string;\n codeVerifier: string;\n redirectUri: string;\n createdAt: number;\n status: \"pending\" | \"completed\" | \"failed\" | \"expired\";\n tokens?: TokenResponse;\n error?: string;\n userInfo?: UserInfo;\n}\n\n/**\n * Token response from Highflame Studio API\n */\nexport interface TokenResponse {\n access_token: string;\n refresh_token?: string; // Optional, not always returned\n expires_in: number; // seconds\n token_type: \"Bearer\";\n expires_at?: number; // computed Unix timestamp in milliseconds\n scope?: string;\n user?: {\n id: string;\n email: string;\n };\n}\n\n/**\n * User information from Highflame Studio API\n */\nexport interface UserInfo {\n id: string;\n email: string;\n}\n\n/**\n * Build the OAuth authorization URL with PKCE parameters\n */\nexport function buildAuthorizationUrl(\n state: string,\n codeChallenge: string,\n redirectUri: string,\n): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: OAUTH_CONFIG.clientId,\n redirect_uri: redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n state: state,\n scope: OAUTH_CONFIG.scopes.join(\" \"),\n });\n\n return `${OAUTH_CONFIG.authUrl}?${params.toString()}`;\n}\n\n/**\n * Exchange authorization code for tokens\n * Public client flow - no client_secret required, PKCE verifier proves identity\n */\nexport async function exchangeCodeForTokens(\n code: string,\n codeVerifier: string,\n redirectUri: string,\n): Promise<{ tokens: TokenResponse; userInfo: UserInfo }> {\n console.log(\"[OAuth] Exchanging code for tokens...\");\n console.log(\"[OAuth] Token URL:\", OAUTH_CONFIG.tokenUrl);\n\n const response = await fetch(OAUTH_CONFIG.tokenUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify({\n grant_type: \"authorization_code\",\n client_id: OAUTH_CONFIG.clientId,\n code: code,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier,\n }),\n signal: AbortSignal.timeout(30000),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error(\"[OAuth] Token exchange failed:\", response.status, errorText);\n throw new Error(`Token exchange failed: ${response.status} ${errorText}`);\n }\n\n const data = (await response.json()) as TokenResponse;\n console.log(\"[OAuth] Token exchange successful\");\n\n // Compute absolute expiry timestamp\n // Use provided expires_in or default to 90 days\n const expiresInSeconds = data.expires_in || TOKEN_EXPIRY_SECONDS;\n data.expires_at = Date.now() + expiresInSeconds * 1000;\n\n // Extract user info from token response\n const userInfo: UserInfo = {\n id: data.user?.id || \"\",\n email: data.user?.email || \"\",\n };\n\n return { tokens: data, userInfo };\n}\n\n/**\n * Refresh access token using refresh token\n * Placeholder for future refresh endpoint implementation\n */\nexport async function refreshAccessToken(\n _refreshToken: string,\n): Promise<TokenResponse | null> {\n // TODO: Implement refresh token endpoint when available\n // For now, return null to indicate re-authentication is needed\n return null;\n}\n\n/**\n * Check if tokens are expired or about to expire\n * @param expiresAt Unix timestamp in milliseconds\n * @param bufferSeconds Buffer time before actual expiry (default: 1 day)\n */\nexport function isTokenExpired(\n expiresAt: number,\n bufferSeconds: number = 86400,\n): boolean {\n return Date.now() >= expiresAt - bufferSeconds * 1000;\n}\n\n/**\n * Create a new OAuth flow state\n * @param guardianPort The port Guardian daemon is running on\n */\nexport function createOAuthState(guardianPort: number): OAuthState {\n const state = generateState();\n const codeVerifier = generateCodeVerifier();\n const redirectUri = `http://127.0.0.1:${guardianPort}/oauth/callback`;\n\n return {\n state,\n codeVerifier,\n redirectUri,\n createdAt: Date.now(),\n status: \"pending\",\n };\n}\n", "import * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\n/**\n * Log levels\n */\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\n// Log file path\nconst LOG_FILE = path.join(os.homedir(), \".overwatch\", \"guardian.log\");\n\n/**\n * Simple logger utility with file output\n */\nexport class Logger {\n private level: LogLevel;\n private fileEnabled: boolean = true;\n\n constructor(level: LogLevel = LogLevel.INFO) {\n this.level = level;\n this.ensureLogDir();\n }\n\n private ensureLogDir(): void {\n try {\n const dir = path.dirname(LOG_FILE);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n } catch {\n this.fileEnabled = false;\n }\n }\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n private getCallerFile(offset: number): string {\n const err = new Error();\n const stack = err.stack?.split(\"\\n\");\n if (stack && stack.length > offset) {\n const callerLine = stack[offset] || \"\";\n const match = callerLine.match(/at\\s+(?:.*\\s+\\()?(.+?):\\d+:\\d+\\)?$/);\n if (match && match[1]) {\n return path.basename(match[1]);\n }\n }\n return \"unknown\";\n }\n\n private formatArgs(args: unknown[]): string {\n if (args.length === 0) return \"\";\n\n return args\n .map((arg) => {\n if (typeof arg === \"object\" && arg !== null) {\n try {\n return JSON.stringify(arg)\n .replace(/^{|}$/g, \"\")\n .replace(/\"([^\"]+)\":/g, \"$1=\");\n } catch {\n return String(arg);\n }\n }\n return String(arg);\n })\n .join(\" \");\n }\n\n private writeToFile(level: string, message: string, args: unknown[]): void {\n if (!this.fileEnabled) return;\n\n try {\n const timestamp = new Date().toISOString();\n const callerFile = this.getCallerFile(4); // Error -> getCallerFile -> writeToFile -> info -> caller\n const formattedArgs = this.formatArgs(args);\n const argsStr = formattedArgs ? \" \" + formattedArgs : \"\";\n const line = `${timestamp} [${level.padEnd(5)}] [${callerFile}] ${message}${argsStr}\\n`;\n fs.appendFileSync(LOG_FILE, line);\n } catch {\n // Silently fail file writes\n }\n }\n\n debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n const callerFile = this.getCallerFile(3); // Error -> getCallerFile -> debug -> caller\n console.debug(`[DEBUG] [${callerFile}] ${message}`, ...args);\n this.writeToFile(\"DEBUG\", message, args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n const callerFile = this.getCallerFile(3);\n console.info(`[INFO ] [${callerFile}] ${message}`, ...args);\n this.writeToFile(\"INFO\", message, args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n const callerFile = this.getCallerFile(3);\n console.warn(`[WARN ] [${callerFile}] ${message}`, ...args);\n this.writeToFile(\"WARN\", message, args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n const callerFile = this.getCallerFile(3);\n console.error(`[ERROR] [${callerFile}] ${message}`, ...args);\n this.writeToFile(\"ERROR\", message, args);\n }\n }\n}\n\n// Singleton logger instance\nexport const logger = new Logger();\n", "/**\n * Performance measurement utility\n */\nexport class PerformanceMonitor {\n private startTime: number;\n\n constructor() {\n this.startTime = Date.now();\n }\n\n /**\n * Measure execution time of async function\n */\n static async measure<T>(\n fn: () => Promise<T>,\n ): Promise<{ result: T; duration: number }> {\n const start = Date.now();\n const result = await fn();\n const duration = Date.now() - start;\n return { result, duration };\n }\n\n /**\n * Measure execution time of sync function\n */\n static measureSync<T>(fn: () => T): { result: T; duration: number } {\n const start = Date.now();\n const result = fn();\n const duration = Date.now() - start;\n return { result, duration };\n }\n\n /**\n * Get uptime in milliseconds\n */\n getUptime(): number {\n return Date.now() - this.startTime;\n }\n}\n", "export * from \"./logger\";\nexport * from \"./performance\";\n", "/**\n * Skills Scanner Types\n * Type definitions for Claude Code skills scanning\n */\n\nexport interface SkillRecord {\n /** Directory name (skill identifier) */\n name: string;\n /** Full path to skill directory */\n path: string;\n /** Full SKILL.md content (raw) */\n content: string;\n /** SHA256 for backend deduplication */\n contentHash: string;\n /** Other files in skill directory */\n files: string[];\n}\n\nexport interface SkillScanResult {\n /** ISO timestamp */\n timestamp: string;\n /** Number of skills found */\n totalSkills: number;\n /** List of scanned skills */\n skills: SkillRecord[];\n /** Duration in milliseconds */\n scanDurationMs: number;\n /** Workspace path (present for project-level scans) */\n workspace?: string;\n}\n", "/**\n * Skills Scanner\n * Stateless scanner for personal skills from:\n * - ~/.claude/skills/ (Claude Code)\n * - ~/.cursor/skills/ (Cursor)\n * Backend handles change detection via contentHash\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport * as crypto from \"crypto\";\nimport { SkillRecord, SkillScanResult } from \"./types\";\nimport { logger } from \"../utils\";\n\nconst CLAUDE_SKILLS_DIR = path.join(os.homedir(), \".claude\", \"skills\");\nconst CURSOR_SKILLS_DIR = path.join(os.homedir(), \".cursor\", \"skills\");\n\nexport class SkillsScanner {\n /**\n * Scan personal skills from both directories:\n * - ~/.claude/skills/\n * - ~/.cursor/skills/\n * Returns current state\n */\n async scan(): Promise<SkillScanResult> {\n const startTime = Date.now();\n\n logger.info(\"Starting skills scan\", {\n directories: [CLAUDE_SKILLS_DIR, CURSOR_SKILLS_DIR],\n });\n\n // Scan both directories in parallel\n const [claudeSkills, cursorSkills] = await Promise.all([\n this.scanDirectory(CLAUDE_SKILLS_DIR),\n this.scanDirectory(CURSOR_SKILLS_DIR),\n ]);\n\n const skills = [...claudeSkills, ...cursorSkills];\n const scanDurationMs = Date.now() - startTime;\n\n const result: SkillScanResult = {\n timestamp: new Date().toISOString(),\n totalSkills: skills.length,\n skills,\n scanDurationMs,\n };\n\n logger.info(\"Skills scan completed\", {\n totalSkills: skills.length,\n durationMs: scanDurationMs,\n });\n\n return result;\n }\n\n /**\n * Scan skills directory\n */\n private async scanDirectory(dir: string): Promise<SkillRecord[]> {\n const skills: SkillRecord[] = [];\n\n if (!(await this.exists(dir))) {\n logger.debug(\"Skills directory does not exist\", { dir });\n return skills;\n }\n\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n\n const skillDir = path.join(dir, entry.name);\n const content = await this.readSkillContent(skillDir);\n\n if (content === null) {\n // No SKILL.md in this directory\n continue;\n }\n\n const files = await this.listSkillFiles(skillDir);\n const contentHash = this.hashContent(content);\n\n skills.push({\n name: entry.name,\n path: skillDir,\n content,\n contentHash,\n files,\n });\n }\n } catch (error) {\n logger.error(\"Failed to scan skills directory\", {\n dir,\n error: String(error),\n });\n }\n\n return skills;\n }\n\n /**\n * Check if a path exists\n */\n private async exists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read full SKILL.md content\n */\n private async readSkillContent(skillDir: string): Promise<string | null> {\n const skillFile = path.join(skillDir, \"SKILL.md\");\n\n if (!(await this.exists(skillFile))) {\n return null;\n }\n\n try {\n return await fs.readFile(skillFile, \"utf-8\");\n } catch (error) {\n logger.error(\"Failed to read skill file\", {\n skillFile,\n error: String(error),\n });\n return null;\n }\n }\n\n /**\n * List files in skill directory (recursive)\n */\n private async listSkillFiles(skillDir: string): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const listFiles = async (\n dir: string,\n prefix: string = \"\"\n ): Promise<void> => {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;\n\n if (entry.isDirectory()) {\n await listFiles(path.join(dir, entry.name), relativePath);\n } else {\n files.push(relativePath);\n }\n }\n };\n\n await listFiles(skillDir);\n } catch (error) {\n logger.error(\"Failed to list skill files\", {\n skillDir,\n error: String(error),\n });\n }\n\n return files;\n }\n\n /**\n * Hash content for backend deduplication\n */\n private hashContent(content: string): string {\n const hash = crypto.createHash(\"sha256\");\n hash.update(content);\n return `sha256:${hash.digest(\"hex\")}`;\n }\n\n /**\n * Scan project-level skills from:\n * - {workspace}/.claude/skills/\n * - {workspace}/.cursor/skills/\n */\n async scanProjectSkills(workspace: string): Promise<SkillScanResult> {\n const startTime = Date.now();\n const claudeSkillsDir = path.join(workspace, \".claude\", \"skills\");\n const cursorSkillsDir = path.join(workspace, \".cursor\", \"skills\");\n\n logger.info(\"Starting project skills scan\", {\n workspace,\n directories: [claudeSkillsDir, cursorSkillsDir],\n });\n\n // Scan both directories in parallel\n const [claudeSkills, cursorSkills] = await Promise.all([\n this.scanDirectory(claudeSkillsDir),\n this.scanDirectory(cursorSkillsDir),\n ]);\n\n const skills = [...claudeSkills, ...cursorSkills];\n const scanDurationMs = Date.now() - startTime;\n\n const result: SkillScanResult = {\n timestamp: new Date().toISOString(),\n totalSkills: skills.length,\n skills,\n scanDurationMs,\n workspace,\n };\n\n logger.info(\"Project skills scan completed\", {\n workspace,\n totalSkills: skills.length,\n durationMs: scanDurationMs,\n });\n\n return result;\n }\n}\n", "/**\n * Skills Scanner Module\n * Exports for scanning Claude Code personal skills\n */\n\nexport * from \"./types\";\nexport * from \"./scanner\";\n", "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help\n} = commander;\n", "/**\n * Hook Installer\n * Installs IDE-specific hooks that integrate with Guardian daemon\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\nimport { getDefaultResponse } from \"./handlers/utils\";\n\nconst SUPPORTED_IDES = [\"cursor\", \"claudecode\", \"github_copilot\"];\n\ninterface InstallResult {\n ide: string;\n hooksPath: string;\n hooksInstalled: boolean;\n}\n\n/**\n * Update ~/.claude/settings.json with auto-approve permissions\n * This prevents Claude Code from prompting for every hook execution\n */\nasync function updateClaudeSettings(hooksDir: string): Promise<void> {\n const settingsPath = path.join(os.homedir(), \".claude\", \"settings.json\");\n const overwatchDir = path.join(os.homedir(), \".overwatch\");\n\n // Permissions to add for auto-approve\n const newPermissions = [\n `Read(${overwatchDir}/**)`,\n `Write(${overwatchDir}/**)`,\n `Bash(${hooksDir}/**)`,\n ];\n\n // Read or create settings\n let settings: any = {};\n if (fs.existsSync(settingsPath)) {\n try {\n settings = JSON.parse(fs.readFileSync(settingsPath, \"utf-8\"));\n } catch {\n settings = {};\n }\n }\n\n // Initialize permissions structure if needed\n if (!settings.permissions) {\n settings.permissions = {};\n }\n if (!Array.isArray(settings.permissions.allow)) {\n settings.permissions.allow = [];\n }\n\n // Add new permissions (avoid duplicates)\n for (const perm of newPermissions) {\n if (!settings.permissions.allow.includes(perm)) {\n settings.permissions.allow.push(perm);\n }\n }\n\n // Write settings\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true });\n fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));\n console.log(`\u2705 Added permissions to ${settingsPath}`);\n}\n\n/**\n * Ensure guardian daemon is running\n */\nasync function ensureDaemonRunning(): Promise<void> {\n const portFile = path.join(os.homedir(), \".overwatch\", \"guardian_port\");\n\n if (!fs.existsSync(portFile)) {\n console.log(\"\u26A0\uFE0F Guardian daemon is not running.\");\n console.log(\" Starting daemon...\");\n\n // Start daemon\n const { spawn } = await import(\"child_process\");\n const daemonPath = path.join(__dirname, \"daemon.js\");\n const guardianDir = path.dirname(__dirname);\n\n const proc = spawn(process.execPath, [daemonPath], {\n detached: true,\n stdio: \"ignore\",\n cwd: guardianDir,\n env: {\n ...process.env,\n NODE_PATH: path.join(guardianDir, \"node_modules\"),\n },\n });\n\n proc.unref();\n\n // Wait for daemon to start\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n if (!fs.existsSync(portFile)) {\n throw new Error(\"Failed to start Guardian daemon\");\n }\n\n console.log(\"\u2705 Guardian daemon started\");\n }\n}\n\n/**\n * Update guardian config with IDE settings\n */\nasync function updateGuardianConfig(\n ide: string,\n enabled: boolean,\n): Promise<void> {\n const configPath = path.join(os.homedir(), \".overwatch\", \"config.json\");\n const ideDir = path.join(os.homedir(), \".overwatch\", ide);\n\n let config: any = {\n version: \"2.0\",\n daemon: {\n autoStart: true,\n ports: [17580, 17581, 17582, 17583, 17584],\n logLevel: \"info\",\n },\n engines: {\n yara: {\n enabled: true,\n rulesDir: path.join(os.homedir(), \".overwatch\", \"rules\", \"pre\"),\n },\n cedar: {\n enabled: true,\n policyFile: path.join(os.homedir(), \".overwatch\", \"policy.cedar\"),\n },\n javelin: {\n enabled: false,\n apiKey: \"env:JAVELIN_API_KEY\",\n },\n },\n ides: {},\n };\n\n // Read existing config if it exists\n if (fs.existsSync(configPath)) {\n config = JSON.parse(fs.readFileSync(configPath, \"utf-8\"));\n }\n\n // Update IDE config\n if (!config.ides) {\n config.ides = {};\n }\n\n config.ides[ide] = {\n enabled,\n mode: \"enforce\",\n hooksInstalled: enabled,\n hooksPath: path.join(ideDir, \"hooks\"),\n };\n\n // Write config\n fs.mkdirSync(path.dirname(configPath), { recursive: true });\n fs.writeFileSync(configPath, JSON.stringify(config, null, 2));\n}\n\n/**\n * Update Cursor hooks.json\n */\nasync function updateCursorHooks(): Promise<void> {\n const cursorHooksPath = path.join(os.homedir(), \".cursor\", \"hooks.json\");\n\n // Read existing hooks.json or create new structure\n let config: any = {\n version: 1,\n description: \"Cursor hooks configuration with Overwatch Security\",\n hooks: {},\n };\n\n if (fs.existsSync(cursorHooksPath)) {\n const existing = JSON.parse(fs.readFileSync(cursorHooksPath, \"utf-8\"));\n // Handle both nested (hooks.hooks) and flat structures\n if (existing.hooks && typeof existing.hooks === \"object\") {\n config = existing;\n } else {\n // Flat structure - migrate to nested\n config.hooks = { ...existing };\n delete config.hooks.version;\n delete config.hooks.description;\n }\n }\n\n // Define overwatch hooks using the universal hook script\n const universalHookPath = path.join(os.homedir(), \".overwatch\", \"hooks\", \"universal-hook.sh\");\n\n const getCmd = (event: string) => {\n const defaultResp = JSON.stringify(getDefaultResponse(event));\n return `${universalHookPath} cursor ${event} '${defaultResp}'`;\n };\n\n const overwatchHooks: Record<string, any[]> = {\n beforeSubmitPrompt: [\n {\n command: getCmd(\"beforeSubmitPrompt\"),\n timeout: 10000,\n },\n ],\n beforeShellExecution: [\n {\n command: getCmd(\"beforeShellExecution\"),\n timeout: 10000,\n },\n ],\n beforeMCPExecution: [\n {\n command: getCmd(\"beforeMCPExecution\"),\n timeout: 10000,\n },\n ],\n beforeTabFileRead: [\n {\n command: getCmd(\"beforeTabFileRead\"),\n timeout: 10000,\n },\n ],\n beforeReadFile: [\n {\n command: getCmd(\"beforeReadFile\"),\n timeout: 10000,\n },\n ],\n afterShellExecution: [\n {\n command: getCmd(\"afterShellExecution\"),\n timeout: 5000,\n },\n ],\n afterMCPExecution: [\n {\n command: getCmd(\"afterMCPExecution\"),\n timeout: 5000,\n },\n ],\n afterFileEdit: [\n {\n command: getCmd(\"afterFileEdit\"),\n timeout: 5000,\n },\n ],\n afterTabFileEdit: [\n {\n command: getCmd(\"afterTabFileEdit\"),\n timeout: 5000,\n },\n ],\n afterAgentResponse: [\n {\n command: getCmd(\"afterAgentResponse\"),\n timeout: 5000,\n },\n ],\n afterAgentThought: [\n {\n command: getCmd(\"afterAgentThought\"),\n timeout: 5000,\n },\n ],\n stop: [\n {\n command: getCmd(\"stop\"),\n timeout: 5000,\n },\n ],\n };\n\n // Merge hooks into config.hooks (preserve existing non-overwatch hooks)\n for (const [event, hooks] of Object.entries(overwatchHooks)) {\n if (!config.hooks[event]) {\n config.hooks[event] = [];\n }\n // Add overwatch hook if not already present\n const existingCommands = config.hooks[event].map((h: any) => h.command);\n for (const hook of hooks) {\n if (!existingCommands.includes(hook.command)) {\n config.hooks[event].push(hook);\n }\n }\n }\n\n // Write back with proper structure\n fs.mkdirSync(path.dirname(cursorHooksPath), { recursive: true });\n fs.writeFileSync(cursorHooksPath, JSON.stringify(config, null, 2));\n console.log(`\u2705 Updated ${cursorHooksPath}`);\n}\n\n/**\n * Update Claude Code hooks.json in the hooks directory\n *\n * Uses ~/.overwatch/universal-hook.sh directly.\n */\nasync function updateClaudeCodeHooks(hooksDir: string): Promise<void> {\n const hooksJsonPath = path.join(hooksDir, \"hooks.json\");\n\n // Create hooks.json with ${CLAUDE_PLUGIN_ROOT} references\n // Claude Code will substitute this variable at runtime\n const config = {\n hooks: {\n UserPromptSubmit: [\n {\n hooks: [\n {\n type: \"command\",\n command: `bash ${os.homedir()}/.overwatch/hooks/universal-hook.sh claudecode UserPromptSubmit '${JSON.stringify(getDefaultResponse(\"UserPromptSubmit\"))}'`,\n },\n ],\n },\n ],\n PreToolUse: [\n {\n matcher: \".*\",\n hooks: [\n {\n type: \"command\",\n command: `bash ${os.homedir()}/.overwatch/hooks/universal-hook.sh claudecode PreToolUse '${JSON.stringify(getDefaultResponse(\"PreToolUse\"))}'`,\n },\n ],\n },\n ],\n PostToolUse: [\n {\n matcher: \".*\",\n hooks: [\n {\n type: \"command\",\n command: `bash ${os.homedir()}/.overwatch/hooks/universal-hook.sh claudecode PostToolUse '${JSON.stringify(getDefaultResponse(\"PostToolUse\"))}'`,\n },\n ],\n },\n ],\n },\n };\n\n fs.mkdirSync(hooksDir, { recursive: true });\n fs.writeFileSync(hooksJsonPath, JSON.stringify(config, null, 2));\n console.log(`\u2705 Created ${hooksJsonPath}`);\n}\n\n/**\n * Update GitHub Copilot hooks.json\n * Creates/updates hooks.json for GitHub Copilot agents\n */\nasync function updateGitHubCopilotHooks(hooksDir: string): Promise<void> {\n const hooksJsonPath = path.join(hooksDir, \"hooks.json\");\n const universalHookPath = path.join(os.homedir(), \".overwatch\", \"hooks\", \"universal-hook.sh\");\n\n // GitHub Copilot hook event names (use same names for both)\n // The extractor handles the mapping to semantic actions internally\n const hookEvents = [\n 'sessionStart',\n 'sessionEnd',\n 'userPromptSubmitted',\n 'preToolUse',\n 'postToolUse',\n 'errorOccurred',\n ];\n\n const getDefaultResponseForHook = (event: string): string => {\n // For blocking hooks, return allow by default\n if (event === \"preToolUse\" || event === \"userPromptSubmitted\") {\n return JSON.stringify({ continue: true });\n }\n return JSON.stringify({ continue: true });\n };\n\n const hooks: Record<string, any[]> = {};\n\n // Create hooks for each GitHub Copilot event\n for (const hookEvent of hookEvents) {\n hooks[hookEvent] = [\n {\n type: \"command\",\n bash: `bash ${universalHookPath} github_copilot ${hookEvent} '${getDefaultResponseForHook(hookEvent)}'`,\n cwd: \".\",\n timeoutSec: 10,\n },\n ];\n }\n\n const config = {\n version: 1,\n hooks,\n };\n\n // Create hooks.json in overwatch directory\n fs.mkdirSync(hooksDir, { recursive: true });\n fs.writeFileSync(hooksJsonPath, JSON.stringify(config, null, 2));\n console.log(`\u2705 Created ${hooksJsonPath}`);\n}\n\n/**\n * Update IDE config based on IDE type\n */\nasync function updateIDEConfig(ide: string, hooksDir: string): Promise<void> {\n switch (ide) {\n case \"cursor\":\n await updateCursorHooks();\n break;\n case \"claudecode\":\n // 1. Add permissions to settings.json for auto-approve (must be first)\n await updateClaudeSettings(hooksDir);\n // 2. Update hooks.json with hook definitions\n await updateClaudeCodeHooks(hooksDir);\n break;\n case \"github_copilot\":\n // Create GitHub Copilot hooks.json\n await updateGitHubCopilotHooks(hooksDir);\n break;\n default:\n throw new Error(`Unsupported IDE: ${ide}`);\n }\n}\n\n/**\n * Copy global policy and rules\n */\nasync function copyGlobalAssets(): Promise<void> {\n const guardianDir = path.dirname(__dirname);\n const overwatchDir = path.join(os.homedir(), \".overwatch\");\n\n // Copy universal hook script\n const hookScript = path.join(guardianDir, \"hooks\", \"universal-hook.sh\");\n if (fs.existsSync(hookScript)) {\n const hooksDir = path.join(overwatchDir, \"hooks\");\n fs.mkdirSync(hooksDir, { recursive: true });\n const targetPath = path.join(hooksDir, \"universal-hook.sh\");\n fs.copyFileSync(hookScript, targetPath);\n fs.chmodSync(targetPath, 0o755);\n console.log(`\u2705 Universal hook script installed to ${targetPath}`);\n }\n\n // Copy YARA rules\n const rulesDir = path.join(guardianDir, \"rules\");\n const targetRulesDir = path.join(overwatchDir, \"rules\");\n\n if (fs.existsSync(rulesDir)) {\n fs.mkdirSync(targetRulesDir, { recursive: true });\n fs.cpSync(rulesDir, targetRulesDir, { recursive: true });\n console.log(`\u2705 Copied YARA rules to ${targetRulesDir}`);\n }\n\n // Copy Cedar policy\n const policyFile = path.join(guardianDir, \"policy.cedar\");\n const targetPolicyFile = path.join(overwatchDir, \"policy.cedar\");\n\n if (fs.existsSync(policyFile)) {\n fs.copyFileSync(policyFile, targetPolicyFile);\n console.log(`\u2705 Copied Cedar policy to ${targetPolicyFile}`);\n }\n\n // Create logs directory\n const logsDir = path.join(overwatchDir, \"logs\");\n fs.mkdirSync(logsDir, { recursive: true });\n}\n\n/**\n * Install hooks for an IDE\n */\nexport async function installHooks(ide: string): Promise<void> {\n if (!SUPPORTED_IDES.includes(ide)) {\n console.error(`\u274C Unsupported IDE: ${ide}`);\n console.error(` Supported IDEs: ${SUPPORTED_IDES.join(\", \")}`);\n process.exit(1);\n }\n\n if (ide === \"claudecode\") {\n console.error(\n `Refer the instructions steps to install the Claude code plugin: https://github.com/highflame-ai/overwatch`,\n );\n process.exit(1);\n }\n\n console.log(`\uD83D\uDD27 Installing Overwatch hooks for ${ide}...`);\n\n try {\n // 1. Ensure guardian is running\n await ensureDaemonRunning();\n\n // 2. Copy global assets (YARA rules, Cedar policy)\n await copyGlobalAssets();\n\n // 3. Create IDE directory\n const ideDir = path.join(os.homedir(), \".overwatch\", ide);\n fs.mkdirSync(ideDir, { recursive: true });\n\n // 4. Create hooks directory (registration metadata)\n const hooksDir = path.join(ideDir, \"hooks\");\n fs.mkdirSync(hooksDir, { recursive: true });\n\n // 5. Update IDE config to use hooks\n await updateIDEConfig(ide, hooksDir);\n\n // 6. Update guardian config\n await updateGuardianConfig(ide, true);\n\n console.log(`\\n\u2705 Hooks installed successfully for ${ide}!`);\n console.log(`\\nNext steps:`);\n console.log(` 1. Restart ${ide} to activate hooks`);\n console.log(` 2. View status: overwatch status`);\n console.log(` 3. Scan MCP servers: overwatch scan`);\n } catch (error) {\n console.error(\n `\u274C Installation failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Uninstall hooks for an IDE\n * @param ide IDE name\n * @param silent If true, don't print messages (used by clear command)\n */\nexport async function uninstallHooks(ide: string, silent = false): Promise<void> {\n if (!SUPPORTED_IDES.includes(ide)) {\n throw new Error(`Unsupported IDE: ${ide}`);\n }\n\n if (ide === \"claudecode\") {\n throw new Error(\n \"Claude Code plugin must be uninstalled manually. See: https://github.com/highflame-ai/overwatch\",\n );\n }\n\n if (!silent) {\n console.log(`\uD83D\uDDD1\uFE0F Uninstalling Overwatch hooks for ${ide}...`);\n }\n\n try {\n const ideDir = path.join(os.homedir(), \".overwatch\", ide);\n\n // Remove from IDE config\n if (ide === \"cursor\") {\n const cursorHooksPath = path.join(os.homedir(), \".cursor\", \"hooks.json\");\n if (fs.existsSync(cursorHooksPath)) {\n const config = JSON.parse(fs.readFileSync(cursorHooksPath, \"utf-8\"));\n\n // Handle both flat and nested hooks.json structures\n const hooks = config.hooks || config;\n\n // Remove overwatch hooks from each event\n for (const [event, eventHooks] of Object.entries(hooks)) {\n if (Array.isArray(eventHooks)) {\n hooks[event] = eventHooks.filter(\n (h: any) => !h.command?.includes(\".overwatch/cursor/hooks\"),\n );\n // Remove empty arrays\n if (hooks[event].length === 0) {\n delete hooks[event];\n }\n }\n }\n\n // Write back with same structure\n if (config.hooks) {\n config.hooks = hooks;\n fs.writeFileSync(cursorHooksPath, JSON.stringify(config, null, 2));\n } else {\n fs.writeFileSync(cursorHooksPath, JSON.stringify(hooks, null, 2));\n }\n console.log(`\u2705 Removed hooks from ${cursorHooksPath}`);\n }\n }\n\n // Remove IDE directory\n if (fs.existsSync(ideDir)) {\n fs.rmSync(ideDir, { recursive: true, force: true });\n console.log(`\u2705 Removed ${ideDir}`);\n }\n\n // Update guardian config\n await updateGuardianConfig(ide, false);\n\n if (!silent) {\n console.log(`\u2705 Hooks uninstalled for ${ide}`);\n }\n } catch (error) {\n throw new Error(\n `Uninstallation failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * List installed hooks\n */\nexport async function listInstalledHooks(): Promise<InstallResult[]> {\n const overwatchDir = path.join(os.homedir(), \".overwatch\");\n const results: InstallResult[] = [];\n\n if (!fs.existsSync(overwatchDir)) {\n return results;\n }\n\n for (const ide of SUPPORTED_IDES) {\n const ideDir = path.join(overwatchDir, ide);\n const hooksPath = path.join(ideDir, \"hooks\");\n\n if (fs.existsSync(hooksPath)) {\n results.push({\n ide,\n hooksPath,\n hooksInstalled: fs.readdirSync(hooksPath).length > 0,\n });\n }\n }\n\n return results;\n}\n", "// import { IDESource, HookEvent } from \"../types\";\nimport * as http from \"http\";\n\n/**\n * Parse JSON body from HTTP request\n */\nexport async function parseBody(\n req: http.IncomingMessage,\n): Promise<Record<string, unknown>> {\n return new Promise((resolve) => {\n let body = \"\";\n req.on(\"data\", (chunk) => {\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n try {\n resolve(JSON.parse(body || \"{}\"));\n } catch {\n resolve({});\n }\n });\n req.on(\"error\", () => resolve({}));\n });\n}\n\n/**\n * Get guardrail config name based on hook type\n */\nexport function getGuardrailConfig(event: string): string {\n switch (event) {\n // Cursor - fast path for tool execution\n case \"beforeShellExecution\":\n case \"beforeMCPExecution\":\n return \"yara\"; // YARA-only for speed\n\n // Claude Code - fast path for tool execution\n case \"PreToolUse\":\n case \"PostToolUse\":\n return \"yara\"; // YARA-only for speed\n\n // GitHub Copilot CLI - fast path for tool execution\n case \"preToolUse\":\n case \"postToolUse\":\n return \"yara\"; // YARA-only for speed\n\n // File read events - full guardrails for content\n case \"beforeReadFile\":\n case \"beforeTabFileRead\":\n return \"guardrails\"; // Full guardrails for file content\n\n // Session events - observational only\n case \"sessionStart\":\n case \"sessionEnd\":\n case \"errorOccurred\":\n return \"none\"; // No validation needed\n\n // Prompt validation - full guardrails\n case \"beforeSubmitPrompt\":\n case \"UserPromptSubmit\":\n case \"userPromptSubmitted\":\n default:\n return \"guardrails\"; // Full guardrails\n }\n}\n\nexport function getDefaultResponse(event: string): Record<string, unknown> {\n switch (event) {\n // Cursor hooks\n case \"beforeSubmitPrompt\":\n return { continue: true };\n case \"beforeShellExecution\":\n case \"beforeMCPExecution\":\n case \"beforeTabFileRead\":\n case \"beforeReadFile\":\n case \"afterShellExecution\":\n case \"afterMCPExecution\":\n case \"afterFileEdit\":\n case \"afterTabFileEdit\":\n case \"afterAgentResponse\":\n case \"afterAgentThought\":\n return { permission: \"allow\" };\n case \"stop\":\n return {};\n\n // Claude Code hooks\n case \"UserPromptSubmit\":\n case \"PreToolUse\":\n case \"PostToolUse\":\n return {};\n\n // GitHub Copilot CLI hooks\n case \"userPromptSubmitted\":\n case \"preToolUse\":\n case \"postToolUse\":\n case \"sessionStart\":\n case \"sessionEnd\":\n case \"errorOccurred\":\n return {};\n\n default:\n return {};\n }\n}\n", "import * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport { execSync } from \"child_process\";\nimport { SystemService, ServiceStatus } from \"./interface\";\n\nexport class LaunchdService implements SystemService {\n private readonly daemonPath: string;\n private readonly plistPath: string;\n private readonly logPath: string;\n private readonly errPath: string;\n\n constructor() {\n // Note: __dirname will be inside dist/services/ or similar, so we need to adjust\n // Assuming structure: guardian/dist/services/launchd.js\n // We want to point to guardian/dist/daemon.js\n this.daemonPath = path.join(__dirname, \"..\", \"daemon.js\");\n this.plistPath = path.join(\n os.homedir(),\n \"Library/LaunchAgents/com.highflame.overwatch.plist\",\n );\n this.logPath = path.join(os.homedir(), \".overwatch\", \"logs\", \"daemon.log\");\n this.errPath = path.join(\n os.homedir(),\n \".overwatch\",\n \"logs\",\n \"daemon-error.log\",\n );\n }\n\n async install(): Promise<void> {\n // Ensure LaunchAgents directory exists\n const launchAgentsDir = path.dirname(this.plistPath);\n if (!fs.existsSync(launchAgentsDir)) {\n fs.mkdirSync(launchAgentsDir, { recursive: true });\n }\n\n // Create plist file\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>com.highflame.overwatch</string>\n <key>ProgramArguments</key>\n <array>\n <string>${process.execPath}</string>\n <string>${this.daemonPath}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${this.logPath}</string>\n <key>StandardErrorPath</key>\n <string>${this.errPath}</string>\n <key>WorkingDirectory</key>\n <string>${path.dirname(path.dirname(__dirname))}</string>\n <key>EnvironmentVariables</key>\n <dict>\n <key>NODE_PATH</key>\n <string>${path.join(path.dirname(path.dirname(__dirname)), \"node_modules\")}</string>\n </dict>\n</dict>\n</plist>`;\n\n // Write plist file\n fs.writeFileSync(this.plistPath, plist);\n console.log(`\u2705 Created launchd plist: ${this.plistPath}`);\n\n // Unload existing service if present (ignore errors)\n try {\n execSync(`launchctl unload \"${this.plistPath}\"`, { stdio: \"ignore\" });\n } catch (error) {\n // Service not loaded, ignore\n }\n\n // Load service\n execSync(`launchctl load \"${this.plistPath}\"`);\n console.log(\"\u2705 Loaded launchd service\");\n }\n\n async uninstall(): Promise<void> {\n if (!fs.existsSync(this.plistPath)) {\n console.log(\"\u2139\uFE0F Launchd service not installed\");\n return;\n }\n\n // Unload service\n try {\n execSync(`launchctl unload \"${this.plistPath}\"`);\n console.log(\"\u2705 Unloaded launchd service\");\n } catch (error) {\n console.log(\"\u26A0\uFE0F Service not running\");\n }\n\n // Remove plist file\n fs.unlinkSync(this.plistPath);\n console.log(`\u2705 Removed ${this.plistPath}`);\n }\n\n async getStatus(): Promise<ServiceStatus> {\n const installed = fs.existsSync(this.plistPath);\n let running = false;\n\n if (installed) {\n try {\n const output = execSync(\n \"launchctl list | grep com.highflame.overwatch\",\n {\n encoding: \"utf-8\",\n },\n );\n running = output.trim().length > 0;\n } catch (error) {\n // Not running\n }\n }\n\n return {\n installed,\n running,\n platform: \"darwin\",\n };\n }\n}\n", "import * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport { execSync } from \"child_process\";\nimport { SystemService, ServiceStatus } from \"./interface\";\n\nexport class SystemdService implements SystemService {\n private readonly daemonPath: string;\n private readonly servicePath: string;\n private readonly logPath: string;\n private readonly errPath: string;\n\n constructor() {\n this.daemonPath = path.join(__dirname, \"..\", \"daemon.js\");\n this.servicePath = path.join(\n os.homedir(),\n \".config/systemd/user/overwatch.service\",\n );\n this.logPath = path.join(os.homedir(), \".overwatch\", \"logs\", \"daemon.log\");\n this.errPath = path.join(\n os.homedir(),\n \".overwatch\",\n \"logs\",\n \"daemon-error.log\",\n );\n }\n\n async install(): Promise<void> {\n // Ensure systemd user directory exists\n const systemdUserDir = path.dirname(this.servicePath);\n if (!fs.existsSync(systemdUserDir)) {\n fs.mkdirSync(systemdUserDir, { recursive: true });\n }\n\n // Create systemd service file\n const serviceFile = `[Unit]\nDescription=Overwatch Guardian Security Daemon\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=${process.execPath} ${this.daemonPath}\nRestart=always\nRestartSec=10\nStandardOutput=append:${this.logPath}\nStandardError=append:${this.errPath}\nWorkingDirectory=${path.dirname(path.dirname(__dirname))}\nEnvironment=\"NODE_PATH=${path.join(path.dirname(path.dirname(__dirname)), \"node_modules\")}\"\n\n[Install]\nWantedBy=default.target\n`;\n\n // Write service file\n fs.writeFileSync(this.servicePath, serviceFile);\n console.log(`\u2705 Created systemd service: ${this.servicePath}`);\n\n // Reload systemd daemon\n execSync(\"systemctl --user daemon-reload\");\n\n // Enable service\n execSync(\"systemctl --user enable overwatch.service\");\n console.log(\"\u2705 Enabled systemd service\");\n\n // Start service\n execSync(\"systemctl --user start overwatch.service\");\n console.log(\"\u2705 Started systemd service\");\n }\n\n async uninstall(): Promise<void> {\n if (!fs.existsSync(this.servicePath)) {\n console.log(\"\u2139\uFE0F Systemd service not installed\");\n return;\n }\n\n // Stop service\n try {\n execSync(\"systemctl --user stop overwatch.service\");\n console.log(\"\u2705 Stopped systemd service\");\n } catch (error) {\n console.log(\"\u26A0\uFE0F Service not running\");\n }\n\n // Disable service\n try {\n execSync(\"systemctl --user disable overwatch.service\");\n console.log(\"\u2705 Disabled systemd service\");\n } catch (error) {\n // Already disabled\n }\n\n // Remove service file\n fs.unlinkSync(this.servicePath);\n console.log(`\u2705 Removed ${this.servicePath}`);\n\n // Reload systemd daemon\n execSync(\"systemctl --user daemon-reload\");\n }\n\n async getStatus(): Promise<ServiceStatus> {\n const installed = fs.existsSync(this.servicePath);\n let running = false;\n\n if (installed) {\n try {\n const output = execSync(\n \"systemctl --user is-active overwatch.service\",\n {\n encoding: \"utf-8\",\n },\n );\n running = output.trim() === \"active\";\n } catch (error) {\n // Not running\n }\n }\n\n return {\n installed,\n running,\n platform: \"linux\",\n };\n }\n}\n", "import { SystemService, ServiceStatus } from \"./interface\";\n\nexport class WindowsService implements SystemService {\n async install(): Promise<void> {\n // Windows service installation requires node-windows or similar\n // For now, provide manual instructions\n console.log(\"\u26A0\uFE0F Windows service installation not yet automated\");\n console.log(\"\");\n console.log(\"Manual installation:\");\n console.log(\"1. Install node-windows: npm install -g node-windows\");\n console.log(\"2. Create service script using node-windows\");\n console.log(\"3. Or use Task Scheduler to run on startup\");\n console.log(\"\");\n console.log(\"See: https://docs.highflame.ai/guardian/windows-service\");\n\n throw new Error(\"Windows service installation not yet implemented\");\n }\n\n async uninstall(): Promise<void> {\n console.log(\"\u26A0\uFE0F Windows service uninstallation not yet automated\");\n throw new Error(\"Windows service uninstallation not yet implemented\");\n }\n\n async getStatus(): Promise<ServiceStatus> {\n return {\n installed: false,\n running: false,\n platform: \"win32\",\n };\n }\n}\n", "/**\n * System Service Manager\n * Installs Guardian daemon as a system service for auto-start on boot\n */\n\nimport { SystemService, ServiceStatus } from \"./services/interface\";\nimport { LaunchdService } from \"./services/launchd\";\nimport { SystemdService } from \"./services/systemd\";\nimport { WindowsService } from \"./services/windows\";\n\n/**\n * Get the service implementation for the current platform\n */\nfunction getService(): SystemService {\n const platform = process.platform;\n if (platform === \"darwin\") {\n return new LaunchdService();\n } else if (platform === \"linux\") {\n return new SystemdService();\n } else if (platform === \"win32\") {\n return new WindowsService();\n } else {\n throw new Error(`Unsupported platform: ${platform}`);\n }\n}\n\n/**\n * Install Guardian as a system service\n */\nexport async function installService(): Promise<void> {\n const platform = process.platform;\n console.log(`\uD83D\uDD27 Installing Guardian as system service (${platform})...`);\n\n try {\n const service = getService();\n await service.install();\n } catch (error) {\n console.error(\n `\u274C Failed to install system service: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Uninstall Guardian system service\n */\nexport async function uninstallService(): Promise<void> {\n const platform = process.platform;\n console.log(`\uD83D\uDDD1\uFE0F Uninstalling Guardian system service (${platform})...`);\n\n try {\n const service = getService();\n await service.uninstall();\n } catch (error) {\n console.error(\n `\u274C Failed to uninstall system service: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Check system service status\n */\nexport async function checkServiceStatus(): Promise<ServiceStatus> {\n const platform = process.platform;\n\n try {\n const service = getService();\n return await service.getStatus();\n } catch (error) {\n // Service not installed or error checking\n return {\n installed: false,\n running: false,\n platform,\n };\n }\n}\n", "/**\n * OAuth authentication module\n * Provides PKCE-based OAuth 2.0 authentication for Highflame\n */\n\n// PKCE utilities\nexport {\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n} from \"./pkce\";\n\n// OAuth flow manager\nexport {\n OAUTH_CONFIG,\n TOKEN_EXPIRY_SECONDS,\n OAuthState,\n TokenResponse,\n UserInfo,\n buildAuthorizationUrl,\n exchangeCodeForTokens,\n refreshAccessToken,\n isTokenExpired,\n createOAuthState,\n} from \"./oauth\";\n\n// CLI OAuth flow\nexport { performCLIOAuthFlow } from \"./cli-oauth\";\n\n// Token persistence\nexport {\n AuthStatus,\n saveTokens,\n loadTokens,\n clearTokens,\n getValidAccessToken,\n needsReauth,\n getAuthStatus,\n} from \"./token-store\";\n\n// HTML utilities\nexport {\n escapeHtml,\n generateSuccessHtml,\n generateErrorHtml,\n} from \"./html-utils\";\n", "/**\n * CLI OAuth 2.0 PKCE flow\n * Handles OAuth authentication flow for CLI commands\n * Starts temporary callback server on ephemeral port\n */\n\nimport * as http from \"http\";\nimport open from \"open\";\nimport {\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n} from \"./pkce\";\nimport { buildAuthorizationUrl, exchangeCodeForTokens } from \"./oauth\";\nimport { saveTokens } from \"./token-store\";\nimport { generateSuccessHtml, generateErrorHtml } from \"./html-utils\";\n\n/** OAuth flow timeout: 5 minutes */\nconst OAUTH_TIMEOUT_MS = 5 * 60 * 1000;\n\n/** Polling interval for callback check */\nconst CALLBACK_POLL_INTERVAL_MS = 100;\n\n/** OAuth callback data structure */\ninterface OAuthCallbackData {\n code: string;\n state: string;\n}\n\n/** Map to store callback data by server instance */\nconst callbackDataMap = new WeakMap<http.Server, OAuthCallbackData>();\n\n/**\n * Perform OAuth PKCE flow for CLI\n * @param openBrowser Whether to open browser automatically (default: true)\n * @returns User email on success\n * @throws Error on failure\n */\nexport async function performCLIOAuthFlow(\n openBrowser: boolean = true,\n): Promise<string> {\n // Generate PKCE values\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = generateCodeChallenge(codeVerifier);\n const state = generateState();\n\n // Start callback server on ephemeral port\n const { server, redirectUri } = await startCallbackServer(state);\n\n try {\n // Build authorization URL\n const authUrl = buildAuthorizationUrl(state, codeChallenge, redirectUri);\n\n // Open browser or print URL\n if (openBrowser) {\n console.log(\"Opening browser for authentication...\");\n console.log(\"(If browser does not open, copy this URL manually)\\n\");\n console.log(` ${authUrl}\\n`);\n await open(authUrl);\n } else {\n console.log(\"Open this URL in your browser:\\n\");\n console.log(` ${authUrl}\\n`);\n }\n\n console.log(\"Waiting for authentication...\");\n\n // Wait for callback\n const { code, callbackState } = await waitForCallback(server, state);\n\n // Verify state matches\n if (callbackState !== state) {\n throw new Error(\"State mismatch - possible CSRF attack\");\n }\n\n // Exchange code for tokens\n const { tokens, userInfo } = await exchangeCodeForTokens(\n code,\n codeVerifier,\n redirectUri,\n );\n\n // Save tokens\n saveTokens(tokens, userInfo);\n\n return userInfo.email;\n } finally {\n // Shutdown callback server\n server.close();\n }\n}\n\n/**\n * Start temporary HTTP server on ephemeral port for OAuth callback\n * @param expectedState The expected state parameter for validation\n */\nfunction startCallbackServer(expectedState: string): Promise<{\n server: http.Server;\n port: number;\n redirectUri: string;\n}> {\n return new Promise((resolve, reject) => {\n const server = http.createServer();\n\n server.on(\"request\", (req, res) => {\n if (!req.url) {\n res.writeHead(400, { \"Content-Type\": \"text/plain\" });\n res.end(\"Bad Request\");\n return;\n }\n\n const parsedUrl = new URL(req.url, `http://${req.headers.host}`);\n\n // Handle OAuth callback\n if (parsedUrl.pathname === \"/oauth/callback\") {\n const code = parsedUrl.searchParams.get(\"code\");\n const state = parsedUrl.searchParams.get(\"state\");\n const error = parsedUrl.searchParams.get(\"error\");\n const errorDescription =\n parsedUrl.searchParams.get(\"error_description\");\n\n if (error) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" });\n res.end(generateErrorHtml(errorDescription || error));\n return;\n }\n\n if (!code || !state) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" });\n res.end(generateErrorHtml(\"Missing authorization code or state\"));\n return;\n }\n\n // Validate state matches expected\n if (state !== expectedState) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" });\n res.end(generateErrorHtml(\"Invalid state parameter\"));\n return;\n }\n\n // Store callback data using WeakMap\n callbackDataMap.set(server, { code, state });\n\n // Send success response\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n generateSuccessHtml(\n \"You can close this window and return to the terminal.\",\n ),\n );\n } else {\n res.writeHead(404, { \"Content-Type\": \"text/plain\" });\n res.end(\"Not Found\");\n }\n });\n\n // Start server on ephemeral port (port 0)\n server.listen(0, \"127.0.0.1\", () => {\n const address = server.address();\n if (!address || typeof address === \"string\") {\n reject(new Error(\"Failed to get server address\"));\n return;\n }\n\n const port = address.port;\n const redirectUri = `http://127.0.0.1:${port}/oauth/callback`;\n\n resolve({ server, port, redirectUri });\n });\n\n server.on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n\n/**\n * Wait for OAuth callback with timeout\n * @param server The HTTP server to monitor\n * @param expectedState The expected state parameter\n */\nfunction waitForCallback(\n server: http.Server,\n expectedState: string,\n): Promise<{ code: string; callbackState: string }> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now();\n\n const checkCallback = () => {\n const callback = callbackDataMap.get(server);\n if (callback) {\n // Validate state matches\n if (callback.state !== expectedState) {\n reject(new Error(\"State mismatch in callback\"));\n return;\n }\n resolve({ code: callback.code, callbackState: callback.state });\n return;\n }\n\n if (Date.now() - startTime > OAUTH_TIMEOUT_MS) {\n reject(new Error(\"OAuth flow timed out. Please try again.\"));\n return;\n }\n\n // Check again after polling interval\n setTimeout(checkCallback, CALLBACK_POLL_INTERVAL_MS);\n };\n\n checkCallback();\n });\n}\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\tif (browser.id in ids) {\n\t\t\tconst browserName = ids[browser.id.toLowerCase()];\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\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\tif (isFallbackAttempt) {\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\tif (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", "import {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\tconst {stdout} = await executePowerShell(command, {powerShellPath: psPath});\n\n\treturn stdout.trim();\n};\n\nexport const convertWslPathToWindows = async path => {\n\t// Don't convert URLs\n\tif (/^[a-z]+:\\/\\//i.test(path)) {\n\t\treturn path;\n\t}\n\n\ttry {\n\t\tconst {stdout} = await execFile('wslpath', ['-aw', path], {encoding: 'utf8'});\n\t\treturn stdout.trim();\n\t} catch {\n\t\t// If wslpath fails, return the original path\n\t\treturn path;\n\t}\n};\n\nexport {default as isWsl} from 'is-wsl';\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\treturn fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')\n\t\t\t? !isInsideContainer() : false;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport default process.env.__IS_WSL_TEST__ ? isWsl : isWsl();\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 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 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", "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';\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 {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 {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 {stdout} = await _execFileAsync('reg', [\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\tconst browser = windowsBrowserProgIds[id];\n\tif (!browser) {\n\t\tthrow new UnknownBrowserError(`Unknown browser ID: ${id}`);\n\t}\n\n\treturn browser;\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", "/**\n * Token storage for OAuth authentication\n * Stores tokens in ~/.overwatch/session.json (separate from config for security)\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport {\n TokenResponse,\n UserInfo,\n isTokenExpired,\n TOKEN_EXPIRY_SECONDS,\n} from \"./oauth\";\nimport { AuthConfig } from \"../types\";\nimport { logger } from \"../utils\";\n\nconst CONFIG_DIR = path.join(os.homedir(), \".overwatch\");\nconst SESSION_PATH = path.join(CONFIG_DIR, \"session.json\");\n\n// File permissions: 600 (read/write for owner only)\nconst SESSION_FILE_MODE = 0o600;\n\n/**\n * Auth status response\n */\nexport interface AuthStatus {\n authenticated: boolean;\n email?: string;\n name?: string;\n orgName?: string;\n expiresAt?: number;\n expired?: boolean;\n}\n\n/**\n * Load session data from session.json\n */\nfunction loadSession(): AuthConfig | null {\n try {\n if (fs.existsSync(SESSION_PATH)) {\n const data = fs.readFileSync(SESSION_PATH, \"utf-8\");\n return JSON.parse(data) as AuthConfig;\n }\n } catch (e) {\n logger.debug(\"Failed to load session file\", {\n error: e instanceof Error ? e.message : String(e),\n path: SESSION_PATH,\n });\n }\n return null;\n}\n\n/**\n * Write session data to session.json with restricted permissions\n */\nfunction writeSession(session: AuthConfig): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n\n const data = JSON.stringify(session, null, 2);\n fs.writeFileSync(SESSION_PATH, data, { mode: SESSION_FILE_MODE });\n\n // Ensure file permissions are set correctly (in case file already existed)\n try {\n fs.chmodSync(SESSION_PATH, SESSION_FILE_MODE);\n } catch (e) {\n // chmod may not be supported on all platforms (e.g., Windows)\n logger.debug(\"Failed to set session file permissions\", {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\n/**\n * Save tokens to session.json file\n */\nexport function saveTokens(tokens: TokenResponse, userInfo?: UserInfo): void {\n // Compute expires_at if not already set\n const expiresAt =\n tokens.expires_at ?? Date.now() + TOKEN_EXPIRY_SECONDS * 1000;\n\n const auth: AuthConfig = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token || \"\",\n expires_at: expiresAt,\n token_type: tokens.token_type,\n user: userInfo\n ? {\n email: userInfo.email,\n }\n : undefined,\n authenticated_at: new Date().toISOString(),\n };\n\n writeSession(auth);\n}\n\n/**\n * Load tokens from session.json file\n */\nexport function loadTokens(): AuthConfig | null {\n return loadSession();\n}\n\n/**\n * Clear tokens by deleting session.json file\n */\nexport function clearTokens(): void {\n try {\n if (fs.existsSync(SESSION_PATH)) {\n fs.unlinkSync(SESSION_PATH);\n }\n } catch (e) {\n logger.debug(\"Failed to delete session file\", {\n error: e instanceof Error ? e.message : String(e),\n path: SESSION_PATH,\n });\n }\n}\n\n/**\n * Get access token if valid, null if expired or missing\n * Attempts to refresh token if expired and refresh token is available\n */\nexport async function getValidAccessToken(): Promise<string | null> {\n const auth = loadTokens();\n if (!auth) return null;\n\n // Check if expired (with 1-day buffer)\n if (isTokenExpired(auth.expires_at)) {\n // Try to refresh if refresh token is available\n if (auth.refresh_token) {\n const { refreshAccessToken } = await import(\"./oauth\");\n const refreshed = await refreshAccessToken(auth.refresh_token);\n if (refreshed) {\n // Save new tokens\n saveTokens(refreshed);\n return refreshed.access_token;\n }\n }\n return null;\n }\n\n return auth.access_token;\n}\n\n/**\n * Check if re-authentication is needed\n * Returns true if tokens are expired or missing\n */\nexport function needsReauth(): boolean {\n const auth = loadTokens();\n if (!auth) return true;\n return isTokenExpired(auth.expires_at);\n}\n\n/**\n * Get auth status for display\n */\nexport function getAuthStatus(): AuthStatus {\n const auth = loadTokens();\n if (!auth) {\n return { authenticated: false };\n }\n\n return {\n authenticated: true,\n email: auth.user?.email,\n name: auth.user?.name,\n orgName: auth.user?.org_name,\n expiresAt: auth.expires_at,\n expired: isTokenExpired(auth.expires_at),\n };\n}\n", "/**\n * HTML utilities for OAuth responses\n * Provides secure HTML generation with proper escaping\n */\n\n/**\n * Escape HTML entities to prevent XSS attacks\n */\nexport function escapeHtml(unsafe: string): string {\n return unsafe\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/**\n * Common styles for OAuth response pages\n */\nconst COMMON_STYLES = `\n body {\n font-family: system-ui, -apple-system, sans-serif;\n text-align: center;\n padding: 50px;\n background: #f5f5f5;\n }\n .container {\n background: white;\n padding: 40px;\n border-radius: 10px;\n max-width: 400px;\n margin: 0 auto;\n box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n }\n h1 {\n margin-bottom: 20px;\n }\n p {\n color: #666;\n margin: 10px 0;\n }\n .success h1 { color: #22c55e; }\n .error h1 { color: #ef4444; }\n .error-message {\n color: #ef4444;\n font-family: monospace;\n background: #fef2f2;\n padding: 10px;\n border-radius: 5px;\n }\n .email {\n font-weight: bold;\n color: #333;\n }\n`;\n\n/**\n * Generate success HTML response for OAuth callback\n * @param message Success message to display\n * @param email Optional user email (will be escaped)\n */\nexport function generateSuccessHtml(message: string, email?: string): string {\n const safeMessage = escapeHtml(message);\n const safeEmail = email ? escapeHtml(email) : \"user\";\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Login Successful</title>\n <style>${COMMON_STYLES}</style>\n</head>\n<body>\n <div class=\"container success\">\n <h1>Login Successful</h1>\n <p>Welcome, <span class=\"email\">${safeEmail}</span>!</p>\n <p>${safeMessage}</p>\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Generate error HTML response for OAuth callback\n * @param error Error message to display (will be escaped)\n */\nexport function generateErrorHtml(error: string): string {\n const safeError = escapeHtml(error);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Login Failed</title>\n <style>${COMMON_STYLES}</style>\n</head>\n<body>\n <div class=\"container error\">\n <h1>Login Failed</h1>\n <p class=\"error-message\">${safeError}</p>\n <p>Please try again from the terminal.</p>\n </div>\n</body>\n</html>`;\n}\n", "/**\n * Config Manager\n * Handles reading, writing, and updating the overwatch config file\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport {\n OverwatchConfig,\n DEFAULT_OVERWATCH_CONFIG,\n LLMConfig,\n HighflameConfig,\n} from \"../types\";\nimport { loadTokens } from \"../auth\";\n\nconst CONFIG_DIR = path.join(os.homedir(), \".overwatch\");\nconst CONFIG_PATH = path.join(CONFIG_DIR, \"config.json\");\n\n/**\n * Load config from file\n */\nexport function loadConfig(): OverwatchConfig | null {\n try {\n if (fs.existsSync(CONFIG_PATH)) {\n const data = fs.readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(data) as OverwatchConfig;\n }\n } catch (e) {\n console.error(\"Failed to load config:\", e);\n }\n return null;\n}\n\n/**\n * Save config to file\n */\nexport function saveConfig(config: OverwatchConfig): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n}\n\n/**\n * Initialize config with defaults if not exists\n */\nexport function initConfig(): OverwatchConfig {\n let config = loadConfig();\n\n if (!config) {\n config = { ...DEFAULT_OVERWATCH_CONFIG };\n config.createdAt = new Date().toISOString();\n saveConfig(config);\n }\n\n return config;\n}\n\n/**\n * Update Highflame base URL\n */\nexport function setBaseUrl(url: string): void {\n const config = loadConfig() || { ...DEFAULT_OVERWATCH_CONFIG };\n\n config.highflame = {\n ...config.highflame,\n baseUrl: url,\n };\n\n saveConfig(config);\n}\n\n/**\n * Get Highflame base URL\n */\nexport function getBaseUrl(): string {\n const config = loadConfig();\n return (\n config?.highflame?.baseUrl ||\n process.env.HIGHFLAME_BASE_URL ||\n \"https://api.highflame.app\"\n );\n}\n\n/**\n * Set LLM API key\n */\nexport function setLLMApiKey(apiKey: string, provider?: string): void {\n const config = loadConfig() || { ...DEFAULT_OVERWATCH_CONFIG };\n\n config.llm = {\n ...config.llm,\n apiKey,\n provider: provider || config.llm?.provider || \"openai\",\n };\n\n saveConfig(config);\n}\n\n/**\n * Get LLM config\n */\nexport function getLLMConfig(): LLMConfig | null {\n const config = loadConfig();\n\n // Check environment variable first\n const envKey = process.env.LLM_API_KEY || process.env.OPENAI_API_KEY;\n if (envKey) {\n return {\n apiKey: envKey,\n provider: config?.llm?.provider || \"openai\",\n };\n }\n\n return config?.llm || null;\n}\n\n/**\n * Get Highflame config\n */\nexport function getHighflameConfig(): HighflameConfig {\n const config = loadConfig();\n return {\n baseUrl: config?.highflame?.baseUrl || \"https://api.highflame.app\",\n };\n}\n\n/**\n * Get JWT token from session for API calls\n */\nexport function getJwtToken(): string | null {\n const authConfig = loadTokens();\n return authConfig?.access_token || null;\n}\n\n/**\n * Update IDE config\n */\nexport function updateIDEConfig(\n ide: \"cursor\" | \"claudecode\" | \"github_copilot\",\n enabled: boolean,\n mode: \"inspect\" | \"enforce\" = \"enforce\",\n hooksPath?: string,\n): void {\n const config = loadConfig() || { ...DEFAULT_OVERWATCH_CONFIG };\n\n if (!config.ides) {\n config.ides = {};\n }\n\n config.ides[ide] = {\n enabled,\n mode,\n hooksInstalled: enabled,\n hooksPath,\n };\n\n saveConfig(config);\n}\n\n/**\n * Display current config (formatted for CLI)\n */\nexport function displayConfig(): void {\n const config = loadConfig();\n\n if (!config) {\n console.log(\"No config found. Run 'overwatch start' to create one.\");\n return;\n }\n\n console.log(\"\\n\uD83D\uDCCB Overwatch Configuration\");\n console.log(\"\u2550\".repeat(40));\n\n console.log(`\\nVersion: ${config.version}`);\n if (config.createdAt) {\n console.log(`Created: ${config.createdAt}`);\n }\n\n console.log(\"\\n\uD83D\uDD17 Highflame API:\");\n console.log(` Base URL: ${config.highflame?.baseUrl || \"(not set)\"}`);\n\n console.log(\"\\n\uD83E\uDD16 LLM Config:\");\n const llmConfig = getLLMConfig();\n if (llmConfig?.apiKey) {\n const maskedKey =\n llmConfig.apiKey.substring(0, 7) + \"...\" + llmConfig.apiKey.slice(-4);\n console.log(` API Key: ${maskedKey}`);\n console.log(` Provider: ${llmConfig.provider || \"openai\"}`);\n } else {\n console.log(\" API Key: (not set)\");\n }\n\n console.log(\"\\n\u2699\uFE0F Engines:\");\n console.log(\n ` YARA: ${config.engines?.yara?.enabled !== false ? \"\u2705\" : \"\u274C\"}`,\n );\n console.log(\n ` Cedar: ${config.engines?.cedar?.enabled !== false ? \"\u2705\" : \"\u274C\"}`,\n );\n console.log(\n ` Javelin: ${config.engines?.javelin?.enabled !== false ? \"\u2705\" : \"\u274C\"}`,\n );\n\n console.log(\"\\n\uD83D\uDCBB IDEs:\");\n if (config.ides) {\n for (const [ide, ideConfig] of Object.entries(config.ides)) {\n if (ideConfig) {\n const status = ideConfig.enabled ? \"\u2705\" : \"\u274C\";\n console.log(` ${ide}: ${status} (${ideConfig.mode || \"inspect\"})`);\n }\n }\n } else {\n console.log(\" No IDEs configured\");\n }\n\n console.log(\"\");\n}\n\n/**\n * Get config file path\n */\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n", "/**\n * Supported IDE types\n */\nexport type IDEType = \"cursor\" | \"claudecode\" | \"github_copilot\";\n\n/**\n * IDE source constants - use these instead of hard-coding strings\n */\nexport const IDE_SOURCES = {\n CURSOR: \"cursor\" as const,\n CLAUDE_CODE: \"claudecode\" as const,\n GITHUB_COPILOT: \"github_copilot\" as const,\n} as const;\n\n/**\n * Operating mode\n */\nexport type OperatingMode = \"inspect\" | \"enforce\";\n\n/**\n * Per-IDE configuration (no longer contains token - uses JWT from session)\n */\nexport interface IDEConfig {\n /** Whether this IDE is enabled */\n enabled?: boolean;\n\n /** Operating mode: inspect (allow all, record) or enforce (block threats) */\n mode: OperatingMode;\n\n /** Whether hooks are installed for this IDE */\n hooksInstalled?: boolean;\n\n /** Path to hooks directory */\n hooksPath?: string;\n}\n\n/**\n * LLM configuration for MCP scanning\n */\nexport interface LLMConfig {\n /** LLM API key for evaluation (e.g., OpenAI, Anthropic) */\n apiKey?: string;\n\n /** LLM provider (openai, anthropic, etc.) */\n provider?: string;\n}\n\n/**\n * Engine configuration\n */\nexport interface EnginesConfig {\n /** YARA engine settings */\n yara?: {\n enabled?: boolean;\n rulesDir?: string;\n };\n\n /** Cedar policy engine settings */\n cedar?: {\n enabled?: boolean;\n policyFile?: string;\n };\n\n /** Javelin (Highflame) remote validation */\n javelin?: {\n enabled?: boolean;\n };\n}\n\n/**\n * Daemon configuration\n */\nexport interface DaemonConfig {\n /** Auto-start daemon on boot */\n autoStart?: boolean;\n\n /** Log level */\n logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n\n /** Preferred ports to try (first available will be used) */\n ports?: number[];\n}\n\n/**\n * Highflame API configuration\n */\nexport interface HighflameConfig {\n /** Highflame API base URL */\n baseUrl?: string;\n}\n\n/**\n * OAuth authentication configuration (stored in session.json)\n */\nexport interface AuthConfig {\n /** OAuth access token (JWT) */\n access_token: string;\n\n /** OAuth refresh token for token renewal */\n refresh_token: string;\n\n /** Token expiry timestamp in milliseconds (Unix epoch) */\n expires_at: number;\n\n /** Token type (always Bearer) */\n token_type: \"Bearer\";\n\n /** Authenticated user information */\n user?: {\n email: string;\n name?: string;\n org_id?: string;\n org_name?: string;\n };\n\n /** ISO timestamp when authentication occurred */\n authenticated_at: string;\n}\n\n/**\n * Admin API configuration (derived from Highflame config)\n */\nexport interface AdminConfig {\n /** Whether admin API is enabled */\n enabled: boolean;\n\n /** Admin API base URL */\n baseUrl: string | null;\n}\n\n/**\n * Unified overwatch config file structure (~/.overwatch/config.json)\n */\nexport interface OverwatchConfig {\n /** Config version */\n version: string;\n\n /** Config creation timestamp */\n createdAt?: string;\n\n /** Highflame API settings */\n highflame?: HighflameConfig;\n\n /** LLM configuration for MCP scanning */\n llm?: LLMConfig;\n\n /** Security engines configuration */\n engines?: EnginesConfig;\n\n /** Remote policy settings */\n remotePolicy?: {\n /** Whether remote policy fetching is enabled */\n enabled?: boolean;\n /** Poll interval in minutes for remote policy refresh */\n pollIntervalMinutes?: number;\n };\n\n /** Per-IDE configurations */\n ides?: {\n cursor?: IDEConfig;\n claudecode?: IDEConfig;\n github_copilot?: IDEConfig;\n };\n\n /** Daemon settings */\n daemon?: DaemonConfig;\n\n /** Global enabled flag */\n enabled?: boolean;\n}\n\n/**\n * Guardian daemon configuration (runtime)\n */\nexport interface GuardianConfig {\n /** IDE type - determines which hooks to use */\n ide?: IDEType;\n\n /** HTTP server port */\n httpPort?: number;\n\n /** Enable debug logging */\n debug?: boolean;\n\n /** Highflame API configuration */\n javelin?: {\n /** Javelin API base URL */\n baseUrl?: string;\n\n /** Request timeout in milliseconds */\n timeout?: number;\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: Required<GuardianConfig> = {\n ide: \"cursor\",\n httpPort: 0, // Ephemeral port - OS assigns available port\n debug: false,\n javelin: {\n baseUrl: \"https://api.highflame.app\",\n timeout: 30000,\n },\n};\n\n/**\n * Default Overwatch config structure\n */\nexport const DEFAULT_OVERWATCH_CONFIG: OverwatchConfig = {\n version: \"2.0\",\n createdAt: new Date().toISOString(),\n highflame: {\n baseUrl: \"https://api.highflame.app\",\n },\n engines: {\n yara: {\n enabled: true,\n },\n cedar: {\n enabled: true,\n },\n javelin: {\n enabled: true,\n },\n },\n daemon: {\n autoStart: true,\n logLevel: \"info\",\n },\n enabled: true,\n};\n", "/**\n * Remote policy types for Guardian\n *\n * These types support fetching and managing Cedar policies from the\n * highflame-admin backend, enabling IDE-specific policy configuration.\n */\n\n/**\n * Remote policy configuration\n */\nexport interface RemotePolicyConfig {\n /** Enable remote policy fetching */\n enabled: boolean;\n\n /** Polling interval in milliseconds (default: 5 minutes) */\n pollIntervalMs: number;\n}\n\n/**\n * Application from admin API (code_agent type)\n */\nexport interface CodeAgentApplication {\n /** Application UUID */\n uuid: string;\n\n /** Application name (e.g., \"cursor-guardian\") */\n name: string;\n\n /** Application type (should be \"code_agent\") */\n type: string;\n\n /** IDE type this application is for */\n ide_type?: string;\n\n /** Whether the application is active */\n is_active: boolean;\n\n /** Application description */\n description?: string;\n\n /** Application configuration */\n config?: Record<string, unknown>;\n}\n\n/**\n * Cedar policy from admin API\n */\nexport interface RemoteCedarPolicy {\n /** Policy UUID */\n uuid: string;\n\n /** Policy name */\n name: string;\n\n /** Cedar policy content (the actual policy text) */\n policy_content: string;\n\n /** Associated application ID */\n application_id?: string;\n\n /** IDE type this policy is for */\n ide_type?: string;\n\n /** Policy version */\n version?: string;\n\n /** Last updated timestamp */\n updated_at: string;\n}\n\n/**\n * Installation event payload sent to admin API\n */\nexport interface InstallationEvent {\n /** User identifier */\n user_id: string;\n\n /** User email address */\n user_email: string;\n\n /** IDE type (cursor, claudecode, github_copilot) */\n ide_type: string;\n\n /** Guardian version */\n version: string;\n\n /** Event timestamp (ISO string) */\n timestamp: string;\n}\n\n/**\n * Policy mapping for IDE-specific policies\n * Uses index signature to allow any IDESource string key\n */\nexport interface PolicyMapping {\n cursor?: PolicyMappingEntry;\n claudecode?: PolicyMappingEntry;\n github_copilot?: PolicyMappingEntry;\n [ide: string]: PolicyMappingEntry | undefined; // index by IDE source string\n}\n\n/**\n * Single policy mapping entry\n */\nexport interface PolicyMappingEntry {\n /** Associated application ID */\n applicationId: string;\n\n /** Cedar policy content */\n policyContent: string;\n\n /** Last updated timestamp */\n lastUpdated: string;\n\n /** Policy version */\n version?: string;\n}\n\n/**\n * Admin API response for applications\n */\nexport interface ApplicationsResponse {\n applications: CodeAgentApplication[];\n total: number;\n}\n\n/**\n * Admin API response for policies\n */\nexport interface PoliciesResponse {\n policies: RemoteCedarPolicy[];\n total: number;\n}\n\n/**\n * Admin API response for installations\n */\nexport interface InstallationsResponse {\n installations: InstallationInfo[];\n total: number;\n}\n\n/**\n * Installation info from admin API\n */\nexport interface InstallationInfo {\n id: string;\n user_id: string;\n user_email: string;\n ide_type: string;\n version: string;\n first_seen_at: string;\n last_seen_at: string;\n}\n\n/**\n * Default remote policy configuration\n */\nexport const DEFAULT_REMOTE_POLICY_CONFIG: RemotePolicyConfig = {\n enabled: true,\n pollIntervalMs: 5 * 60 * 1000, // 5 minutes\n};\n", "/**\n * Overwatch CLI\n * Standalone security daemon for IDE-agnostic AI agent security\n */\n\nimport { Command } from \"commander\";\nimport { installHooks, uninstallHooks, listInstalledHooks } from \"./installer\";\nimport {\n installService,\n uninstallService,\n checkServiceStatus,\n} from \"./service\";\nimport {\n getAuthStatus,\n clearTokens,\n needsReauth,\n performCLIOAuthFlow,\n} from \"./auth\";\nimport {\n initConfig,\n setBaseUrl,\n setLLMApiKey,\n displayConfig,\n getConfigPath,\n} from \"./config\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\nconst program = new Command();\n\n/**\n * Get guardian status from port file\n */\nasync function getGuardianStatus(): Promise<{\n running: boolean;\n port?: number;\n}> {\n const portFile = path.join(os.homedir(), \".overwatch\", \"guardian_port\");\n\n if (!fs.existsSync(portFile)) {\n return { running: false };\n }\n\n try {\n const port = parseInt(fs.readFileSync(portFile, \"utf-8\").trim());\n\n // Check if daemon is actually responding\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n method: \"GET\",\n signal: AbortSignal.timeout(2000),\n });\n\n if (response.ok) {\n return { running: true, port };\n }\n } catch (error) {\n // Daemon not responding\n }\n\n return { running: false };\n}\n\n/**\n * Start guardian daemon\n */\nasync function startDaemon(\n options: { debug?: boolean; browser?: boolean } = {},\n) {\n const openBrowser = options.browser !== false; // Default to true\n\n // Check if authentication is needed BEFORE starting daemon\n if (needsReauth()) {\n console.log(\"\\nAuthentication required...\");\n try {\n const userEmail = await performCLIOAuthFlow(openBrowser);\n console.log(`\\n\u2705 Logged in successfully as ${userEmail}`);\n } catch (error) {\n console.error(\n `\\n\u274C Login failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n } else {\n const authStatus = getAuthStatus();\n if (authStatus.email) {\n console.log(`\\n\uD83D\uDD10 Authenticated as: ${authStatus.email}`);\n }\n }\n\n // Initialize config if not exists\n initConfig();\n\n // Now start daemon if not running\n let status = await getGuardianStatus();\n if (!status.running) {\n console.log(\"\\n\uD83D\uDE80 Starting Guardian daemon...\");\n\n const { spawn } = await import(\"child_process\");\n const daemonPath = path.join(__dirname, \"daemon.js\");\n const guardianDir = path.dirname(__dirname);\n\n const args = [];\n if (options.debug) {\n args.push(\"--debug\");\n }\n\n // Spawn daemon as detached process\n const proc = spawn(process.execPath, [daemonPath, ...args], {\n detached: true,\n stdio: \"ignore\",\n cwd: guardianDir,\n env: {\n ...process.env,\n NODE_PATH: path.join(guardianDir, \"node_modules\"),\n },\n });\n\n proc.unref();\n\n // Wait for daemon to start and write port file\n // Increased to 10s as remote policy initialization can be slow\n await new Promise((resolve) => setTimeout(resolve, 10000));\n\n status = await getGuardianStatus();\n if (!status.running) {\n console.error(\"\u274C Failed to start Guardian. Check logs:\");\n console.error(` cat ~/.overwatch/guardian.log`);\n process.exit(1);\n }\n\n console.log(`\u2705 Guardian started on port ${status.port}`);\n } else {\n console.log(`\u2705 Guardian is already running on port ${status.port}`);\n }\n\n console.log(`\\n\uD83D\uDCCA Dashboard: http://localhost:${status.port}/dashboard`);\n}\n\n/**\n * Stop guardian daemon\n */\nasync function stopDaemon() {\n const status = await getGuardianStatus();\n\n if (!status.running) {\n console.log(\"\u2139\uFE0F Guardian is not running\");\n return;\n }\n\n console.log(\"\uD83D\uDED1 Stopping Guardian daemon...\");\n\n try {\n // Try graceful shutdown via API\n await fetch(`http://127.0.0.1:${status.port}/shutdown`, {\n method: \"POST\",\n signal: AbortSignal.timeout(5000),\n });\n\n // Wait for shutdown\n await new Promise((resolve) => setTimeout(resolve, 5000));\n\n const newStatus = await getGuardianStatus();\n if (!newStatus.running) {\n console.log(\"\u2705 Guardian stopped successfully\");\n } else {\n console.log(\"\u26A0\uFE0F Guardian may still be running. Check manually.\");\n }\n } catch (error) {\n console.error(\"\u274C Failed to stop Guardian gracefully\");\n console.error(' Try: pkill -f \"overwatch-daemon\"');\n }\n}\n\n/**\n * Show guardian status\n */\nasync function statusDaemon() {\n const status = await getGuardianStatus();\n\n if (status.running) {\n console.log(`\u2705 Guardian is running on port ${status.port}`);\n console.log(` Dashboard: http://localhost:${status.port}/dashboard`);\n\n // Get additional stats from health endpoint\n try {\n const response = await fetch(`http://127.0.0.1:${status.port}/health`);\n const health = (await response.json()) as any;\n console.log(` Events recorded: ${health.eventCount || 0}`);\n } catch (error) {\n // Can't get detailed stats\n }\n } else {\n console.log(\"\u274C Guardian is not running\");\n console.log(\"\\nStart guardian: overwatch start\");\n }\n\n // Show service status\n const serviceStatus = await checkServiceStatus();\n if (serviceStatus.installed) {\n console.log(\n `\\n System service: ${serviceStatus.running ? \"\u2705 Running\" : \"\u26A0\uFE0F Installed but not running\"}`,\n );\n }\n}\n\n/**\n * Restart daemon\n */\nasync function restartDaemon(options: { debug?: boolean } = {}) {\n await stopDaemon();\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await startDaemon(options);\n}\n\n/**\n * Show installed hooks\n */\nasync function showHooks() {\n const hooks = await listInstalledHooks();\n\n if (hooks.length === 0) {\n console.log(\"No hooks installed\");\n console.log(\"\\nInstall hooks: overwatch install <ide>\");\n console.log(\n \"Supported IDEs: cursor, claudecode, github_copilot\",\n );\n return;\n }\n\n console.log(\"Installed hooks:\");\n for (const { ide, hooksPath, hooksInstalled } of hooks) {\n const status = hooksInstalled ? \"\u2705\" : \"\u26A0\uFE0F\";\n console.log(` ${status} ${ide}: ${hooksPath}`);\n }\n}\n\n// Configure CLI\nprogram\n .name(\"overwatch\")\n .description(\"Overwatch - IDE-Agnostic Security Daemon\")\n .version(\"1.0.0\");\n\n// Daemon management commands\nprogram\n .command(\"start\")\n .description(\"Start Guardian daemon (authenticates if needed)\")\n .option(\"--debug\", \"Enable debug logging\")\n .option(\"--no-browser\", \"Print auth URL instead of opening browser\")\n .action(startDaemon);\n\nprogram.command(\"stop\").description(\"Stop Guardian daemon\").action(stopDaemon);\n\nprogram\n .command(\"status\")\n .description(\"Show Guardian status and installed hooks\")\n .action(async () => {\n await statusDaemon();\n console.log(\"\");\n await showHooks();\n });\n\nprogram\n .command(\"restart\")\n .description(\"Restart Guardian daemon\")\n .option(\"--debug\", \"Enable debug logging\")\n .action(restartDaemon);\n\n// Hook installation commands\nprogram\n .command(\"install <ide>\")\n .description(\n \"Install hooks for IDE (cursor, claudecode, github_copilot)\",\n )\n .action(installHooks);\n\nprogram\n .command(\"uninstall <ide>\")\n .description(\"Uninstall hooks for IDE\")\n .action(async (ide: string) => {\n try {\n await uninstallHooks(ide);\n } catch (error) {\n console.error(\n `\u274C ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n });\n\nprogram.command(\"hooks\").description(\"List installed hooks\").action(showHooks);\n\n// System service commands\nprogram\n .command(\"install-service\")\n .description(\"Install as system service (auto-start on boot)\")\n .action(installService);\n\nprogram\n .command(\"uninstall-service\")\n .description(\"Uninstall system service\")\n .action(uninstallService);\n\n// Config commands\nconst configCmd = program\n .command(\"config\")\n .description(\"Manage Overwatch configuration\");\n\nconfigCmd\n .command(\"show\")\n .description(\"Display current configuration\")\n .action(() => {\n displayConfig();\n });\n\nconfigCmd\n .command(\"set-url <url>\")\n .description(\"Set Highflame API base URL\")\n .action((url: string) => {\n setBaseUrl(url);\n console.log(`\u2705 Base URL set to: ${url}`);\n console.log(\"Restarting daemon...\");\n restartDaemon();\n });\n\nconfigCmd\n .command(\"set-llm-key <key>\")\n .description(\"Set LLM API key for MCP scanning\")\n .option(\n \"-p, --provider <provider>\",\n \"LLM provider (openai, anthropic)\",\n \"openai\",\n )\n .action((key: string, options: { provider: string }) => {\n setLLMApiKey(key, options.provider);\n const maskedKey = key.substring(0, 7) + \"...\" + key.slice(-4);\n console.log(`\u2705 LLM API key set: ${maskedKey}`);\n console.log(` Provider: ${options.provider}`);\n });\n\nconfigCmd\n .command(\"path\")\n .description(\"Show config file path\")\n .action(() => {\n console.log(getConfigPath());\n });\n\n// Authentication commands\nprogram\n .command(\"login\")\n .description(\"Login to Highflame\")\n .option(\"--no-browser\", \"Print auth URL instead of opening browser\")\n .action(async (options: { browser: boolean }) => {\n try {\n const userEmail = await performCLIOAuthFlow(options.browser);\n console.log(`\\n\u2705 Logged in successfully as ${userEmail}`);\n } catch (error) {\n console.error(\n `\\n\u274C Login failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n });\n\nprogram\n .command(\"logout\")\n .description(\"Clear stored authentication tokens\")\n .action(() => {\n clearTokens();\n console.log(\"\u2705 Logged out successfully\");\n });\n\nprogram\n .command(\"whoami\")\n .description(\"Show current authenticated user\")\n .action(() => {\n const status = getAuthStatus();\n\n if (!status.authenticated) {\n console.log(\"\u274C Not logged in\");\n console.log(\"\\nRun: overwatch login\");\n return;\n }\n\n if (status.expired) {\n console.log(\"\u26A0\uFE0F Session expired\");\n console.log(\"\\nRun: overwatch login\");\n return;\n }\n\n console.log(`\u2705 Logged in as: ${status.email || \"unknown\"}`);\n if (status.name) {\n console.log(` Name: ${status.name}`);\n }\n if (status.orgName) {\n console.log(` Organization: ${status.orgName}`);\n }\n if (status.expiresAt) {\n const expiryDate = new Date(status.expiresAt);\n const daysLeft = Math.ceil(\n (status.expiresAt - Date.now()) / (1000 * 60 * 60 * 24),\n );\n console.log(\n ` Session expires: ${expiryDate.toLocaleDateString()} (${daysLeft} days)`,\n );\n }\n });\n\n// Clear/Reset command\nprogram\n .command(\"clear\")\n .description(\"Reset Overwatch config and auth (keeps events and scan data)\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"--all\", \"Also remove all local data (events, scans, logs)\")\n .action(async (options: { yes?: boolean; all?: boolean }) => {\n const overwatchDir = path.join(os.homedir(), \".overwatch\");\n\n // Confirmation prompt unless --yes flag is provided\n if (!options.yes) {\n console.log(\"\\n\u26A0\uFE0F This will reset Overwatch:\");\n console.log(\" \u2022 Stop the Guardian daemon\");\n console.log(\" \u2022 Uninstall system service (if installed)\");\n console.log(\" \u2022 Uninstall hooks from all IDEs\");\n console.log(\" \u2022 Clear authentication tokens\");\n console.log(\" \u2022 Remove config.json\");\n if (options.all) {\n console.log(\" \u2022 Remove all local data (events, scans, logs)\");\n } else {\n console.log(\" \u2022 Keep local data (events, scans, logs)\");\n }\n console.log(\"\\n\");\n\n // Simple confirmation using readline\n const readline = await import(\"readline\");\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question('Type \"yes\" to confirm: ', resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== \"yes\") {\n console.log(\"\u274C Cancelled\");\n process.exit(0);\n }\n }\n\n console.log(\"\\n\uD83E\uDDF9 Resetting Overwatch...\\n\");\n\n // 1. Stop daemon if running\n const status = await getGuardianStatus();\n if (status.running) {\n console.log(\"\uD83D\uDED1 Stopping Guardian daemon...\");\n try {\n await fetch(`http://127.0.0.1:${status.port}/shutdown`, {\n method: \"POST\",\n signal: AbortSignal.timeout(5000),\n });\n await new Promise((resolve) => setTimeout(resolve, 2000));\n console.log(\" \u2705 Daemon stopped\");\n } catch {\n console.log(\" \u26A0\uFE0F Could not stop daemon gracefully\");\n }\n } else {\n console.log(\"\u2139\uFE0F Daemon not running\");\n }\n\n // 2. Uninstall system service if installed\n const serviceStatus = await checkServiceStatus();\n if (serviceStatus.installed) {\n console.log(\"\uD83D\uDD27 Uninstalling system service...\");\n try {\n await uninstallService();\n console.log(\" \u2705 System service uninstalled\");\n } catch {\n console.log(\" \u26A0\uFE0F Could not uninstall system service\");\n }\n }\n\n // 3. Uninstall hooks from all IDEs (except claudecode which requires manual uninstall)\n const installedHooks = await listInstalledHooks();\n if (installedHooks.length > 0) {\n console.log(\"\uD83D\uDD27 Uninstalling IDE hooks...\");\n for (const { ide } of installedHooks) {\n if (ide === \"claudecode\") {\n console.log(` \u26A0\uFE0F Claude Code plugin must be uninstalled manually`);\n continue;\n }\n try {\n await uninstallHooks(ide, true);\n console.log(` \u2705 Uninstalled hooks for ${ide}`);\n } catch {\n console.log(` \u26A0\uFE0F Could not uninstall hooks for ${ide}`);\n }\n }\n }\n\n // 4. Clear authentication tokens\n console.log(\"\uD83D\uDD10 Clearing authentication...\");\n clearTokens();\n console.log(\" \u2705 Authentication cleared\");\n\n // 5. Remove config and optionally data files\n if (fs.existsSync(overwatchDir)) {\n if (options.all) {\n // Remove entire directory\n console.log(\"\uD83D\uDDD1\uFE0F Removing all Overwatch data...\");\n fs.rmSync(overwatchDir, { recursive: true, force: true });\n console.log(\" \u2705 All data removed\");\n } else {\n // Remove only config files, keep data\n console.log(\"\uD83D\uDDD1\uFE0F Removing config files (keeping data)...\");\n const filesToRemove = [\"config.json\", \"session.json\", \"guardian_port\"];\n const dirsToRemove = [\"cursor\", \"claudecode\", \"github_copilot\"];\n\n for (const file of filesToRemove) {\n const filePath = path.join(overwatchDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n for (const dir of dirsToRemove) {\n const dirPath = path.join(overwatchDir, dir);\n if (fs.existsSync(dirPath)) {\n fs.rmSync(dirPath, { recursive: true, force: true });\n }\n }\n console.log(\" \u2705 Config files removed\");\n console.log(\" \u2139\uFE0F Events and scan data preserved\");\n }\n }\n\n console.log(\"\\n\u2705 Overwatch has been reset\");\n console.log(\"\\nTo get started again:\");\n console.log(\" 1. Run: overwatch start\");\n console.log(\" 2. Install hooks: overwatch install <ide>\");\n });\n\n// Scan command (delegates to daemon)\nprogram\n .command(\"scan\")\n .description(\"Scan MCP servers for security issues\")\n .action(async () => {\n const status = await getGuardianStatus();\n\n if (!status.running) {\n console.error(\"\u274C Guardian is not running. Start it first:\");\n console.error(\" overwatch start\");\n process.exit(1);\n }\n\n console.log(\"\uD83D\uDD0D Scanning MCP servers...\");\n\n try {\n const response = await fetch(`http://127.0.0.1:${status.port}/scan`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ action: \"run\" }),\n });\n\n const result = (await response.json()) as any;\n\n if (result.error) {\n console.error(`\u274C Scan failed: ${result.error}`);\n process.exit(1);\n }\n\n console.log(\n `\u2705 Scan complete: ${result.total_servers} server(s) scanned`,\n );\n\n if (result.total_issues > 0) {\n console.log(`\u26A0\uFE0F Found ${result.total_issues} security issue(s)`);\n console.log(\n ` View details: http://localhost:${status.port}/dashboard`,\n );\n }\n } catch (error) {\n console.error(\n `\u274C Scan failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n });\n\n// Scan skills command\nprogram\n .command(\"scan-skills\")\n .description(\"Scan Claude Code skills for security review\")\n .option(\"--json\", \"Output raw JSON\")\n .action(async (options: { json?: boolean }) => {\n if (!options.json) {\n console.log(\"\uD83D\uDD0D Scanning Claude Code skills...\");\n }\n\n try {\n // Import scanner directly - no daemon required\n const { SkillsScanner } = await import(\"./skills\");\n\n const scanner = new SkillsScanner();\n const result = await scanner.scan();\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(`\u2705 Scan complete: ${result.totalSkills} skill(s) found`);\n console.log(` Duration: ${result.scanDurationMs}ms`);\n\n if (result.skills && result.skills.length > 0) {\n console.log(\"\\n\uD83D\uDCDA Skills:\");\n for (const skill of result.skills) {\n console.log(` \u2022 ${skill.name}`);\n console.log(` Path: ${skill.path}`);\n console.log(` Files: ${skill.files.join(\", \")}`);\n }\n }\n }\n } catch (error) {\n console.error(\n `\u274C Scan failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n process.exit(1);\n }\n });\n\n// Parse arguments\nprogram.parse();\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,wCAAAA,UAAA;AAIA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAMA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAAA,MAC/B;AAAA,IACF;AAEA,IAAAD,SAAQ,iBAAiBC;AACzB,IAAAD,SAAQ,uBAAuBE;AAAA;AAAA;;;AC1C/B;AAAA,2CAAAC,UAAA;AAAA,QAAM,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,UAAU,OAAO,KAAK,CAAC;AAAA,IAC1E;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAGHD,SAAQ,MAAM;",
6
+ "names": ["exports", "CommanderError", "InvalidArgumentError", "exports", "InvalidArgumentError", "Argument", "exports", "Help", "cmd", "exports", "InvalidArgumentError", "Option", "str", "exports", "exports", "childProcess", "path", "fs", "process", "Argument", "CommanderError", "Help", "Option", "Command", "option", "exports", "module", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "fs", "path", "os", "fs", "path", "os", "crypto", "commander", "fs", "path", "os", "fs", "path", "os", "import_child_process", "platform", "import_node_process", "import_node_child_process", "import_promises", "import_node_util", "import_node_child_process", "import_node_fs", "import_node_fs", "fs", "fs", "process", "os", "fs", "import_node_process", "childProcess", "process", "execFile", "childProcess", "fs", "fsConstants", "powerShellPath", "path", "import_node_util", "import_node_process", "import_node_child_process", "import_node_util", "import_node_process", "import_node_child_process", "process", "import_node_process", "import_node_util", "import_node_child_process", "execFileAsync", "process", "import_node_util", "import_node_child_process", "execFileAsync", "execFileAsync", "defaultBrowser", "process", "import_node_process", "process", "__dirname", "path", "process", "apps", "defaultBrowser", "powerShellPath", "fs", "fsConstants", "childProcess", "fs", "path", "os", "fs", "path", "os", "CONFIG_DIR", "fs", "path", "os", "program", "SkillsScanner"]
7
+ }