@rsbuild/core 0.6.7 → 0.6.9

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 (54) hide show
  1. package/compiled/commander/{typings/index.d.ts → index.d.ts} +26 -24
  2. package/compiled/commander/index.js +3528 -1
  3. package/compiled/commander/package.json +1 -1
  4. package/compiled/connect-history-api-fallback/index.js +186 -1
  5. package/compiled/dotenv/{lib/main.d.ts → index.d.ts} +16 -12
  6. package/compiled/dotenv/index.js +458 -1
  7. package/compiled/dotenv/package.json +1 -1
  8. package/compiled/dotenv-expand/{lib/main.d.ts → index.d.ts} +9 -7
  9. package/compiled/dotenv-expand/index.js +146 -1
  10. package/compiled/dotenv-expand/package.json +1 -1
  11. package/compiled/http-compression/index.js +185 -1
  12. package/compiled/launch-editor-middleware/index.js +843 -1
  13. package/compiled/on-finished/index.d.ts +2 -2
  14. package/compiled/on-finished/index.js +390 -3
  15. package/compiled/on-finished/package.json +1 -1
  16. package/compiled/open/index.d.ts +1 -153
  17. package/compiled/open/index.js +526 -1
  18. package/compiled/open/package.json +1 -1
  19. package/compiled/sirv/index.d.ts +1 -0
  20. package/compiled/sirv/index.js +798 -1
  21. package/compiled/sirv/package.json +1 -1
  22. package/compiled/webpack-dev-middleware/index.d.ts +1 -0
  23. package/compiled/webpack-dev-middleware/index.js +6696 -0
  24. package/compiled/webpack-dev-middleware/license +20 -0
  25. package/compiled/webpack-dev-middleware/package.json +1 -0
  26. package/compiled/webpack-dev-middleware/schema-utils.js +1 -0
  27. package/compiled/ws/index.d.ts +7 -15
  28. package/compiled/ws/index.js +4885 -1
  29. package/compiled/ws/package.json +1 -1
  30. package/dist/cli/commands.js +1 -1
  31. package/dist/cli/prepare.js +1 -1
  32. package/dist/client/format.d.ts +5 -0
  33. package/dist/client/{formatStats.js → format.js} +22 -46
  34. package/dist/client/hmr.d.ts +5 -0
  35. package/dist/client/hmr.mjs +201 -474
  36. package/dist/client/overlay.mjs +208 -237
  37. package/dist/createContext.js +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/plugins/target.js +19 -16
  40. package/dist/provider/plugins/swc.js +1 -0
  41. package/dist/provider/shared.js +2 -2
  42. package/dist/server/devMiddleware.js +1 -1
  43. package/dist/server/devServer.js +6 -1
  44. package/dist/server/getDevMiddlewares.d.ts +3 -0
  45. package/dist/server/getDevMiddlewares.js +6 -8
  46. package/dist/server/helper.d.ts +4 -4
  47. package/dist/server/middlewares.d.ts +5 -2
  48. package/dist/server/middlewares.js +1 -7
  49. package/package.json +6 -5
  50. package/compiled/open/license +0 -9
  51. package/compiled/sirv/sirv.d.ts +0 -27
  52. package/dist/client/formatStats.d.ts +0 -12
  53. package/dist/client/hmr/createSocketUrl.d.ts +0 -12
  54. package/dist/client/hmr/index.d.ts +0 -4
@@ -1 +1,3528 @@
1
- (()=>{var t={81:t=>{"use strict";t.exports=require("child_process")},361:t=>{"use strict";t.exports=require("events")},147:t=>{"use strict";t.exports=require("fs")},17:t=>{"use strict";t.exports=require("path")},282:t=>{"use strict";t.exports=require("process")},975:(t,e,i)=>{const{InvalidArgumentError:n}=i(422);class Argument{constructor(t,e){this.description=e||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(t[0]){case"<":this.required=true;this._name=t.slice(1,-1);break;case"[":this.required=false;this._name=t.slice(1,-1);break;default:this.required=true;this._name=t;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}argParser(t){this.parseArg=t;return this}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(t){const e=t.name()+(t.variadic===true?"...":"");return t.required?"<"+e+">":"["+e+"]"}e.Argument=Argument;e.humanReadableArgName=humanReadableArgName},965:(t,e,i)=>{const n=i(361).EventEmitter;const s=i(81);const r=i(17);const o=i(147);const a=i(282);const{Argument:h,humanReadableArgName:l}=i(975);const{CommanderError:u}=i(422);const{Help:c}=i(455);const{Option:p,DualOptions:d}=i(985);const{suggestSimilar:m}=i(745);class Command extends n{constructor(t){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this.registeredArguments=[];this._args=this.registeredArguments;this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=t||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:t=>a.stdout.write(t),writeErr:t=>a.stderr.write(t),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:undefined,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:undefined,outputError:(t,e)=>e(t)};this._hidden=false;this._helpOption=undefined;this._addImplicitHelpCommand=undefined;this._helpCommand=undefined;this._helpConfiguration={}}copyInheritedSettings(t){this._outputConfiguration=t._outputConfiguration;this._helpOption=t._helpOption;this._helpCommand=t._helpCommand;this._helpConfiguration=t._helpConfiguration;this._exitCallback=t._exitCallback;this._storeOptionsAsProperties=t._storeOptionsAsProperties;this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue;this._allowExcessArguments=t._allowExcessArguments;this._enablePositionalOptions=t._enablePositionalOptions;this._showHelpAfterError=t._showHelpAfterError;this._showSuggestionAfterError=t._showSuggestionAfterError;return this}_getCommandAndAncestors(){const t=[];for(let e=this;e;e=e.parent){t.push(e)}return t}command(t,e,i){let n=e;let s=i;if(typeof n==="object"&&n!==null){s=n;n=null}s=s||{};const[,r,o]=t.match(/([^ ]+) *(.*)/);const a=this.createCommand(r);if(n){a.description(n);a._executableHandler=true}if(s.isDefault)this._defaultCommandName=a._name;a._hidden=!!(s.noHelp||s.hidden);a._executableFile=s.executableFile||null;if(o)a.arguments(o);this._registerCommand(a);a.parent=this;a.copyInheritedSettings(this);if(n)return this;return a}createCommand(t){return new Command(t)}createHelp(){return Object.assign(new c,this.configureHelp())}configureHelp(t){if(t===undefined)return this._helpConfiguration;this._helpConfiguration=t;return this}configureOutput(t){if(t===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,t);return this}showHelpAfterError(t=true){if(typeof t!=="string")t=!!t;this._showHelpAfterError=t;return this}showSuggestionAfterError(t=true){this._showSuggestionAfterError=!!t;return this}addCommand(t,e){if(!t._name){throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`)}e=e||{};if(e.isDefault)this._defaultCommandName=t._name;if(e.noHelp||e.hidden)t._hidden=true;this._registerCommand(t);t.parent=this;t._checkForBrokenPassThrough();return this}createArgument(t,e){return new h(t,e)}argument(t,e,i,n){const s=this.createArgument(t,e);if(typeof i==="function"){s.default(n).argParser(i)}else{s.default(i)}this.addArgument(s);return this}arguments(t){t.trim().split(/ +/).forEach((t=>{this.argument(t)}));return this}addArgument(t){const e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic){throw new Error(`only the last argument can be variadic '${e.name()}'`)}if(t.required&&t.defaultValue!==undefined&&t.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${t.name()}'`)}this.registeredArguments.push(t);return this}helpCommand(t,e){if(typeof t==="boolean"){this._addImplicitHelpCommand=t;return this}t=t??"help [command]";const[,i,n]=t.match(/([^ ]+) *(.*)/);const s=e??"display help for command";const r=this.createCommand(i);r.helpOption(false);if(n)r.arguments(n);if(s)r.description(s);this._addImplicitHelpCommand=true;this._helpCommand=r;return this}addHelpCommand(t,e){if(typeof t!=="object"){this.helpCommand(t,e);return this}this._addImplicitHelpCommand=true;this._helpCommand=t;return this}_getHelpCommand(){const t=this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"));if(t){if(this._helpCommand===undefined){this.helpCommand(undefined,undefined)}return this._helpCommand}return null}hook(t,e){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t)){throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`)}if(this._lifeCycleHooks[t]){this._lifeCycleHooks[t].push(e)}else{this._lifeCycleHooks[t]=[e]}return this}exitOverride(t){if(t){this._exitCallback=t}else{this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync"){throw t}else{}}}return this}_exit(t,e,i){if(this._exitCallback){this._exitCallback(new u(t,e,i))}a.exit(t)}action(t){const listener=e=>{const i=this.registeredArguments.length;const n=e.slice(0,i);if(this._storeOptionsAsProperties){n[i]=this}else{n[i]=this.opts()}n.push(this);return t.apply(this,n)};this._actionHandler=listener;return this}createOption(t,e){return new p(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(t){if(t.code==="commander.invalidArgument"){const e=`${n} ${t.message}`;this.error(e,{exitCode:t.exitCode,code:t.code})}throw t}}_registerOption(t){const e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){const i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'\n- already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){const knownBy=t=>[t.name()].concat(t.aliases());const e=knownBy(t).find((t=>this._findCommand(t)));if(e){const i=knownBy(this._findCommand(e)).join("|");const n=knownBy(t).join("|");throw new Error(`cannot add command '${n}' as already have command '${i}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);const e=t.name();const i=t.attributeName();if(t.negate){const e=t.long.replace(/^--no-/,"--");if(!this._findOption(e)){this.setOptionValueWithSource(i,t.defaultValue===undefined?true:t.defaultValue,"default")}}else if(t.defaultValue!==undefined){this.setOptionValueWithSource(i,t.defaultValue,"default")}const handleOptionValue=(e,n,s)=>{if(e==null&&t.presetArg!==undefined){e=t.presetArg}const r=this.getOptionValue(i);if(e!==null&&t.parseArg){e=this._callParseArg(t,e,r,n)}else if(e!==null&&t.variadic){e=t._concatValue(e,r)}if(e==null){if(t.negate){e=false}else if(t.isBoolean()||t.optional){e=true}else{e=""}}this.setOptionValueWithSource(i,e,s)};this.on("option:"+e,(e=>{const i=`error: option '${t.flags}' argument '${e}' is invalid.`;handleOptionValue(e,i,"cli")}));if(t.envVar){this.on("optionEnv:"+e,(e=>{const i=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;handleOptionValue(e,i,"env")}))}return this}_optionEx(t,e,i,n,s){if(typeof e==="object"&&e instanceof p){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const r=this.createOption(e,i);r.makeOptionMandatory(!!t.mandatory);if(typeof n==="function"){r.default(s).argParser(n)}else if(n instanceof RegExp){const t=n;n=(e,i)=>{const n=t.exec(e);return n?n[0]:i};r.default(s).argParser(n)}else{r.default(n)}return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:true},t,e,i,n)}combineFlagAndOptionalValue(t=true){this._combineFlagAndOptionalValue=!!t;return this}allowUnknownOption(t=true){this._allowUnknownOption=!!t;return this}allowExcessArguments(t=true){this._allowExcessArguments=!!t;return this}enablePositionalOptions(t=true){this._enablePositionalOptions=!!t;return this}passThroughOptions(t=true){this._passThroughOptions=!!t;this._checkForBrokenPassThrough();return this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions){throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}}storeOptionsAsProperties(t=true){if(this.options.length){throw new Error("call .storeOptionsAsProperties() before adding options")}if(Object.keys(this._optionValues).length){throw new Error("call .storeOptionsAsProperties() before setting option values")}this._storeOptionsAsProperties=!!t;return this}getOptionValue(t){if(this._storeOptionsAsProperties){return this[t]}return this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,undefined)}setOptionValueWithSource(t,e,i){if(this._storeOptionsAsProperties){this[t]=e}else{this._optionValues[t]=e}this._optionValueSources[t]=i;return this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;this._getCommandAndAncestors().forEach((i=>{if(i.getOptionValueSource(t)!==undefined){e=i.getOptionValueSource(t)}}));return e}_prepareUserArgs(t,e){if(t!==undefined&&!Array.isArray(t)){throw new Error("first parameter to parse must be array or undefined")}e=e||{};if(t===undefined){t=a.argv;if(a.versions&&a.versions.electron){e.from="electron"}}this.rawArgs=t.slice();let i;switch(e.from){case undefined:case"node":this._scriptPath=t[1];i=t.slice(2);break;case"electron":if(a.defaultApp){this._scriptPath=t[1];i=t.slice(2)}else{i=t.slice(1)}break;case"user":i=t.slice(0);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return i}parse(t,e){const i=this._prepareUserArgs(t,e);this._parseCommand([],i);return this}async parseAsync(t,e){const i=this._prepareUserArgs(t,e);await this._parseCommand([],i);return this}_executeSubCommand(t,e){e=e.slice();let i=false;const n=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(t,e){const i=r.resolve(t,e);if(o.existsSync(i))return i;if(n.includes(r.extname(e)))return undefined;const s=n.find((t=>o.existsSync(`${i}${t}`)));if(s)return`${i}${s}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let h=t._executableFile||`${this._name}-${t._name}`;let l=this._executableDir||"";if(this._scriptPath){let t;try{t=o.realpathSync(this._scriptPath)}catch(e){t=this._scriptPath}l=r.resolve(r.dirname(t),l)}if(l){let e=findFile(l,h);if(!e&&!t._executableFile&&this._scriptPath){const i=r.basename(this._scriptPath,r.extname(this._scriptPath));if(i!==this._name){e=findFile(l,`${i}-${t._name}`)}}h=e||h}i=n.includes(r.extname(h));let c;if(a.platform!=="win32"){if(i){e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.argv[0],e,{stdio:"inherit"})}else{c=s.spawn(h,e,{stdio:"inherit"})}}else{e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.execPath,e,{stdio:"inherit"})}if(!c.killed){const t=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];t.forEach((t=>{a.on(t,(()=>{if(c.killed===false&&c.exitCode===null){c.kill(t)}}))}))}const p=this._exitCallback;c.on("close",((t,e)=>{t=t??1;if(!p){a.exit(t)}else{p(new u(t,"commander.executeSubCommandAsync","(close)"))}}));c.on("error",(e=>{if(e.code==="ENOENT"){const e=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const i=`'${h}' does not exist\n - if '${t._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 - ${e}`;throw new Error(i)}else if(e.code==="EACCES"){throw new Error(`'${h}' not executable`)}if(!p){a.exit(1)}else{const t=new u(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e;p(t)}}));this.runningCommand=c}_dispatchSubcommand(t,e,i){const n=this._findCommand(t);if(!n)this.help({error:true});let s;s=this._chainOrCallSubCommandHook(s,n,"preSubcommand");s=this._chainOrCall(s,(()=>{if(n._executableHandler){this._executeSubCommand(n,e.concat(i))}else{return n._parseCommand(e,i)}}));return s}_dispatchHelpCommand(t){if(!t){this.help()}const e=this._findCommand(t);if(e&&!e._executableHandler){e.help()}return this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((t,e)=>{if(t.required&&this.args[e]==null){this.missingArgument(t.name())}}));if(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic){return}if(this.args.length>this.registeredArguments.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(t,e,i)=>{let n=e;if(e!==null&&t.parseArg){const s=`error: command-argument value '${e}' is invalid for argument '${t.name()}'.`;n=this._callParseArg(t,e,i,s)}return n};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach(((e,i)=>{let n=e.defaultValue;if(e.variadic){if(i<this.args.length){n=this.args.slice(i);if(e.parseArg){n=n.reduce(((t,i)=>myParseArg(e,i,t)),e.defaultValue)}}else if(n===undefined){n=[]}}else if(i<this.args.length){n=this.args[i];if(e.parseArg){n=myParseArg(e,n,e.defaultValue)}}t[i]=n}));this.processedArgs=t}_chainOrCall(t,e){if(t&&t.then&&typeof t.then==="function"){return t.then((()=>e()))}return e()}_chainOrCallHooks(t,e){let i=t;const n=[];this._getCommandAndAncestors().reverse().filter((t=>t._lifeCycleHooks[e]!==undefined)).forEach((t=>{t._lifeCycleHooks[e].forEach((e=>{n.push({hookedCommand:t,callback:e})}))}));if(e==="postAction"){n.reverse()}n.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))}));return i}_chainOrCallSubCommandHook(t,e,i){let n=t;if(this._lifeCycleHooks[i]!==undefined){this._lifeCycleHooks[i].forEach((t=>{n=this._chainOrCall(n,(()=>t(this,e)))}))}return n}_parseCommand(t,e){const i=this.parseOptions(e);this._parseOptionsEnv();this._parseOptionsImplied();t=t.concat(i.operands);e=i.unknown;this.args=t.concat(e);if(t&&this._findCommand(t[0])){return this._dispatchSubcommand(t[0],t.slice(1),e)}if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name()){return this._dispatchHelpCommand(t[1])}if(this._defaultCommandName){this._outputHelpIfRequested(e);return this._dispatchSubcommand(this._defaultCommandName,t,e)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}this._outputHelpIfRequested(i.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(i.unknown.length>0){this.unknownOption(i.unknown[0])}};const n=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let i;i=this._chainOrCallHooks(i,"preAction");i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs)));if(this.parent){i=this._chainOrCall(i,(()=>{this.parent.emit(n,t,e)}))}i=this._chainOrCallHooks(i,"postAction");return i}if(this.parent&&this.parent.listenerCount(n)){checkForUnknownOptions();this._processArguments();this.parent.emit(n,t,e)}else if(t.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",t,e)}if(this.listenerCount("command:*")){this.emit("command:*",t,e)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(t){if(!t)return undefined;return this.commands.find((e=>e._name===t||e._aliases.includes(t)))}_findOption(t){return this.options.find((e=>e.is(t)))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((t=>{t.options.forEach((e=>{if(e.mandatory&&t.getOptionValue(e.attributeName())===undefined){t.missingMandatoryOptionValue(e)}}))}))}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const e=t.attributeName();if(this.getOptionValue(e)===undefined){return false}return this.getOptionValueSource(e)!=="default"}));const e=t.filter((t=>t.conflictsWith.length>0));e.forEach((e=>{const i=t.find((t=>e.conflictsWith.includes(t.attributeName())));if(i){this._conflictingOption(e,i)}}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((t=>{t._checkForConflictingLocalOptions()}))}parseOptions(t){const e=[];const i=[];let n=e;const s=t.slice();function maybeOption(t){return t.length>1&&t[0]==="-"}let r=null;while(s.length){const t=s.shift();if(t==="--"){if(n===i)n.push(t);n.push(...s);break}if(r&&!maybeOption(t)){this.emit(`option:${r.name()}`,t);continue}r=null;if(maybeOption(t)){const e=this._findOption(t);if(e){if(e.required){const t=s.shift();if(t===undefined)this.optionMissingArgument(e);this.emit(`option:${e.name()}`,t)}else if(e.optional){let t=null;if(s.length>0&&!maybeOption(s[0])){t=s.shift()}this.emit(`option:${e.name()}`,t)}else{this.emit(`option:${e.name()}`)}r=e.variadic?e:null;continue}}if(t.length>2&&t[0]==="-"&&t[1]!=="-"){const e=this._findOption(`-${t[1]}`);if(e){if(e.required||e.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${e.name()}`,t.slice(2))}else{this.emit(`option:${e.name()}`);s.unshift(`-${t.slice(2)}`)}continue}}if(/^--[^=]+=/.test(t)){const e=t.indexOf("=");const i=this._findOption(t.slice(0,e));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(e+1));continue}}if(maybeOption(t)){n=i}if((this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(t)){e.push(t);if(s.length>0)i.push(...s);break}else if(this._getHelpCommand()&&t===this._getHelpCommand().name()){e.push(t);if(s.length>0)e.push(...s);break}else if(this._defaultCommandName){i.push(t);if(s.length>0)i.push(...s);break}}if(this._passThroughOptions){n.push(t);if(s.length>0)n.push(...s);break}n.push(t)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={};const e=this.options.length;for(let i=0;i<e;i++){const e=this.options[i].attributeName();t[e]=e===this._versionOptionName?this._version:this[e]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(((t,e)=>Object.assign(t,e.opts())),{})}error(t,e){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const i=e||{};const n=i.exitCode||1;const s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in a.env){const e=t.attributeName();if(this.getOptionValue(e)===undefined||["default","config","env"].includes(this.getOptionValueSource(e))){if(t.required||t.optional){this.emit(`optionEnv:${t.name()}`,a.env[t.envVar])}else{this.emit(`optionEnv:${t.name()}`)}}}}))}_parseOptionsImplied(){const t=new d(this.options);const hasCustomOptionValue=t=>this.getOptionValue(t)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((e=>e.implied!==undefined&&hasCustomOptionValue(e.attributeName())&&t.valueFromOption(this.getOptionValue(e.attributeName()),e))).forEach((t=>{Object.keys(t.implied).filter((t=>!hasCustomOptionValue(t))).forEach((e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")}))}))}missingArgument(t){const e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){const e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){const findBestOptionFromValue=t=>{const e=t.attributeName();const i=this.getOptionValue(e);const n=this.options.find((t=>t.negate&&e===t.attributeName()));const s=this.options.find((t=>!t.negate&&e===t.attributeName()));if(n&&(n.presetArg===undefined&&i===false||n.presetArg!==undefined&&i===n.presetArg)){return n}return s||t};const getErrorMessage=t=>{const e=findBestOptionFromValue(t);const i=e.attributeName();const n=this.getOptionValueSource(i);if(n==="env"){return`environment variable '${e.envVar}'`}return`option '${e.flags}'`};const i=`error: ${getErrorMessage(t)} cannot be used with ${getErrorMessage(e)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[];let n=this;do{const t=n.createHelp().visibleOptions(n).filter((t=>t.long)).map((t=>t.long));i=i.concat(t);n=n.parent}while(n&&!n._enablePositionalOptions);e=m(t,i)}const i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const e=this.registeredArguments.length;const i=e===1?"":"s";const n=this.parent?` for '${this.name()}'`:"";const s=`error: too many arguments${n}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let e="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name());if(t.alias())i.push(t.alias())}));e=m(t,i)}const i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===undefined)return this._version;this._version=t;e=e||"-V, --version";i=i||"output the version number";const n=this.createOption(e,i);this._versionOptionName=n.attributeName();this._registerOption(n);this.on("option:"+n.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`);this._exit(0,"commander.version",t)}));return this}description(t,e){if(t===undefined&&e===undefined)return this._description;this._description=t;if(e){this._argsDescription=e}return this}summary(t){if(t===undefined)return this._summary;this._summary=t;return this}alias(t){if(t===undefined)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){e=this.commands[this.commands.length-1]}if(t===e._name)throw new Error("Command alias can't be the same as its name");const i=this.parent?._findCommand(t);if(i){const e=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${e}'`)}e._aliases.push(t);return this}aliases(t){if(t===undefined)return this._aliases;t.forEach((t=>this.alias(t)));return this}usage(t){if(t===undefined){if(this._usage)return this._usage;const t=this.registeredArguments.map((t=>l(t)));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}this._usage=t;return this}name(t){if(t===undefined)return this._name;this._name=t;return this}nameFromFilename(t){this._name=r.basename(t,r.extname(t));return this}executableDir(t){if(t===undefined)return this._executableDir;this._executableDir=t;return this}helpInformation(t){const e=this.createHelp();if(e.helpWidth===undefined){e.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return e.formatHelp(this,e)}_getHelpContext(t){t=t||{};const e={error:!!t.error};let i;if(e.error){i=t=>this._outputConfiguration.writeErr(t)}else{i=t=>this._outputConfiguration.writeOut(t)}e.write=t.write||i;e.command=this;return e}outputHelp(t){let e;if(typeof t==="function"){e=t;t=undefined}const i=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach((t=>t.emit("beforeAllHelp",i)));this.emit("beforeHelp",i);let n=this.helpInformation(i);if(e){n=e(n);if(typeof n!=="string"&&!Buffer.isBuffer(n)){throw new Error("outputHelp callback must return a string or a Buffer")}}i.write(n);if(this._getHelpOption()?.long){this.emit(this._getHelpOption().long)}this.emit("afterHelp",i);this._getCommandAndAncestors().forEach((t=>t.emit("afterAllHelp",i)))}helpOption(t,e){if(typeof t==="boolean"){if(t){this._helpOption=this._helpOption??undefined}else{this._helpOption=null}return this}t=t??"-h, --help";e=e??"display help for command";this._helpOption=this.createOption(t,e);return this}_getHelpOption(){if(this._helpOption===undefined){this.helpOption(undefined,undefined)}return this._helpOption}addHelpOption(t){this._helpOption=t;return this}help(t){this.outputHelp(t);let e=a.exitCode||0;if(e===0&&t&&typeof t!=="function"&&t.error){e=1}this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t)){throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`)}const n=`${t}Help`;this.on(n,(t=>{let i;if(typeof e==="function"){i=e({error:t.error,command:t.command})}else{i=e}if(i){t.write(`${i}\n`)}}));return this}_outputHelpIfRequested(t){const e=this._getHelpOption();const i=e&&t.find((t=>e.is(t)));if(i){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}}function incrementNodeInspectorPort(t){return t.map((t=>{if(!t.startsWith("--inspect")){return t}let e;let i="127.0.0.1";let n="9229";let s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null){e=s[1]}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){e=s[1];if(/^\d+$/.test(s[3])){n=s[3]}else{i=s[3]}}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){e=s[1];i=s[3];n=s[4]}if(e&&n!=="0"){return`${e}=${i}:${parseInt(n)+1}`}return t}))}e.Command=Command},422:(t,e)=>{class CommanderError extends Error{constructor(t,e,i){super(i);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name;this.code=e;this.exitCode=t;this.nestedError=undefined}}class InvalidArgumentError extends CommanderError{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}e.CommanderError=CommanderError;e.InvalidArgumentError=InvalidArgumentError},455:(t,e,i)=>{const{humanReadableArgName:n}=i(975);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false;this.showGlobalOptions=false}visibleCommands(t){const e=t.commands.filter((t=>!t._hidden));const i=t._getHelpCommand();if(i&&!i._hidden){e.push(i)}if(this.sortSubcommands){e.sort(((t,e)=>t.name().localeCompare(e.name())))}return e}compareOptions(t,e){const getSortKey=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");return getSortKey(t).localeCompare(getSortKey(e))}visibleOptions(t){const e=t.options.filter((t=>!t.hidden));const i=t._getHelpOption();if(i&&!i.hidden){const n=i.short&&t._findOption(i.short);const s=i.long&&t._findOption(i.long);if(!n&&!s){e.push(i)}else if(i.long&&!s){e.push(t.createOption(i.long,i.description))}else if(i.short&&!n){e.push(t.createOption(i.short,i.description))}}if(this.sortOptions){e.sort(this.compareOptions)}return e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];const e=[];for(let i=t.parent;i;i=i.parent){const t=i.options.filter((t=>!t.hidden));e.push(...t)}if(this.sortOptions){e.sort(this.compareOptions)}return e}visibleArguments(t){if(t._argsDescription){t.registeredArguments.forEach((e=>{e.description=e.description||t._argsDescription[e.name()]||""}))}if(t.registeredArguments.find((t=>t.description))){return t.registeredArguments}return[]}subcommandTerm(t){const e=t.registeredArguments.map((t=>n(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce(((t,i)=>Math.max(t,e.subcommandTerm(i).length)),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce(((t,i)=>Math.max(t,e.optionTerm(i).length)),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce(((t,i)=>Math.max(t,e.optionTerm(i).length)),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce(((t,i)=>Math.max(t,e.argumentTerm(i).length)),0)}commandUsage(t){let e=t._name;if(t._aliases[0]){e=e+"|"+t._aliases[0]}let i="";for(let e=t.parent;e;e=e.parent){i=e.name()+" "+i}return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){const i=t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean";if(i){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}}if(t.presetArg!==undefined&&t.optional){e.push(`preset: ${JSON.stringify(t.presetArg)}`)}if(t.envVar!==undefined){e.push(`env: ${t.envVar}`)}if(e.length>0){return`${t.description} (${e.join(", ")})`}return t.description}argumentDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(e.length>0){const i=`(${e.join(", ")})`;if(t.description){return`${t.description} ${i}`}return i}return t.description}formatHelp(t,e){const i=e.padWidth(t,e);const n=e.helpWidth||80;const s=2;const r=2;function formatItem(t,o){if(o){const a=`${t.padEnd(i+r)}${o}`;return e.wrap(a,n-s,i+r)}return t}function formatList(t){return t.join("\n").replace(/^/gm," ".repeat(s))}let o=[`Usage: ${e.commandUsage(t)}`,""];const a=e.commandDescription(t);if(a.length>0){o=o.concat([e.wrap(a,n,0),""])}const h=e.visibleArguments(t).map((t=>formatItem(e.argumentTerm(t),e.argumentDescription(t))));if(h.length>0){o=o.concat(["Arguments:",formatList(h),""])}const l=e.visibleOptions(t).map((t=>formatItem(e.optionTerm(t),e.optionDescription(t))));if(l.length>0){o=o.concat(["Options:",formatList(l),""])}if(this.showGlobalOptions){const i=e.visibleGlobalOptions(t).map((t=>formatItem(e.optionTerm(t),e.optionDescription(t))));if(i.length>0){o=o.concat(["Global Options:",formatList(i),""])}}const u=e.visibleCommands(t).map((t=>formatItem(e.subcommandTerm(t),e.subcommandDescription(t))));if(u.length>0){o=o.concat(["Commands:",formatList(u),""])}return o.join("\n")}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}wrap(t,e,i,n=40){const s=" \\f\\t\\v   -    \ufeff";const r=new RegExp(`[\\n][${s}]+`);if(t.match(r))return t;const o=e-i;if(o<n)return t;const a=t.slice(0,i);const h=t.slice(i).replace("\r\n","\n");const l=" ".repeat(i);const u="​";const c=`\\s${u}`;const p=new RegExp(`\n|.{1,${o-1}}([${c}]|$)|[^${c}]+?([${c}]|$)`,"g");const d=h.match(p)||[];return a+d.map(((t,e)=>{if(t==="\n")return"";return(e>0?l:"")+t.trimEnd()})).join("\n")}}e.Help=Help},985:(t,e,i)=>{const{InvalidArgumentError:n}=i(422);class Option{constructor(t,e){this.flags=t;this.description=e||"";this.required=t.includes("<");this.optional=t.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(t);this.mandatory=false;const i=splitOptionFlags(t);this.short=i.shortFlag;this.long=i.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}preset(t){this.presetArg=t;return this}conflicts(t){this.conflictsWith=this.conflictsWith.concat(t);return this}implies(t){let e=t;if(typeof t==="string"){e={[t]:true}}this.implied=Object.assign(this.implied||{},e);return this}env(t){this.envVar=t;return this}argParser(t){this.parseArg=t;return this}makeOptionMandatory(t=true){this.mandatory=!!t;return this}hideHelp(t=true){this.hidden=!!t;return this}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(t){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;t.forEach((t=>{if(t.negate){this.negativeOptions.set(t.attributeName(),t)}else{this.positiveOptions.set(t.attributeName(),t)}}));this.negativeOptions.forEach(((t,e)=>{if(this.positiveOptions.has(e)){this.dualOptions.add(e)}}))}valueFromOption(t,e){const i=e.attributeName();if(!this.dualOptions.has(i))return true;const n=this.negativeOptions.get(i).presetArg;const s=n!==undefined?n:false;return e.negate===(s===t)}}function camelcase(t){return t.split("-").reduce(((t,e)=>t+e[0].toUpperCase()+e.slice(1)))}function splitOptionFlags(t){let e;let i;const n=t.split(/[ |,]+/);if(n.length>1&&!/^[[<]/.test(n[1]))e=n.shift();i=n.shift();if(!e&&/^-[^-]$/.test(i)){e=i;i=undefined}return{shortFlag:e,longFlag:i}}e.Option=Option;e.DualOptions=DualOptions},745:(t,e)=>{const i=3;function editDistance(t,e){if(Math.abs(t.length-e.length)>i)return Math.max(t.length,e.length);const n=[];for(let e=0;e<=t.length;e++){n[e]=[e]}for(let t=0;t<=e.length;t++){n[0][t]=t}for(let i=1;i<=e.length;i++){for(let s=1;s<=t.length;s++){let r=1;if(t[s-1]===e[i-1]){r=0}else{r=1}n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r);if(s>1&&i>1&&t[s-1]===e[i-2]&&t[s-2]===e[i-1]){n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1)}}}return n[t.length][e.length]}function suggestSimilar(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const n=t.startsWith("--");if(n){t=t.slice(2);e=e.map((t=>t.slice(2)))}let s=[];let r=i;const o=.4;e.forEach((e=>{if(e.length<=1)return;const i=editDistance(t,e);const n=Math.max(t.length,e.length);const a=(n-i)/n;if(a>o){if(i<r){r=i;s=[e]}else if(i===r){s.push(e)}}}));s.sort(((t,e)=>t.localeCompare(e)));if(n){s=s.map((t=>`--${t}`))}if(s.length>1){return`\n(Did you mean one of ${s.join(", ")}?)`}if(s.length===1){return`\n(Did you mean ${s[0]}?)`}return""}e.suggestSimilar=suggestSimilar}};var e={};function __nccwpck_require__(i){var n=e[i];if(n!==undefined){return n.exports}var s=e[i]={exports:{}};var r=true;try{t[i](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete e[i]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var i={};(()=>{var t=i;const{Argument:e}=__nccwpck_require__(975);const{Command:n}=__nccwpck_require__(965);const{CommanderError:s,InvalidArgumentError:r}=__nccwpck_require__(422);const{Help:o}=__nccwpck_require__(455);const{Option:a}=__nccwpck_require__(985);t.program=new n;t.createCommand=t=>new n(t);t.createOption=(t,e)=>new a(t,e);t.createArgument=(t,i)=>new e(t,i);t.Command=n;t.Option=a;t.Argument=e;t.Help=o;t.CommanderError=s;t.InvalidArgumentError=r;t.InvalidOptionArgumentError=r})();module.exports=i})();
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ var __webpack_modules__ = ({
3
+
4
+ /***/ 81:
5
+ /***/ ((module) => {
6
+
7
+ "use strict";
8
+ module.exports = require("child_process");
9
+
10
+ /***/ }),
11
+
12
+ /***/ 361:
13
+ /***/ ((module) => {
14
+
15
+ "use strict";
16
+ module.exports = require("events");
17
+
18
+ /***/ }),
19
+
20
+ /***/ 147:
21
+ /***/ ((module) => {
22
+
23
+ "use strict";
24
+ module.exports = require("fs");
25
+
26
+ /***/ }),
27
+
28
+ /***/ 17:
29
+ /***/ ((module) => {
30
+
31
+ "use strict";
32
+ module.exports = require("path");
33
+
34
+ /***/ }),
35
+
36
+ /***/ 282:
37
+ /***/ ((module) => {
38
+
39
+ "use strict";
40
+ module.exports = require("process");
41
+
42
+ /***/ }),
43
+
44
+ /***/ 975:
45
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
46
+
47
+ const { InvalidArgumentError } = __nccwpck_require__(422);
48
+
49
+ class Argument {
50
+ /**
51
+ * Initialize a new command argument with the given name and description.
52
+ * The default is that the argument is required, and you can explicitly
53
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
54
+ *
55
+ * @param {string} name
56
+ * @param {string} [description]
57
+ */
58
+
59
+ constructor(name, description) {
60
+ this.description = description || '';
61
+ this.variadic = false;
62
+ this.parseArg = undefined;
63
+ this.defaultValue = undefined;
64
+ this.defaultValueDescription = undefined;
65
+ this.argChoices = undefined;
66
+
67
+ switch (name[0]) {
68
+ case '<': // e.g. <required>
69
+ this.required = true;
70
+ this._name = name.slice(1, -1);
71
+ break;
72
+ case '[': // e.g. [optional]
73
+ this.required = false;
74
+ this._name = name.slice(1, -1);
75
+ break;
76
+ default:
77
+ this.required = true;
78
+ this._name = name;
79
+ break;
80
+ }
81
+
82
+ if (this._name.length > 3 && this._name.slice(-3) === '...') {
83
+ this.variadic = true;
84
+ this._name = this._name.slice(0, -3);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Return argument name.
90
+ *
91
+ * @return {string}
92
+ */
93
+
94
+ name() {
95
+ return this._name;
96
+ }
97
+
98
+ /**
99
+ * @package internal use only
100
+ */
101
+
102
+ _concatValue(value, previous) {
103
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
104
+ return [value];
105
+ }
106
+
107
+ return previous.concat(value);
108
+ }
109
+
110
+ /**
111
+ * Set the default value, and optionally supply the description to be displayed in the help.
112
+ *
113
+ * @param {*} value
114
+ * @param {string} [description]
115
+ * @return {Argument}
116
+ */
117
+
118
+ default(value, description) {
119
+ this.defaultValue = value;
120
+ this.defaultValueDescription = description;
121
+ return this;
122
+ }
123
+
124
+ /**
125
+ * Set the custom handler for processing CLI command arguments into argument values.
126
+ *
127
+ * @param {Function} [fn]
128
+ * @return {Argument}
129
+ */
130
+
131
+ argParser(fn) {
132
+ this.parseArg = fn;
133
+ return this;
134
+ }
135
+
136
+ /**
137
+ * Only allow argument value to be one of choices.
138
+ *
139
+ * @param {string[]} values
140
+ * @return {Argument}
141
+ */
142
+
143
+ choices(values) {
144
+ this.argChoices = values.slice();
145
+ this.parseArg = (arg, previous) => {
146
+ if (!this.argChoices.includes(arg)) {
147
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
148
+ }
149
+ if (this.variadic) {
150
+ return this._concatValue(arg, previous);
151
+ }
152
+ return arg;
153
+ };
154
+ return this;
155
+ }
156
+
157
+ /**
158
+ * Make argument required.
159
+ */
160
+ argRequired() {
161
+ this.required = true;
162
+ return this;
163
+ }
164
+
165
+ /**
166
+ * Make argument optional.
167
+ */
168
+ argOptional() {
169
+ this.required = false;
170
+ return this;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Takes an argument and returns its human readable equivalent for help usage.
176
+ *
177
+ * @param {Argument} arg
178
+ * @return {string}
179
+ * @private
180
+ */
181
+
182
+ function humanReadableArgName(arg) {
183
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
184
+
185
+ return arg.required
186
+ ? '<' + nameOutput + '>'
187
+ : '[' + nameOutput + ']';
188
+ }
189
+
190
+ exports.Argument = Argument;
191
+ exports.humanReadableArgName = humanReadableArgName;
192
+
193
+
194
+ /***/ }),
195
+
196
+ /***/ 965:
197
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
198
+
199
+ const EventEmitter = (__nccwpck_require__(361).EventEmitter);
200
+ const childProcess = __nccwpck_require__(81);
201
+ const path = __nccwpck_require__(17);
202
+ const fs = __nccwpck_require__(147);
203
+ const process = __nccwpck_require__(282);
204
+
205
+ const { Argument, humanReadableArgName } = __nccwpck_require__(975);
206
+ const { CommanderError } = __nccwpck_require__(422);
207
+ const { Help } = __nccwpck_require__(455);
208
+ const { Option, DualOptions } = __nccwpck_require__(985);
209
+ const { suggestSimilar } = __nccwpck_require__(745);
210
+
211
+ class Command extends EventEmitter {
212
+ /**
213
+ * Initialize a new `Command`.
214
+ *
215
+ * @param {string} [name]
216
+ */
217
+
218
+ constructor(name) {
219
+ super();
220
+ /** @type {Command[]} */
221
+ this.commands = [];
222
+ /** @type {Option[]} */
223
+ this.options = [];
224
+ this.parent = null;
225
+ this._allowUnknownOption = false;
226
+ this._allowExcessArguments = true;
227
+ /** @type {Argument[]} */
228
+ this.registeredArguments = [];
229
+ this._args = this.registeredArguments; // deprecated old name
230
+ /** @type {string[]} */
231
+ this.args = []; // cli args with options removed
232
+ this.rawArgs = [];
233
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
234
+ this._scriptPath = null;
235
+ this._name = name || '';
236
+ this._optionValues = {};
237
+ this._optionValueSources = {}; // default, env, cli etc
238
+ this._storeOptionsAsProperties = false;
239
+ this._actionHandler = null;
240
+ this._executableHandler = false;
241
+ this._executableFile = null; // custom name for executable
242
+ this._executableDir = null; // custom search directory for subcommands
243
+ this._defaultCommandName = null;
244
+ this._exitCallback = null;
245
+ this._aliases = [];
246
+ this._combineFlagAndOptionalValue = true;
247
+ this._description = '';
248
+ this._summary = '';
249
+ this._argsDescription = undefined; // legacy
250
+ this._enablePositionalOptions = false;
251
+ this._passThroughOptions = false;
252
+ this._lifeCycleHooks = {}; // a hash of arrays
253
+ /** @type {(boolean | string)} */
254
+ this._showHelpAfterError = false;
255
+ this._showSuggestionAfterError = true;
256
+
257
+ // see .configureOutput() for docs
258
+ this._outputConfiguration = {
259
+ writeOut: (str) => process.stdout.write(str),
260
+ writeErr: (str) => process.stderr.write(str),
261
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
262
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
263
+ outputError: (str, write) => write(str)
264
+ };
265
+
266
+ this._hidden = false;
267
+ /** @type {(Option | null | undefined)} */
268
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
269
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
270
+ /** @type {Command} */
271
+ this._helpCommand = undefined; // lazy initialised, inherited
272
+ this._helpConfiguration = {};
273
+ }
274
+
275
+ /**
276
+ * Copy settings that are useful to have in common across root command and subcommands.
277
+ *
278
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
279
+ *
280
+ * @param {Command} sourceCommand
281
+ * @return {Command} `this` command for chaining
282
+ */
283
+ copyInheritedSettings(sourceCommand) {
284
+ this._outputConfiguration = sourceCommand._outputConfiguration;
285
+ this._helpOption = sourceCommand._helpOption;
286
+ this._helpCommand = sourceCommand._helpCommand;
287
+ this._helpConfiguration = sourceCommand._helpConfiguration;
288
+ this._exitCallback = sourceCommand._exitCallback;
289
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
290
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
291
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
292
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
293
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
294
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
295
+
296
+ return this;
297
+ }
298
+
299
+ /**
300
+ * @returns {Command[]}
301
+ * @private
302
+ */
303
+
304
+ _getCommandAndAncestors() {
305
+ const result = [];
306
+ for (let command = this; command; command = command.parent) {
307
+ result.push(command);
308
+ }
309
+ return result;
310
+ }
311
+
312
+ /**
313
+ * Define a command.
314
+ *
315
+ * There are two styles of command: pay attention to where to put the description.
316
+ *
317
+ * @example
318
+ * // Command implemented using action handler (description is supplied separately to `.command`)
319
+ * program
320
+ * .command('clone <source> [destination]')
321
+ * .description('clone a repository into a newly created directory')
322
+ * .action((source, destination) => {
323
+ * console.log('clone command called');
324
+ * });
325
+ *
326
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
327
+ * program
328
+ * .command('start <service>', 'start named service')
329
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
330
+ *
331
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
332
+ * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
333
+ * @param {Object} [execOpts] - configuration options (for executable)
334
+ * @return {Command} returns new command for action handler, or `this` for executable command
335
+ */
336
+
337
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
338
+ let desc = actionOptsOrExecDesc;
339
+ let opts = execOpts;
340
+ if (typeof desc === 'object' && desc !== null) {
341
+ opts = desc;
342
+ desc = null;
343
+ }
344
+ opts = opts || {};
345
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
346
+
347
+ const cmd = this.createCommand(name);
348
+ if (desc) {
349
+ cmd.description(desc);
350
+ cmd._executableHandler = true;
351
+ }
352
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
353
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
354
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
355
+ if (args) cmd.arguments(args);
356
+ this._registerCommand(cmd);
357
+ cmd.parent = this;
358
+ cmd.copyInheritedSettings(this);
359
+
360
+ if (desc) return this;
361
+ return cmd;
362
+ }
363
+
364
+ /**
365
+ * Factory routine to create a new unattached command.
366
+ *
367
+ * See .command() for creating an attached subcommand, which uses this routine to
368
+ * create the command. You can override createCommand to customise subcommands.
369
+ *
370
+ * @param {string} [name]
371
+ * @return {Command} new command
372
+ */
373
+
374
+ createCommand(name) {
375
+ return new Command(name);
376
+ }
377
+
378
+ /**
379
+ * You can customise the help with a subclass of Help by overriding createHelp,
380
+ * or by overriding Help properties using configureHelp().
381
+ *
382
+ * @return {Help}
383
+ */
384
+
385
+ createHelp() {
386
+ return Object.assign(new Help(), this.configureHelp());
387
+ }
388
+
389
+ /**
390
+ * You can customise the help by overriding Help properties using configureHelp(),
391
+ * or with a subclass of Help by overriding createHelp().
392
+ *
393
+ * @param {Object} [configuration] - configuration options
394
+ * @return {(Command|Object)} `this` command for chaining, or stored configuration
395
+ */
396
+
397
+ configureHelp(configuration) {
398
+ if (configuration === undefined) return this._helpConfiguration;
399
+
400
+ this._helpConfiguration = configuration;
401
+ return this;
402
+ }
403
+
404
+ /**
405
+ * The default output goes to stdout and stderr. You can customise this for special
406
+ * applications. You can also customise the display of errors by overriding outputError.
407
+ *
408
+ * The configuration properties are all functions:
409
+ *
410
+ * // functions to change where being written, stdout and stderr
411
+ * writeOut(str)
412
+ * writeErr(str)
413
+ * // matching functions to specify width for wrapping help
414
+ * getOutHelpWidth()
415
+ * getErrHelpWidth()
416
+ * // functions based on what is being written out
417
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
418
+ *
419
+ * @param {Object} [configuration] - configuration options
420
+ * @return {(Command|Object)} `this` command for chaining, or stored configuration
421
+ */
422
+
423
+ configureOutput(configuration) {
424
+ if (configuration === undefined) return this._outputConfiguration;
425
+
426
+ Object.assign(this._outputConfiguration, configuration);
427
+ return this;
428
+ }
429
+
430
+ /**
431
+ * Display the help or a custom message after an error occurs.
432
+ *
433
+ * @param {(boolean|string)} [displayHelp]
434
+ * @return {Command} `this` command for chaining
435
+ */
436
+ showHelpAfterError(displayHelp = true) {
437
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
438
+ this._showHelpAfterError = displayHelp;
439
+ return this;
440
+ }
441
+
442
+ /**
443
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
444
+ *
445
+ * @param {boolean} [displaySuggestion]
446
+ * @return {Command} `this` command for chaining
447
+ */
448
+ showSuggestionAfterError(displaySuggestion = true) {
449
+ this._showSuggestionAfterError = !!displaySuggestion;
450
+ return this;
451
+ }
452
+
453
+ /**
454
+ * Add a prepared subcommand.
455
+ *
456
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
457
+ *
458
+ * @param {Command} cmd - new subcommand
459
+ * @param {Object} [opts] - configuration options
460
+ * @return {Command} `this` command for chaining
461
+ */
462
+
463
+ addCommand(cmd, opts) {
464
+ if (!cmd._name) {
465
+ throw new Error(`Command passed to .addCommand() must have a name
466
+ - specify the name in Command constructor or using .name()`);
467
+ }
468
+
469
+ opts = opts || {};
470
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
471
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
472
+
473
+ this._registerCommand(cmd);
474
+ cmd.parent = this;
475
+ cmd._checkForBrokenPassThrough();
476
+
477
+ return this;
478
+ }
479
+
480
+ /**
481
+ * Factory routine to create a new unattached argument.
482
+ *
483
+ * See .argument() for creating an attached argument, which uses this routine to
484
+ * create the argument. You can override createArgument to return a custom argument.
485
+ *
486
+ * @param {string} name
487
+ * @param {string} [description]
488
+ * @return {Argument} new argument
489
+ */
490
+
491
+ createArgument(name, description) {
492
+ return new Argument(name, description);
493
+ }
494
+
495
+ /**
496
+ * Define argument syntax for command.
497
+ *
498
+ * The default is that the argument is required, and you can explicitly
499
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
500
+ *
501
+ * @example
502
+ * program.argument('<input-file>');
503
+ * program.argument('[output-file]');
504
+ *
505
+ * @param {string} name
506
+ * @param {string} [description]
507
+ * @param {(Function|*)} [fn] - custom argument processing function
508
+ * @param {*} [defaultValue]
509
+ * @return {Command} `this` command for chaining
510
+ */
511
+ argument(name, description, fn, defaultValue) {
512
+ const argument = this.createArgument(name, description);
513
+ if (typeof fn === 'function') {
514
+ argument.default(defaultValue).argParser(fn);
515
+ } else {
516
+ argument.default(fn);
517
+ }
518
+ this.addArgument(argument);
519
+ return this;
520
+ }
521
+
522
+ /**
523
+ * Define argument syntax for command, adding multiple at once (without descriptions).
524
+ *
525
+ * See also .argument().
526
+ *
527
+ * @example
528
+ * program.arguments('<cmd> [env]');
529
+ *
530
+ * @param {string} names
531
+ * @return {Command} `this` command for chaining
532
+ */
533
+
534
+ arguments(names) {
535
+ names.trim().split(/ +/).forEach((detail) => {
536
+ this.argument(detail);
537
+ });
538
+ return this;
539
+ }
540
+
541
+ /**
542
+ * Define argument syntax for command, adding a prepared argument.
543
+ *
544
+ * @param {Argument} argument
545
+ * @return {Command} `this` command for chaining
546
+ */
547
+ addArgument(argument) {
548
+ const previousArgument = this.registeredArguments.slice(-1)[0];
549
+ if (previousArgument && previousArgument.variadic) {
550
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
551
+ }
552
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
553
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
554
+ }
555
+ this.registeredArguments.push(argument);
556
+ return this;
557
+ }
558
+
559
+ /**
560
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
561
+ *
562
+ * program.helpCommand('help [cmd]');
563
+ * program.helpCommand('help [cmd]', 'show help');
564
+ * program.helpCommand(false); // suppress default help command
565
+ * program.helpCommand(true); // add help command even if no subcommands
566
+ *
567
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
568
+ * @param {string} [description] - custom description
569
+ * @return {Command} `this` command for chaining
570
+ */
571
+
572
+ helpCommand(enableOrNameAndArgs, description) {
573
+ if (typeof enableOrNameAndArgs === 'boolean') {
574
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
575
+ return this;
576
+ }
577
+
578
+ enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
579
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
580
+ const helpDescription = description ?? 'display help for command';
581
+
582
+ const helpCommand = this.createCommand(helpName);
583
+ helpCommand.helpOption(false);
584
+ if (helpArgs) helpCommand.arguments(helpArgs);
585
+ if (helpDescription) helpCommand.description(helpDescription);
586
+
587
+ this._addImplicitHelpCommand = true;
588
+ this._helpCommand = helpCommand;
589
+
590
+ return this;
591
+ }
592
+
593
+ /**
594
+ * Add prepared custom help command.
595
+ *
596
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
597
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
598
+ * @return {Command} `this` command for chaining
599
+ */
600
+ addHelpCommand(helpCommand, deprecatedDescription) {
601
+ // If not passed an object, call through to helpCommand for backwards compatibility,
602
+ // as addHelpCommand was originally used like helpCommand is now.
603
+ if (typeof helpCommand !== 'object') {
604
+ this.helpCommand(helpCommand, deprecatedDescription);
605
+ return this;
606
+ }
607
+
608
+ this._addImplicitHelpCommand = true;
609
+ this._helpCommand = helpCommand;
610
+ return this;
611
+ }
612
+
613
+ /**
614
+ * Lazy create help command.
615
+ *
616
+ * @return {(Command|null)}
617
+ * @package
618
+ */
619
+ _getHelpCommand() {
620
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ??
621
+ (this.commands.length && !this._actionHandler && !this._findCommand('help'));
622
+
623
+ if (hasImplicitHelpCommand) {
624
+ if (this._helpCommand === undefined) {
625
+ this.helpCommand(undefined, undefined); // use default name and description
626
+ }
627
+ return this._helpCommand;
628
+ }
629
+ return null;
630
+ }
631
+
632
+ /**
633
+ * Add hook for life cycle event.
634
+ *
635
+ * @param {string} event
636
+ * @param {Function} listener
637
+ * @return {Command} `this` command for chaining
638
+ */
639
+
640
+ hook(event, listener) {
641
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
642
+ if (!allowedValues.includes(event)) {
643
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
644
+ Expecting one of '${allowedValues.join("', '")}'`);
645
+ }
646
+ if (this._lifeCycleHooks[event]) {
647
+ this._lifeCycleHooks[event].push(listener);
648
+ } else {
649
+ this._lifeCycleHooks[event] = [listener];
650
+ }
651
+ return this;
652
+ }
653
+
654
+ /**
655
+ * Register callback to use as replacement for calling process.exit.
656
+ *
657
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
658
+ * @return {Command} `this` command for chaining
659
+ */
660
+
661
+ exitOverride(fn) {
662
+ if (fn) {
663
+ this._exitCallback = fn;
664
+ } else {
665
+ this._exitCallback = (err) => {
666
+ if (err.code !== 'commander.executeSubCommandAsync') {
667
+ throw err;
668
+ } else {
669
+ // Async callback from spawn events, not useful to throw.
670
+ }
671
+ };
672
+ }
673
+ return this;
674
+ }
675
+
676
+ /**
677
+ * Call process.exit, and _exitCallback if defined.
678
+ *
679
+ * @param {number} exitCode exit code for using with process.exit
680
+ * @param {string} code an id string representing the error
681
+ * @param {string} message human-readable description of the error
682
+ * @return never
683
+ * @private
684
+ */
685
+
686
+ _exit(exitCode, code, message) {
687
+ if (this._exitCallback) {
688
+ this._exitCallback(new CommanderError(exitCode, code, message));
689
+ // Expecting this line is not reached.
690
+ }
691
+ process.exit(exitCode);
692
+ }
693
+
694
+ /**
695
+ * Register callback `fn` for the command.
696
+ *
697
+ * @example
698
+ * program
699
+ * .command('serve')
700
+ * .description('start service')
701
+ * .action(function() {
702
+ * // do work here
703
+ * });
704
+ *
705
+ * @param {Function} fn
706
+ * @return {Command} `this` command for chaining
707
+ */
708
+
709
+ action(fn) {
710
+ const listener = (args) => {
711
+ // The .action callback takes an extra parameter which is the command or options.
712
+ const expectedArgsCount = this.registeredArguments.length;
713
+ const actionArgs = args.slice(0, expectedArgsCount);
714
+ if (this._storeOptionsAsProperties) {
715
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
716
+ } else {
717
+ actionArgs[expectedArgsCount] = this.opts();
718
+ }
719
+ actionArgs.push(this);
720
+
721
+ return fn.apply(this, actionArgs);
722
+ };
723
+ this._actionHandler = listener;
724
+ return this;
725
+ }
726
+
727
+ /**
728
+ * Factory routine to create a new unattached option.
729
+ *
730
+ * See .option() for creating an attached option, which uses this routine to
731
+ * create the option. You can override createOption to return a custom option.
732
+ *
733
+ * @param {string} flags
734
+ * @param {string} [description]
735
+ * @return {Option} new option
736
+ */
737
+
738
+ createOption(flags, description) {
739
+ return new Option(flags, description);
740
+ }
741
+
742
+ /**
743
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
744
+ *
745
+ * @param {(Option | Argument)} target
746
+ * @param {string} value
747
+ * @param {*} previous
748
+ * @param {string} invalidArgumentMessage
749
+ * @private
750
+ */
751
+
752
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
753
+ try {
754
+ return target.parseArg(value, previous);
755
+ } catch (err) {
756
+ if (err.code === 'commander.invalidArgument') {
757
+ const message = `${invalidArgumentMessage} ${err.message}`;
758
+ this.error(message, { exitCode: err.exitCode, code: err.code });
759
+ }
760
+ throw err;
761
+ }
762
+ }
763
+
764
+ /**
765
+ * Check for option flag conflicts.
766
+ * Register option if no conflicts found, or throw on conflict.
767
+ *
768
+ * @param {Option} option
769
+ * @api private
770
+ */
771
+
772
+ _registerOption(option) {
773
+ const matchingOption = (option.short && this._findOption(option.short)) ||
774
+ (option.long && this._findOption(option.long));
775
+ if (matchingOption) {
776
+ const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;
777
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
778
+ - already used by option '${matchingOption.flags}'`);
779
+ }
780
+
781
+ this.options.push(option);
782
+ }
783
+
784
+ /**
785
+ * Check for command name and alias conflicts with existing commands.
786
+ * Register command if no conflicts found, or throw on conflict.
787
+ *
788
+ * @param {Command} command
789
+ * @api private
790
+ */
791
+
792
+ _registerCommand(command) {
793
+ const knownBy = (cmd) => {
794
+ return [cmd.name()].concat(cmd.aliases());
795
+ };
796
+
797
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
798
+ if (alreadyUsed) {
799
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
800
+ const newCmd = knownBy(command).join('|');
801
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
802
+ }
803
+
804
+ this.commands.push(command);
805
+ }
806
+
807
+ /**
808
+ * Add an option.
809
+ *
810
+ * @param {Option} option
811
+ * @return {Command} `this` command for chaining
812
+ */
813
+ addOption(option) {
814
+ this._registerOption(option);
815
+
816
+ const oname = option.name();
817
+ const name = option.attributeName();
818
+
819
+ // store default value
820
+ if (option.negate) {
821
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
822
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
823
+ if (!this._findOption(positiveLongFlag)) {
824
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');
825
+ }
826
+ } else if (option.defaultValue !== undefined) {
827
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
828
+ }
829
+
830
+ // handler for cli and env supplied values
831
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
832
+ // val is null for optional option used without an optional-argument.
833
+ // val is undefined for boolean and negated option.
834
+ if (val == null && option.presetArg !== undefined) {
835
+ val = option.presetArg;
836
+ }
837
+
838
+ // custom processing
839
+ const oldValue = this.getOptionValue(name);
840
+ if (val !== null && option.parseArg) {
841
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
842
+ } else if (val !== null && option.variadic) {
843
+ val = option._concatValue(val, oldValue);
844
+ }
845
+
846
+ // Fill-in appropriate missing values. Long winded but easy to follow.
847
+ if (val == null) {
848
+ if (option.negate) {
849
+ val = false;
850
+ } else if (option.isBoolean() || option.optional) {
851
+ val = true;
852
+ } else {
853
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
854
+ }
855
+ }
856
+ this.setOptionValueWithSource(name, val, valueSource);
857
+ };
858
+
859
+ this.on('option:' + oname, (val) => {
860
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
861
+ handleOptionValue(val, invalidValueMessage, 'cli');
862
+ });
863
+
864
+ if (option.envVar) {
865
+ this.on('optionEnv:' + oname, (val) => {
866
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
867
+ handleOptionValue(val, invalidValueMessage, 'env');
868
+ });
869
+ }
870
+
871
+ return this;
872
+ }
873
+
874
+ /**
875
+ * Internal implementation shared by .option() and .requiredOption()
876
+ *
877
+ * @private
878
+ */
879
+ _optionEx(config, flags, description, fn, defaultValue) {
880
+ if (typeof flags === 'object' && flags instanceof Option) {
881
+ throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
882
+ }
883
+ const option = this.createOption(flags, description);
884
+ option.makeOptionMandatory(!!config.mandatory);
885
+ if (typeof fn === 'function') {
886
+ option.default(defaultValue).argParser(fn);
887
+ } else if (fn instanceof RegExp) {
888
+ // deprecated
889
+ const regex = fn;
890
+ fn = (val, def) => {
891
+ const m = regex.exec(val);
892
+ return m ? m[0] : def;
893
+ };
894
+ option.default(defaultValue).argParser(fn);
895
+ } else {
896
+ option.default(fn);
897
+ }
898
+
899
+ return this.addOption(option);
900
+ }
901
+
902
+ /**
903
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
904
+ *
905
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
906
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
907
+ *
908
+ * See the README for more details, and see also addOption() and requiredOption().
909
+ *
910
+ * @example
911
+ * program
912
+ * .option('-p, --pepper', 'add pepper')
913
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
914
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
915
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
916
+ *
917
+ * @param {string} flags
918
+ * @param {string} [description]
919
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
920
+ * @param {*} [defaultValue]
921
+ * @return {Command} `this` command for chaining
922
+ */
923
+
924
+ option(flags, description, parseArg, defaultValue) {
925
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
926
+ }
927
+
928
+ /**
929
+ * Add a required option which must have a value after parsing. This usually means
930
+ * the option must be specified on the command line. (Otherwise the same as .option().)
931
+ *
932
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
933
+ *
934
+ * @param {string} flags
935
+ * @param {string} [description]
936
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
937
+ * @param {*} [defaultValue]
938
+ * @return {Command} `this` command for chaining
939
+ */
940
+
941
+ requiredOption(flags, description, parseArg, defaultValue) {
942
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
943
+ }
944
+
945
+ /**
946
+ * Alter parsing of short flags with optional values.
947
+ *
948
+ * @example
949
+ * // for `.option('-f,--flag [value]'):
950
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
951
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
952
+ *
953
+ * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
954
+ */
955
+ combineFlagAndOptionalValue(combine = true) {
956
+ this._combineFlagAndOptionalValue = !!combine;
957
+ return this;
958
+ }
959
+
960
+ /**
961
+ * Allow unknown options on the command line.
962
+ *
963
+ * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
964
+ * for unknown options.
965
+ */
966
+ allowUnknownOption(allowUnknown = true) {
967
+ this._allowUnknownOption = !!allowUnknown;
968
+ return this;
969
+ }
970
+
971
+ /**
972
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
973
+ *
974
+ * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
975
+ * for excess arguments.
976
+ */
977
+ allowExcessArguments(allowExcess = true) {
978
+ this._allowExcessArguments = !!allowExcess;
979
+ return this;
980
+ }
981
+
982
+ /**
983
+ * Enable positional options. Positional means global options are specified before subcommands which lets
984
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
985
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
986
+ *
987
+ * @param {boolean} [positional=true]
988
+ */
989
+ enablePositionalOptions(positional = true) {
990
+ this._enablePositionalOptions = !!positional;
991
+ return this;
992
+ }
993
+
994
+ /**
995
+ * Pass through options that come after command-arguments rather than treat them as command-options,
996
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
997
+ * positional options to have been enabled on the program (parent commands).
998
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
999
+ *
1000
+ * @param {boolean} [passThrough=true]
1001
+ * for unknown options.
1002
+ */
1003
+ passThroughOptions(passThrough = true) {
1004
+ this._passThroughOptions = !!passThrough;
1005
+ this._checkForBrokenPassThrough();
1006
+ return this;
1007
+ }
1008
+
1009
+ /**
1010
+ * @private
1011
+ */
1012
+
1013
+ _checkForBrokenPassThrough() {
1014
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1015
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * Whether to store option values as properties on command object,
1021
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1022
+ *
1023
+ * @param {boolean} [storeAsProperties=true]
1024
+ * @return {Command} `this` command for chaining
1025
+ */
1026
+
1027
+ storeOptionsAsProperties(storeAsProperties = true) {
1028
+ if (this.options.length) {
1029
+ throw new Error('call .storeOptionsAsProperties() before adding options');
1030
+ }
1031
+ if (Object.keys(this._optionValues).length) {
1032
+ throw new Error('call .storeOptionsAsProperties() before setting option values');
1033
+ }
1034
+ this._storeOptionsAsProperties = !!storeAsProperties;
1035
+ return this;
1036
+ }
1037
+
1038
+ /**
1039
+ * Retrieve option value.
1040
+ *
1041
+ * @param {string} key
1042
+ * @return {Object} value
1043
+ */
1044
+
1045
+ getOptionValue(key) {
1046
+ if (this._storeOptionsAsProperties) {
1047
+ return this[key];
1048
+ }
1049
+ return this._optionValues[key];
1050
+ }
1051
+
1052
+ /**
1053
+ * Store option value.
1054
+ *
1055
+ * @param {string} key
1056
+ * @param {Object} value
1057
+ * @return {Command} `this` command for chaining
1058
+ */
1059
+
1060
+ setOptionValue(key, value) {
1061
+ return this.setOptionValueWithSource(key, value, undefined);
1062
+ }
1063
+
1064
+ /**
1065
+ * Store option value and where the value came from.
1066
+ *
1067
+ * @param {string} key
1068
+ * @param {Object} value
1069
+ * @param {string} source - expected values are default/config/env/cli/implied
1070
+ * @return {Command} `this` command for chaining
1071
+ */
1072
+
1073
+ setOptionValueWithSource(key, value, source) {
1074
+ if (this._storeOptionsAsProperties) {
1075
+ this[key] = value;
1076
+ } else {
1077
+ this._optionValues[key] = value;
1078
+ }
1079
+ this._optionValueSources[key] = source;
1080
+ return this;
1081
+ }
1082
+
1083
+ /**
1084
+ * Get source of option value.
1085
+ * Expected values are default | config | env | cli | implied
1086
+ *
1087
+ * @param {string} key
1088
+ * @return {string}
1089
+ */
1090
+
1091
+ getOptionValueSource(key) {
1092
+ return this._optionValueSources[key];
1093
+ }
1094
+
1095
+ /**
1096
+ * Get source of option value. See also .optsWithGlobals().
1097
+ * Expected values are default | config | env | cli | implied
1098
+ *
1099
+ * @param {string} key
1100
+ * @return {string}
1101
+ */
1102
+
1103
+ getOptionValueSourceWithGlobals(key) {
1104
+ // global overwrites local, like optsWithGlobals
1105
+ let source;
1106
+ this._getCommandAndAncestors().forEach((cmd) => {
1107
+ if (cmd.getOptionValueSource(key) !== undefined) {
1108
+ source = cmd.getOptionValueSource(key);
1109
+ }
1110
+ });
1111
+ return source;
1112
+ }
1113
+
1114
+ /**
1115
+ * Get user arguments from implied or explicit arguments.
1116
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1117
+ *
1118
+ * @private
1119
+ */
1120
+
1121
+ _prepareUserArgs(argv, parseOptions) {
1122
+ if (argv !== undefined && !Array.isArray(argv)) {
1123
+ throw new Error('first parameter to parse must be array or undefined');
1124
+ }
1125
+ parseOptions = parseOptions || {};
1126
+
1127
+ // Default to using process.argv
1128
+ if (argv === undefined) {
1129
+ argv = process.argv;
1130
+ // @ts-ignore: unknown property
1131
+ if (process.versions && process.versions.electron) {
1132
+ parseOptions.from = 'electron';
1133
+ }
1134
+ }
1135
+ this.rawArgs = argv.slice();
1136
+
1137
+ // make it a little easier for callers by supporting various argv conventions
1138
+ let userArgs;
1139
+ switch (parseOptions.from) {
1140
+ case undefined:
1141
+ case 'node':
1142
+ this._scriptPath = argv[1];
1143
+ userArgs = argv.slice(2);
1144
+ break;
1145
+ case 'electron':
1146
+ // @ts-ignore: unknown property
1147
+ if (process.defaultApp) {
1148
+ this._scriptPath = argv[1];
1149
+ userArgs = argv.slice(2);
1150
+ } else {
1151
+ userArgs = argv.slice(1);
1152
+ }
1153
+ break;
1154
+ case 'user':
1155
+ userArgs = argv.slice(0);
1156
+ break;
1157
+ default:
1158
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1159
+ }
1160
+
1161
+ // Find default name for program from arguments.
1162
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1163
+ this._name = this._name || 'program';
1164
+
1165
+ return userArgs;
1166
+ }
1167
+
1168
+ /**
1169
+ * Parse `argv`, setting options and invoking commands when defined.
1170
+ *
1171
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1172
+ * and the script being run in argv[1], with user parameters after that.
1173
+ *
1174
+ * @example
1175
+ * program.parse(process.argv);
1176
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1177
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1178
+ *
1179
+ * @param {string[]} [argv] - optional, defaults to process.argv
1180
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1181
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1182
+ * @return {Command} `this` command for chaining
1183
+ */
1184
+
1185
+ parse(argv, parseOptions) {
1186
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1187
+ this._parseCommand([], userArgs);
1188
+
1189
+ return this;
1190
+ }
1191
+
1192
+ /**
1193
+ * Parse `argv`, setting options and invoking commands when defined.
1194
+ *
1195
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1196
+ *
1197
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1198
+ * and the script being run in argv[1], with user parameters after that.
1199
+ *
1200
+ * @example
1201
+ * await program.parseAsync(process.argv);
1202
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1203
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1204
+ *
1205
+ * @param {string[]} [argv]
1206
+ * @param {Object} [parseOptions]
1207
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1208
+ * @return {Promise}
1209
+ */
1210
+
1211
+ async parseAsync(argv, parseOptions) {
1212
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1213
+ await this._parseCommand([], userArgs);
1214
+
1215
+ return this;
1216
+ }
1217
+
1218
+ /**
1219
+ * Execute a sub-command executable.
1220
+ *
1221
+ * @private
1222
+ */
1223
+
1224
+ _executeSubCommand(subcommand, args) {
1225
+ args = args.slice();
1226
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
1227
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1228
+
1229
+ function findFile(baseDir, baseName) {
1230
+ // Look for specified file
1231
+ const localBin = path.resolve(baseDir, baseName);
1232
+ if (fs.existsSync(localBin)) return localBin;
1233
+
1234
+ // Stop looking if candidate already has an expected extension.
1235
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
1236
+
1237
+ // Try all the extensions.
1238
+ const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));
1239
+ if (foundExt) return `${localBin}${foundExt}`;
1240
+
1241
+ return undefined;
1242
+ }
1243
+
1244
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1245
+ this._checkForMissingMandatoryOptions();
1246
+ this._checkForConflictingOptions();
1247
+
1248
+ // executableFile and executableDir might be full path, or just a name
1249
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1250
+ let executableDir = this._executableDir || '';
1251
+ if (this._scriptPath) {
1252
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1253
+ try {
1254
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1255
+ } catch (err) {
1256
+ resolvedScriptPath = this._scriptPath;
1257
+ }
1258
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1259
+ }
1260
+
1261
+ // Look for a local file in preference to a command in PATH.
1262
+ if (executableDir) {
1263
+ let localFile = findFile(executableDir, executableFile);
1264
+
1265
+ // Legacy search using prefix of script name instead of command name
1266
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1267
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1268
+ if (legacyName !== this._name) {
1269
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1270
+ }
1271
+ }
1272
+ executableFile = localFile || executableFile;
1273
+ }
1274
+
1275
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1276
+
1277
+ let proc;
1278
+ if (process.platform !== 'win32') {
1279
+ if (launchWithNode) {
1280
+ args.unshift(executableFile);
1281
+ // add executable arguments to spawn
1282
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1283
+
1284
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1285
+ } else {
1286
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1287
+ }
1288
+ } else {
1289
+ args.unshift(executableFile);
1290
+ // add executable arguments to spawn
1291
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1292
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1293
+ }
1294
+
1295
+ if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
1296
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1297
+ signals.forEach((signal) => {
1298
+ // @ts-ignore
1299
+ process.on(signal, () => {
1300
+ if (proc.killed === false && proc.exitCode === null) {
1301
+ proc.kill(signal);
1302
+ }
1303
+ });
1304
+ });
1305
+ }
1306
+
1307
+ // By default terminate process when spawned process terminates.
1308
+ const exitCallback = this._exitCallback;
1309
+ proc.on('close', (code, _signal) => {
1310
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1311
+ if (!exitCallback) {
1312
+ process.exit(code);
1313
+ } else {
1314
+ exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));
1315
+ }
1316
+ });
1317
+ proc.on('error', (err) => {
1318
+ // @ts-ignore
1319
+ if (err.code === 'ENOENT') {
1320
+ const executableDirMessage = executableDir
1321
+ ? `searched for local subcommand relative to directory '${executableDir}'`
1322
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1323
+ const executableMissing = `'${executableFile}' does not exist
1324
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1325
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1326
+ - ${executableDirMessage}`;
1327
+ throw new Error(executableMissing);
1328
+ // @ts-ignore
1329
+ } else if (err.code === 'EACCES') {
1330
+ throw new Error(`'${executableFile}' not executable`);
1331
+ }
1332
+ if (!exitCallback) {
1333
+ process.exit(1);
1334
+ } else {
1335
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
1336
+ wrappedError.nestedError = err;
1337
+ exitCallback(wrappedError);
1338
+ }
1339
+ });
1340
+
1341
+ // Store the reference to the child process
1342
+ this.runningCommand = proc;
1343
+ }
1344
+
1345
+ /**
1346
+ * @private
1347
+ */
1348
+
1349
+ _dispatchSubcommand(commandName, operands, unknown) {
1350
+ const subCommand = this._findCommand(commandName);
1351
+ if (!subCommand) this.help({ error: true });
1352
+
1353
+ let promiseChain;
1354
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');
1355
+ promiseChain = this._chainOrCall(promiseChain, () => {
1356
+ if (subCommand._executableHandler) {
1357
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1358
+ } else {
1359
+ return subCommand._parseCommand(operands, unknown);
1360
+ }
1361
+ });
1362
+ return promiseChain;
1363
+ }
1364
+
1365
+ /**
1366
+ * Invoke help directly if possible, or dispatch if necessary.
1367
+ * e.g. help foo
1368
+ *
1369
+ * @private
1370
+ */
1371
+
1372
+ _dispatchHelpCommand(subcommandName) {
1373
+ if (!subcommandName) {
1374
+ this.help();
1375
+ }
1376
+ const subCommand = this._findCommand(subcommandName);
1377
+ if (subCommand && !subCommand._executableHandler) {
1378
+ subCommand.help();
1379
+ }
1380
+
1381
+ // Fallback to parsing the help flag to invoke the help.
1382
+ return this._dispatchSubcommand(subcommandName, [], [
1383
+ this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'
1384
+ ]);
1385
+ }
1386
+
1387
+ /**
1388
+ * Check this.args against expected this.registeredArguments.
1389
+ *
1390
+ * @private
1391
+ */
1392
+
1393
+ _checkNumberOfArguments() {
1394
+ // too few
1395
+ this.registeredArguments.forEach((arg, i) => {
1396
+ if (arg.required && this.args[i] == null) {
1397
+ this.missingArgument(arg.name());
1398
+ }
1399
+ });
1400
+ // too many
1401
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1402
+ return;
1403
+ }
1404
+ if (this.args.length > this.registeredArguments.length) {
1405
+ this._excessArguments(this.args);
1406
+ }
1407
+ }
1408
+
1409
+ /**
1410
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1411
+ *
1412
+ * @private
1413
+ */
1414
+
1415
+ _processArguments() {
1416
+ const myParseArg = (argument, value, previous) => {
1417
+ // Extra processing for nice error message on parsing failure.
1418
+ let parsedValue = value;
1419
+ if (value !== null && argument.parseArg) {
1420
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1421
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1422
+ }
1423
+ return parsedValue;
1424
+ };
1425
+
1426
+ this._checkNumberOfArguments();
1427
+
1428
+ const processedArgs = [];
1429
+ this.registeredArguments.forEach((declaredArg, index) => {
1430
+ let value = declaredArg.defaultValue;
1431
+ if (declaredArg.variadic) {
1432
+ // Collect together remaining arguments for passing together as an array.
1433
+ if (index < this.args.length) {
1434
+ value = this.args.slice(index);
1435
+ if (declaredArg.parseArg) {
1436
+ value = value.reduce((processed, v) => {
1437
+ return myParseArg(declaredArg, v, processed);
1438
+ }, declaredArg.defaultValue);
1439
+ }
1440
+ } else if (value === undefined) {
1441
+ value = [];
1442
+ }
1443
+ } else if (index < this.args.length) {
1444
+ value = this.args[index];
1445
+ if (declaredArg.parseArg) {
1446
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1447
+ }
1448
+ }
1449
+ processedArgs[index] = value;
1450
+ });
1451
+ this.processedArgs = processedArgs;
1452
+ }
1453
+
1454
+ /**
1455
+ * Once we have a promise we chain, but call synchronously until then.
1456
+ *
1457
+ * @param {(Promise|undefined)} promise
1458
+ * @param {Function} fn
1459
+ * @return {(Promise|undefined)}
1460
+ * @private
1461
+ */
1462
+
1463
+ _chainOrCall(promise, fn) {
1464
+ // thenable
1465
+ if (promise && promise.then && typeof promise.then === 'function') {
1466
+ // already have a promise, chain callback
1467
+ return promise.then(() => fn());
1468
+ }
1469
+ // callback might return a promise
1470
+ return fn();
1471
+ }
1472
+
1473
+ /**
1474
+ *
1475
+ * @param {(Promise|undefined)} promise
1476
+ * @param {string} event
1477
+ * @return {(Promise|undefined)}
1478
+ * @private
1479
+ */
1480
+
1481
+ _chainOrCallHooks(promise, event) {
1482
+ let result = promise;
1483
+ const hooks = [];
1484
+ this._getCommandAndAncestors()
1485
+ .reverse()
1486
+ .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
1487
+ .forEach(hookedCommand => {
1488
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1489
+ hooks.push({ hookedCommand, callback });
1490
+ });
1491
+ });
1492
+ if (event === 'postAction') {
1493
+ hooks.reverse();
1494
+ }
1495
+
1496
+ hooks.forEach((hookDetail) => {
1497
+ result = this._chainOrCall(result, () => {
1498
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1499
+ });
1500
+ });
1501
+ return result;
1502
+ }
1503
+
1504
+ /**
1505
+ *
1506
+ * @param {(Promise|undefined)} promise
1507
+ * @param {Command} subCommand
1508
+ * @param {string} event
1509
+ * @return {(Promise|undefined)}
1510
+ * @private
1511
+ */
1512
+
1513
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1514
+ let result = promise;
1515
+ if (this._lifeCycleHooks[event] !== undefined) {
1516
+ this._lifeCycleHooks[event].forEach((hook) => {
1517
+ result = this._chainOrCall(result, () => {
1518
+ return hook(this, subCommand);
1519
+ });
1520
+ });
1521
+ }
1522
+ return result;
1523
+ }
1524
+
1525
+ /**
1526
+ * Process arguments in context of this command.
1527
+ * Returns action result, in case it is a promise.
1528
+ *
1529
+ * @private
1530
+ */
1531
+
1532
+ _parseCommand(operands, unknown) {
1533
+ const parsed = this.parseOptions(unknown);
1534
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
1535
+ this._parseOptionsImplied();
1536
+ operands = operands.concat(parsed.operands);
1537
+ unknown = parsed.unknown;
1538
+ this.args = operands.concat(unknown);
1539
+
1540
+ if (operands && this._findCommand(operands[0])) {
1541
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1542
+ }
1543
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1544
+ return this._dispatchHelpCommand(operands[1]);
1545
+ }
1546
+ if (this._defaultCommandName) {
1547
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
1548
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1549
+ }
1550
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1551
+ // probably missing subcommand and no handler, user needs help (and exit)
1552
+ this.help({ error: true });
1553
+ }
1554
+
1555
+ this._outputHelpIfRequested(parsed.unknown);
1556
+ this._checkForMissingMandatoryOptions();
1557
+ this._checkForConflictingOptions();
1558
+
1559
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1560
+ const checkForUnknownOptions = () => {
1561
+ if (parsed.unknown.length > 0) {
1562
+ this.unknownOption(parsed.unknown[0]);
1563
+ }
1564
+ };
1565
+
1566
+ const commandEvent = `command:${this.name()}`;
1567
+ if (this._actionHandler) {
1568
+ checkForUnknownOptions();
1569
+ this._processArguments();
1570
+
1571
+ let promiseChain;
1572
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
1573
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1574
+ if (this.parent) {
1575
+ promiseChain = this._chainOrCall(promiseChain, () => {
1576
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1577
+ });
1578
+ }
1579
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1580
+ return promiseChain;
1581
+ }
1582
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1583
+ checkForUnknownOptions();
1584
+ this._processArguments();
1585
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1586
+ } else if (operands.length) {
1587
+ if (this._findCommand('*')) { // legacy default command
1588
+ return this._dispatchSubcommand('*', operands, unknown);
1589
+ }
1590
+ if (this.listenerCount('command:*')) {
1591
+ // skip option check, emit event for possible misspelling suggestion
1592
+ this.emit('command:*', operands, unknown);
1593
+ } else if (this.commands.length) {
1594
+ this.unknownCommand();
1595
+ } else {
1596
+ checkForUnknownOptions();
1597
+ this._processArguments();
1598
+ }
1599
+ } else if (this.commands.length) {
1600
+ checkForUnknownOptions();
1601
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1602
+ this.help({ error: true });
1603
+ } else {
1604
+ checkForUnknownOptions();
1605
+ this._processArguments();
1606
+ // fall through for caller to handle after calling .parse()
1607
+ }
1608
+ }
1609
+
1610
+ /**
1611
+ * Find matching command.
1612
+ *
1613
+ * @private
1614
+ */
1615
+ _findCommand(name) {
1616
+ if (!name) return undefined;
1617
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
1618
+ }
1619
+
1620
+ /**
1621
+ * Return an option matching `arg` if any.
1622
+ *
1623
+ * @param {string} arg
1624
+ * @return {Option}
1625
+ * @package internal use only
1626
+ */
1627
+
1628
+ _findOption(arg) {
1629
+ return this.options.find(option => option.is(arg));
1630
+ }
1631
+
1632
+ /**
1633
+ * Display an error message if a mandatory option does not have a value.
1634
+ * Called after checking for help flags in leaf subcommand.
1635
+ *
1636
+ * @private
1637
+ */
1638
+
1639
+ _checkForMissingMandatoryOptions() {
1640
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1641
+ this._getCommandAndAncestors().forEach((cmd) => {
1642
+ cmd.options.forEach((anOption) => {
1643
+ if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
1644
+ cmd.missingMandatoryOptionValue(anOption);
1645
+ }
1646
+ });
1647
+ });
1648
+ }
1649
+
1650
+ /**
1651
+ * Display an error message if conflicting options are used together in this.
1652
+ *
1653
+ * @private
1654
+ */
1655
+ _checkForConflictingLocalOptions() {
1656
+ const definedNonDefaultOptions = this.options.filter(
1657
+ (option) => {
1658
+ const optionKey = option.attributeName();
1659
+ if (this.getOptionValue(optionKey) === undefined) {
1660
+ return false;
1661
+ }
1662
+ return this.getOptionValueSource(optionKey) !== 'default';
1663
+ }
1664
+ );
1665
+
1666
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
1667
+ (option) => option.conflictsWith.length > 0
1668
+ );
1669
+
1670
+ optionsWithConflicting.forEach((option) => {
1671
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
1672
+ option.conflictsWith.includes(defined.attributeName())
1673
+ );
1674
+ if (conflictingAndDefined) {
1675
+ this._conflictingOption(option, conflictingAndDefined);
1676
+ }
1677
+ });
1678
+ }
1679
+
1680
+ /**
1681
+ * Display an error message if conflicting options are used together.
1682
+ * Called after checking for help flags in leaf subcommand.
1683
+ *
1684
+ * @private
1685
+ */
1686
+ _checkForConflictingOptions() {
1687
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1688
+ this._getCommandAndAncestors().forEach((cmd) => {
1689
+ cmd._checkForConflictingLocalOptions();
1690
+ });
1691
+ }
1692
+
1693
+ /**
1694
+ * Parse options from `argv` removing known options,
1695
+ * and return argv split into operands and unknown arguments.
1696
+ *
1697
+ * Examples:
1698
+ *
1699
+ * argv => operands, unknown
1700
+ * --known kkk op => [op], []
1701
+ * op --known kkk => [op], []
1702
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1703
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1704
+ *
1705
+ * @param {string[]} argv
1706
+ * @return {{operands: string[], unknown: string[]}}
1707
+ */
1708
+
1709
+ parseOptions(argv) {
1710
+ const operands = []; // operands, not options or values
1711
+ const unknown = []; // first unknown option and remaining unknown args
1712
+ let dest = operands;
1713
+ const args = argv.slice();
1714
+
1715
+ function maybeOption(arg) {
1716
+ return arg.length > 1 && arg[0] === '-';
1717
+ }
1718
+
1719
+ // parse options
1720
+ let activeVariadicOption = null;
1721
+ while (args.length) {
1722
+ const arg = args.shift();
1723
+
1724
+ // literal
1725
+ if (arg === '--') {
1726
+ if (dest === unknown) dest.push(arg);
1727
+ dest.push(...args);
1728
+ break;
1729
+ }
1730
+
1731
+ if (activeVariadicOption && !maybeOption(arg)) {
1732
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1733
+ continue;
1734
+ }
1735
+ activeVariadicOption = null;
1736
+
1737
+ if (maybeOption(arg)) {
1738
+ const option = this._findOption(arg);
1739
+ // recognised option, call listener to assign value with possible custom processing
1740
+ if (option) {
1741
+ if (option.required) {
1742
+ const value = args.shift();
1743
+ if (value === undefined) this.optionMissingArgument(option);
1744
+ this.emit(`option:${option.name()}`, value);
1745
+ } else if (option.optional) {
1746
+ let value = null;
1747
+ // historical behaviour is optional value is following arg unless an option
1748
+ if (args.length > 0 && !maybeOption(args[0])) {
1749
+ value = args.shift();
1750
+ }
1751
+ this.emit(`option:${option.name()}`, value);
1752
+ } else { // boolean flag
1753
+ this.emit(`option:${option.name()}`);
1754
+ }
1755
+ activeVariadicOption = option.variadic ? option : null;
1756
+ continue;
1757
+ }
1758
+ }
1759
+
1760
+ // Look for combo options following single dash, eat first one if known.
1761
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1762
+ const option = this._findOption(`-${arg[1]}`);
1763
+ if (option) {
1764
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
1765
+ // option with value following in same argument
1766
+ this.emit(`option:${option.name()}`, arg.slice(2));
1767
+ } else {
1768
+ // boolean option, emit and put back remainder of arg for further processing
1769
+ this.emit(`option:${option.name()}`);
1770
+ args.unshift(`-${arg.slice(2)}`);
1771
+ }
1772
+ continue;
1773
+ }
1774
+ }
1775
+
1776
+ // Look for known long flag with value, like --foo=bar
1777
+ if (/^--[^=]+=/.test(arg)) {
1778
+ const index = arg.indexOf('=');
1779
+ const option = this._findOption(arg.slice(0, index));
1780
+ if (option && (option.required || option.optional)) {
1781
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1782
+ continue;
1783
+ }
1784
+ }
1785
+
1786
+ // Not a recognised option by this command.
1787
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1788
+
1789
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1790
+ if (maybeOption(arg)) {
1791
+ dest = unknown;
1792
+ }
1793
+
1794
+ // If using positionalOptions, stop processing our options at subcommand.
1795
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1796
+ if (this._findCommand(arg)) {
1797
+ operands.push(arg);
1798
+ if (args.length > 0) unknown.push(...args);
1799
+ break;
1800
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1801
+ operands.push(arg);
1802
+ if (args.length > 0) operands.push(...args);
1803
+ break;
1804
+ } else if (this._defaultCommandName) {
1805
+ unknown.push(arg);
1806
+ if (args.length > 0) unknown.push(...args);
1807
+ break;
1808
+ }
1809
+ }
1810
+
1811
+ // If using passThroughOptions, stop processing options at first command-argument.
1812
+ if (this._passThroughOptions) {
1813
+ dest.push(arg);
1814
+ if (args.length > 0) dest.push(...args);
1815
+ break;
1816
+ }
1817
+
1818
+ // add arg
1819
+ dest.push(arg);
1820
+ }
1821
+
1822
+ return { operands, unknown };
1823
+ }
1824
+
1825
+ /**
1826
+ * Return an object containing local option values as key-value pairs.
1827
+ *
1828
+ * @return {Object}
1829
+ */
1830
+ opts() {
1831
+ if (this._storeOptionsAsProperties) {
1832
+ // Preserve original behaviour so backwards compatible when still using properties
1833
+ const result = {};
1834
+ const len = this.options.length;
1835
+
1836
+ for (let i = 0; i < len; i++) {
1837
+ const key = this.options[i].attributeName();
1838
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1839
+ }
1840
+ return result;
1841
+ }
1842
+
1843
+ return this._optionValues;
1844
+ }
1845
+
1846
+ /**
1847
+ * Return an object containing merged local and global option values as key-value pairs.
1848
+ *
1849
+ * @return {Object}
1850
+ */
1851
+ optsWithGlobals() {
1852
+ // globals overwrite locals
1853
+ return this._getCommandAndAncestors().reduce(
1854
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
1855
+ {}
1856
+ );
1857
+ }
1858
+
1859
+ /**
1860
+ * Display error message and exit (or call exitOverride).
1861
+ *
1862
+ * @param {string} message
1863
+ * @param {Object} [errorOptions]
1864
+ * @param {string} [errorOptions.code] - an id string representing the error
1865
+ * @param {number} [errorOptions.exitCode] - used with process.exit
1866
+ */
1867
+ error(message, errorOptions) {
1868
+ // output handling
1869
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
1870
+ if (typeof this._showHelpAfterError === 'string') {
1871
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1872
+ } else if (this._showHelpAfterError) {
1873
+ this._outputConfiguration.writeErr('\n');
1874
+ this.outputHelp({ error: true });
1875
+ }
1876
+
1877
+ // exit handling
1878
+ const config = errorOptions || {};
1879
+ const exitCode = config.exitCode || 1;
1880
+ const code = config.code || 'commander.error';
1881
+ this._exit(exitCode, code, message);
1882
+ }
1883
+
1884
+ /**
1885
+ * Apply any option related environment variables, if option does
1886
+ * not have a value from cli or client code.
1887
+ *
1888
+ * @private
1889
+ */
1890
+ _parseOptionsEnv() {
1891
+ this.options.forEach((option) => {
1892
+ if (option.envVar && option.envVar in process.env) {
1893
+ const optionKey = option.attributeName();
1894
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
1895
+ if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {
1896
+ if (option.required || option.optional) { // option can take a value
1897
+ // keep very simple, optional always takes value
1898
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1899
+ } else { // boolean
1900
+ // keep very simple, only care that envVar defined and not the value
1901
+ this.emit(`optionEnv:${option.name()}`);
1902
+ }
1903
+ }
1904
+ }
1905
+ });
1906
+ }
1907
+
1908
+ /**
1909
+ * Apply any implied option values, if option is undefined or default value.
1910
+ *
1911
+ * @private
1912
+ */
1913
+ _parseOptionsImplied() {
1914
+ const dualHelper = new DualOptions(this.options);
1915
+ const hasCustomOptionValue = (optionKey) => {
1916
+ return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));
1917
+ };
1918
+ this.options
1919
+ .filter(option => (option.implied !== undefined) &&
1920
+ hasCustomOptionValue(option.attributeName()) &&
1921
+ dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))
1922
+ .forEach((option) => {
1923
+ Object.keys(option.implied)
1924
+ .filter(impliedKey => !hasCustomOptionValue(impliedKey))
1925
+ .forEach(impliedKey => {
1926
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');
1927
+ });
1928
+ });
1929
+ }
1930
+
1931
+ /**
1932
+ * Argument `name` is missing.
1933
+ *
1934
+ * @param {string} name
1935
+ * @private
1936
+ */
1937
+
1938
+ missingArgument(name) {
1939
+ const message = `error: missing required argument '${name}'`;
1940
+ this.error(message, { code: 'commander.missingArgument' });
1941
+ }
1942
+
1943
+ /**
1944
+ * `Option` is missing an argument.
1945
+ *
1946
+ * @param {Option} option
1947
+ * @private
1948
+ */
1949
+
1950
+ optionMissingArgument(option) {
1951
+ const message = `error: option '${option.flags}' argument missing`;
1952
+ this.error(message, { code: 'commander.optionMissingArgument' });
1953
+ }
1954
+
1955
+ /**
1956
+ * `Option` does not have a value, and is a mandatory option.
1957
+ *
1958
+ * @param {Option} option
1959
+ * @private
1960
+ */
1961
+
1962
+ missingMandatoryOptionValue(option) {
1963
+ const message = `error: required option '${option.flags}' not specified`;
1964
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
1965
+ }
1966
+
1967
+ /**
1968
+ * `Option` conflicts with another option.
1969
+ *
1970
+ * @param {Option} option
1971
+ * @param {Option} conflictingOption
1972
+ * @private
1973
+ */
1974
+ _conflictingOption(option, conflictingOption) {
1975
+ // The calling code does not know whether a negated option is the source of the
1976
+ // value, so do some work to take an educated guess.
1977
+ const findBestOptionFromValue = (option) => {
1978
+ const optionKey = option.attributeName();
1979
+ const optionValue = this.getOptionValue(optionKey);
1980
+ const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());
1981
+ const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());
1982
+ if (negativeOption && (
1983
+ (negativeOption.presetArg === undefined && optionValue === false) ||
1984
+ (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)
1985
+ )) {
1986
+ return negativeOption;
1987
+ }
1988
+ return positiveOption || option;
1989
+ };
1990
+
1991
+ const getErrorMessage = (option) => {
1992
+ const bestOption = findBestOptionFromValue(option);
1993
+ const optionKey = bestOption.attributeName();
1994
+ const source = this.getOptionValueSource(optionKey);
1995
+ if (source === 'env') {
1996
+ return `environment variable '${bestOption.envVar}'`;
1997
+ }
1998
+ return `option '${bestOption.flags}'`;
1999
+ };
2000
+
2001
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2002
+ this.error(message, { code: 'commander.conflictingOption' });
2003
+ }
2004
+
2005
+ /**
2006
+ * Unknown option `flag`.
2007
+ *
2008
+ * @param {string} flag
2009
+ * @private
2010
+ */
2011
+
2012
+ unknownOption(flag) {
2013
+ if (this._allowUnknownOption) return;
2014
+ let suggestion = '';
2015
+
2016
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2017
+ // Looping to pick up the global options too
2018
+ let candidateFlags = [];
2019
+ let command = this;
2020
+ do {
2021
+ const moreFlags = command.createHelp().visibleOptions(command)
2022
+ .filter(option => option.long)
2023
+ .map(option => option.long);
2024
+ candidateFlags = candidateFlags.concat(moreFlags);
2025
+ command = command.parent;
2026
+ } while (command && !command._enablePositionalOptions);
2027
+ suggestion = suggestSimilar(flag, candidateFlags);
2028
+ }
2029
+
2030
+ const message = `error: unknown option '${flag}'${suggestion}`;
2031
+ this.error(message, { code: 'commander.unknownOption' });
2032
+ }
2033
+
2034
+ /**
2035
+ * Excess arguments, more than expected.
2036
+ *
2037
+ * @param {string[]} receivedArgs
2038
+ * @private
2039
+ */
2040
+
2041
+ _excessArguments(receivedArgs) {
2042
+ if (this._allowExcessArguments) return;
2043
+
2044
+ const expected = this.registeredArguments.length;
2045
+ const s = (expected === 1) ? '' : 's';
2046
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2047
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2048
+ this.error(message, { code: 'commander.excessArguments' });
2049
+ }
2050
+
2051
+ /**
2052
+ * Unknown command.
2053
+ *
2054
+ * @private
2055
+ */
2056
+
2057
+ unknownCommand() {
2058
+ const unknownName = this.args[0];
2059
+ let suggestion = '';
2060
+
2061
+ if (this._showSuggestionAfterError) {
2062
+ const candidateNames = [];
2063
+ this.createHelp().visibleCommands(this).forEach((command) => {
2064
+ candidateNames.push(command.name());
2065
+ // just visible alias
2066
+ if (command.alias()) candidateNames.push(command.alias());
2067
+ });
2068
+ suggestion = suggestSimilar(unknownName, candidateNames);
2069
+ }
2070
+
2071
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2072
+ this.error(message, { code: 'commander.unknownCommand' });
2073
+ }
2074
+
2075
+ /**
2076
+ * Get or set the program version.
2077
+ *
2078
+ * This method auto-registers the "-V, --version" option which will print the version number.
2079
+ *
2080
+ * You can optionally supply the flags and description to override the defaults.
2081
+ *
2082
+ * @param {string} [str]
2083
+ * @param {string} [flags]
2084
+ * @param {string} [description]
2085
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2086
+ */
2087
+
2088
+ version(str, flags, description) {
2089
+ if (str === undefined) return this._version;
2090
+ this._version = str;
2091
+ flags = flags || '-V, --version';
2092
+ description = description || 'output the version number';
2093
+ const versionOption = this.createOption(flags, description);
2094
+ this._versionOptionName = versionOption.attributeName();
2095
+ this._registerOption(versionOption);
2096
+
2097
+ this.on('option:' + versionOption.name(), () => {
2098
+ this._outputConfiguration.writeOut(`${str}\n`);
2099
+ this._exit(0, 'commander.version', str);
2100
+ });
2101
+ return this;
2102
+ }
2103
+
2104
+ /**
2105
+ * Set the description.
2106
+ *
2107
+ * @param {string} [str]
2108
+ * @param {Object} [argsDescription]
2109
+ * @return {(string|Command)}
2110
+ */
2111
+ description(str, argsDescription) {
2112
+ if (str === undefined && argsDescription === undefined) return this._description;
2113
+ this._description = str;
2114
+ if (argsDescription) {
2115
+ this._argsDescription = argsDescription;
2116
+ }
2117
+ return this;
2118
+ }
2119
+
2120
+ /**
2121
+ * Set the summary. Used when listed as subcommand of parent.
2122
+ *
2123
+ * @param {string} [str]
2124
+ * @return {(string|Command)}
2125
+ */
2126
+ summary(str) {
2127
+ if (str === undefined) return this._summary;
2128
+ this._summary = str;
2129
+ return this;
2130
+ }
2131
+
2132
+ /**
2133
+ * Set an alias for the command.
2134
+ *
2135
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2136
+ *
2137
+ * @param {string} [alias]
2138
+ * @return {(string|Command)}
2139
+ */
2140
+
2141
+ alias(alias) {
2142
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2143
+
2144
+ /** @type {Command} */
2145
+ let command = this;
2146
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2147
+ // assume adding alias for last added executable subcommand, rather than this
2148
+ command = this.commands[this.commands.length - 1];
2149
+ }
2150
+
2151
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
2152
+ const matchingCommand = this.parent?._findCommand(alias);
2153
+ if (matchingCommand) {
2154
+ // c.f. _registerCommand
2155
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');
2156
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2157
+ }
2158
+
2159
+ command._aliases.push(alias);
2160
+ return this;
2161
+ }
2162
+
2163
+ /**
2164
+ * Set aliases for the command.
2165
+ *
2166
+ * Only the first alias is shown in the auto-generated help.
2167
+ *
2168
+ * @param {string[]} [aliases]
2169
+ * @return {(string[]|Command)}
2170
+ */
2171
+
2172
+ aliases(aliases) {
2173
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2174
+ if (aliases === undefined) return this._aliases;
2175
+
2176
+ aliases.forEach((alias) => this.alias(alias));
2177
+ return this;
2178
+ }
2179
+
2180
+ /**
2181
+ * Set / get the command usage `str`.
2182
+ *
2183
+ * @param {string} [str]
2184
+ * @return {(string|Command)}
2185
+ */
2186
+
2187
+ usage(str) {
2188
+ if (str === undefined) {
2189
+ if (this._usage) return this._usage;
2190
+
2191
+ const args = this.registeredArguments.map((arg) => {
2192
+ return humanReadableArgName(arg);
2193
+ });
2194
+ return [].concat(
2195
+ (this.options.length || (this._helpOption !== null) ? '[options]' : []),
2196
+ (this.commands.length ? '[command]' : []),
2197
+ (this.registeredArguments.length ? args : [])
2198
+ ).join(' ');
2199
+ }
2200
+
2201
+ this._usage = str;
2202
+ return this;
2203
+ }
2204
+
2205
+ /**
2206
+ * Get or set the name of the command.
2207
+ *
2208
+ * @param {string} [str]
2209
+ * @return {(string|Command)}
2210
+ */
2211
+
2212
+ name(str) {
2213
+ if (str === undefined) return this._name;
2214
+ this._name = str;
2215
+ return this;
2216
+ }
2217
+
2218
+ /**
2219
+ * Set the name of the command from script filename, such as process.argv[1],
2220
+ * or require.main.filename, or __filename.
2221
+ *
2222
+ * (Used internally and public although not documented in README.)
2223
+ *
2224
+ * @example
2225
+ * program.nameFromFilename(require.main.filename);
2226
+ *
2227
+ * @param {string} filename
2228
+ * @return {Command}
2229
+ */
2230
+
2231
+ nameFromFilename(filename) {
2232
+ this._name = path.basename(filename, path.extname(filename));
2233
+
2234
+ return this;
2235
+ }
2236
+
2237
+ /**
2238
+ * Get or set the directory for searching for executable subcommands of this command.
2239
+ *
2240
+ * @example
2241
+ * program.executableDir(__dirname);
2242
+ * // or
2243
+ * program.executableDir('subcommands');
2244
+ *
2245
+ * @param {string} [path]
2246
+ * @return {(string|null|Command)}
2247
+ */
2248
+
2249
+ executableDir(path) {
2250
+ if (path === undefined) return this._executableDir;
2251
+ this._executableDir = path;
2252
+ return this;
2253
+ }
2254
+
2255
+ /**
2256
+ * Return program help documentation.
2257
+ *
2258
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2259
+ * @return {string}
2260
+ */
2261
+
2262
+ helpInformation(contextOptions) {
2263
+ const helper = this.createHelp();
2264
+ if (helper.helpWidth === undefined) {
2265
+ helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2266
+ }
2267
+ return helper.formatHelp(this, helper);
2268
+ }
2269
+
2270
+ /**
2271
+ * @private
2272
+ */
2273
+
2274
+ _getHelpContext(contextOptions) {
2275
+ contextOptions = contextOptions || {};
2276
+ const context = { error: !!contextOptions.error };
2277
+ let write;
2278
+ if (context.error) {
2279
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2280
+ } else {
2281
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2282
+ }
2283
+ context.write = contextOptions.write || write;
2284
+ context.command = this;
2285
+ return context;
2286
+ }
2287
+
2288
+ /**
2289
+ * Output help information for this command.
2290
+ *
2291
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2292
+ *
2293
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2294
+ */
2295
+
2296
+ outputHelp(contextOptions) {
2297
+ let deprecatedCallback;
2298
+ if (typeof contextOptions === 'function') {
2299
+ deprecatedCallback = contextOptions;
2300
+ contextOptions = undefined;
2301
+ }
2302
+ const context = this._getHelpContext(contextOptions);
2303
+
2304
+ this._getCommandAndAncestors().reverse().forEach(command => command.emit('beforeAllHelp', context));
2305
+ this.emit('beforeHelp', context);
2306
+
2307
+ let helpInformation = this.helpInformation(context);
2308
+ if (deprecatedCallback) {
2309
+ helpInformation = deprecatedCallback(helpInformation);
2310
+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
2311
+ throw new Error('outputHelp callback must return a string or a Buffer');
2312
+ }
2313
+ }
2314
+ context.write(helpInformation);
2315
+
2316
+ if (this._getHelpOption()?.long) {
2317
+ this.emit(this._getHelpOption().long); // deprecated
2318
+ }
2319
+ this.emit('afterHelp', context);
2320
+ this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));
2321
+ }
2322
+
2323
+ /**
2324
+ * You can pass in flags and a description to customise the built-in help option.
2325
+ * Pass in false to disable the built-in help option.
2326
+ *
2327
+ * @example
2328
+ * program.helpOption('-?, --help' 'show help'); // customise
2329
+ * program.helpOption(false); // disable
2330
+ *
2331
+ * @param {(string | boolean)} flags
2332
+ * @param {string} [description]
2333
+ * @return {Command} `this` command for chaining
2334
+ */
2335
+
2336
+ helpOption(flags, description) {
2337
+ // Support disabling built-in help option.
2338
+ if (typeof flags === 'boolean') {
2339
+ if (flags) {
2340
+ this._helpOption = this._helpOption ?? undefined; // preserve existing option
2341
+ } else {
2342
+ this._helpOption = null; // disable
2343
+ }
2344
+ return this;
2345
+ }
2346
+
2347
+ // Customise flags and description.
2348
+ flags = flags ?? '-h, --help';
2349
+ description = description ?? 'display help for command';
2350
+ this._helpOption = this.createOption(flags, description);
2351
+
2352
+ return this;
2353
+ }
2354
+
2355
+ /**
2356
+ * Lazy create help option.
2357
+ * Returns null if has been disabled with .helpOption(false).
2358
+ *
2359
+ * @returns {(Option | null)} the help option
2360
+ * @package internal use only
2361
+ */
2362
+ _getHelpOption() {
2363
+ // Lazy create help option on demand.
2364
+ if (this._helpOption === undefined) {
2365
+ this.helpOption(undefined, undefined);
2366
+ }
2367
+ return this._helpOption;
2368
+ }
2369
+
2370
+ /**
2371
+ * Supply your own option to use for the built-in help option.
2372
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2373
+ *
2374
+ * @param {Option} option
2375
+ * @return {Command} `this` command for chaining
2376
+ */
2377
+ addHelpOption(option) {
2378
+ this._helpOption = option;
2379
+ return this;
2380
+ }
2381
+
2382
+ /**
2383
+ * Output help information and exit.
2384
+ *
2385
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2386
+ *
2387
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2388
+ */
2389
+
2390
+ help(contextOptions) {
2391
+ this.outputHelp(contextOptions);
2392
+ let exitCode = process.exitCode || 0;
2393
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
2394
+ exitCode = 1;
2395
+ }
2396
+ // message: do not have all displayed text available so only passing placeholder.
2397
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2398
+ }
2399
+
2400
+ /**
2401
+ * Add additional text to be displayed with the built-in help.
2402
+ *
2403
+ * Position is 'before' or 'after' to affect just this command,
2404
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2405
+ *
2406
+ * @param {string} position - before or after built-in help
2407
+ * @param {(string | Function)} text - string to add, or a function returning a string
2408
+ * @return {Command} `this` command for chaining
2409
+ */
2410
+ addHelpText(position, text) {
2411
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2412
+ if (!allowedValues.includes(position)) {
2413
+ throw new Error(`Unexpected value for position to addHelpText.
2414
+ Expecting one of '${allowedValues.join("', '")}'`);
2415
+ }
2416
+ const helpEvent = `${position}Help`;
2417
+ this.on(helpEvent, (context) => {
2418
+ let helpStr;
2419
+ if (typeof text === 'function') {
2420
+ helpStr = text({ error: context.error, command: context.command });
2421
+ } else {
2422
+ helpStr = text;
2423
+ }
2424
+ // Ignore falsy value when nothing to output.
2425
+ if (helpStr) {
2426
+ context.write(`${helpStr}\n`);
2427
+ }
2428
+ });
2429
+ return this;
2430
+ }
2431
+
2432
+ /**
2433
+ * Output help information if help flags specified
2434
+ *
2435
+ * @param {Array} args - array of options to search for help flags
2436
+ * @private
2437
+ */
2438
+
2439
+ _outputHelpIfRequested(args) {
2440
+ const helpOption = this._getHelpOption();
2441
+ const helpRequested = helpOption && args.find(arg => helpOption.is(arg));
2442
+ if (helpRequested) {
2443
+ this.outputHelp();
2444
+ // (Do not have all displayed text available so only passing placeholder.)
2445
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2446
+ }
2447
+ }
2448
+ }
2449
+
2450
+ /**
2451
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2452
+ *
2453
+ * @param {string[]} args - array of arguments from node.execArgv
2454
+ * @returns {string[]}
2455
+ * @private
2456
+ */
2457
+
2458
+ function incrementNodeInspectorPort(args) {
2459
+ // Testing for these options:
2460
+ // --inspect[=[host:]port]
2461
+ // --inspect-brk[=[host:]port]
2462
+ // --inspect-port=[host:]port
2463
+ return args.map((arg) => {
2464
+ if (!arg.startsWith('--inspect')) {
2465
+ return arg;
2466
+ }
2467
+ let debugOption;
2468
+ let debugHost = '127.0.0.1';
2469
+ let debugPort = '9229';
2470
+ let match;
2471
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2472
+ // e.g. --inspect
2473
+ debugOption = match[1];
2474
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2475
+ debugOption = match[1];
2476
+ if (/^\d+$/.test(match[3])) {
2477
+ // e.g. --inspect=1234
2478
+ debugPort = match[3];
2479
+ } else {
2480
+ // e.g. --inspect=localhost
2481
+ debugHost = match[3];
2482
+ }
2483
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2484
+ // e.g. --inspect=localhost:1234
2485
+ debugOption = match[1];
2486
+ debugHost = match[3];
2487
+ debugPort = match[4];
2488
+ }
2489
+
2490
+ if (debugOption && debugPort !== '0') {
2491
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2492
+ }
2493
+ return arg;
2494
+ });
2495
+ }
2496
+
2497
+ exports.Command = Command;
2498
+
2499
+
2500
+ /***/ }),
2501
+
2502
+ /***/ 422:
2503
+ /***/ ((__unused_webpack_module, exports) => {
2504
+
2505
+ /**
2506
+ * CommanderError class
2507
+ * @class
2508
+ */
2509
+ class CommanderError extends Error {
2510
+ /**
2511
+ * Constructs the CommanderError class
2512
+ * @param {number} exitCode suggested exit code which could be used with process.exit
2513
+ * @param {string} code an id string representing the error
2514
+ * @param {string} message human-readable description of the error
2515
+ * @constructor
2516
+ */
2517
+ constructor(exitCode, code, message) {
2518
+ super(message);
2519
+ // properly capture stack trace in Node.js
2520
+ Error.captureStackTrace(this, this.constructor);
2521
+ this.name = this.constructor.name;
2522
+ this.code = code;
2523
+ this.exitCode = exitCode;
2524
+ this.nestedError = undefined;
2525
+ }
2526
+ }
2527
+
2528
+ /**
2529
+ * InvalidArgumentError class
2530
+ * @class
2531
+ */
2532
+ class InvalidArgumentError extends CommanderError {
2533
+ /**
2534
+ * Constructs the InvalidArgumentError class
2535
+ * @param {string} [message] explanation of why argument is invalid
2536
+ * @constructor
2537
+ */
2538
+ constructor(message) {
2539
+ super(1, 'commander.invalidArgument', message);
2540
+ // properly capture stack trace in Node.js
2541
+ Error.captureStackTrace(this, this.constructor);
2542
+ this.name = this.constructor.name;
2543
+ }
2544
+ }
2545
+
2546
+ exports.CommanderError = CommanderError;
2547
+ exports.InvalidArgumentError = InvalidArgumentError;
2548
+
2549
+
2550
+ /***/ }),
2551
+
2552
+ /***/ 455:
2553
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
2554
+
2555
+ const { humanReadableArgName } = __nccwpck_require__(975);
2556
+
2557
+ /**
2558
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
2559
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
2560
+ * @typedef { import("./argument.js").Argument } Argument
2561
+ * @typedef { import("./command.js").Command } Command
2562
+ * @typedef { import("./option.js").Option } Option
2563
+ */
2564
+
2565
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
2566
+ class Help {
2567
+ constructor() {
2568
+ this.helpWidth = undefined;
2569
+ this.sortSubcommands = false;
2570
+ this.sortOptions = false;
2571
+ this.showGlobalOptions = false;
2572
+ }
2573
+
2574
+ /**
2575
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
2576
+ *
2577
+ * @param {Command} cmd
2578
+ * @returns {Command[]}
2579
+ */
2580
+
2581
+ visibleCommands(cmd) {
2582
+ const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);
2583
+ const helpCommand = cmd._getHelpCommand();
2584
+ if (helpCommand && !helpCommand._hidden) {
2585
+ visibleCommands.push(helpCommand);
2586
+ }
2587
+ if (this.sortSubcommands) {
2588
+ visibleCommands.sort((a, b) => {
2589
+ // @ts-ignore: overloaded return type
2590
+ return a.name().localeCompare(b.name());
2591
+ });
2592
+ }
2593
+ return visibleCommands;
2594
+ }
2595
+
2596
+ /**
2597
+ * Compare options for sort.
2598
+ *
2599
+ * @param {Option} a
2600
+ * @param {Option} b
2601
+ * @returns number
2602
+ */
2603
+ compareOptions(a, b) {
2604
+ const getSortKey = (option) => {
2605
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
2606
+ return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');
2607
+ };
2608
+ return getSortKey(a).localeCompare(getSortKey(b));
2609
+ }
2610
+
2611
+ /**
2612
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
2613
+ *
2614
+ * @param {Command} cmd
2615
+ * @returns {Option[]}
2616
+ */
2617
+
2618
+ visibleOptions(cmd) {
2619
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
2620
+ // Built-in help option.
2621
+ const helpOption = cmd._getHelpOption();
2622
+ if (helpOption && !helpOption.hidden) {
2623
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
2624
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
2625
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
2626
+ if (!removeShort && !removeLong) {
2627
+ visibleOptions.push(helpOption); // no changes needed
2628
+ } else if (helpOption.long && !removeLong) {
2629
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
2630
+ } else if (helpOption.short && !removeShort) {
2631
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
2632
+ }
2633
+ }
2634
+ if (this.sortOptions) {
2635
+ visibleOptions.sort(this.compareOptions);
2636
+ }
2637
+ return visibleOptions;
2638
+ }
2639
+
2640
+ /**
2641
+ * Get an array of the visible global options. (Not including help.)
2642
+ *
2643
+ * @param {Command} cmd
2644
+ * @returns {Option[]}
2645
+ */
2646
+
2647
+ visibleGlobalOptions(cmd) {
2648
+ if (!this.showGlobalOptions) return [];
2649
+
2650
+ const globalOptions = [];
2651
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
2652
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
2653
+ globalOptions.push(...visibleOptions);
2654
+ }
2655
+ if (this.sortOptions) {
2656
+ globalOptions.sort(this.compareOptions);
2657
+ }
2658
+ return globalOptions;
2659
+ }
2660
+
2661
+ /**
2662
+ * Get an array of the arguments if any have a description.
2663
+ *
2664
+ * @param {Command} cmd
2665
+ * @returns {Argument[]}
2666
+ */
2667
+
2668
+ visibleArguments(cmd) {
2669
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
2670
+ if (cmd._argsDescription) {
2671
+ cmd.registeredArguments.forEach(argument => {
2672
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || '';
2673
+ });
2674
+ }
2675
+
2676
+ // If there are any arguments with a description then return all the arguments.
2677
+ if (cmd.registeredArguments.find(argument => argument.description)) {
2678
+ return cmd.registeredArguments;
2679
+ }
2680
+ return [];
2681
+ }
2682
+
2683
+ /**
2684
+ * Get the command term to show in the list of subcommands.
2685
+ *
2686
+ * @param {Command} cmd
2687
+ * @returns {string}
2688
+ */
2689
+
2690
+ subcommandTerm(cmd) {
2691
+ // Legacy. Ignores custom usage string, and nested commands.
2692
+ const args = cmd.registeredArguments.map(arg => humanReadableArgName(arg)).join(' ');
2693
+ return cmd._name +
2694
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
2695
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
2696
+ (args ? ' ' + args : '');
2697
+ }
2698
+
2699
+ /**
2700
+ * Get the option term to show in the list of options.
2701
+ *
2702
+ * @param {Option} option
2703
+ * @returns {string}
2704
+ */
2705
+
2706
+ optionTerm(option) {
2707
+ return option.flags;
2708
+ }
2709
+
2710
+ /**
2711
+ * Get the argument term to show in the list of arguments.
2712
+ *
2713
+ * @param {Argument} argument
2714
+ * @returns {string}
2715
+ */
2716
+
2717
+ argumentTerm(argument) {
2718
+ return argument.name();
2719
+ }
2720
+
2721
+ /**
2722
+ * Get the longest command term length.
2723
+ *
2724
+ * @param {Command} cmd
2725
+ * @param {Help} helper
2726
+ * @returns {number}
2727
+ */
2728
+
2729
+ longestSubcommandTermLength(cmd, helper) {
2730
+ return helper.visibleCommands(cmd).reduce((max, command) => {
2731
+ return Math.max(max, helper.subcommandTerm(command).length);
2732
+ }, 0);
2733
+ }
2734
+
2735
+ /**
2736
+ * Get the longest option term length.
2737
+ *
2738
+ * @param {Command} cmd
2739
+ * @param {Help} helper
2740
+ * @returns {number}
2741
+ */
2742
+
2743
+ longestOptionTermLength(cmd, helper) {
2744
+ return helper.visibleOptions(cmd).reduce((max, option) => {
2745
+ return Math.max(max, helper.optionTerm(option).length);
2746
+ }, 0);
2747
+ }
2748
+
2749
+ /**
2750
+ * Get the longest global option term length.
2751
+ *
2752
+ * @param {Command} cmd
2753
+ * @param {Help} helper
2754
+ * @returns {number}
2755
+ */
2756
+
2757
+ longestGlobalOptionTermLength(cmd, helper) {
2758
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
2759
+ return Math.max(max, helper.optionTerm(option).length);
2760
+ }, 0);
2761
+ }
2762
+
2763
+ /**
2764
+ * Get the longest argument term length.
2765
+ *
2766
+ * @param {Command} cmd
2767
+ * @param {Help} helper
2768
+ * @returns {number}
2769
+ */
2770
+
2771
+ longestArgumentTermLength(cmd, helper) {
2772
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
2773
+ return Math.max(max, helper.argumentTerm(argument).length);
2774
+ }, 0);
2775
+ }
2776
+
2777
+ /**
2778
+ * Get the command usage to be displayed at the top of the built-in help.
2779
+ *
2780
+ * @param {Command} cmd
2781
+ * @returns {string}
2782
+ */
2783
+
2784
+ commandUsage(cmd) {
2785
+ // Usage
2786
+ let cmdName = cmd._name;
2787
+ if (cmd._aliases[0]) {
2788
+ cmdName = cmdName + '|' + cmd._aliases[0];
2789
+ }
2790
+ let ancestorCmdNames = '';
2791
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
2792
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
2793
+ }
2794
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
2795
+ }
2796
+
2797
+ /**
2798
+ * Get the description for the command.
2799
+ *
2800
+ * @param {Command} cmd
2801
+ * @returns {string}
2802
+ */
2803
+
2804
+ commandDescription(cmd) {
2805
+ // @ts-ignore: overloaded return type
2806
+ return cmd.description();
2807
+ }
2808
+
2809
+ /**
2810
+ * Get the subcommand summary to show in the list of subcommands.
2811
+ * (Fallback to description for backwards compatibility.)
2812
+ *
2813
+ * @param {Command} cmd
2814
+ * @returns {string}
2815
+ */
2816
+
2817
+ subcommandDescription(cmd) {
2818
+ // @ts-ignore: overloaded return type
2819
+ return cmd.summary() || cmd.description();
2820
+ }
2821
+
2822
+ /**
2823
+ * Get the option description to show in the list of options.
2824
+ *
2825
+ * @param {Option} option
2826
+ * @return {string}
2827
+ */
2828
+
2829
+ optionDescription(option) {
2830
+ const extraInfo = [];
2831
+
2832
+ if (option.argChoices) {
2833
+ extraInfo.push(
2834
+ // use stringify to match the display of the default value
2835
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
2836
+ }
2837
+ if (option.defaultValue !== undefined) {
2838
+ // default for boolean and negated more for programmer than end user,
2839
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
2840
+ const showDefault = option.required || option.optional ||
2841
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
2842
+ if (showDefault) {
2843
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
2844
+ }
2845
+ }
2846
+ // preset for boolean and negated are more for programmer than end user
2847
+ if (option.presetArg !== undefined && option.optional) {
2848
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
2849
+ }
2850
+ if (option.envVar !== undefined) {
2851
+ extraInfo.push(`env: ${option.envVar}`);
2852
+ }
2853
+ if (extraInfo.length > 0) {
2854
+ return `${option.description} (${extraInfo.join(', ')})`;
2855
+ }
2856
+
2857
+ return option.description;
2858
+ }
2859
+
2860
+ /**
2861
+ * Get the argument description to show in the list of arguments.
2862
+ *
2863
+ * @param {Argument} argument
2864
+ * @return {string}
2865
+ */
2866
+
2867
+ argumentDescription(argument) {
2868
+ const extraInfo = [];
2869
+ if (argument.argChoices) {
2870
+ extraInfo.push(
2871
+ // use stringify to match the display of the default value
2872
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
2873
+ }
2874
+ if (argument.defaultValue !== undefined) {
2875
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
2876
+ }
2877
+ if (extraInfo.length > 0) {
2878
+ const extraDescripton = `(${extraInfo.join(', ')})`;
2879
+ if (argument.description) {
2880
+ return `${argument.description} ${extraDescripton}`;
2881
+ }
2882
+ return extraDescripton;
2883
+ }
2884
+ return argument.description;
2885
+ }
2886
+
2887
+ /**
2888
+ * Generate the built-in help text.
2889
+ *
2890
+ * @param {Command} cmd
2891
+ * @param {Help} helper
2892
+ * @returns {string}
2893
+ */
2894
+
2895
+ formatHelp(cmd, helper) {
2896
+ const termWidth = helper.padWidth(cmd, helper);
2897
+ const helpWidth = helper.helpWidth || 80;
2898
+ const itemIndentWidth = 2;
2899
+ const itemSeparatorWidth = 2; // between term and description
2900
+ function formatItem(term, description) {
2901
+ if (description) {
2902
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
2903
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
2904
+ }
2905
+ return term;
2906
+ }
2907
+ function formatList(textArray) {
2908
+ return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
2909
+ }
2910
+
2911
+ // Usage
2912
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
2913
+
2914
+ // Description
2915
+ const commandDescription = helper.commandDescription(cmd);
2916
+ if (commandDescription.length > 0) {
2917
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);
2918
+ }
2919
+
2920
+ // Arguments
2921
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
2922
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
2923
+ });
2924
+ if (argumentList.length > 0) {
2925
+ output = output.concat(['Arguments:', formatList(argumentList), '']);
2926
+ }
2927
+
2928
+ // Options
2929
+ const optionList = helper.visibleOptions(cmd).map((option) => {
2930
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
2931
+ });
2932
+ if (optionList.length > 0) {
2933
+ output = output.concat(['Options:', formatList(optionList), '']);
2934
+ }
2935
+
2936
+ if (this.showGlobalOptions) {
2937
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
2938
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
2939
+ });
2940
+ if (globalOptionList.length > 0) {
2941
+ output = output.concat(['Global Options:', formatList(globalOptionList), '']);
2942
+ }
2943
+ }
2944
+
2945
+ // Commands
2946
+ const commandList = helper.visibleCommands(cmd).map((cmd) => {
2947
+ return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
2948
+ });
2949
+ if (commandList.length > 0) {
2950
+ output = output.concat(['Commands:', formatList(commandList), '']);
2951
+ }
2952
+
2953
+ return output.join('\n');
2954
+ }
2955
+
2956
+ /**
2957
+ * Calculate the pad width from the maximum term length.
2958
+ *
2959
+ * @param {Command} cmd
2960
+ * @param {Help} helper
2961
+ * @returns {number}
2962
+ */
2963
+
2964
+ padWidth(cmd, helper) {
2965
+ return Math.max(
2966
+ helper.longestOptionTermLength(cmd, helper),
2967
+ helper.longestGlobalOptionTermLength(cmd, helper),
2968
+ helper.longestSubcommandTermLength(cmd, helper),
2969
+ helper.longestArgumentTermLength(cmd, helper)
2970
+ );
2971
+ }
2972
+
2973
+ /**
2974
+ * Wrap the given string to width characters per line, with lines after the first indented.
2975
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
2976
+ *
2977
+ * @param {string} str
2978
+ * @param {number} width
2979
+ * @param {number} indent
2980
+ * @param {number} [minColumnWidth=40]
2981
+ * @return {string}
2982
+ *
2983
+ */
2984
+
2985
+ wrap(str, width, indent, minColumnWidth = 40) {
2986
+ // Full \s characters, minus the linefeeds.
2987
+ const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
2988
+ // Detect manually wrapped and indented strings by searching for line break followed by spaces.
2989
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
2990
+ if (str.match(manualIndent)) return str;
2991
+ // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
2992
+ const columnWidth = width - indent;
2993
+ if (columnWidth < minColumnWidth) return str;
2994
+
2995
+ const leadingStr = str.slice(0, indent);
2996
+ const columnText = str.slice(indent).replace('\r\n', '\n');
2997
+ const indentString = ' '.repeat(indent);
2998
+ const zeroWidthSpace = '\u200B';
2999
+ const breaks = `\\s${zeroWidthSpace}`;
3000
+ // Match line end (so empty lines don't collapse),
3001
+ // or as much text as will fit in column, or excess text up to first break.
3002
+ const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');
3003
+ const lines = columnText.match(regex) || [];
3004
+ return leadingStr + lines.map((line, i) => {
3005
+ if (line === '\n') return ''; // preserve empty lines
3006
+ return ((i > 0) ? indentString : '') + line.trimEnd();
3007
+ }).join('\n');
3008
+ }
3009
+ }
3010
+
3011
+ exports.Help = Help;
3012
+
3013
+
3014
+ /***/ }),
3015
+
3016
+ /***/ 985:
3017
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
3018
+
3019
+ const { InvalidArgumentError } = __nccwpck_require__(422);
3020
+
3021
+ class Option {
3022
+ /**
3023
+ * Initialize a new `Option` with the given `flags` and `description`.
3024
+ *
3025
+ * @param {string} flags
3026
+ * @param {string} [description]
3027
+ */
3028
+
3029
+ constructor(flags, description) {
3030
+ this.flags = flags;
3031
+ this.description = description || '';
3032
+
3033
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
3034
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
3035
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
3036
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
3037
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
3038
+ const optionFlags = splitOptionFlags(flags);
3039
+ this.short = optionFlags.shortFlag;
3040
+ this.long = optionFlags.longFlag;
3041
+ this.negate = false;
3042
+ if (this.long) {
3043
+ this.negate = this.long.startsWith('--no-');
3044
+ }
3045
+ this.defaultValue = undefined;
3046
+ this.defaultValueDescription = undefined;
3047
+ this.presetArg = undefined;
3048
+ this.envVar = undefined;
3049
+ this.parseArg = undefined;
3050
+ this.hidden = false;
3051
+ this.argChoices = undefined;
3052
+ this.conflictsWith = [];
3053
+ this.implied = undefined;
3054
+ }
3055
+
3056
+ /**
3057
+ * Set the default value, and optionally supply the description to be displayed in the help.
3058
+ *
3059
+ * @param {*} value
3060
+ * @param {string} [description]
3061
+ * @return {Option}
3062
+ */
3063
+
3064
+ default(value, description) {
3065
+ this.defaultValue = value;
3066
+ this.defaultValueDescription = description;
3067
+ return this;
3068
+ }
3069
+
3070
+ /**
3071
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
3072
+ * The custom processing (parseArg) is called.
3073
+ *
3074
+ * @example
3075
+ * new Option('--color').default('GREYSCALE').preset('RGB');
3076
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
3077
+ *
3078
+ * @param {*} arg
3079
+ * @return {Option}
3080
+ */
3081
+
3082
+ preset(arg) {
3083
+ this.presetArg = arg;
3084
+ return this;
3085
+ }
3086
+
3087
+ /**
3088
+ * Add option name(s) that conflict with this option.
3089
+ * An error will be displayed if conflicting options are found during parsing.
3090
+ *
3091
+ * @example
3092
+ * new Option('--rgb').conflicts('cmyk');
3093
+ * new Option('--js').conflicts(['ts', 'jsx']);
3094
+ *
3095
+ * @param {(string | string[])} names
3096
+ * @return {Option}
3097
+ */
3098
+
3099
+ conflicts(names) {
3100
+ this.conflictsWith = this.conflictsWith.concat(names);
3101
+ return this;
3102
+ }
3103
+
3104
+ /**
3105
+ * Specify implied option values for when this option is set and the implied options are not.
3106
+ *
3107
+ * The custom processing (parseArg) is not called on the implied values.
3108
+ *
3109
+ * @example
3110
+ * program
3111
+ * .addOption(new Option('--log', 'write logging information to file'))
3112
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
3113
+ *
3114
+ * @param {Object} impliedOptionValues
3115
+ * @return {Option}
3116
+ */
3117
+ implies(impliedOptionValues) {
3118
+ let newImplied = impliedOptionValues;
3119
+ if (typeof impliedOptionValues === 'string') {
3120
+ // string is not documented, but easy mistake and we can do what user probably intended.
3121
+ newImplied = { [impliedOptionValues]: true };
3122
+ }
3123
+ this.implied = Object.assign(this.implied || {}, newImplied);
3124
+ return this;
3125
+ }
3126
+
3127
+ /**
3128
+ * Set environment variable to check for option value.
3129
+ *
3130
+ * An environment variable is only used if when processed the current option value is
3131
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
3132
+ *
3133
+ * @param {string} name
3134
+ * @return {Option}
3135
+ */
3136
+
3137
+ env(name) {
3138
+ this.envVar = name;
3139
+ return this;
3140
+ }
3141
+
3142
+ /**
3143
+ * Set the custom handler for processing CLI option arguments into option values.
3144
+ *
3145
+ * @param {Function} [fn]
3146
+ * @return {Option}
3147
+ */
3148
+
3149
+ argParser(fn) {
3150
+ this.parseArg = fn;
3151
+ return this;
3152
+ }
3153
+
3154
+ /**
3155
+ * Whether the option is mandatory and must have a value after parsing.
3156
+ *
3157
+ * @param {boolean} [mandatory=true]
3158
+ * @return {Option}
3159
+ */
3160
+
3161
+ makeOptionMandatory(mandatory = true) {
3162
+ this.mandatory = !!mandatory;
3163
+ return this;
3164
+ }
3165
+
3166
+ /**
3167
+ * Hide option in help.
3168
+ *
3169
+ * @param {boolean} [hide=true]
3170
+ * @return {Option}
3171
+ */
3172
+
3173
+ hideHelp(hide = true) {
3174
+ this.hidden = !!hide;
3175
+ return this;
3176
+ }
3177
+
3178
+ /**
3179
+ * @package internal use only
3180
+ */
3181
+
3182
+ _concatValue(value, previous) {
3183
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
3184
+ return [value];
3185
+ }
3186
+
3187
+ return previous.concat(value);
3188
+ }
3189
+
3190
+ /**
3191
+ * Only allow option value to be one of choices.
3192
+ *
3193
+ * @param {string[]} values
3194
+ * @return {Option}
3195
+ */
3196
+
3197
+ choices(values) {
3198
+ this.argChoices = values.slice();
3199
+ this.parseArg = (arg, previous) => {
3200
+ if (!this.argChoices.includes(arg)) {
3201
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
3202
+ }
3203
+ if (this.variadic) {
3204
+ return this._concatValue(arg, previous);
3205
+ }
3206
+ return arg;
3207
+ };
3208
+ return this;
3209
+ }
3210
+
3211
+ /**
3212
+ * Return option name.
3213
+ *
3214
+ * @return {string}
3215
+ */
3216
+
3217
+ name() {
3218
+ if (this.long) {
3219
+ return this.long.replace(/^--/, '');
3220
+ }
3221
+ return this.short.replace(/^-/, '');
3222
+ }
3223
+
3224
+ /**
3225
+ * Return option name, in a camelcase format that can be used
3226
+ * as a object attribute key.
3227
+ *
3228
+ * @return {string}
3229
+ */
3230
+
3231
+ attributeName() {
3232
+ return camelcase(this.name().replace(/^no-/, ''));
3233
+ }
3234
+
3235
+ /**
3236
+ * Check if `arg` matches the short or long flag.
3237
+ *
3238
+ * @param {string} arg
3239
+ * @return {boolean}
3240
+ * @package internal use only
3241
+ */
3242
+
3243
+ is(arg) {
3244
+ return this.short === arg || this.long === arg;
3245
+ }
3246
+
3247
+ /**
3248
+ * Return whether a boolean option.
3249
+ *
3250
+ * Options are one of boolean, negated, required argument, or optional argument.
3251
+ *
3252
+ * @return {boolean}
3253
+ * @package internal use only
3254
+ */
3255
+
3256
+ isBoolean() {
3257
+ return !this.required && !this.optional && !this.negate;
3258
+ }
3259
+ }
3260
+
3261
+ /**
3262
+ * This class is to make it easier to work with dual options, without changing the existing
3263
+ * implementation. We support separate dual options for separate positive and negative options,
3264
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
3265
+ * use cases, but is tricky for others where we want separate behaviours despite
3266
+ * the single shared option value.
3267
+ */
3268
+ class DualOptions {
3269
+ /**
3270
+ * @param {Option[]} options
3271
+ */
3272
+ constructor(options) {
3273
+ this.positiveOptions = new Map();
3274
+ this.negativeOptions = new Map();
3275
+ this.dualOptions = new Set();
3276
+ options.forEach(option => {
3277
+ if (option.negate) {
3278
+ this.negativeOptions.set(option.attributeName(), option);
3279
+ } else {
3280
+ this.positiveOptions.set(option.attributeName(), option);
3281
+ }
3282
+ });
3283
+ this.negativeOptions.forEach((value, key) => {
3284
+ if (this.positiveOptions.has(key)) {
3285
+ this.dualOptions.add(key);
3286
+ }
3287
+ });
3288
+ }
3289
+
3290
+ /**
3291
+ * Did the value come from the option, and not from possible matching dual option?
3292
+ *
3293
+ * @param {*} value
3294
+ * @param {Option} option
3295
+ * @returns {boolean}
3296
+ */
3297
+ valueFromOption(value, option) {
3298
+ const optionKey = option.attributeName();
3299
+ if (!this.dualOptions.has(optionKey)) return true;
3300
+
3301
+ // Use the value to deduce if (probably) came from the option.
3302
+ const preset = this.negativeOptions.get(optionKey).presetArg;
3303
+ const negativeValue = (preset !== undefined) ? preset : false;
3304
+ return option.negate === (negativeValue === value);
3305
+ }
3306
+ }
3307
+
3308
+ /**
3309
+ * Convert string from kebab-case to camelCase.
3310
+ *
3311
+ * @param {string} str
3312
+ * @return {string}
3313
+ * @private
3314
+ */
3315
+
3316
+ function camelcase(str) {
3317
+ return str.split('-').reduce((str, word) => {
3318
+ return str + word[0].toUpperCase() + word.slice(1);
3319
+ });
3320
+ }
3321
+
3322
+ /**
3323
+ * Split the short and long flag out of something like '-m,--mixed <value>'
3324
+ *
3325
+ * @private
3326
+ */
3327
+
3328
+ function splitOptionFlags(flags) {
3329
+ let shortFlag;
3330
+ let longFlag;
3331
+ // Use original very loose parsing to maintain backwards compatibility for now,
3332
+ // which allowed for example unintended `-sw, --short-word` [sic].
3333
+ const flagParts = flags.split(/[ |,]+/);
3334
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
3335
+ longFlag = flagParts.shift();
3336
+ // Add support for lone short flag without significantly changing parsing!
3337
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
3338
+ shortFlag = longFlag;
3339
+ longFlag = undefined;
3340
+ }
3341
+ return { shortFlag, longFlag };
3342
+ }
3343
+
3344
+ exports.Option = Option;
3345
+ exports.DualOptions = DualOptions;
3346
+
3347
+
3348
+ /***/ }),
3349
+
3350
+ /***/ 745:
3351
+ /***/ ((__unused_webpack_module, exports) => {
3352
+
3353
+ const maxDistance = 3;
3354
+
3355
+ function editDistance(a, b) {
3356
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
3357
+ // Calculating optimal string alignment distance, no substring is edited more than once.
3358
+ // (Simple implementation.)
3359
+
3360
+ // Quick early exit, return worst case.
3361
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
3362
+
3363
+ // distance between prefix substrings of a and b
3364
+ const d = [];
3365
+
3366
+ // pure deletions turn a into empty string
3367
+ for (let i = 0; i <= a.length; i++) {
3368
+ d[i] = [i];
3369
+ }
3370
+ // pure insertions turn empty string into b
3371
+ for (let j = 0; j <= b.length; j++) {
3372
+ d[0][j] = j;
3373
+ }
3374
+
3375
+ // fill matrix
3376
+ for (let j = 1; j <= b.length; j++) {
3377
+ for (let i = 1; i <= a.length; i++) {
3378
+ let cost = 1;
3379
+ if (a[i - 1] === b[j - 1]) {
3380
+ cost = 0;
3381
+ } else {
3382
+ cost = 1;
3383
+ }
3384
+ d[i][j] = Math.min(
3385
+ d[i - 1][j] + 1, // deletion
3386
+ d[i][j - 1] + 1, // insertion
3387
+ d[i - 1][j - 1] + cost // substitution
3388
+ );
3389
+ // transposition
3390
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
3391
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
3392
+ }
3393
+ }
3394
+ }
3395
+
3396
+ return d[a.length][b.length];
3397
+ }
3398
+
3399
+ /**
3400
+ * Find close matches, restricted to same number of edits.
3401
+ *
3402
+ * @param {string} word
3403
+ * @param {string[]} candidates
3404
+ * @returns {string}
3405
+ */
3406
+
3407
+ function suggestSimilar(word, candidates) {
3408
+ if (!candidates || candidates.length === 0) return '';
3409
+ // remove possible duplicates
3410
+ candidates = Array.from(new Set(candidates));
3411
+
3412
+ const searchingOptions = word.startsWith('--');
3413
+ if (searchingOptions) {
3414
+ word = word.slice(2);
3415
+ candidates = candidates.map(candidate => candidate.slice(2));
3416
+ }
3417
+
3418
+ let similar = [];
3419
+ let bestDistance = maxDistance;
3420
+ const minSimilarity = 0.4;
3421
+ candidates.forEach((candidate) => {
3422
+ if (candidate.length <= 1) return; // no one character guesses
3423
+
3424
+ const distance = editDistance(word, candidate);
3425
+ const length = Math.max(word.length, candidate.length);
3426
+ const similarity = (length - distance) / length;
3427
+ if (similarity > minSimilarity) {
3428
+ if (distance < bestDistance) {
3429
+ // better edit distance, throw away previous worse matches
3430
+ bestDistance = distance;
3431
+ similar = [candidate];
3432
+ } else if (distance === bestDistance) {
3433
+ similar.push(candidate);
3434
+ }
3435
+ }
3436
+ });
3437
+
3438
+ similar.sort((a, b) => a.localeCompare(b));
3439
+ if (searchingOptions) {
3440
+ similar = similar.map(candidate => `--${candidate}`);
3441
+ }
3442
+
3443
+ if (similar.length > 1) {
3444
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
3445
+ }
3446
+ if (similar.length === 1) {
3447
+ return `\n(Did you mean ${similar[0]}?)`;
3448
+ }
3449
+ return '';
3450
+ }
3451
+
3452
+ exports.suggestSimilar = suggestSimilar;
3453
+
3454
+
3455
+ /***/ })
3456
+
3457
+ /******/ });
3458
+ /************************************************************************/
3459
+ /******/ // The module cache
3460
+ /******/ var __webpack_module_cache__ = {};
3461
+ /******/
3462
+ /******/ // The require function
3463
+ /******/ function __nccwpck_require__(moduleId) {
3464
+ /******/ // Check if module is in cache
3465
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
3466
+ /******/ if (cachedModule !== undefined) {
3467
+ /******/ return cachedModule.exports;
3468
+ /******/ }
3469
+ /******/ // Create a new module (and put it into the cache)
3470
+ /******/ var module = __webpack_module_cache__[moduleId] = {
3471
+ /******/ // no module.id needed
3472
+ /******/ // no module.loaded needed
3473
+ /******/ exports: {}
3474
+ /******/ };
3475
+ /******/
3476
+ /******/ // Execute the module function
3477
+ /******/ var threw = true;
3478
+ /******/ try {
3479
+ /******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
3480
+ /******/ threw = false;
3481
+ /******/ } finally {
3482
+ /******/ if(threw) delete __webpack_module_cache__[moduleId];
3483
+ /******/ }
3484
+ /******/
3485
+ /******/ // Return the exports of the module
3486
+ /******/ return module.exports;
3487
+ /******/ }
3488
+ /******/
3489
+ /************************************************************************/
3490
+ /******/ /* webpack/runtime/compat */
3491
+ /******/
3492
+ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
3493
+ /******/
3494
+ /************************************************************************/
3495
+ var __webpack_exports__ = {};
3496
+ // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
3497
+ (() => {
3498
+ var exports = __webpack_exports__;
3499
+ const { Argument } = __nccwpck_require__(975);
3500
+ const { Command } = __nccwpck_require__(965);
3501
+ const { CommanderError, InvalidArgumentError } = __nccwpck_require__(422);
3502
+ const { Help } = __nccwpck_require__(455);
3503
+ const { Option } = __nccwpck_require__(985);
3504
+
3505
+ exports.program = new Command();
3506
+
3507
+ exports.createCommand = (name) => new Command(name);
3508
+ exports.createOption = (flags, description) => new Option(flags, description);
3509
+ exports.createArgument = (name, description) => new Argument(name, description);
3510
+
3511
+ /**
3512
+ * Expose classes
3513
+ */
3514
+
3515
+ exports.Command = Command;
3516
+ exports.Option = Option;
3517
+ exports.Argument = Argument;
3518
+ exports.Help = Help;
3519
+
3520
+ exports.CommanderError = CommanderError;
3521
+ exports.InvalidArgumentError = InvalidArgumentError;
3522
+ exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
3523
+
3524
+ })();
3525
+
3526
+ module.exports = __webpack_exports__;
3527
+ /******/ })()
3528
+ ;