gant-core 2.0.2 → 2.0.4

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