@caporal/core
Version:
A full-featured framework for building command line applications (cli) with node.js
2 lines • 32.6 kB
JavaScript
module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=29)}([function(t,e){t.exports=require("chalk")},function(t,e){t.exports=require("path")},function(t,e){t.exports=require("util")},function(t,e){t.exports=require("lodash/filter")},function(t,e){t.exports=require("lodash/flatMap")},function(t,e){t.exports=require("lodash/reduce")},function(t,e){t.exports=require("winston")},function(t,e){t.exports=require("os")},function(t,e){t.exports=require("lodash/map")},function(t,e){t.exports=require("tabtab")},function(t,e){t.exports=require("fs")},function(t,e){t.exports=require("lodash/kebabCase")},function(t,e){t.exports=require("lodash/replace")},function(t,e){t.exports=require("lodash/invert")},function(t,e){t.exports=require("lodash/zipObject")},function(t,e){t.exports=require("table")},function(t,e){t.exports=require("events")},function(t,e){t.exports=require("lodash/mapKeys")},function(t,e){t.exports=require("lodash/camelCase")},function(t,e){t.exports=require("lodash/isNumber")},function(t,e){t.exports=require("lodash/sortBy")},function(t,e){t.exports=require("lodash/findIndex")},function(t,e){t.exports=require("lodash/fp/filter")},function(t,e){t.exports=require("lodash/fp/map")},function(t,e){t.exports=require("wrap-ansi")},function(t,e){t.exports=require("lodash/pickBy")},function(t,e){t.exports=require("glob")},function(t,e,r){"use strict";(function(t){r.d(e,"a",(function(){return i}));var n=r(1),o=r.n(n);function i(){try{return r(28)(o.a.join(t,"..","..","..","package.json")).version}catch(t){}}}).call(this,"/index.js")},function(t,e){function r(t){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}r.keys=function(){return[]},r.resolve=r,t.exports=r,r.id=28},function(t,e,r){"use strict";r.r(e),r.d(e,"Command",(function(){return Se})),r.d(e,"CaporalValidator",(function(){return $})),r.d(e,"OptionValueType",(function(){return M})),r.d(e,"chalk",(function(){return w.a})),r.d(e,"parseArgv",(function(){return Rt})),r.d(e,"parseLine",(function(){return Bt})),r.d(e,"program",(function(){return De})),r.d(e,"Program",(function(){return Te}));var n={};r.r(n),r.d(n,"command",(function(){return lt})),r.d(n,"header",(function(){return dt})),r.d(n,"program",(function(){return ht})),r.d(n,"usage",(function(){return pt})),r.d(n,"custom",(function(){return mt}));var o=r(16),i=r(10),s=r.n(i),a=r(1),c=r.n(a),u=r(11),l=r.n(u),d=r(17),h=r.n(d),p=r(5),m=r.n(p);class f extends Error{constructor(t,e={}){var r,n,o;super(t),o=void 0,(n="meta")in(r=this)?Object.defineProperty(r,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[n]=o,Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name,this.meta=e,Error.captureStackTrace(this,this.constructor)}}class g extends f{constructor(t){super("string"==typeof t?t:t.message,{error:t})}}var v=r(6),y=r(2),b=r(0),w=r.n(b),O=r(12),C=r.n(O),A=r(7);const x=v.format.printf(t=>{const{level:e,...r}=t;let{message:n}=t,o="";const i=function(t){if(!_.colorsEnabled)return t;let e=t;switch(t){case"error":e=w.a.bold.redBright(t);break;case"warn":e=w.a.hex("#FF9900")(t);break;case"info":e=w.a.hex("#569cd6")(t);break;case"debug":case"silly":e=w.a.dim(t)}return e}(e),s=function(t){if(delete t.message,delete t[Symbol.for("level")],delete t[Symbol.for("message")],delete t[Symbol.for("splat")],Object.keys(t).length)return Object(y.inspect)(t,{showHidden:!1,colors:_.colorsEnabled});return""}(r);if(""!==s&&(n+=`${A.EOL}${i}: ${s}`),"error"===e){const t=" ".repeat(r.paddingLeft||7);o=A.EOL,n=`${C()(n,new RegExp(A.EOL,"g"),A.EOL+t)}${A.EOL}`}return`${o}${i}: ${n}`});let _=function(){const t=Object(v.createLogger)({transports:[new v.transports.Console({format:v.format.combine(v.format.splat(),x)})]});return t.disableColors=()=>{t.transports[0].format=x,t.colorsEnabled=!1},t.colorsEnabled=!1!==b.supportsColor,t}();function N(t){"debug"==_.level?_.log({level:"error",...t,message:t.message+"\n\n"+t.stack,stack:t.stack,name:t.name}):_.error(t.message),process.exitCode=1}class E extends f{constructor(t){super("Caporal setup error: Invalid flag validator setup.",{validator:t})}}class j extends f{constructor(t,e){super(`Missing required argument ${w.a.bold(t.name)}.`,{argument:t,command:e})}}class P extends f{constructor(t,e){super(`Missing required flag ${w.a.bold(t.allNotations.join(" | "))}.`,{flag:t,command:e})}}function B(t){return t.replace(/<([^>]+)>/gi,t=>w.a.hex("#569cd6")(t)).replace(/<command>/gi,t=>w.a.keyword("orange")(t)).replace(/\[([^[\]]+)\]/gi,t=>w.a.hex("#aaa")(t)).replace(/ --?([^\s,]+)/gi,t=>w.a.green(t))}class k extends f{constructor(t,e){super(`The following error${e.length>1?"s":""} occured:\n`+e.map(t=>"- "+t.message.replace(/\n/g,"\n ")).join("\n")+"\n\n"+w.a.dim("Synopsis: ")+B(t.synopsis),{errors:e})}}class q extends f{constructor(t){let e;e=t&&!t.isProgramCommand()?`Caporal Error: You haven't defined any action for command '${t.name}'.\nUse .action() to do so.`:"Caporal Error: You haven't defined any action for program.\nUse .action() to do so.",super(e,{cmd:t})}}class S extends f{constructor(t){super("Syntax error in option synopsis: "+t,{synopsis:t})}}var R=r(18),L=r.n(R);let $,M;!function(t){t[t.NUMBER=1]="NUMBER",t[t.BOOLEAN=2]="BOOLEAN",t[t.STRING=4]="STRING",t[t.ARRAY=8]="ARRAY"}($||($={})),function(t){t[t.Optional=0]="Optional",t[t.Required=1]="Required",t[t.None=2]="None"}(M||(M={}));const I=/^-[a-z]$/i,H=/^--[a-z]{2,}/i,T=/^(-[a-zA-Z]|--\D{1}[\w-]+)/;function D(t){return 1===t.length?t:L()(t)}function U(t,e=!0){return t=t.replace(/([[\]<>]+)/g,"").replace("...","").replace(/^no-/,""),e?D(t):t}function V(t){const e=Math.min(t.length,2);return"-".repeat(e)+l()(t)}function G(t){return!isNaN(parseFloat(t))&&isFinite(Number(t))}function z(t){return void 0!==t&&"--"!==t&&T.test(t)}function F(t){return D(t.replace(/^--?(no-)?/,""))}function J(t){const e={variadic:!1,valueType:M.None,valueRequired:!1,allNames:[],allNotations:[],name:"",notation:"",synopsis:t},r=t.split(/[\s\t,]+/).reduce((t,e)=>{var r;return r=e,H.test(r)?(t.longNotation=e,t.longName=U(e.substring(2)),t.allNames.push(t.longName),t.allNotations.push(e)):!function(t){return I.test(t)}(e)?"["===e.substring(0,1)?(t.valueType=M.Optional,t.valueRequired=!1,t.variadic="..."===e.substr(-4,3)):"<"===e.substring(0,1)&&(t.valueType=M.Required,t.valueRequired=!0,t.variadic="..."===e.substr(-4,3)):(t.shortNotation=e,t.shortName=e.substring(1),t.allNames.push(t.shortName),t.allNotations.push(e)),t},e);if(void 0===r.longName&&void 0===r.shortName)throw new S(t);return r.name=r.longName||r.shortName,r.notation=r.longNotation||r.shortNotation,{...r}}var Y=r(19),W=r.n(Y);function K(t){if("number"!=typeof t)return!1;return(Object.values($).filter(W.a).reduce((t,e)=>t|e,0)&t)===t}function Q(t){return K(t)&&Boolean(t&$.NUMBER)}function Z(t){return K(t)&&Boolean(t&$.STRING)}function X(t){return K(t)&&Boolean(t&$.BOOLEAN)}function tt(t){void 0!==t&&("number"==typeof t?function(t){if(!K(t))throw new E(t)}(t):function(t){if(!("function"==typeof t||t instanceof RegExp||Array.isArray(t)))throw new E(t)}(t))}function et(t){let e;if(X(t.validator)||"boolean"in t&&t.boolean&&!1!==t.default)e="boolean";else if(Q(t.validator))e="number";else if(Array.isArray(t.validator)){const r=JSON.stringify(t.validator);r.length<300&&(e="one of "+r.substr(1,r.length-2))}return e}var rt=r(15),nt=r(3),ot=r.n(nt);function it(t,e={}){return Object(rt.table)(t,{border:Object(rt.getBorderCharacters)("void"),columnDefault:{paddingLeft:0,paddingRight:2},columns:{0:{paddingLeft:4,width:35},1:{width:55,wrapWord:!0,paddingRight:0}},drawHorizontalLine:()=>!1,...e})}function st(t){return void 0===t.default||"boolean"in t&&t.boolean&&!1===t.default?void 0:"default: "+JSON.stringify(t.default)}function at(t,e,r="OPTIONS"){if(!(t=ot()(t,"visible")).length)return"";const{chalk:n,eol:o,table:i,spaces:s}=e;return s+n.bold(r)+o+o+i(t.map(t=>{const r=st(t),i=[t.typeHint,r].filter(t=>t).join(", ");return[function(t,{eol:e,chalk:r}){return t.synopsis+(t.required&&void 0===t.default?e+r.dim("required"):"")}(t,e),t.description+(i.length?o+n.dim(i):"")]}))}var ct=r(20),ut=r.n(ct);const lt=async t=>{const{cmd:e,globalOptions:r,eol:n,eol3:o,colorize:i,tpl:s}=t,a=ut()(e.options,"name"),c=Array.from(r.keys());return i(e.synopsis+o+await s("custom",t)+function(t,e,r="ARGUMENTS"){if(!t.length)return"";const{chalk:n,eol:o,eol2:i,table:s,spaces:a}=e;return a+n.bold(r)+i+s(t.map(t=>{const e=st(t),r=[t.typeHint,e].filter(t=>t).join(", "),i=t.description+(r.length?o+n.dim(r):"");return[t.synopsis,i]}))}(e.args,t)+n+at(a,t)+n+at(c,t,"GLOBAL OPTIONS"))},dt=t=>{var e;const{prog:r,chalk:n,spaces:o,eol:i,eol2:s}=t,a="test"===(null===(e=process.env)||void 0===e?void 0:"production")?"":r.getVersion();return i+o+(r.getName()||r.getBin())+" "+(a||"")+(r.getDescription()?" — "+n.dim(r.getDescription()):"")+s},ht=async t=>{const{prog:e,globalOptions:r,eol:n,eol3:o,colorize:i,tpl:s}=t,a=await e.getAllCommands(),c=Array.from(r.keys());return i(await e.getSynopsis()+o+await s("custom",t)+function(t,e,r="COMMANDS"){const{chalk:n,prog:o,eol2:i,table:s,spaces:a}=e,c=`Type '${o.getBin()} help <command>' to get some help about a command`;return a+n.bold(r)+` ${n.dim("—")} `+n.dim(c)+i+s(t.filter(t=>t.visible).map(t=>[n.keyword("orange")(t.name),t.description||""]))}(a,t)+n+at(c,t,"GLOBAL OPTIONS"))},pt=async t=>{var e;const{tpl:r,prog:n,chalk:o,spaces:i,eol:s}=t;let{cmd:a}=t;return a||await n.hasCommands()||(t.cmd=a=n.progCommand),`${i+o.bold("USAGE")} ${(null===(e=a)||void 0===e?void 0:e.name)?"— "+o.dim(a.name):""}\n ${s+i+i+o.dim("▸")} `+(a?await r("command",t):await r("program",t))},mt=t=>{const{prog:e,cmd:r,eol2:n,eol3:o,chalk:i,colorize:s,customHelp:a,indent:c}=t,u=a.get(r||e);if(u){const t=u.map(({text:t,options:e})=>{let r="";e.sectionName&&(r+=i.bold(e.sectionName)+n);const a=e.colorize?s(t):t;return r+=e.sectionName?c(a):a,r+o}).join("");return c(t)+o}return""},ft=new Map(Object.entries(n)),gt=new Map;function vt(t,e,r){const n={sectionName:"",colorize:!0,...r},o=gt.get(t)||[];o.push({text:e,options:n}),gt.set(t,o)}async function yt(t,e){const r=ft.get(t);if(!r)throw Error(`Caporal setup error: Unknown help template '${t}'`);return r(e)}async function bt(t,e){const r=function(t,e){const r=" ".repeat(2);return{prog:t,cmd:e,chalk:w.a,colorize:B,customHelp:gt,tpl:yt,globalOptions:Zt(),table:it,spaces:r,indent:(t,e=r)=>e+C()(t.trim(),/(\r\n|\r|\n)/g,"\n"+e),eol:"\n",eol2:"\n\n",eol3:"\n\n\n"}}(t,e);return[await yt("header",r),await yt("usage",r)].join("")}var wt=r(9),Ot=r.n(wt),Ct=r(13),At=r.n(Ct),xt=r(21),_t=r.n(xt);function Nt(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Et(t){return"--"===t}function jt(t){return/^true|false$/.test(t)?"true"===t:G(t)?parseFloat(t):t}function Pt(t,e,r){const n=F(t);return r.string.includes(n)?function(t){return t+""}(e):r.boolean.includes(n)||"boolean"==typeof e?"boolean"==typeof(o=e)?o:/^true|1|yes|on$/.test(o):r.autoCast?jt(e):e;var o}function Bt(t,e={}){return Rt(e,t.split(" "))}class kt{constructor(t){this.argv=t,Nt(this,"cursor",void 0),Nt(this,"ddashHandled",!1),this.cursor=0}toJSON(){return{cursor:this.cursor,ddashHandled:this.ddashHandled,current:this.current,argv:this.argv}}markDdashHandled(){return this.ddashHandled=!0,this}hasDdashHandled(){return this.ddashHandled}next(){return this.argv[this.cursor+1]}slice(t,e){return this.argv.slice(t,e)}sliceFromHere(t){return this.slice(this.cursor,t)}forward(t=1){return-1===t?this.end():(this.cursor+=t,!0)}end(){return this.cursor=this.length,!0}get current(){return this.argv[this.cursor]}get length(){return this.argv.length}}class qt{constructor(t,e){this.config=t,Nt(this,"args",[]),Nt(this,"ddash",[]),Nt(this,"rawArgv",void 0),Nt(this,"line",void 0),Nt(this,"variadicId",void 0),Nt(this,"key","args"),this.line=e.join(" "),this.rawArgv=e}toJSON(){return{args:this.args,ddash:this.ddash,rawArgv:this.rawArgv,line:this.line}}inVariadicContext(){const t=this[this.key].length;if(this.config.variadic.includes(t)&&(this.variadicId=t),void 0!==this.variadicId)return!0}markDdashHandled(t){return this.config.ddash&&(this.key="ddash"),t.markDdashHandled().forward()}push(...t){return this[this.key].push(...t.map(this.config.autoCast?jt:String)),!0}pushVariadic(t){const e=t.sliceFromHere(),r=function(t){const e=t.indexOf("--"),r=_t()(t,z);return e<r&&-1!==e?-1:r}(e);return this.variadicId=this.variadicId||0,(this[this.key][this.variadicId]=this[this.key][this.variadicId]||[]).push(...e.slice(0,-1===r?void 0:r).filter(t=>!Et(t)).map(this.config.autoCast?jt:String)),t.forward(r)}visit(t){return!(!t.current||z(t.current)&&!t.hasDdashHandled())&&(Et(t.current)?this.markDdashHandled(t):this.inVariadicContext()?this.pushVariadic(t):(this.push(t.current),t.forward()))}}class St{constructor(t){this.config=t,Nt(this,"options",{}),Nt(this,"rawOptions",{})}toJSON(){return{options:this.options,rawOptions:this.rawOptions}}handleOptWithoutValue(t,e){const r=e.next(),n=z(r)||Et(r)||void 0===r;this.compute(t,Pt(t,!!n||r,this.config)),n||e.forward()}handleConcatenatedOpts(t,e,r){if(void 0===r){r=!0;const n=t.next(),o=e[e.length-1],i=this.config.alias[o];n&&!z(n)&&!Et(n)&&!this.isBoolean(o,i)&&(t.forward(),r=n)}this.computeMulti(e,r)}visit(t){if(!t.current||!z(t.current)||t.hasDdashHandled())return!1;const[e,r]=t.current.split("=",2),n=!!(o=e).match(/^-([a-z]{2,})/i)&&o.substr(1).split("");var o;return n?this.handleConcatenatedOpts(t,n,r):r?this.compute(e,Pt(e,r,this.config)):this.handleOptWithoutValue(e,t),t.forward()}compute(t,e){const r="--no-"===t.substr(0,5);const n=F(t),o=this.config.alias[n];if(this.isVariadic(n,o)){const r=this.options[n];this.rawOptions[t]=this.options[n]=(i=r,Array.isArray(i)?r:[r]).concat(e)}else this.rawOptions[t]=this.options[n]=r?!e:e;var i;o&&(this.options[o]=this.options[n])}computeMulti(t,e){const r=t.length;t.forEach((t,n)=>{const o=this.config.alias[t];this.options[t]=n+1!==r||Pt(t,e,this.config),this.rawOptions["-"+t]=this.options[t],o&&(this.options[o]=this.options[t])})}isVariadic(t,e){return t in this.options&&(this.config.variadic.includes(t)||this.config.variadic.includes(e))}isBoolean(t,e){return this.config.boolean.includes(t)||this.config.boolean.includes(e)}}function Rt(t={},e=process.argv.slice(2)){const r={autoCast:!0,ddash:!1,alias:{},boolean:[],string:[],variadic:[],...t};r.alias={...r.alias,...At()(r.alias)};const n=new kt(e),o=new St(r),i=new qt(r,e),s=[i,o];for(;n.current;)s.some(t=>t.visit(n));return{...o.toJSON(),...i.toJSON()}}const Lt=require;async function $t(t){var e;const{dir:r,name:n}=c.a.parse(t),o=c.a.join(r,n),i=Lt(o);return null!==(e=i.default)&&void 0!==e?e:i}async function Mt(t,e){const r=t.getCommands(),n=t=>r.find(e=>e.name===t||e.hasAlias(t));let o,i;for(i=0;i<e.length;i++){const r=e.slice(0,i+1).join(" ");if(e[i].startsWith("-"))break;o=n(r)||await It(t,r)||o}return o}async function It(t,e){if(void 0===t.discoveryPath)return;const r=e.split(" ").join("/");try{const n=c.a.join(t.discoveryPath,r);return(await $t(n))({createCommand:Re.bind(null,t,e),program:t})}catch(t){}}var Ht=r(4),Tt=r.n(Ht);const Dt=new Map;function Ut(t,e,r={}){let{validator:n,required:o,hidden:i}=r;o=Boolean(o),tt(n);const s=J(t);let a=s.valueType===M.None||X(n);n&&!X(n)&&(a=!1);const c={kind:"option",default:1==a?Boolean(r.default):r.default,description:e,choices:Array.isArray(n)?n:[],...s,required:o,visible:!i,boolean:a,validator:n};return c.typeHint=et(c),c}const Vt=async({program:t,command:e})=>{const r=await bt(t,e);return console.log(r),t.emit("help",r),!1},Gt=({program:t})=>(console.log(t.getVersion()),t.emit("version",t.getVersion()),!1),zt=({logger:t})=>{t.disableColors()},Ft=({logger:t})=>{t.level="silly"},Jt=({logger:t})=>{t.level="warn"},Yt=({logger:t})=>{t.silent=!0},Wt=({program:t})=>async function(t){return Ot.a.install({name:t.getBin(),completer:t.getBin()})}(t),Kt=({program:t})=>async function(t){return Ot.a.uninstall({name:t.getBin()})}(t);let Qt;function Zt(){return void 0===Qt&&(Qt=Xt()),Qt}function Xt(){const t=Ut("-h, --help","Display global help or command-related help."),e=Ut("-v, --verbose","Verbose mode: will also output debug messages."),r=Ut("--quiet","Quiet mode - only displays warn and error messages."),n=Ut("--silent","Silent mode: does not output anything, giving no indication of success or failure other than the exit code."),o=Ut("-V, --version","Display version."),i=Ut("--no-color","Disable use of colors in output."),s=Ut("--install-completion","Install completion for your shell.",{hidden:!0}),a=Ut("--uninstall-completion","Uninstall completion for your shell.",{hidden:!0});return new Map([[t,Vt],[o,Gt],[i,zt],[e,Ft],[r,Jt],[n,Yt],[s,Wt],[a,Kt]])}async function te(t,e,r){const{options:n}=t,o={...t,logger:_,program:e,command:r},i=Object.entries(n).map(([t])=>{const e=function(t){for(const[e,r]of Zt())if(e.allNames.includes(t))return r}(t);if(e)return e(o)});return(await Promise.all(i)).some(t=>!1===t)}function ee(t,e){if(t===e)return 0;if(!t.length||!e.length)return t.length||e.length;let r=0,n=0,o=0;const i=[...Array(e.length+1).keys()];for(let s=0;s<t.length;s++){o=s,n=s+1;for(let a=0;a<e.length;a++)r=t[s]===e[a]?o:Math.min(o,i[a+1],n)+1,o=i[a+1],i[a]=n,n=r;i[i.length-1]=r}return r}const re=(t,e)=>t.distance-e.distance,ne=t=>t.distance<=2;function oe(t,e){return e.map(e=>((t,e)=>({suggestion:e,distance:ee(t,e)}))(t,e)).filter(ne).sort(re).map(t=>t.suggestion)}function ie(t,e){return[...e].map((e,r)=>e!=t.charAt(r)?w.a.bold.greenBright(e):e).join("")}var se=r(22),ae=r.n(se),ce=r(23),ue=r.n(ce);class le extends f{constructor(t,e){const r=ae()(t=>t.name.length>1),n=ue()(t=>t.name)([...r(e.options),...Zt().keys()]),o=oe(t,n);let i=`Unknown option ${w.a.bold.redBright(V(t))}. `;o.length&&(i+="Did you mean "+o.map(e=>ie(V(t),V(e))).join(" or maybe ")+" ?"),super(i,{flag:t,command:e})}}var de=r(24),he=r.n(de);class pe extends f{constructor(t,e){const r=ot()(Tt()(t.getCommands(),t=>[t.name,...t.getAliases()]));let n="";if(e){n=`Unknown command ${w.a.bold(e)}.`;const t=oe(e,r);t.length&&(n+=" Did you mean "+t.map(t=>ie(e,t)).join(" or maybe ")+" ?")}else n="Unspecified command. Available commands are:\n"+he()(r.map(t=>w.a.whiteBright(t)).join(", "),60)+".\n\nFor more help, type "+w.a.whiteBright(t.getBin()+" --help");super(n,{command:e})}}function me(t){return"allNotations"in t}class fe extends f{constructor({value:t,error:e,validator:r,context:n}){let o=e instanceof Error?e.message:e;const i=me(n)?"option":"argument",s=me(n)?n.allNotations.join("|"):n.synopsis;if(K(r))switch(r){case $.NUMBER:o=Object(y.format)('Invalid value for %s %s.\nExpected a %s but got "%s".',i,w.a.redBright(s),w.a.underline("number"),w.a.redBright(t));break;case $.BOOLEAN:o=Object(y.format)('Invalid value for %s %s.\nExpected a %s (true, false, 0, 1), but got "%s".',i,w.a.redBright(s),w.a.underline("boolean"),w.a.redBright(t));break;case $.STRING:o=Object(y.format)('Invalid value for %s %s.\nExpected a %s, but got "%s".',i,w.a.redBright(s),w.a.underline("string"),w.a.redBright(t))}else Array.isArray(r)?o=Object(y.format)('Invalid value for %s %s.\nExpected one of %s, but got "%s".',i,w.a.redBright(s),"'"+r.join("', '")+"'",w.a.redBright(t)):r instanceof RegExp&&(o=Object(y.format)('Invalid value for %s %s.\nExpected a value matching %s, but got "%s".',i,w.a.redBright(s),w.a.whiteBright(r.toString()),w.a.redBright(t)));super(o+"")}}class ge extends f{constructor(t,e,r){const n=e.min===e.max?`exactly ${e.min}.`:`between ${e.min} and ${e.max}.`,o=t.isProgramCommand()?"":"for command "+w.a.bold(t.name);super(Object(y.format)("Too many argument(s) %s. Got %s, expected %s",o,w.a.bold.redBright(r),w.a.bold.greenBright(n)),{command:t})}}function ve(t,e,r,n=!1){if(!n&&function(t){return K(t)&&Boolean(t&$.ARRAY)}(t))return function(t,e,r){const n="string"==typeof e?e.split(","):Array.isArray(e)?e:[e];return Tt()(n,e=>ve(t,e,r,!0))}(t,e,r);if(Array.isArray(e))throw new fe({error:"Expected a scalar value, got an array",value:e,validator:t,context:r});return Q(t)?function(t,e,r){const n=e+"";if(Array.isArray(e)||!G(n))throw new fe({value:e,validator:t,context:r});return parseFloat(n)}(t,e,r):Z(t)?function(t){return t+""}(e):X(t)?function(t,e){if("boolean"==typeof t)return t;if(!1===/^(true|false|yes|no|0|1)$/i.test(String(t)))throw new fe({value:t,validator:$.BOOLEAN,context:e});return!1===/^0|no|false$/.test(String(t))}(e,r):e}function ye(t,e,r){return"function"==typeof e?async function t(e,r,n){if(Array.isArray(r))return Promise.all(r.map(r=>t(e,r,n)));try{return await e(r)}catch(t){throw new fe({validator:e,value:r,error:t,context:n})}}(e,t,r):e instanceof RegExp?function t(e,r,n){if(Array.isArray(r))return r.map(r=>t(e,r,n));if(!e.test(r+""))throw new fe({validator:e,value:r,context:n});return r}(e,t,r):Array.isArray(e)?function t(e,r,n){if(Array.isArray(r))r.forEach(r=>t(e,r,n));else if(!1===e.includes(r))throw new fe({validator:e,value:r,context:n});return r}(e,t,r):K(e)?ve(e,t,r):t}function be(t,e,r){const n=t.args.reduce((r,n)=>(void 0===e[n.name]&&n.required&&r.push(new j(n,t)),r),[]);if(t.strictArgsCount){const e=function(t,e){const r=function(t){return{min:function(t){return t.args.filter(t=>t.required).length}(t),max:function(t){return t.args.some(t=>t.variadic)}(t)?1/0:t.args.length}}(t),n=Object.keys(e).length;if(r.max!==1/0&&r.max<Object.keys(e).length)return new ge(t,r,n)}(t,r);e&&n.push(e)}return n}function we(t,e){const r=t.name.split(" ").length;return e.slice(r)}async function Oe(t,e){const r=t.isProgramCommand()?e:we(t,e),n=function(t,e){return t.args.reduce((t,r,n)=>(void 0!==e[n]?t[r.name]=e[n]:void 0!==r.default&&(t[r.name]=r.default),t),{})}(t,r),o=[],i=m()(n,(e,r,n)=>{const i=function(t,e){return t.args.find(t=>t.name===e)}(t,n);try{if(!i)throw new f("Unknown argumment "+n);e[n]=function(t,e){return t.validator?ye(e,t.validator,t):e}(i,r)}catch(t){o.push(t)}return e},{}),s=await m()(i,async(t,e,r)=>{const n=await t;return n[r]=await e,n},Promise.resolve({}));return o.push(...be(t,s,r)),{args:s,errors:o}}async function Ce(t,e){e=function(t,e){return t.options.reduce((t,e)=>(void 0===t[e.name]&&void 0!==e.default&&(t[e.name]=e.default),t),e)}(t,e);const r=[],n=m()(e,(...e)=>{const[n,o,i]=e,s=function(t){for(const[e]of Zt())if(e.allNames.includes(t))return e}(i)||function(t,e){return t.options.find(t=>t.allNames.find(t=>t===e))}(t,i);try{if(s)n[i]=function(t,e){return t.validator?ye(e,t.validator,t):e}(s,o);else if(t.strictOptions)throw new le(i,t)}catch(t){r.push(t)}return n},{}),o=await m()(n,async(t,e,r)=>{const n=await t;return n[r]=await e,n},Promise.resolve({}));return r.push(...function(t,e){return t.options.reduce((r,n)=>(void 0===e[n.name]&&n.required&&r.push(new P(n,t)),r),[])}(t,o)),{options:o,errors:r}}function Ae(t,e,r={}){const{validator:n,default:o}=r;tt(n);const i=function(t){const e=U(t=t.trim(),!1),r=U(t),n=function(t){return"<"===t.substring(0,1)}(t),o=function(t){return"..."===t.substr(-4,3)||t.endsWith("...")}(t);return{name:r,synopsis:n?`<${e}${o?"...":""}>`:`[${e}${o?"...":""}]`,required:n,variadic:o}}(t),s={kind:"argument",default:o,description:e,choices:Array.isArray(n)?n:[],validator:n,...i};return s.typeHint=et(s),s}var xe=r(8),_e=r.n(xe),Ne=r(14),Ee=r.n(Ne),je=r(25),Pe=r.n(je);function Be(t){const e=_e()(t.options,"name"),r=_e()(t.options,t=>t.shortName||t.longName),n=Ee()(e,r);return Pe()({...n,...At()(n)})}function ke(t){const e=t;let r=t;return{reset:()=>(r=e,r),get:t=>r[t],getAll:()=>r,set:t=>Object.assign(r,t)}}function qe(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}class Se{constructor(t,e,r,n={}){qe(this,"program",void 0),qe(this,"_action",void 0),qe(this,"_lastAddedArgOrOpt",void 0),qe(this,"_aliases",[]),qe(this,"_name",void 0),qe(this,"_config",void 0),qe(this,"description",void 0),qe(this,"options",[]),qe(this,"args",[]),this.program=t,this._name=e,this.description=r,this._config=ke({visible:!0,...n})}alias(...t){return this._aliases.push(...t),this}get name(){return this.isProgramCommand()?"":this._name}argument(t,e,r={}){return this._lastAddedArgOrOpt=Ae(t,e,r),this.args.push(this._lastAddedArgOrOpt),this}action(t){return this._action=t,this}command(t,e,r={}){return this.program.command(t,e,r)}default(){return this.program.defaultCommand=this,this}hasAlias(t){return this._aliases.includes(t)}getAliases(){return this._aliases}isProgramCommand(){return"__self_cmd"===this._name}isHelpCommand(){return"help"===this._name}hide(){return this.configure({visible:!1})}option(t,e,r={}){const n=this._lastAddedArgOrOpt=Ut(t,e,r);return this.options.push(n),this}getParserConfig(){const t={boolean:[],string:[],alias:Be(this),autoCast:this.autoCast,variadic:[],ddash:!1};let e=this.options.reduce((t,e)=>(e.boolean&&t.boolean.push(e.name),Z(e.validator)&&t.string.push(e.name),e.variadic&&t.variadic.push(e.name),t),t);return e=this.args.reduce((t,e,r)=>(this.isProgramCommand()||r++,X(e.validator)&&t.boolean.push(r),Z(e.validator)&&t.string.push(r),e.variadic&&t.variadic.push(r),t),e),e}get synopsis(){const t=this.options.length?this.options.some(t=>t.required)?"<OPTIONS...>":"[OPTIONS...]":"",e="__self_cmd"!==this._name?" "+this._name:"";return(this.program.getBin()+e+" "+this.args.map(t=>t.synopsis).join(" ")+" "+t).trim()}help(t,e={}){return vt(this,t,e),this}configure(t){return this._config.set(t),this}getConfigProperty(t){return this._config.get(t)}get autoCast(){var t;return null!==(t=this.getConfigProperty("autoCast"))&&void 0!==t?t:this.program.getConfigProperty("autoCast")}complete(t){if(!this._lastAddedArgOrOpt)throw new Error("Caporal setup error: you should only call `.complete()` after .argument() or .option().");return function(t,e){Dt.set(t,e)}(this._lastAddedArgOrOpt,t),this}strict(t=!0){return this.configure({strictArgsCount:t,strictOptions:t})}get strictOptions(){var t;return null!==(t=this.getConfigProperty("strictOptions"))&&void 0!==t?t:this.program.getConfigProperty("strictOptions")}get strictArgsCount(){var t;return null!==(t=this.getConfigProperty("strictArgsCount"))&&void 0!==t?t:this.program.getConfigProperty("strictArgsCount")}cast(t){return this.configure({autoCast:t})}get visible(){return this.getConfigProperty("visible")}async run(t){const e={args:[],options:{},line:"",rawOptions:{},rawArgv:[],ddash:[],...t};try{const t=await async function(t,e){const{args:r,options:n}=e,{options:o,errors:i}=await Ce(t,n),{args:s,errors:a}=await Oe(t,r);return{...e,args:s,options:o,errors:[...a,...i]}}(this,e),{args:r,options:n,ddash:o,errors:i}=t;if(await te(t,this.program,this))return-1;if(i.length)throw new k(this,i);if(!this._action)throw new q(this);return await this._action({args:r,options:n,ddash:o,logger:_,program:this.program,command:this})}catch(t){const e=Object.getPrototypeOf(t).constructor.name;throw t instanceof f&&"Error"!==e?t:new g(t)}}}function Re(...t){return new Se(...t)}var Le=r(26),$e=r.n(Le);async function Me(t,e){const r=await function(t,e="js,ts"){return new Promise((r,n)=>{if(!s.a.existsSync(t))return n(new Error(`'${t}' does not exist!`));$e()(`**/*.{${e}}`,{cwd:t},(function(t,e){if(t)return n(t);r(e)}))})}(e),n=await Promise.all(r.map(t=>$t(c.a.join(e,t)))),o=Ee()(r,n);return _e()(o,(e,r)=>{const{dir:n,name:o}=c.a.parse(r),i=n?[...n.split("/"),o].join(" "):o;return e({createCommand:Re.bind(null,t,i),program:t})})}var Ie=r(27);function He(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}class Te extends o.EventEmitter{constructor(){super(),He(this,"commands",[]),He(this,"_config",void 0),He(this,"_version",void 0),He(this,"_name",void 0),He(this,"_description",void 0),He(this,"_programmaticMode",!1),He(this,"defaultCommand",void 0),He(this,"_progCommand",void 0),He(this,"_bin",void 0),He(this,"_discoveryPath",void 0),He(this,"_discoveredCommands",void 0),He(this,"NUMBER",$.NUMBER),He(this,"STRING",$.STRING),He(this,"ARRAY",$.ARRAY),He(this,"BOOLEAN",$.BOOLEAN),this._bin=c.a.basename(process.argv[1]),this._version=Object(Ie.a)(),this._config=ke({strictArgsCount:!0,strictOptions:!0,autoCast:!0,logLevelEnvVar:"CAPORAL_LOG_LEVEL"}),this.setupHelpCommand(),this.setupErrorHandlers()}setupErrorHandlers(){process.once("unhandledRejection",t=>{if(this._programmaticMode)throw t;this.emit("error",t)}),this.on("error",N)}get progCommand(){return void 0===this._progCommand&&(this._progCommand=Re(this,"__self_cmd","")),this._progCommand}setupHelpCommand(){return this.command("help","Get help about a specific command").argument("[command]","Command name to get help for. If the command does not exist, global help will be displayed.").action(async t=>{const{args:e}=t,r=e.command?await Mt(this,[e.command]):void 0;return Vt({...t,command:r}),-1}).hide()}help(t,e={}){return vt(this,t,e),this}strict(t=!0){return this.configure({strictArgsCount:t,strictOptions:t})}configure(t){return this._config.set(t),this}getConfigProperty(t){return this._config.get(t)}async getSynopsis(){return(this.getBin()+" "+(await this.hasCommands()?"<command> ":"")+"[ARGUMENTS...] [OPTIONS...]").trim()}get discoveryPath(){return this._discoveryPath}getVersion(){return this._version}version(t){return this._version=t,this}name(t){return this._name=t,this}getName(){return this._name}getDescription(){return this._description}description(t){return this._description=t,this}getBin(){return this._bin}bin(t){return this._bin=t,this}logger(t){return _=t,this}disableGlobalOption(t){return function(t){const e=Zt();for(const[r]of e)if(r.allNames.includes(t)||r.allNotations.includes(t))return e.delete(r);return!1}(t)||_.warn("Cannot disable global option %s. Either the global option does not exist or has already been disabled."),this}getCommands(){return this.commands}command(t,e,r={}){const n=Re(this,t,e,r);return this.commands.push(n),n}async hasCommands(){return(await this.getAllCommands()).length>1}async getAllCommands(){const t=await this.scanCommands();return[...this.commands,...t]}getLogLevelOverride(){return process.env[this.getConfigProperty("logLevelEnvVar")]}cast(t){return this.configure({autoCast:t})}action(t){return this.progCommand.action(t),this}argument(t,e,r={}){return this.progCommand.argument(t,e,r)}option(t,e,r={}){if(r.global){!function(t,e){Zt().set(t,e)}(Ut(t,e,r),r.action)}else this.progCommand.option(t,e,r);return this}discover(t){let e;try{e=s.a.statSync(t)}catch(t){}if(!e||!e.isDirectory())throw new Error("Caporal setup error: parameter `dirPath` of discover() should be a directory");return this._discoveryPath=t,this}async scanCommands(){return void 0===this._discoveryPath?[]:(this._discoveredCommands||(this._discoveredCommands=await Me(this,this._discoveryPath)),this._discoveredCommands)}reset(){return this.commands=[],this._progCommand=void 0,this.setupHelpCommand(),this}async run(t){t||(t=process.env.CAPORAL_CMD_LINE?process.env.CAPORAL_CMD_LINE.split(" ").slice(1):process.argv.slice(2));const e=await this.findCommand(t),r=Rt(null==e?void 0:e.getParserConfig(),t);return this._run(r,e)}async findCommand(t){return await Mt(this,t)||this.defaultCommand||this._progCommand}async _run(t,e){const r=this.getLogLevelOverride();if(r&&Object.keys(_.levels).includes(r)&&(_.level=r),!e){const e={...t,errors:[],args:{}};if(await te(e,this))return this.emit("run"),-1;throw new pe(this,t.rawArgv[0])}const n=await e.run(t);return this.emit("run",n),n}async exec(t,e={},r=[]){this._programmaticMode=!0;const n=await this.findCommand(t);return e=h()(e,(t,e)=>l()(e)),this._run({args:t,options:e,line:t.join(" "),rawOptions:e,rawArgv:t,ddash:r},n)}}const De=new Te;e.default=De}]);
//# sourceMappingURL=index.js.map