Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.cjs 105KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920
  1. 'use strict';
  2. var assert = require('assert');
  3. class YError extends Error {
  4. constructor(msg) {
  5. super(msg || 'yargs error');
  6. this.name = 'YError';
  7. Error.captureStackTrace(this, YError);
  8. }
  9. }
  10. let previouslyVisitedConfigs = [];
  11. let shim;
  12. function applyExtends(config, cwd, mergeExtends, _shim) {
  13. shim = _shim;
  14. let defaultConfig = {};
  15. if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
  16. if (typeof config.extends !== 'string')
  17. return defaultConfig;
  18. const isPath = /\.json|\..*rc$/.test(config.extends);
  19. let pathToDefault = null;
  20. if (!isPath) {
  21. try {
  22. pathToDefault = require.resolve(config.extends);
  23. }
  24. catch (_err) {
  25. return config;
  26. }
  27. }
  28. else {
  29. pathToDefault = getPathToDefaultConfig(cwd, config.extends);
  30. }
  31. checkForCircularExtends(pathToDefault);
  32. previouslyVisitedConfigs.push(pathToDefault);
  33. defaultConfig = isPath
  34. ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
  35. : require(config.extends);
  36. delete config.extends;
  37. defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
  38. }
  39. previouslyVisitedConfigs = [];
  40. return mergeExtends
  41. ? mergeDeep(defaultConfig, config)
  42. : Object.assign({}, defaultConfig, config);
  43. }
  44. function checkForCircularExtends(cfgPath) {
  45. if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
  46. throw new YError(`Circular extended configurations: '${cfgPath}'.`);
  47. }
  48. }
  49. function getPathToDefaultConfig(cwd, pathToExtend) {
  50. return shim.path.resolve(cwd, pathToExtend);
  51. }
  52. function mergeDeep(config1, config2) {
  53. const target = {};
  54. function isObject(obj) {
  55. return obj && typeof obj === 'object' && !Array.isArray(obj);
  56. }
  57. Object.assign(target, config1);
  58. for (const key of Object.keys(config2)) {
  59. if (isObject(config2[key]) && isObject(target[key])) {
  60. target[key] = mergeDeep(config1[key], config2[key]);
  61. }
  62. else {
  63. target[key] = config2[key];
  64. }
  65. }
  66. return target;
  67. }
  68. function parseCommand(cmd) {
  69. const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
  70. const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
  71. const bregex = /\.*[\][<>]/g;
  72. const firstCommand = splitCommand.shift();
  73. if (!firstCommand)
  74. throw new Error(`No command found in: ${cmd}`);
  75. const parsedCommand = {
  76. cmd: firstCommand.replace(bregex, ''),
  77. demanded: [],
  78. optional: [],
  79. };
  80. splitCommand.forEach((cmd, i) => {
  81. let variadic = false;
  82. cmd = cmd.replace(/\s/g, '');
  83. if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
  84. variadic = true;
  85. if (/^\[/.test(cmd)) {
  86. parsedCommand.optional.push({
  87. cmd: cmd.replace(bregex, '').split('|'),
  88. variadic,
  89. });
  90. }
  91. else {
  92. parsedCommand.demanded.push({
  93. cmd: cmd.replace(bregex, '').split('|'),
  94. variadic,
  95. });
  96. }
  97. });
  98. return parsedCommand;
  99. }
  100. const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
  101. function argsert(arg1, arg2, arg3) {
  102. function parseArgs() {
  103. return typeof arg1 === 'object'
  104. ? [{ demanded: [], optional: [] }, arg1, arg2]
  105. : [
  106. parseCommand(`cmd ${arg1}`),
  107. arg2,
  108. arg3,
  109. ];
  110. }
  111. try {
  112. let position = 0;
  113. const [parsed, callerArguments, _length] = parseArgs();
  114. const args = [].slice.call(callerArguments);
  115. while (args.length && args[args.length - 1] === undefined)
  116. args.pop();
  117. const length = _length || args.length;
  118. if (length < parsed.demanded.length) {
  119. throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
  120. }
  121. const totalCommands = parsed.demanded.length + parsed.optional.length;
  122. if (length > totalCommands) {
  123. throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
  124. }
  125. parsed.demanded.forEach(demanded => {
  126. const arg = args.shift();
  127. const observedType = guessType(arg);
  128. const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
  129. if (matchingTypes.length === 0)
  130. argumentTypeError(observedType, demanded.cmd, position);
  131. position += 1;
  132. });
  133. parsed.optional.forEach(optional => {
  134. if (args.length === 0)
  135. return;
  136. const arg = args.shift();
  137. const observedType = guessType(arg);
  138. const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
  139. if (matchingTypes.length === 0)
  140. argumentTypeError(observedType, optional.cmd, position);
  141. position += 1;
  142. });
  143. }
  144. catch (err) {
  145. console.warn(err.stack);
  146. }
  147. }
  148. function guessType(arg) {
  149. if (Array.isArray(arg)) {
  150. return 'array';
  151. }
  152. else if (arg === null) {
  153. return 'null';
  154. }
  155. return typeof arg;
  156. }
  157. function argumentTypeError(observedType, allowedTypes, position) {
  158. throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
  159. }
  160. function isPromise(maybePromise) {
  161. return (!!maybePromise &&
  162. !!maybePromise.then &&
  163. typeof maybePromise.then === 'function');
  164. }
  165. function assertNotStrictEqual(actual, expected, shim, message) {
  166. shim.assert.notStrictEqual(actual, expected, message);
  167. }
  168. function assertSingleKey(actual, shim) {
  169. shim.assert.strictEqual(typeof actual, 'string');
  170. }
  171. function objectKeys(object) {
  172. return Object.keys(object);
  173. }
  174. function objFilter(original = {}, filter = () => true) {
  175. const obj = {};
  176. objectKeys(original).forEach(key => {
  177. if (filter(key, original[key])) {
  178. obj[key] = original[key];
  179. }
  180. });
  181. return obj;
  182. }
  183. function globalMiddlewareFactory(globalMiddleware, context) {
  184. return function (callback, applyBeforeValidation = false) {
  185. argsert('<array|function> [boolean]', [callback, applyBeforeValidation], arguments.length);
  186. if (Array.isArray(callback)) {
  187. for (let i = 0; i < callback.length; i++) {
  188. if (typeof callback[i] !== 'function') {
  189. throw Error('middleware must be a function');
  190. }
  191. callback[i].applyBeforeValidation = applyBeforeValidation;
  192. }
  193. Array.prototype.push.apply(globalMiddleware, callback);
  194. }
  195. else if (typeof callback === 'function') {
  196. callback.applyBeforeValidation = applyBeforeValidation;
  197. globalMiddleware.push(callback);
  198. }
  199. return context;
  200. };
  201. }
  202. function commandMiddlewareFactory(commandMiddleware) {
  203. if (!commandMiddleware)
  204. return [];
  205. return commandMiddleware.map(middleware => {
  206. middleware.applyBeforeValidation = false;
  207. return middleware;
  208. });
  209. }
  210. function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
  211. const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true');
  212. return middlewares.reduce((acc, middleware) => {
  213. if (middleware.applyBeforeValidation !== beforeValidation) {
  214. return acc;
  215. }
  216. if (isPromise(acc)) {
  217. return acc
  218. .then(initialObj => Promise.all([
  219. initialObj,
  220. middleware(initialObj, yargs),
  221. ]))
  222. .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
  223. }
  224. else {
  225. const result = middleware(acc, yargs);
  226. if (beforeValidation && isPromise(result))
  227. throw beforeValidationError;
  228. return isPromise(result)
  229. ? result.then(middlewareObj => Object.assign(acc, middlewareObj))
  230. : Object.assign(acc, result);
  231. }
  232. }, argv);
  233. }
  234. function getProcessArgvBinIndex() {
  235. if (isBundledElectronApp())
  236. return 0;
  237. return 1;
  238. }
  239. function isBundledElectronApp() {
  240. return isElectronApp() && !process.defaultApp;
  241. }
  242. function isElectronApp() {
  243. return !!process.versions.electron;
  244. }
  245. function hideBin(argv) {
  246. return argv.slice(getProcessArgvBinIndex() + 1);
  247. }
  248. function getProcessArgvBin() {
  249. return process.argv[getProcessArgvBinIndex()];
  250. }
  251. var processArgv = /*#__PURE__*/Object.freeze({
  252. __proto__: null,
  253. hideBin: hideBin,
  254. getProcessArgvBin: getProcessArgvBin
  255. });
  256. function whichModule(exported) {
  257. if (typeof require === 'undefined')
  258. return null;
  259. for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
  260. mod = require.cache[files[i]];
  261. if (mod.exports === exported)
  262. return mod;
  263. }
  264. return null;
  265. }
  266. const DEFAULT_MARKER = /(^\*)|(^\$0)/;
  267. function command(yargs, usage, validation, globalMiddleware = [], shim) {
  268. const self = {};
  269. let handlers = {};
  270. let aliasMap = {};
  271. let defaultCommand;
  272. self.addHandler = function addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
  273. let aliases = [];
  274. const middlewares = commandMiddlewareFactory(commandMiddleware);
  275. handler = handler || (() => { });
  276. if (Array.isArray(cmd)) {
  277. if (isCommandAndAliases(cmd)) {
  278. [cmd, ...aliases] = cmd;
  279. }
  280. else {
  281. for (const command of cmd) {
  282. self.addHandler(command);
  283. }
  284. }
  285. }
  286. else if (isCommandHandlerDefinition(cmd)) {
  287. let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
  288. ? cmd.command
  289. : moduleName(cmd);
  290. if (cmd.aliases)
  291. command = [].concat(command).concat(cmd.aliases);
  292. self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
  293. return;
  294. }
  295. else if (isCommandBuilderDefinition(builder)) {
  296. self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
  297. return;
  298. }
  299. if (typeof cmd === 'string') {
  300. const parsedCommand = parseCommand(cmd);
  301. aliases = aliases.map(alias => parseCommand(alias).cmd);
  302. let isDefault = false;
  303. const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
  304. if (DEFAULT_MARKER.test(c)) {
  305. isDefault = true;
  306. return false;
  307. }
  308. return true;
  309. });
  310. if (parsedAliases.length === 0 && isDefault)
  311. parsedAliases.push('$0');
  312. if (isDefault) {
  313. parsedCommand.cmd = parsedAliases[0];
  314. aliases = parsedAliases.slice(1);
  315. cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
  316. }
  317. aliases.forEach(alias => {
  318. aliasMap[alias] = parsedCommand.cmd;
  319. });
  320. if (description !== false) {
  321. usage.command(cmd, description, isDefault, aliases, deprecated);
  322. }
  323. handlers[parsedCommand.cmd] = {
  324. original: cmd,
  325. description,
  326. handler,
  327. builder: builder || {},
  328. middlewares,
  329. deprecated,
  330. demanded: parsedCommand.demanded,
  331. optional: parsedCommand.optional,
  332. };
  333. if (isDefault)
  334. defaultCommand = handlers[parsedCommand.cmd];
  335. }
  336. };
  337. self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) {
  338. opts = opts || {};
  339. if (typeof opts.recurse !== 'boolean')
  340. opts.recurse = false;
  341. if (!Array.isArray(opts.extensions))
  342. opts.extensions = ['js'];
  343. const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
  344. opts.visit = function visit(obj, joined, filename) {
  345. const visited = parentVisit(obj, joined, filename);
  346. if (visited) {
  347. if (~context.files.indexOf(joined))
  348. return visited;
  349. context.files.push(joined);
  350. self.addHandler(visited);
  351. }
  352. return visited;
  353. };
  354. shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
  355. };
  356. function moduleName(obj) {
  357. const mod = whichModule(obj);
  358. if (!mod)
  359. throw new Error(`No command name given for module: ${shim.inspect(obj)}`);
  360. return commandFromFilename(mod.filename);
  361. }
  362. function commandFromFilename(filename) {
  363. return shim.path.basename(filename, shim.path.extname(filename));
  364. }
  365. function extractDesc({ describe, description, desc, }) {
  366. for (const test of [describe, description, desc]) {
  367. if (typeof test === 'string' || test === false)
  368. return test;
  369. assertNotStrictEqual(test, true, shim);
  370. }
  371. return false;
  372. }
  373. self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
  374. self.getCommandHandlers = () => handlers;
  375. self.hasDefaultCommand = () => !!defaultCommand;
  376. self.runCommand = function runCommand(command, yargs, parsed, commandIndex) {
  377. let aliases = parsed.aliases;
  378. const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand;
  379. const currentContext = yargs.getContext();
  380. let numFiles = currentContext.files.length;
  381. const parentCommands = currentContext.commands.slice();
  382. let innerArgv = parsed.argv;
  383. let positionalMap = {};
  384. if (command) {
  385. currentContext.commands.push(command);
  386. currentContext.fullCommands.push(commandHandler.original);
  387. }
  388. const builder = commandHandler.builder;
  389. if (isCommandBuilderCallback(builder)) {
  390. const builderOutput = builder(yargs.reset(parsed.aliases));
  391. const innerYargs = isYargsInstance(builderOutput) ? builderOutput : yargs;
  392. if (shouldUpdateUsage(innerYargs)) {
  393. innerYargs
  394. .getUsageInstance()
  395. .usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
  396. }
  397. innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
  398. aliases = innerYargs.parsed.aliases;
  399. }
  400. else if (isCommandBuilderOptionDefinitions(builder)) {
  401. const innerYargs = yargs.reset(parsed.aliases);
  402. if (shouldUpdateUsage(innerYargs)) {
  403. innerYargs
  404. .getUsageInstance()
  405. .usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
  406. }
  407. Object.keys(commandHandler.builder).forEach(key => {
  408. innerYargs.option(key, builder[key]);
  409. });
  410. innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
  411. aliases = innerYargs.parsed.aliases;
  412. }
  413. if (!yargs._hasOutput()) {
  414. positionalMap = populatePositionals(commandHandler, innerArgv, currentContext);
  415. }
  416. const middlewares = globalMiddleware
  417. .slice(0)
  418. .concat(commandHandler.middlewares);
  419. applyMiddleware(innerArgv, yargs, middlewares, true);
  420. if (!yargs._hasOutput()) {
  421. yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error, !command);
  422. }
  423. if (commandHandler.handler && !yargs._hasOutput()) {
  424. yargs._setHasOutput();
  425. const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
  426. yargs._postProcess(innerArgv, populateDoubleDash);
  427. innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
  428. let handlerResult;
  429. if (isPromise(innerArgv)) {
  430. handlerResult = innerArgv.then(argv => commandHandler.handler(argv));
  431. }
  432. else {
  433. handlerResult = commandHandler.handler(innerArgv);
  434. }
  435. const handlerFinishCommand = yargs.getHandlerFinishCommand();
  436. if (isPromise(handlerResult)) {
  437. yargs.getUsageInstance().cacheHelpMessage();
  438. handlerResult
  439. .then(value => {
  440. if (handlerFinishCommand) {
  441. handlerFinishCommand(value);
  442. }
  443. })
  444. .catch(error => {
  445. try {
  446. yargs.getUsageInstance().fail(null, error);
  447. }
  448. catch (err) {
  449. }
  450. })
  451. .then(() => {
  452. yargs.getUsageInstance().clearCachedHelpMessage();
  453. });
  454. }
  455. else {
  456. if (handlerFinishCommand) {
  457. handlerFinishCommand(handlerResult);
  458. }
  459. }
  460. }
  461. if (command) {
  462. currentContext.commands.pop();
  463. currentContext.fullCommands.pop();
  464. }
  465. numFiles = currentContext.files.length - numFiles;
  466. if (numFiles > 0)
  467. currentContext.files.splice(numFiles * -1, numFiles);
  468. return innerArgv;
  469. };
  470. function shouldUpdateUsage(yargs) {
  471. return (!yargs.getUsageInstance().getUsageDisabled() &&
  472. yargs.getUsageInstance().getUsage().length === 0);
  473. }
  474. function usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
  475. const c = DEFAULT_MARKER.test(commandHandler.original)
  476. ? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
  477. : commandHandler.original;
  478. const pc = parentCommands.filter(c => {
  479. return !DEFAULT_MARKER.test(c);
  480. });
  481. pc.push(c);
  482. return `$0 ${pc.join(' ')}`;
  483. }
  484. self.runDefaultBuilderOn = function (yargs) {
  485. assertNotStrictEqual(defaultCommand, undefined, shim);
  486. if (shouldUpdateUsage(yargs)) {
  487. const commandString = DEFAULT_MARKER.test(defaultCommand.original)
  488. ? defaultCommand.original
  489. : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
  490. yargs.getUsageInstance().usage(commandString, defaultCommand.description);
  491. }
  492. const builder = defaultCommand.builder;
  493. if (isCommandBuilderCallback(builder)) {
  494. builder(yargs);
  495. }
  496. else if (!isCommandBuilderDefinition(builder)) {
  497. Object.keys(builder).forEach(key => {
  498. yargs.option(key, builder[key]);
  499. });
  500. }
  501. };
  502. function populatePositionals(commandHandler, argv, context) {
  503. argv._ = argv._.slice(context.commands.length);
  504. const demanded = commandHandler.demanded.slice(0);
  505. const optional = commandHandler.optional.slice(0);
  506. const positionalMap = {};
  507. validation.positionalCount(demanded.length, argv._.length);
  508. while (demanded.length) {
  509. const demand = demanded.shift();
  510. populatePositional(demand, argv, positionalMap);
  511. }
  512. while (optional.length) {
  513. const maybe = optional.shift();
  514. populatePositional(maybe, argv, positionalMap);
  515. }
  516. argv._ = context.commands.concat(argv._.map(a => '' + a));
  517. postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original));
  518. return positionalMap;
  519. }
  520. function populatePositional(positional, argv, positionalMap) {
  521. const cmd = positional.cmd[0];
  522. if (positional.variadic) {
  523. positionalMap[cmd] = argv._.splice(0).map(String);
  524. }
  525. else {
  526. if (argv._.length)
  527. positionalMap[cmd] = [String(argv._.shift())];
  528. }
  529. }
  530. function postProcessPositionals(argv, positionalMap, parseOptions) {
  531. const options = Object.assign({}, yargs.getOptions());
  532. options.default = Object.assign(parseOptions.default, options.default);
  533. for (const key of Object.keys(parseOptions.alias)) {
  534. options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
  535. }
  536. options.array = options.array.concat(parseOptions.array);
  537. options.config = {};
  538. const unparsed = [];
  539. Object.keys(positionalMap).forEach(key => {
  540. positionalMap[key].map(value => {
  541. if (options.configuration['unknown-options-as-args'])
  542. options.key[key] = true;
  543. unparsed.push(`--${key}`);
  544. unparsed.push(value);
  545. });
  546. });
  547. if (!unparsed.length)
  548. return;
  549. const config = Object.assign({}, options.configuration, {
  550. 'populate--': true,
  551. });
  552. const parsed = shim.Parser.detailed(unparsed, Object.assign({}, options, {
  553. configuration: config,
  554. }));
  555. if (parsed.error) {
  556. yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
  557. }
  558. else {
  559. const positionalKeys = Object.keys(positionalMap);
  560. Object.keys(positionalMap).forEach(key => {
  561. positionalKeys.push(...parsed.aliases[key]);
  562. });
  563. Object.keys(parsed.argv).forEach(key => {
  564. if (positionalKeys.indexOf(key) !== -1) {
  565. if (!positionalMap[key])
  566. positionalMap[key] = parsed.argv[key];
  567. argv[key] = parsed.argv[key];
  568. }
  569. });
  570. }
  571. }
  572. self.cmdToParseOptions = function (cmdString) {
  573. const parseOptions = {
  574. array: [],
  575. default: {},
  576. alias: {},
  577. demand: {},
  578. };
  579. const parsed = parseCommand(cmdString);
  580. parsed.demanded.forEach(d => {
  581. const [cmd, ...aliases] = d.cmd;
  582. if (d.variadic) {
  583. parseOptions.array.push(cmd);
  584. parseOptions.default[cmd] = [];
  585. }
  586. parseOptions.alias[cmd] = aliases;
  587. parseOptions.demand[cmd] = true;
  588. });
  589. parsed.optional.forEach(o => {
  590. const [cmd, ...aliases] = o.cmd;
  591. if (o.variadic) {
  592. parseOptions.array.push(cmd);
  593. parseOptions.default[cmd] = [];
  594. }
  595. parseOptions.alias[cmd] = aliases;
  596. });
  597. return parseOptions;
  598. };
  599. self.reset = () => {
  600. handlers = {};
  601. aliasMap = {};
  602. defaultCommand = undefined;
  603. return self;
  604. };
  605. const frozens = [];
  606. self.freeze = () => {
  607. frozens.push({
  608. handlers,
  609. aliasMap,
  610. defaultCommand,
  611. });
  612. };
  613. self.unfreeze = () => {
  614. const frozen = frozens.pop();
  615. assertNotStrictEqual(frozen, undefined, shim);
  616. ({ handlers, aliasMap, defaultCommand } = frozen);
  617. };
  618. return self;
  619. }
  620. function isCommandBuilderDefinition(builder) {
  621. return (typeof builder === 'object' &&
  622. !!builder.builder &&
  623. typeof builder.handler === 'function');
  624. }
  625. function isCommandAndAliases(cmd) {
  626. if (cmd.every(c => typeof c === 'string')) {
  627. return true;
  628. }
  629. else {
  630. return false;
  631. }
  632. }
  633. function isCommandBuilderCallback(builder) {
  634. return typeof builder === 'function';
  635. }
  636. function isCommandBuilderOptionDefinitions(builder) {
  637. return typeof builder === 'object';
  638. }
  639. function isCommandHandlerDefinition(cmd) {
  640. return typeof cmd === 'object' && !Array.isArray(cmd);
  641. }
  642. function setBlocking(blocking) {
  643. if (typeof process === 'undefined')
  644. return;
  645. [process.stdout, process.stderr].forEach(_stream => {
  646. const stream = _stream;
  647. if (stream._handle &&
  648. stream.isTTY &&
  649. typeof stream._handle.setBlocking === 'function') {
  650. stream._handle.setBlocking(blocking);
  651. }
  652. });
  653. }
  654. function usage(yargs, y18n, shim) {
  655. const __ = y18n.__;
  656. const self = {};
  657. const fails = [];
  658. self.failFn = function failFn(f) {
  659. fails.push(f);
  660. };
  661. let failMessage = null;
  662. let showHelpOnFail = true;
  663. self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
  664. function parseFunctionArgs() {
  665. return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
  666. }
  667. const [enabled, message] = parseFunctionArgs();
  668. failMessage = message;
  669. showHelpOnFail = enabled;
  670. return self;
  671. };
  672. let failureOutput = false;
  673. self.fail = function fail(msg, err) {
  674. const logger = yargs._getLoggerInstance();
  675. if (fails.length) {
  676. for (let i = fails.length - 1; i >= 0; --i) {
  677. fails[i](msg, err, self);
  678. }
  679. }
  680. else {
  681. if (yargs.getExitProcess())
  682. setBlocking(true);
  683. if (!failureOutput) {
  684. failureOutput = true;
  685. if (showHelpOnFail) {
  686. yargs.showHelp('error');
  687. logger.error();
  688. }
  689. if (msg || err)
  690. logger.error(msg || err);
  691. if (failMessage) {
  692. if (msg || err)
  693. logger.error('');
  694. logger.error(failMessage);
  695. }
  696. }
  697. err = err || new YError(msg);
  698. if (yargs.getExitProcess()) {
  699. return yargs.exit(1);
  700. }
  701. else if (yargs._hasParseCallback()) {
  702. return yargs.exit(1, err);
  703. }
  704. else {
  705. throw err;
  706. }
  707. }
  708. };
  709. let usages = [];
  710. let usageDisabled = false;
  711. self.usage = (msg, description) => {
  712. if (msg === null) {
  713. usageDisabled = true;
  714. usages = [];
  715. return self;
  716. }
  717. usageDisabled = false;
  718. usages.push([msg, description || '']);
  719. return self;
  720. };
  721. self.getUsage = () => {
  722. return usages;
  723. };
  724. self.getUsageDisabled = () => {
  725. return usageDisabled;
  726. };
  727. self.getPositionalGroupName = () => {
  728. return __('Positionals:');
  729. };
  730. let examples = [];
  731. self.example = (cmd, description) => {
  732. examples.push([cmd, description || '']);
  733. };
  734. let commands = [];
  735. self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
  736. if (isDefault) {
  737. commands = commands.map(cmdArray => {
  738. cmdArray[2] = false;
  739. return cmdArray;
  740. });
  741. }
  742. commands.push([cmd, description || '', isDefault, aliases, deprecated]);
  743. };
  744. self.getCommands = () => commands;
  745. let descriptions = {};
  746. self.describe = function describe(keyOrKeys, desc) {
  747. if (Array.isArray(keyOrKeys)) {
  748. keyOrKeys.forEach(k => {
  749. self.describe(k, desc);
  750. });
  751. }
  752. else if (typeof keyOrKeys === 'object') {
  753. Object.keys(keyOrKeys).forEach(k => {
  754. self.describe(k, keyOrKeys[k]);
  755. });
  756. }
  757. else {
  758. descriptions[keyOrKeys] = desc;
  759. }
  760. };
  761. self.getDescriptions = () => descriptions;
  762. let epilogs = [];
  763. self.epilog = msg => {
  764. epilogs.push(msg);
  765. };
  766. let wrapSet = false;
  767. let wrap;
  768. self.wrap = cols => {
  769. wrapSet = true;
  770. wrap = cols;
  771. };
  772. function getWrap() {
  773. if (!wrapSet) {
  774. wrap = windowWidth();
  775. wrapSet = true;
  776. }
  777. return wrap;
  778. }
  779. const deferY18nLookupPrefix = '__yargsString__:';
  780. self.deferY18nLookup = str => deferY18nLookupPrefix + str;
  781. self.help = function help() {
  782. if (cachedHelpMessage)
  783. return cachedHelpMessage;
  784. normalizeAliases();
  785. const base$0 = yargs.customScriptName
  786. ? yargs.$0
  787. : shim.path.basename(yargs.$0);
  788. const demandedOptions = yargs.getDemandedOptions();
  789. const demandedCommands = yargs.getDemandedCommands();
  790. const deprecatedOptions = yargs.getDeprecatedOptions();
  791. const groups = yargs.getGroups();
  792. const options = yargs.getOptions();
  793. let keys = [];
  794. keys = keys.concat(Object.keys(descriptions));
  795. keys = keys.concat(Object.keys(demandedOptions));
  796. keys = keys.concat(Object.keys(demandedCommands));
  797. keys = keys.concat(Object.keys(options.default));
  798. keys = keys.filter(filterHiddenOptions);
  799. keys = Object.keys(keys.reduce((acc, key) => {
  800. if (key !== '_')
  801. acc[key] = true;
  802. return acc;
  803. }, {}));
  804. const theWrap = getWrap();
  805. const ui = shim.cliui({
  806. width: theWrap,
  807. wrap: !!theWrap,
  808. });
  809. if (!usageDisabled) {
  810. if (usages.length) {
  811. usages.forEach(usage => {
  812. ui.div(`${usage[0].replace(/\$0/g, base$0)}`);
  813. if (usage[1]) {
  814. ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
  815. }
  816. });
  817. ui.div();
  818. }
  819. else if (commands.length) {
  820. let u = null;
  821. if (demandedCommands._) {
  822. u = `${base$0} <${__('command')}>\n`;
  823. }
  824. else {
  825. u = `${base$0} [${__('command')}]\n`;
  826. }
  827. ui.div(`${u}`);
  828. }
  829. }
  830. if (commands.length) {
  831. ui.div(__('Commands:'));
  832. const context = yargs.getContext();
  833. const parentCommands = context.commands.length
  834. ? `${context.commands.join(' ')} `
  835. : '';
  836. if (yargs.getParserConfiguration()['sort-commands'] === true) {
  837. commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
  838. }
  839. commands.forEach(command => {
  840. const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
  841. ui.span({
  842. text: commandString,
  843. padding: [0, 2, 0, 2],
  844. width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
  845. }, { text: command[1] });
  846. const hints = [];
  847. if (command[2])
  848. hints.push(`[${__('default')}]`);
  849. if (command[3] && command[3].length) {
  850. hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
  851. }
  852. if (command[4]) {
  853. if (typeof command[4] === 'string') {
  854. hints.push(`[${__('deprecated: %s', command[4])}]`);
  855. }
  856. else {
  857. hints.push(`[${__('deprecated')}]`);
  858. }
  859. }
  860. if (hints.length) {
  861. ui.div({
  862. text: hints.join(' '),
  863. padding: [0, 0, 0, 2],
  864. align: 'right',
  865. });
  866. }
  867. else {
  868. ui.div();
  869. }
  870. });
  871. ui.div();
  872. }
  873. const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
  874. keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
  875. aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
  876. const defaultGroup = __('Options:');
  877. if (!groups[defaultGroup])
  878. groups[defaultGroup] = [];
  879. addUngroupedKeys(keys, options.alias, groups, defaultGroup);
  880. const isLongSwitch = (sw) => /^--/.test(getText(sw));
  881. const displayedGroups = Object.keys(groups)
  882. .filter(groupName => groups[groupName].length > 0)
  883. .map(groupName => {
  884. const normalizedKeys = groups[groupName]
  885. .filter(filterHiddenOptions)
  886. .map(key => {
  887. if (~aliasKeys.indexOf(key))
  888. return key;
  889. for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
  890. if (~(options.alias[aliasKey] || []).indexOf(key))
  891. return aliasKey;
  892. }
  893. return key;
  894. });
  895. return { groupName, normalizedKeys };
  896. })
  897. .filter(({ normalizedKeys }) => normalizedKeys.length > 0)
  898. .map(({ groupName, normalizedKeys }) => {
  899. const switches = normalizedKeys.reduce((acc, key) => {
  900. acc[key] = [key]
  901. .concat(options.alias[key] || [])
  902. .map(sw => {
  903. if (groupName === self.getPositionalGroupName())
  904. return sw;
  905. else {
  906. return ((/^[0-9]$/.test(sw)
  907. ? ~options.boolean.indexOf(key)
  908. ? '-'
  909. : '--'
  910. : sw.length > 1
  911. ? '--'
  912. : '-') + sw);
  913. }
  914. })
  915. .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
  916. ? 0
  917. : isLongSwitch(sw1)
  918. ? 1
  919. : -1)
  920. .join(', ');
  921. return acc;
  922. }, {});
  923. return { groupName, normalizedKeys, switches };
  924. });
  925. const shortSwitchesUsed = displayedGroups
  926. .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
  927. .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
  928. if (shortSwitchesUsed) {
  929. displayedGroups
  930. .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
  931. .forEach(({ normalizedKeys, switches }) => {
  932. normalizedKeys.forEach(key => {
  933. if (isLongSwitch(switches[key])) {
  934. switches[key] = addIndentation(switches[key], '-x, '.length);
  935. }
  936. });
  937. });
  938. }
  939. displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
  940. ui.div(groupName);
  941. normalizedKeys.forEach(key => {
  942. const kswitch = switches[key];
  943. let desc = descriptions[key] || '';
  944. let type = null;
  945. if (~desc.lastIndexOf(deferY18nLookupPrefix))
  946. desc = __(desc.substring(deferY18nLookupPrefix.length));
  947. if (~options.boolean.indexOf(key))
  948. type = `[${__('boolean')}]`;
  949. if (~options.count.indexOf(key))
  950. type = `[${__('count')}]`;
  951. if (~options.string.indexOf(key))
  952. type = `[${__('string')}]`;
  953. if (~options.normalize.indexOf(key))
  954. type = `[${__('string')}]`;
  955. if (~options.array.indexOf(key))
  956. type = `[${__('array')}]`;
  957. if (~options.number.indexOf(key))
  958. type = `[${__('number')}]`;
  959. const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
  960. ? `[${__('deprecated: %s', deprecated)}]`
  961. : `[${__('deprecated')}]`;
  962. const extra = [
  963. key in deprecatedOptions
  964. ? deprecatedExtra(deprecatedOptions[key])
  965. : null,
  966. type,
  967. key in demandedOptions ? `[${__('required')}]` : null,
  968. options.choices && options.choices[key]
  969. ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
  970. : null,
  971. defaultString(options.default[key], options.defaultDescription[key]),
  972. ]
  973. .filter(Boolean)
  974. .join(' ');
  975. ui.span({
  976. text: getText(kswitch),
  977. padding: [0, 2, 0, 2 + getIndentation(kswitch)],
  978. width: maxWidth(switches, theWrap) + 4,
  979. }, desc);
  980. if (extra)
  981. ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
  982. else
  983. ui.div();
  984. });
  985. ui.div();
  986. });
  987. if (examples.length) {
  988. ui.div(__('Examples:'));
  989. examples.forEach(example => {
  990. example[0] = example[0].replace(/\$0/g, base$0);
  991. });
  992. examples.forEach(example => {
  993. if (example[1] === '') {
  994. ui.div({
  995. text: example[0],
  996. padding: [0, 2, 0, 2],
  997. });
  998. }
  999. else {
  1000. ui.div({
  1001. text: example[0],
  1002. padding: [0, 2, 0, 2],
  1003. width: maxWidth(examples, theWrap) + 4,
  1004. }, {
  1005. text: example[1],
  1006. });
  1007. }
  1008. });
  1009. ui.div();
  1010. }
  1011. if (epilogs.length > 0) {
  1012. const e = epilogs
  1013. .map(epilog => epilog.replace(/\$0/g, base$0))
  1014. .join('\n');
  1015. ui.div(`${e}\n`);
  1016. }
  1017. return ui.toString().replace(/\s*$/, '');
  1018. };
  1019. function maxWidth(table, theWrap, modifier) {
  1020. let width = 0;
  1021. if (!Array.isArray(table)) {
  1022. table = Object.values(table).map(v => [v]);
  1023. }
  1024. table.forEach(v => {
  1025. width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
  1026. });
  1027. if (theWrap)
  1028. width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
  1029. return width;
  1030. }
  1031. function normalizeAliases() {
  1032. const demandedOptions = yargs.getDemandedOptions();
  1033. const options = yargs.getOptions();
  1034. (Object.keys(options.alias) || []).forEach(key => {
  1035. options.alias[key].forEach(alias => {
  1036. if (descriptions[alias])
  1037. self.describe(key, descriptions[alias]);
  1038. if (alias in demandedOptions)
  1039. yargs.demandOption(key, demandedOptions[alias]);
  1040. if (~options.boolean.indexOf(alias))
  1041. yargs.boolean(key);
  1042. if (~options.count.indexOf(alias))
  1043. yargs.count(key);
  1044. if (~options.string.indexOf(alias))
  1045. yargs.string(key);
  1046. if (~options.normalize.indexOf(alias))
  1047. yargs.normalize(key);
  1048. if (~options.array.indexOf(alias))
  1049. yargs.array(key);
  1050. if (~options.number.indexOf(alias))
  1051. yargs.number(key);
  1052. });
  1053. });
  1054. }
  1055. let cachedHelpMessage;
  1056. self.cacheHelpMessage = function () {
  1057. cachedHelpMessage = this.help();
  1058. };
  1059. self.clearCachedHelpMessage = function () {
  1060. cachedHelpMessage = undefined;
  1061. };
  1062. function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
  1063. let groupedKeys = [];
  1064. let toCheck = null;
  1065. Object.keys(groups).forEach(group => {
  1066. groupedKeys = groupedKeys.concat(groups[group]);
  1067. });
  1068. keys.forEach(key => {
  1069. toCheck = [key].concat(aliases[key]);
  1070. if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
  1071. groups[defaultGroup].push(key);
  1072. }
  1073. });
  1074. return groupedKeys;
  1075. }
  1076. function filterHiddenOptions(key) {
  1077. return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
  1078. yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
  1079. }
  1080. self.showHelp = (level) => {
  1081. const logger = yargs._getLoggerInstance();
  1082. if (!level)
  1083. level = 'error';
  1084. const emit = typeof level === 'function' ? level : logger[level];
  1085. emit(self.help());
  1086. };
  1087. self.functionDescription = fn => {
  1088. const description = fn.name
  1089. ? shim.Parser.decamelize(fn.name, '-')
  1090. : __('generated-value');
  1091. return ['(', description, ')'].join('');
  1092. };
  1093. self.stringifiedValues = function stringifiedValues(values, separator) {
  1094. let string = '';
  1095. const sep = separator || ', ';
  1096. const array = [].concat(values);
  1097. if (!values || !array.length)
  1098. return string;
  1099. array.forEach(value => {
  1100. if (string.length)
  1101. string += sep;
  1102. string += JSON.stringify(value);
  1103. });
  1104. return string;
  1105. };
  1106. function defaultString(value, defaultDescription) {
  1107. let string = `[${__('default:')} `;
  1108. if (value === undefined && !defaultDescription)
  1109. return null;
  1110. if (defaultDescription) {
  1111. string += defaultDescription;
  1112. }
  1113. else {
  1114. switch (typeof value) {
  1115. case 'string':
  1116. string += `"${value}"`;
  1117. break;
  1118. case 'object':
  1119. string += JSON.stringify(value);
  1120. break;
  1121. default:
  1122. string += value;
  1123. }
  1124. }
  1125. return `${string}]`;
  1126. }
  1127. function windowWidth() {
  1128. const maxWidth = 80;
  1129. if (shim.process.stdColumns) {
  1130. return Math.min(maxWidth, shim.process.stdColumns);
  1131. }
  1132. else {
  1133. return maxWidth;
  1134. }
  1135. }
  1136. let version = null;
  1137. self.version = ver => {
  1138. version = ver;
  1139. };
  1140. self.showVersion = () => {
  1141. const logger = yargs._getLoggerInstance();
  1142. logger.log(version);
  1143. };
  1144. self.reset = function reset(localLookup) {
  1145. failMessage = null;
  1146. failureOutput = false;
  1147. usages = [];
  1148. usageDisabled = false;
  1149. epilogs = [];
  1150. examples = [];
  1151. commands = [];
  1152. descriptions = objFilter(descriptions, k => !localLookup[k]);
  1153. return self;
  1154. };
  1155. const frozens = [];
  1156. self.freeze = function freeze() {
  1157. frozens.push({
  1158. failMessage,
  1159. failureOutput,
  1160. usages,
  1161. usageDisabled,
  1162. epilogs,
  1163. examples,
  1164. commands,
  1165. descriptions,
  1166. });
  1167. };
  1168. self.unfreeze = function unfreeze() {
  1169. const frozen = frozens.pop();
  1170. assertNotStrictEqual(frozen, undefined, shim);
  1171. ({
  1172. failMessage,
  1173. failureOutput,
  1174. usages,
  1175. usageDisabled,
  1176. epilogs,
  1177. examples,
  1178. commands,
  1179. descriptions,
  1180. } = frozen);
  1181. };
  1182. return self;
  1183. }
  1184. function isIndentedText(text) {
  1185. return typeof text === 'object';
  1186. }
  1187. function addIndentation(text, indent) {
  1188. return isIndentedText(text)
  1189. ? { text: text.text, indentation: text.indentation + indent }
  1190. : { text, indentation: indent };
  1191. }
  1192. function getIndentation(text) {
  1193. return isIndentedText(text) ? text.indentation : 0;
  1194. }
  1195. function getText(text) {
  1196. return isIndentedText(text) ? text.text : text;
  1197. }
  1198. const completionShTemplate = `###-begin-{{app_name}}-completions-###
  1199. #
  1200. # yargs command completion script
  1201. #
  1202. # Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
  1203. # or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
  1204. #
  1205. _yargs_completions()
  1206. {
  1207. local cur_word args type_list
  1208. cur_word="\${COMP_WORDS[COMP_CWORD]}"
  1209. args=("\${COMP_WORDS[@]}")
  1210. # ask yargs to generate completions.
  1211. type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
  1212. COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
  1213. # if no match was found, fall back to filename completion
  1214. if [ \${#COMPREPLY[@]} -eq 0 ]; then
  1215. COMPREPLY=()
  1216. fi
  1217. return 0
  1218. }
  1219. complete -o default -F _yargs_completions {{app_name}}
  1220. ###-end-{{app_name}}-completions-###
  1221. `;
  1222. const completionZshTemplate = `###-begin-{{app_name}}-completions-###
  1223. #
  1224. # yargs command completion script
  1225. #
  1226. # Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
  1227. # or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.
  1228. #
  1229. _{{app_name}}_yargs_completions()
  1230. {
  1231. local reply
  1232. local si=$IFS
  1233. IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
  1234. IFS=$si
  1235. _describe 'values' reply
  1236. }
  1237. compdef _{{app_name}}_yargs_completions {{app_name}}
  1238. ###-end-{{app_name}}-completions-###
  1239. `;
  1240. function completion(yargs, usage, command, shim) {
  1241. const self = {
  1242. completionKey: 'get-yargs-completions',
  1243. };
  1244. let aliases;
  1245. self.setParsed = function setParsed(parsed) {
  1246. aliases = parsed.aliases;
  1247. };
  1248. const zshShell = (shim.getEnv('SHELL') && shim.getEnv('SHELL').indexOf('zsh') !== -1) ||
  1249. (shim.getEnv('ZSH_NAME') && shim.getEnv('ZSH_NAME').indexOf('zsh') !== -1);
  1250. self.getCompletion = function getCompletion(args, done) {
  1251. const completions = [];
  1252. const current = args.length ? args[args.length - 1] : '';
  1253. const argv = yargs.parse(args, true);
  1254. const parentCommands = yargs.getContext().commands;
  1255. function runCompletionFunction(argv) {
  1256. assertNotStrictEqual(completionFunction, null, shim);
  1257. if (isSyncCompletionFunction(completionFunction)) {
  1258. const result = completionFunction(current, argv);
  1259. if (isPromise(result)) {
  1260. return result
  1261. .then(list => {
  1262. shim.process.nextTick(() => {
  1263. done(list);
  1264. });
  1265. })
  1266. .catch(err => {
  1267. shim.process.nextTick(() => {
  1268. throw err;
  1269. });
  1270. });
  1271. }
  1272. return done(result);
  1273. }
  1274. else {
  1275. return completionFunction(current, argv, completions => {
  1276. done(completions);
  1277. });
  1278. }
  1279. }
  1280. if (completionFunction) {
  1281. return isPromise(argv)
  1282. ? argv.then(runCompletionFunction)
  1283. : runCompletionFunction(argv);
  1284. }
  1285. const handlers = command.getCommandHandlers();
  1286. for (let i = 0, ii = args.length; i < ii; ++i) {
  1287. if (handlers[args[i]] && handlers[args[i]].builder) {
  1288. const builder = handlers[args[i]].builder;
  1289. if (isCommandBuilderCallback(builder)) {
  1290. const y = yargs.reset();
  1291. builder(y);
  1292. return y.argv;
  1293. }
  1294. }
  1295. }
  1296. if (!current.match(/^-/) &&
  1297. parentCommands[parentCommands.length - 1] !== current) {
  1298. usage.getCommands().forEach(usageCommand => {
  1299. const commandName = parseCommand(usageCommand[0]).cmd;
  1300. if (args.indexOf(commandName) === -1) {
  1301. if (!zshShell) {
  1302. completions.push(commandName);
  1303. }
  1304. else {
  1305. const desc = usageCommand[1] || '';
  1306. completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
  1307. }
  1308. }
  1309. });
  1310. }
  1311. if (current.match(/^-/) || (current === '' && completions.length === 0)) {
  1312. const descs = usage.getDescriptions();
  1313. const options = yargs.getOptions();
  1314. Object.keys(options.key).forEach(key => {
  1315. const negable = !!options.configuration['boolean-negation'] &&
  1316. options.boolean.includes(key);
  1317. let keyAndAliases = [key].concat(aliases[key] || []);
  1318. if (negable)
  1319. keyAndAliases = keyAndAliases.concat(keyAndAliases.map(key => `no-${key}`));
  1320. function completeOptionKey(key) {
  1321. const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1);
  1322. if (notInArgs) {
  1323. const startsByTwoDashes = (s) => /^--/.test(s);
  1324. const isShortOption = (s) => /^[^0-9]$/.test(s);
  1325. const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
  1326. if (!zshShell) {
  1327. completions.push(dashes + key);
  1328. }
  1329. else {
  1330. const desc = descs[key] || '';
  1331. completions.push(dashes +
  1332. `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`);
  1333. }
  1334. }
  1335. }
  1336. completeOptionKey(key);
  1337. if (negable && !!options.default[key])
  1338. completeOptionKey(`no-${key}`);
  1339. });
  1340. }
  1341. done(completions);
  1342. };
  1343. self.generateCompletionScript = function generateCompletionScript($0, cmd) {
  1344. let script = zshShell
  1345. ? completionZshTemplate
  1346. : completionShTemplate;
  1347. const name = shim.path.basename($0);
  1348. if ($0.match(/\.js$/))
  1349. $0 = `./${$0}`;
  1350. script = script.replace(/{{app_name}}/g, name);
  1351. script = script.replace(/{{completion_command}}/g, cmd);
  1352. return script.replace(/{{app_path}}/g, $0);
  1353. };
  1354. let completionFunction = null;
  1355. self.registerFunction = fn => {
  1356. completionFunction = fn;
  1357. };
  1358. return self;
  1359. }
  1360. function isSyncCompletionFunction(completionFunction) {
  1361. return completionFunction.length < 3;
  1362. }
  1363. function levenshtein(a, b) {
  1364. if (a.length === 0)
  1365. return b.length;
  1366. if (b.length === 0)
  1367. return a.length;
  1368. const matrix = [];
  1369. let i;
  1370. for (i = 0; i <= b.length; i++) {
  1371. matrix[i] = [i];
  1372. }
  1373. let j;
  1374. for (j = 0; j <= a.length; j++) {
  1375. matrix[0][j] = j;
  1376. }
  1377. for (i = 1; i <= b.length; i++) {
  1378. for (j = 1; j <= a.length; j++) {
  1379. if (b.charAt(i - 1) === a.charAt(j - 1)) {
  1380. matrix[i][j] = matrix[i - 1][j - 1];
  1381. }
  1382. else {
  1383. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
  1384. }
  1385. }
  1386. }
  1387. return matrix[b.length][a.length];
  1388. }
  1389. const specialKeys = ['$0', '--', '_'];
  1390. function validation(yargs, usage, y18n, shim) {
  1391. const __ = y18n.__;
  1392. const __n = y18n.__n;
  1393. const self = {};
  1394. self.nonOptionCount = function nonOptionCount(argv) {
  1395. const demandedCommands = yargs.getDemandedCommands();
  1396. const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
  1397. const _s = positionalCount - yargs.getContext().commands.length;
  1398. if (demandedCommands._ &&
  1399. (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
  1400. if (_s < demandedCommands._.min) {
  1401. if (demandedCommands._.minMsg !== undefined) {
  1402. usage.fail(demandedCommands._.minMsg
  1403. ? demandedCommands._.minMsg
  1404. .replace(/\$0/g, _s.toString())
  1405. .replace(/\$1/, demandedCommands._.min.toString())
  1406. : null);
  1407. }
  1408. else {
  1409. usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
  1410. }
  1411. }
  1412. else if (_s > demandedCommands._.max) {
  1413. if (demandedCommands._.maxMsg !== undefined) {
  1414. usage.fail(demandedCommands._.maxMsg
  1415. ? demandedCommands._.maxMsg
  1416. .replace(/\$0/g, _s.toString())
  1417. .replace(/\$1/, demandedCommands._.max.toString())
  1418. : null);
  1419. }
  1420. else {
  1421. usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
  1422. }
  1423. }
  1424. }
  1425. };
  1426. self.positionalCount = function positionalCount(required, observed) {
  1427. if (observed < required) {
  1428. usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
  1429. }
  1430. };
  1431. self.requiredArguments = function requiredArguments(argv) {
  1432. const demandedOptions = yargs.getDemandedOptions();
  1433. let missing = null;
  1434. for (const key of Object.keys(demandedOptions)) {
  1435. if (!Object.prototype.hasOwnProperty.call(argv, key) ||
  1436. typeof argv[key] === 'undefined') {
  1437. missing = missing || {};
  1438. missing[key] = demandedOptions[key];
  1439. }
  1440. }
  1441. if (missing) {
  1442. const customMsgs = [];
  1443. for (const key of Object.keys(missing)) {
  1444. const msg = missing[key];
  1445. if (msg && customMsgs.indexOf(msg) < 0) {
  1446. customMsgs.push(msg);
  1447. }
  1448. }
  1449. const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
  1450. usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
  1451. }
  1452. };
  1453. self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
  1454. const commandKeys = yargs.getCommandInstance().getCommands();
  1455. const unknown = [];
  1456. const currentContext = yargs.getContext();
  1457. Object.keys(argv).forEach(key => {
  1458. if (specialKeys.indexOf(key) === -1 &&
  1459. !Object.prototype.hasOwnProperty.call(positionalMap, key) &&
  1460. !Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) &&
  1461. !self.isValidAndSomeAliasIsNotNew(key, aliases)) {
  1462. unknown.push(key);
  1463. }
  1464. });
  1465. if (checkPositionals &&
  1466. (currentContext.commands.length > 0 ||
  1467. commandKeys.length > 0 ||
  1468. isDefaultCommand)) {
  1469. argv._.slice(currentContext.commands.length).forEach(key => {
  1470. if (commandKeys.indexOf('' + key) === -1) {
  1471. unknown.push('' + key);
  1472. }
  1473. });
  1474. }
  1475. if (unknown.length > 0) {
  1476. usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
  1477. }
  1478. };
  1479. self.unknownCommands = function unknownCommands(argv) {
  1480. const commandKeys = yargs.getCommandInstance().getCommands();
  1481. const unknown = [];
  1482. const currentContext = yargs.getContext();
  1483. if (currentContext.commands.length > 0 || commandKeys.length > 0) {
  1484. argv._.slice(currentContext.commands.length).forEach(key => {
  1485. if (commandKeys.indexOf('' + key) === -1) {
  1486. unknown.push('' + key);
  1487. }
  1488. });
  1489. }
  1490. if (unknown.length > 0) {
  1491. usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
  1492. return true;
  1493. }
  1494. else {
  1495. return false;
  1496. }
  1497. };
  1498. self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
  1499. if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
  1500. return false;
  1501. }
  1502. const newAliases = yargs.parsed.newAliases;
  1503. for (const a of [key, ...aliases[key]]) {
  1504. if (!Object.prototype.hasOwnProperty.call(newAliases, a) ||
  1505. !newAliases[key]) {
  1506. return true;
  1507. }
  1508. }
  1509. return false;
  1510. };
  1511. self.limitedChoices = function limitedChoices(argv) {
  1512. const options = yargs.getOptions();
  1513. const invalid = {};
  1514. if (!Object.keys(options.choices).length)
  1515. return;
  1516. Object.keys(argv).forEach(key => {
  1517. if (specialKeys.indexOf(key) === -1 &&
  1518. Object.prototype.hasOwnProperty.call(options.choices, key)) {
  1519. [].concat(argv[key]).forEach(value => {
  1520. if (options.choices[key].indexOf(value) === -1 &&
  1521. value !== undefined) {
  1522. invalid[key] = (invalid[key] || []).concat(value);
  1523. }
  1524. });
  1525. }
  1526. });
  1527. const invalidKeys = Object.keys(invalid);
  1528. if (!invalidKeys.length)
  1529. return;
  1530. let msg = __('Invalid values:');
  1531. invalidKeys.forEach(key => {
  1532. msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
  1533. });
  1534. usage.fail(msg);
  1535. };
  1536. let checks = [];
  1537. self.check = function check(f, global) {
  1538. checks.push({
  1539. func: f,
  1540. global,
  1541. });
  1542. };
  1543. self.customChecks = function customChecks(argv, aliases) {
  1544. for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
  1545. const func = f.func;
  1546. let result = null;
  1547. try {
  1548. result = func(argv, aliases);
  1549. }
  1550. catch (err) {
  1551. usage.fail(err.message ? err.message : err, err);
  1552. continue;
  1553. }
  1554. if (!result) {
  1555. usage.fail(__('Argument check failed: %s', func.toString()));
  1556. }
  1557. else if (typeof result === 'string' || result instanceof Error) {
  1558. usage.fail(result.toString(), result);
  1559. }
  1560. }
  1561. };
  1562. let implied = {};
  1563. self.implies = function implies(key, value) {
  1564. argsert('<string|object> [array|number|string]', [key, value], arguments.length);
  1565. if (typeof key === 'object') {
  1566. Object.keys(key).forEach(k => {
  1567. self.implies(k, key[k]);
  1568. });
  1569. }
  1570. else {
  1571. yargs.global(key);
  1572. if (!implied[key]) {
  1573. implied[key] = [];
  1574. }
  1575. if (Array.isArray(value)) {
  1576. value.forEach(i => self.implies(key, i));
  1577. }
  1578. else {
  1579. assertNotStrictEqual(value, undefined, shim);
  1580. implied[key].push(value);
  1581. }
  1582. }
  1583. };
  1584. self.getImplied = function getImplied() {
  1585. return implied;
  1586. };
  1587. function keyExists(argv, val) {
  1588. const num = Number(val);
  1589. val = isNaN(num) ? val : num;
  1590. if (typeof val === 'number') {
  1591. val = argv._.length >= val;
  1592. }
  1593. else if (val.match(/^--no-.+/)) {
  1594. val = val.match(/^--no-(.+)/)[1];
  1595. val = !argv[val];
  1596. }
  1597. else {
  1598. val = argv[val];
  1599. }
  1600. return val;
  1601. }
  1602. self.implications = function implications(argv) {
  1603. const implyFail = [];
  1604. Object.keys(implied).forEach(key => {
  1605. const origKey = key;
  1606. (implied[key] || []).forEach(value => {
  1607. let key = origKey;
  1608. const origValue = value;
  1609. key = keyExists(argv, key);
  1610. value = keyExists(argv, value);
  1611. if (key && !value) {
  1612. implyFail.push(` ${origKey} -> ${origValue}`);
  1613. }
  1614. });
  1615. });
  1616. if (implyFail.length) {
  1617. let msg = `${__('Implications failed:')}\n`;
  1618. implyFail.forEach(value => {
  1619. msg += value;
  1620. });
  1621. usage.fail(msg);
  1622. }
  1623. };
  1624. let conflicting = {};
  1625. self.conflicts = function conflicts(key, value) {
  1626. argsert('<string|object> [array|string]', [key, value], arguments.length);
  1627. if (typeof key === 'object') {
  1628. Object.keys(key).forEach(k => {
  1629. self.conflicts(k, key[k]);
  1630. });
  1631. }
  1632. else {
  1633. yargs.global(key);
  1634. if (!conflicting[key]) {
  1635. conflicting[key] = [];
  1636. }
  1637. if (Array.isArray(value)) {
  1638. value.forEach(i => self.conflicts(key, i));
  1639. }
  1640. else {
  1641. conflicting[key].push(value);
  1642. }
  1643. }
  1644. };
  1645. self.getConflicting = () => conflicting;
  1646. self.conflicting = function conflictingFn(argv) {
  1647. Object.keys(argv).forEach(key => {
  1648. if (conflicting[key]) {
  1649. conflicting[key].forEach(value => {
  1650. if (value && argv[key] !== undefined && argv[value] !== undefined) {
  1651. usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
  1652. }
  1653. });
  1654. }
  1655. });
  1656. };
  1657. self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
  1658. const threshold = 3;
  1659. potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
  1660. let recommended = null;
  1661. let bestDistance = Infinity;
  1662. for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
  1663. const d = levenshtein(cmd, candidate);
  1664. if (d <= threshold && d < bestDistance) {
  1665. bestDistance = d;
  1666. recommended = candidate;
  1667. }
  1668. }
  1669. if (recommended)
  1670. usage.fail(__('Did you mean %s?', recommended));
  1671. };
  1672. self.reset = function reset(localLookup) {
  1673. implied = objFilter(implied, k => !localLookup[k]);
  1674. conflicting = objFilter(conflicting, k => !localLookup[k]);
  1675. checks = checks.filter(c => c.global);
  1676. return self;
  1677. };
  1678. const frozens = [];
  1679. self.freeze = function freeze() {
  1680. frozens.push({
  1681. implied,
  1682. checks,
  1683. conflicting,
  1684. });
  1685. };
  1686. self.unfreeze = function unfreeze() {
  1687. const frozen = frozens.pop();
  1688. assertNotStrictEqual(frozen, undefined, shim);
  1689. ({ implied, checks, conflicting } = frozen);
  1690. };
  1691. return self;
  1692. }
  1693. let shim$1;
  1694. function YargsWithShim(_shim) {
  1695. shim$1 = _shim;
  1696. return Yargs;
  1697. }
  1698. function Yargs(processArgs = [], cwd = shim$1.process.cwd(), parentRequire) {
  1699. const self = {};
  1700. let command$1;
  1701. let completion$1 = null;
  1702. let groups = {};
  1703. const globalMiddleware = [];
  1704. let output = '';
  1705. const preservedGroups = {};
  1706. let usage$1;
  1707. let validation$1;
  1708. let handlerFinishCommand = null;
  1709. const y18n = shim$1.y18n;
  1710. self.middleware = globalMiddlewareFactory(globalMiddleware, self);
  1711. self.scriptName = function (scriptName) {
  1712. self.customScriptName = true;
  1713. self.$0 = scriptName;
  1714. return self;
  1715. };
  1716. let default$0;
  1717. if (/\b(node|iojs|electron)(\.exe)?$/.test(shim$1.process.argv()[0])) {
  1718. default$0 = shim$1.process.argv().slice(1, 2);
  1719. }
  1720. else {
  1721. default$0 = shim$1.process.argv().slice(0, 1);
  1722. }
  1723. self.$0 = default$0
  1724. .map(x => {
  1725. const b = rebase(cwd, x);
  1726. return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
  1727. })
  1728. .join(' ')
  1729. .trim();
  1730. if (shim$1.getEnv('_') && shim$1.getProcessArgvBin() === shim$1.getEnv('_')) {
  1731. self.$0 = shim$1
  1732. .getEnv('_')
  1733. .replace(`${shim$1.path.dirname(shim$1.process.execPath())}/`, '');
  1734. }
  1735. const context = { resets: -1, commands: [], fullCommands: [], files: [] };
  1736. self.getContext = () => context;
  1737. let hasOutput = false;
  1738. let exitError = null;
  1739. self.exit = (code, err) => {
  1740. hasOutput = true;
  1741. exitError = err;
  1742. if (exitProcess)
  1743. shim$1.process.exit(code);
  1744. };
  1745. let completionCommand = null;
  1746. self.completion = function (cmd, desc, fn) {
  1747. argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
  1748. if (typeof desc === 'function') {
  1749. fn = desc;
  1750. desc = undefined;
  1751. }
  1752. completionCommand = cmd || completionCommand || 'completion';
  1753. if (!desc && desc !== false) {
  1754. desc = 'generate completion script';
  1755. }
  1756. self.command(completionCommand, desc);
  1757. if (fn)
  1758. completion$1.registerFunction(fn);
  1759. return self;
  1760. };
  1761. let options;
  1762. self.resetOptions = self.reset = function resetOptions(aliases = {}) {
  1763. context.resets++;
  1764. options = options || {};
  1765. const tmpOptions = {};
  1766. tmpOptions.local = options.local ? options.local : [];
  1767. tmpOptions.configObjects = options.configObjects
  1768. ? options.configObjects
  1769. : [];
  1770. const localLookup = {};
  1771. tmpOptions.local.forEach(l => {
  1772. localLookup[l] = true;
  1773. (aliases[l] || []).forEach(a => {
  1774. localLookup[a] = true;
  1775. });
  1776. });
  1777. Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => {
  1778. const keys = groups[groupName].filter(key => !(key in localLookup));
  1779. if (keys.length > 0) {
  1780. acc[groupName] = keys;
  1781. }
  1782. return acc;
  1783. }, {}));
  1784. groups = {};
  1785. const arrayOptions = [
  1786. 'array',
  1787. 'boolean',
  1788. 'string',
  1789. 'skipValidation',
  1790. 'count',
  1791. 'normalize',
  1792. 'number',
  1793. 'hiddenOptions',
  1794. ];
  1795. const objectOptions = [
  1796. 'narg',
  1797. 'key',
  1798. 'alias',
  1799. 'default',
  1800. 'defaultDescription',
  1801. 'config',
  1802. 'choices',
  1803. 'demandedOptions',
  1804. 'demandedCommands',
  1805. 'coerce',
  1806. 'deprecatedOptions',
  1807. ];
  1808. arrayOptions.forEach(k => {
  1809. tmpOptions[k] = (options[k] || []).filter((k) => !localLookup[k]);
  1810. });
  1811. objectOptions.forEach((k) => {
  1812. tmpOptions[k] = objFilter(options[k], k => !localLookup[k]);
  1813. });
  1814. tmpOptions.envPrefix = options.envPrefix;
  1815. options = tmpOptions;
  1816. usage$1 = usage$1 ? usage$1.reset(localLookup) : usage(self, y18n, shim$1);
  1817. validation$1 = validation$1
  1818. ? validation$1.reset(localLookup)
  1819. : validation(self, usage$1, y18n, shim$1);
  1820. command$1 = command$1
  1821. ? command$1.reset()
  1822. : command(self, usage$1, validation$1, globalMiddleware, shim$1);
  1823. if (!completion$1)
  1824. completion$1 = completion(self, usage$1, command$1, shim$1);
  1825. completionCommand = null;
  1826. output = '';
  1827. exitError = null;
  1828. hasOutput = false;
  1829. self.parsed = false;
  1830. return self;
  1831. };
  1832. self.resetOptions();
  1833. const frozens = [];
  1834. function freeze() {
  1835. frozens.push({
  1836. options,
  1837. configObjects: options.configObjects.slice(0),
  1838. exitProcess,
  1839. groups,
  1840. strict,
  1841. strictCommands,
  1842. strictOptions,
  1843. completionCommand,
  1844. output,
  1845. exitError,
  1846. hasOutput,
  1847. parsed: self.parsed,
  1848. parseFn,
  1849. parseContext,
  1850. handlerFinishCommand,
  1851. });
  1852. usage$1.freeze();
  1853. validation$1.freeze();
  1854. command$1.freeze();
  1855. }
  1856. function unfreeze() {
  1857. const frozen = frozens.pop();
  1858. assertNotStrictEqual(frozen, undefined, shim$1);
  1859. let configObjects;
  1860. ({
  1861. options,
  1862. configObjects,
  1863. exitProcess,
  1864. groups,
  1865. output,
  1866. exitError,
  1867. hasOutput,
  1868. parsed: self.parsed,
  1869. strict,
  1870. strictCommands,
  1871. strictOptions,
  1872. completionCommand,
  1873. parseFn,
  1874. parseContext,
  1875. handlerFinishCommand,
  1876. } = frozen);
  1877. options.configObjects = configObjects;
  1878. usage$1.unfreeze();
  1879. validation$1.unfreeze();
  1880. command$1.unfreeze();
  1881. }
  1882. self.boolean = function (keys) {
  1883. argsert('<array|string>', [keys], arguments.length);
  1884. populateParserHintArray('boolean', keys);
  1885. return self;
  1886. };
  1887. self.array = function (keys) {
  1888. argsert('<array|string>', [keys], arguments.length);
  1889. populateParserHintArray('array', keys);
  1890. return self;
  1891. };
  1892. self.number = function (keys) {
  1893. argsert('<array|string>', [keys], arguments.length);
  1894. populateParserHintArray('number', keys);
  1895. return self;
  1896. };
  1897. self.normalize = function (keys) {
  1898. argsert('<array|string>', [keys], arguments.length);
  1899. populateParserHintArray('normalize', keys);
  1900. return self;
  1901. };
  1902. self.count = function (keys) {
  1903. argsert('<array|string>', [keys], arguments.length);
  1904. populateParserHintArray('count', keys);
  1905. return self;
  1906. };
  1907. self.string = function (keys) {
  1908. argsert('<array|string>', [keys], arguments.length);
  1909. populateParserHintArray('string', keys);
  1910. return self;
  1911. };
  1912. self.requiresArg = function (keys) {
  1913. argsert('<array|string|object> [number]', [keys], arguments.length);
  1914. if (typeof keys === 'string' && options.narg[keys]) {
  1915. return self;
  1916. }
  1917. else {
  1918. populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN);
  1919. }
  1920. return self;
  1921. };
  1922. self.skipValidation = function (keys) {
  1923. argsert('<array|string>', [keys], arguments.length);
  1924. populateParserHintArray('skipValidation', keys);
  1925. return self;
  1926. };
  1927. function populateParserHintArray(type, keys) {
  1928. keys = [].concat(keys);
  1929. keys.forEach(key => {
  1930. key = sanitizeKey(key);
  1931. options[type].push(key);
  1932. });
  1933. }
  1934. self.nargs = function (key, value) {
  1935. argsert('<string|object|array> [number]', [key, value], arguments.length);
  1936. populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value);
  1937. return self;
  1938. };
  1939. self.choices = function (key, value) {
  1940. argsert('<object|string|array> [string|array]', [key, value], arguments.length);
  1941. populateParserHintArrayDictionary(self.choices, 'choices', key, value);
  1942. return self;
  1943. };
  1944. self.alias = function (key, value) {
  1945. argsert('<object|string|array> [string|array]', [key, value], arguments.length);
  1946. populateParserHintArrayDictionary(self.alias, 'alias', key, value);
  1947. return self;
  1948. };
  1949. self.default = self.defaults = function (key, value, defaultDescription) {
  1950. argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
  1951. if (defaultDescription) {
  1952. assertSingleKey(key, shim$1);
  1953. options.defaultDescription[key] = defaultDescription;
  1954. }
  1955. if (typeof value === 'function') {
  1956. assertSingleKey(key, shim$1);
  1957. if (!options.defaultDescription[key])
  1958. options.defaultDescription[key] = usage$1.functionDescription(value);
  1959. value = value.call();
  1960. }
  1961. populateParserHintSingleValueDictionary(self.default, 'default', key, value);
  1962. return self;
  1963. };
  1964. self.describe = function (key, desc) {
  1965. argsert('<object|string|array> [string]', [key, desc], arguments.length);
  1966. setKey(key, true);
  1967. usage$1.describe(key, desc);
  1968. return self;
  1969. };
  1970. function setKey(key, set) {
  1971. populateParserHintSingleValueDictionary(setKey, 'key', key, set);
  1972. return self;
  1973. }
  1974. function demandOption(keys, msg) {
  1975. argsert('<object|string|array> [string]', [keys, msg], arguments.length);
  1976. populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg);
  1977. return self;
  1978. }
  1979. self.demandOption = demandOption;
  1980. self.coerce = function (keys, value) {
  1981. argsert('<object|string|array> [function]', [keys, value], arguments.length);
  1982. populateParserHintSingleValueDictionary(self.coerce, 'coerce', keys, value);
  1983. return self;
  1984. };
  1985. function populateParserHintSingleValueDictionary(builder, type, key, value) {
  1986. populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
  1987. options[type][key] = value;
  1988. });
  1989. }
  1990. function populateParserHintArrayDictionary(builder, type, key, value) {
  1991. populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
  1992. options[type][key] = (options[type][key] || []).concat(value);
  1993. });
  1994. }
  1995. function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) {
  1996. if (Array.isArray(key)) {
  1997. key.forEach(k => {
  1998. builder(k, value);
  1999. });
  2000. }
  2001. else if (((key) => typeof key === 'object')(key)) {
  2002. for (const k of objectKeys(key)) {
  2003. builder(k, key[k]);
  2004. }
  2005. }
  2006. else {
  2007. singleKeyHandler(type, sanitizeKey(key), value);
  2008. }
  2009. }
  2010. function sanitizeKey(key) {
  2011. if (key === '__proto__')
  2012. return '___proto___';
  2013. return key;
  2014. }
  2015. function deleteFromParserHintObject(optionKey) {
  2016. objectKeys(options).forEach((hintKey) => {
  2017. if (((key) => key === 'configObjects')(hintKey))
  2018. return;
  2019. const hint = options[hintKey];
  2020. if (Array.isArray(hint)) {
  2021. if (~hint.indexOf(optionKey))
  2022. hint.splice(hint.indexOf(optionKey), 1);
  2023. }
  2024. else if (typeof hint === 'object') {
  2025. delete hint[optionKey];
  2026. }
  2027. });
  2028. delete usage$1.getDescriptions()[optionKey];
  2029. }
  2030. self.config = function config(key = 'config', msg, parseFn) {
  2031. argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
  2032. if (typeof key === 'object' && !Array.isArray(key)) {
  2033. key = applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
  2034. options.configObjects = (options.configObjects || []).concat(key);
  2035. return self;
  2036. }
  2037. if (typeof msg === 'function') {
  2038. parseFn = msg;
  2039. msg = undefined;
  2040. }
  2041. self.describe(key, msg || usage$1.deferY18nLookup('Path to JSON config file'));
  2042. (Array.isArray(key) ? key : [key]).forEach(k => {
  2043. options.config[k] = parseFn || true;
  2044. });
  2045. return self;
  2046. };
  2047. self.example = function (cmd, description) {
  2048. argsert('<string|array> [string]', [cmd, description], arguments.length);
  2049. if (Array.isArray(cmd)) {
  2050. cmd.forEach(exampleParams => self.example(...exampleParams));
  2051. }
  2052. else {
  2053. usage$1.example(cmd, description);
  2054. }
  2055. return self;
  2056. };
  2057. self.command = function (cmd, description, builder, handler, middlewares, deprecated) {
  2058. argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
  2059. command$1.addHandler(cmd, description, builder, handler, middlewares, deprecated);
  2060. return self;
  2061. };
  2062. self.commandDir = function (dir, opts) {
  2063. argsert('<string> [object]', [dir, opts], arguments.length);
  2064. const req = parentRequire || shim$1.require;
  2065. command$1.addDirectory(dir, self.getContext(), req, shim$1.getCallerFile(), opts);
  2066. return self;
  2067. };
  2068. self.demand = self.required = self.require = function demand(keys, max, msg) {
  2069. if (Array.isArray(max)) {
  2070. max.forEach(key => {
  2071. assertNotStrictEqual(msg, true, shim$1);
  2072. demandOption(key, msg);
  2073. });
  2074. max = Infinity;
  2075. }
  2076. else if (typeof max !== 'number') {
  2077. msg = max;
  2078. max = Infinity;
  2079. }
  2080. if (typeof keys === 'number') {
  2081. assertNotStrictEqual(msg, true, shim$1);
  2082. self.demandCommand(keys, max, msg, msg);
  2083. }
  2084. else if (Array.isArray(keys)) {
  2085. keys.forEach(key => {
  2086. assertNotStrictEqual(msg, true, shim$1);
  2087. demandOption(key, msg);
  2088. });
  2089. }
  2090. else {
  2091. if (typeof msg === 'string') {
  2092. demandOption(keys, msg);
  2093. }
  2094. else if (msg === true || typeof msg === 'undefined') {
  2095. demandOption(keys);
  2096. }
  2097. }
  2098. return self;
  2099. };
  2100. self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) {
  2101. argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
  2102. if (typeof max !== 'number') {
  2103. minMsg = max;
  2104. max = Infinity;
  2105. }
  2106. self.global('_', false);
  2107. options.demandedCommands._ = {
  2108. min,
  2109. max,
  2110. minMsg,
  2111. maxMsg,
  2112. };
  2113. return self;
  2114. };
  2115. self.getDemandedOptions = () => {
  2116. argsert([], 0);
  2117. return options.demandedOptions;
  2118. };
  2119. self.getDemandedCommands = () => {
  2120. argsert([], 0);
  2121. return options.demandedCommands;
  2122. };
  2123. self.deprecateOption = function deprecateOption(option, message) {
  2124. argsert('<string> [string|boolean]', [option, message], arguments.length);
  2125. options.deprecatedOptions[option] = message;
  2126. return self;
  2127. };
  2128. self.getDeprecatedOptions = () => {
  2129. argsert([], 0);
  2130. return options.deprecatedOptions;
  2131. };
  2132. self.implies = function (key, value) {
  2133. argsert('<string|object> [number|string|array]', [key, value], arguments.length);
  2134. validation$1.implies(key, value);
  2135. return self;
  2136. };
  2137. self.conflicts = function (key1, key2) {
  2138. argsert('<string|object> [string|array]', [key1, key2], arguments.length);
  2139. validation$1.conflicts(key1, key2);
  2140. return self;
  2141. };
  2142. self.usage = function (msg, description, builder, handler) {
  2143. argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
  2144. if (description !== undefined) {
  2145. assertNotStrictEqual(msg, null, shim$1);
  2146. if ((msg || '').match(/^\$0( |$)/)) {
  2147. return self.command(msg, description, builder, handler);
  2148. }
  2149. else {
  2150. throw new YError('.usage() description must start with $0 if being used as alias for .command()');
  2151. }
  2152. }
  2153. else {
  2154. usage$1.usage(msg);
  2155. return self;
  2156. }
  2157. };
  2158. self.epilogue = self.epilog = function (msg) {
  2159. argsert('<string>', [msg], arguments.length);
  2160. usage$1.epilog(msg);
  2161. return self;
  2162. };
  2163. self.fail = function (f) {
  2164. argsert('<function>', [f], arguments.length);
  2165. usage$1.failFn(f);
  2166. return self;
  2167. };
  2168. self.onFinishCommand = function (f) {
  2169. argsert('<function>', [f], arguments.length);
  2170. handlerFinishCommand = f;
  2171. return self;
  2172. };
  2173. self.getHandlerFinishCommand = () => handlerFinishCommand;
  2174. self.check = function (f, _global) {
  2175. argsert('<function> [boolean]', [f, _global], arguments.length);
  2176. validation$1.check(f, _global !== false);
  2177. return self;
  2178. };
  2179. self.global = function global(globals, global) {
  2180. argsert('<string|array> [boolean]', [globals, global], arguments.length);
  2181. globals = [].concat(globals);
  2182. if (global !== false) {
  2183. options.local = options.local.filter(l => globals.indexOf(l) === -1);
  2184. }
  2185. else {
  2186. globals.forEach(g => {
  2187. if (options.local.indexOf(g) === -1)
  2188. options.local.push(g);
  2189. });
  2190. }
  2191. return self;
  2192. };
  2193. self.pkgConf = function pkgConf(key, rootPath) {
  2194. argsert('<string> [string]', [key, rootPath], arguments.length);
  2195. let conf = null;
  2196. const obj = pkgUp(rootPath || cwd);
  2197. if (obj[key] && typeof obj[key] === 'object') {
  2198. conf = applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
  2199. options.configObjects = (options.configObjects || []).concat(conf);
  2200. }
  2201. return self;
  2202. };
  2203. const pkgs = {};
  2204. function pkgUp(rootPath) {
  2205. const npath = rootPath || '*';
  2206. if (pkgs[npath])
  2207. return pkgs[npath];
  2208. let obj = {};
  2209. try {
  2210. let startDir = rootPath || shim$1.mainFilename;
  2211. if (!rootPath && shim$1.path.extname(startDir)) {
  2212. startDir = shim$1.path.dirname(startDir);
  2213. }
  2214. const pkgJsonPath = shim$1.findUp(startDir, (dir, names) => {
  2215. if (names.includes('package.json')) {
  2216. return 'package.json';
  2217. }
  2218. else {
  2219. return undefined;
  2220. }
  2221. });
  2222. assertNotStrictEqual(pkgJsonPath, undefined, shim$1);
  2223. obj = JSON.parse(shim$1.readFileSync(pkgJsonPath, 'utf8'));
  2224. }
  2225. catch (_noop) { }
  2226. pkgs[npath] = obj || {};
  2227. return pkgs[npath];
  2228. }
  2229. let parseFn = null;
  2230. let parseContext = null;
  2231. self.parse = function parse(args, shortCircuit, _parseFn) {
  2232. argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
  2233. freeze();
  2234. if (typeof args === 'undefined') {
  2235. const argv = self._parseArgs(processArgs);
  2236. const tmpParsed = self.parsed;
  2237. unfreeze();
  2238. self.parsed = tmpParsed;
  2239. return argv;
  2240. }
  2241. if (typeof shortCircuit === 'object') {
  2242. parseContext = shortCircuit;
  2243. shortCircuit = _parseFn;
  2244. }
  2245. if (typeof shortCircuit === 'function') {
  2246. parseFn = shortCircuit;
  2247. shortCircuit = false;
  2248. }
  2249. if (!shortCircuit)
  2250. processArgs = args;
  2251. if (parseFn)
  2252. exitProcess = false;
  2253. const parsed = self._parseArgs(args, !!shortCircuit);
  2254. completion$1.setParsed(self.parsed);
  2255. if (parseFn)
  2256. parseFn(exitError, parsed, output);
  2257. unfreeze();
  2258. return parsed;
  2259. };
  2260. self._getParseContext = () => parseContext || {};
  2261. self._hasParseCallback = () => !!parseFn;
  2262. self.option = self.options = function option(key, opt) {
  2263. argsert('<string|object> [object]', [key, opt], arguments.length);
  2264. if (typeof key === 'object') {
  2265. Object.keys(key).forEach(k => {
  2266. self.options(k, key[k]);
  2267. });
  2268. }
  2269. else {
  2270. if (typeof opt !== 'object') {
  2271. opt = {};
  2272. }
  2273. options.key[key] = true;
  2274. if (opt.alias)
  2275. self.alias(key, opt.alias);
  2276. const deprecate = opt.deprecate || opt.deprecated;
  2277. if (deprecate) {
  2278. self.deprecateOption(key, deprecate);
  2279. }
  2280. const demand = opt.demand || opt.required || opt.require;
  2281. if (demand) {
  2282. self.demand(key, demand);
  2283. }
  2284. if (opt.demandOption) {
  2285. self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
  2286. }
  2287. if (opt.conflicts) {
  2288. self.conflicts(key, opt.conflicts);
  2289. }
  2290. if ('default' in opt) {
  2291. self.default(key, opt.default);
  2292. }
  2293. if (opt.implies !== undefined) {
  2294. self.implies(key, opt.implies);
  2295. }
  2296. if (opt.nargs !== undefined) {
  2297. self.nargs(key, opt.nargs);
  2298. }
  2299. if (opt.config) {
  2300. self.config(key, opt.configParser);
  2301. }
  2302. if (opt.normalize) {
  2303. self.normalize(key);
  2304. }
  2305. if (opt.choices) {
  2306. self.choices(key, opt.choices);
  2307. }
  2308. if (opt.coerce) {
  2309. self.coerce(key, opt.coerce);
  2310. }
  2311. if (opt.group) {
  2312. self.group(key, opt.group);
  2313. }
  2314. if (opt.boolean || opt.type === 'boolean') {
  2315. self.boolean(key);
  2316. if (opt.alias)
  2317. self.boolean(opt.alias);
  2318. }
  2319. if (opt.array || opt.type === 'array') {
  2320. self.array(key);
  2321. if (opt.alias)
  2322. self.array(opt.alias);
  2323. }
  2324. if (opt.number || opt.type === 'number') {
  2325. self.number(key);
  2326. if (opt.alias)
  2327. self.number(opt.alias);
  2328. }
  2329. if (opt.string || opt.type === 'string') {
  2330. self.string(key);
  2331. if (opt.alias)
  2332. self.string(opt.alias);
  2333. }
  2334. if (opt.count || opt.type === 'count') {
  2335. self.count(key);
  2336. }
  2337. if (typeof opt.global === 'boolean') {
  2338. self.global(key, opt.global);
  2339. }
  2340. if (opt.defaultDescription) {
  2341. options.defaultDescription[key] = opt.defaultDescription;
  2342. }
  2343. if (opt.skipValidation) {
  2344. self.skipValidation(key);
  2345. }
  2346. const desc = opt.describe || opt.description || opt.desc;
  2347. self.describe(key, desc);
  2348. if (opt.hidden) {
  2349. self.hide(key);
  2350. }
  2351. if (opt.requiresArg) {
  2352. self.requiresArg(key);
  2353. }
  2354. }
  2355. return self;
  2356. };
  2357. self.getOptions = () => options;
  2358. self.positional = function (key, opts) {
  2359. argsert('<string> <object>', [key, opts], arguments.length);
  2360. if (context.resets === 0) {
  2361. throw new YError(".positional() can only be called in a command's builder function");
  2362. }
  2363. const supportedOpts = [
  2364. 'default',
  2365. 'defaultDescription',
  2366. 'implies',
  2367. 'normalize',
  2368. 'choices',
  2369. 'conflicts',
  2370. 'coerce',
  2371. 'type',
  2372. 'describe',
  2373. 'desc',
  2374. 'description',
  2375. 'alias',
  2376. ];
  2377. opts = objFilter(opts, (k, v) => {
  2378. let accept = supportedOpts.indexOf(k) !== -1;
  2379. if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1)
  2380. accept = false;
  2381. return accept;
  2382. });
  2383. const fullCommand = context.fullCommands[context.fullCommands.length - 1];
  2384. const parseOptions = fullCommand
  2385. ? command$1.cmdToParseOptions(fullCommand)
  2386. : {
  2387. array: [],
  2388. alias: {},
  2389. default: {},
  2390. demand: {},
  2391. };
  2392. objectKeys(parseOptions).forEach(pk => {
  2393. const parseOption = parseOptions[pk];
  2394. if (Array.isArray(parseOption)) {
  2395. if (parseOption.indexOf(key) !== -1)
  2396. opts[pk] = true;
  2397. }
  2398. else {
  2399. if (parseOption[key] && !(pk in opts))
  2400. opts[pk] = parseOption[key];
  2401. }
  2402. });
  2403. self.group(key, usage$1.getPositionalGroupName());
  2404. return self.option(key, opts);
  2405. };
  2406. self.group = function group(opts, groupName) {
  2407. argsert('<string|array> <string>', [opts, groupName], arguments.length);
  2408. const existing = preservedGroups[groupName] || groups[groupName];
  2409. if (preservedGroups[groupName]) {
  2410. delete preservedGroups[groupName];
  2411. }
  2412. const seen = {};
  2413. groups[groupName] = (existing || []).concat(opts).filter(key => {
  2414. if (seen[key])
  2415. return false;
  2416. return (seen[key] = true);
  2417. });
  2418. return self;
  2419. };
  2420. self.getGroups = () => Object.assign({}, groups, preservedGroups);
  2421. self.env = function (prefix) {
  2422. argsert('[string|boolean]', [prefix], arguments.length);
  2423. if (prefix === false)
  2424. delete options.envPrefix;
  2425. else
  2426. options.envPrefix = prefix || '';
  2427. return self;
  2428. };
  2429. self.wrap = function (cols) {
  2430. argsert('<number|null|undefined>', [cols], arguments.length);
  2431. usage$1.wrap(cols);
  2432. return self;
  2433. };
  2434. let strict = false;
  2435. self.strict = function (enabled) {
  2436. argsert('[boolean]', [enabled], arguments.length);
  2437. strict = enabled !== false;
  2438. return self;
  2439. };
  2440. self.getStrict = () => strict;
  2441. let strictCommands = false;
  2442. self.strictCommands = function (enabled) {
  2443. argsert('[boolean]', [enabled], arguments.length);
  2444. strictCommands = enabled !== false;
  2445. return self;
  2446. };
  2447. self.getStrictCommands = () => strictCommands;
  2448. let strictOptions = false;
  2449. self.strictOptions = function (enabled) {
  2450. argsert('[boolean]', [enabled], arguments.length);
  2451. strictOptions = enabled !== false;
  2452. return self;
  2453. };
  2454. self.getStrictOptions = () => strictOptions;
  2455. let parserConfig = {};
  2456. self.parserConfiguration = function parserConfiguration(config) {
  2457. argsert('<object>', [config], arguments.length);
  2458. parserConfig = config;
  2459. return self;
  2460. };
  2461. self.getParserConfiguration = () => parserConfig;
  2462. self.showHelp = function (level) {
  2463. argsert('[string|function]', [level], arguments.length);
  2464. if (!self.parsed)
  2465. self._parseArgs(processArgs);
  2466. if (command$1.hasDefaultCommand()) {
  2467. context.resets++;
  2468. command$1.runDefaultBuilderOn(self);
  2469. }
  2470. usage$1.showHelp(level);
  2471. return self;
  2472. };
  2473. let versionOpt = null;
  2474. self.version = function version(opt, msg, ver) {
  2475. const defaultVersionOpt = 'version';
  2476. argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
  2477. if (versionOpt) {
  2478. deleteFromParserHintObject(versionOpt);
  2479. usage$1.version(undefined);
  2480. versionOpt = null;
  2481. }
  2482. if (arguments.length === 0) {
  2483. ver = guessVersion();
  2484. opt = defaultVersionOpt;
  2485. }
  2486. else if (arguments.length === 1) {
  2487. if (opt === false) {
  2488. return self;
  2489. }
  2490. ver = opt;
  2491. opt = defaultVersionOpt;
  2492. }
  2493. else if (arguments.length === 2) {
  2494. ver = msg;
  2495. msg = undefined;
  2496. }
  2497. versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
  2498. msg = msg || usage$1.deferY18nLookup('Show version number');
  2499. usage$1.version(ver || undefined);
  2500. self.boolean(versionOpt);
  2501. self.describe(versionOpt, msg);
  2502. return self;
  2503. };
  2504. function guessVersion() {
  2505. const obj = pkgUp();
  2506. return obj.version || 'unknown';
  2507. }
  2508. let helpOpt = null;
  2509. self.addHelpOpt = self.help = function addHelpOpt(opt, msg) {
  2510. const defaultHelpOpt = 'help';
  2511. argsert('[string|boolean] [string]', [opt, msg], arguments.length);
  2512. if (helpOpt) {
  2513. deleteFromParserHintObject(helpOpt);
  2514. helpOpt = null;
  2515. }
  2516. if (arguments.length === 1) {
  2517. if (opt === false)
  2518. return self;
  2519. }
  2520. helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
  2521. self.boolean(helpOpt);
  2522. self.describe(helpOpt, msg || usage$1.deferY18nLookup('Show help'));
  2523. return self;
  2524. };
  2525. const defaultShowHiddenOpt = 'show-hidden';
  2526. options.showHiddenOpt = defaultShowHiddenOpt;
  2527. self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) {
  2528. argsert('[string|boolean] [string]', [opt, msg], arguments.length);
  2529. if (arguments.length === 1) {
  2530. if (opt === false)
  2531. return self;
  2532. }
  2533. const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt;
  2534. self.boolean(showHiddenOpt);
  2535. self.describe(showHiddenOpt, msg || usage$1.deferY18nLookup('Show hidden options'));
  2536. options.showHiddenOpt = showHiddenOpt;
  2537. return self;
  2538. };
  2539. self.hide = function hide(key) {
  2540. argsert('<string>', [key], arguments.length);
  2541. options.hiddenOptions.push(key);
  2542. return self;
  2543. };
  2544. self.showHelpOnFail = function showHelpOnFail(enabled, message) {
  2545. argsert('[boolean|string] [string]', [enabled, message], arguments.length);
  2546. usage$1.showHelpOnFail(enabled, message);
  2547. return self;
  2548. };
  2549. let exitProcess = true;
  2550. self.exitProcess = function (enabled = true) {
  2551. argsert('[boolean]', [enabled], arguments.length);
  2552. exitProcess = enabled;
  2553. return self;
  2554. };
  2555. self.getExitProcess = () => exitProcess;
  2556. self.showCompletionScript = function ($0, cmd) {
  2557. argsert('[string] [string]', [$0, cmd], arguments.length);
  2558. $0 = $0 || self.$0;
  2559. _logger.log(completion$1.generateCompletionScript($0, cmd || completionCommand || 'completion'));
  2560. return self;
  2561. };
  2562. self.getCompletion = function (args, done) {
  2563. argsert('<array> <function>', [args, done], arguments.length);
  2564. completion$1.getCompletion(args, done);
  2565. };
  2566. self.locale = function (locale) {
  2567. argsert('[string]', [locale], arguments.length);
  2568. if (!locale) {
  2569. guessLocale();
  2570. return y18n.getLocale();
  2571. }
  2572. detectLocale = false;
  2573. y18n.setLocale(locale);
  2574. return self;
  2575. };
  2576. self.updateStrings = self.updateLocale = function (obj) {
  2577. argsert('<object>', [obj], arguments.length);
  2578. detectLocale = false;
  2579. y18n.updateLocale(obj);
  2580. return self;
  2581. };
  2582. let detectLocale = true;
  2583. self.detectLocale = function (detect) {
  2584. argsert('<boolean>', [detect], arguments.length);
  2585. detectLocale = detect;
  2586. return self;
  2587. };
  2588. self.getDetectLocale = () => detectLocale;
  2589. const _logger = {
  2590. log(...args) {
  2591. if (!self._hasParseCallback())
  2592. console.log(...args);
  2593. hasOutput = true;
  2594. if (output.length)
  2595. output += '\n';
  2596. output += args.join(' ');
  2597. },
  2598. error(...args) {
  2599. if (!self._hasParseCallback())
  2600. console.error(...args);
  2601. hasOutput = true;
  2602. if (output.length)
  2603. output += '\n';
  2604. output += args.join(' ');
  2605. },
  2606. };
  2607. self._getLoggerInstance = () => _logger;
  2608. self._hasOutput = () => hasOutput;
  2609. self._setHasOutput = () => {
  2610. hasOutput = true;
  2611. };
  2612. let recommendCommands;
  2613. self.recommendCommands = function (recommend = true) {
  2614. argsert('[boolean]', [recommend], arguments.length);
  2615. recommendCommands = recommend;
  2616. return self;
  2617. };
  2618. self.getUsageInstance = () => usage$1;
  2619. self.getValidationInstance = () => validation$1;
  2620. self.getCommandInstance = () => command$1;
  2621. self.terminalWidth = () => {
  2622. argsert([], 0);
  2623. return shim$1.process.stdColumns;
  2624. };
  2625. Object.defineProperty(self, 'argv', {
  2626. get: () => self._parseArgs(processArgs),
  2627. enumerable: true,
  2628. });
  2629. self._parseArgs = function parseArgs(args, shortCircuit, _calledFromCommand, commandIndex) {
  2630. let skipValidation = !!_calledFromCommand;
  2631. args = args || processArgs;
  2632. options.__ = y18n.__;
  2633. options.configuration = self.getParserConfiguration();
  2634. const populateDoubleDash = !!options.configuration['populate--'];
  2635. const config = Object.assign({}, options.configuration, {
  2636. 'populate--': true,
  2637. });
  2638. const parsed = shim$1.Parser.detailed(args, Object.assign({}, options, {
  2639. configuration: Object.assign({ 'parse-positional-numbers': false }, config),
  2640. }));
  2641. let argv = parsed.argv;
  2642. if (parseContext)
  2643. argv = Object.assign({}, argv, parseContext);
  2644. const aliases = parsed.aliases;
  2645. argv.$0 = self.$0;
  2646. self.parsed = parsed;
  2647. try {
  2648. guessLocale();
  2649. if (shortCircuit) {
  2650. return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
  2651. }
  2652. if (helpOpt) {
  2653. const helpCmds = [helpOpt]
  2654. .concat(aliases[helpOpt] || [])
  2655. .filter(k => k.length > 1);
  2656. if (~helpCmds.indexOf('' + argv._[argv._.length - 1])) {
  2657. argv._.pop();
  2658. argv[helpOpt] = true;
  2659. }
  2660. }
  2661. const handlerKeys = command$1.getCommands();
  2662. const requestCompletions = completion$1.completionKey in argv;
  2663. const skipRecommendation = argv[helpOpt] || requestCompletions;
  2664. const skipDefaultCommand = skipRecommendation &&
  2665. (handlerKeys.length > 1 || handlerKeys[0] !== '$0');
  2666. if (argv._.length) {
  2667. if (handlerKeys.length) {
  2668. let firstUnknownCommand;
  2669. for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
  2670. cmd = String(argv._[i]);
  2671. if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
  2672. const innerArgv = command$1.runCommand(cmd, self, parsed, i + 1);
  2673. return self._postProcess(innerArgv, populateDoubleDash);
  2674. }
  2675. else if (!firstUnknownCommand && cmd !== completionCommand) {
  2676. firstUnknownCommand = cmd;
  2677. break;
  2678. }
  2679. }
  2680. if (command$1.hasDefaultCommand() && !skipDefaultCommand) {
  2681. const innerArgv = command$1.runCommand(null, self, parsed);
  2682. return self._postProcess(innerArgv, populateDoubleDash);
  2683. }
  2684. if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
  2685. validation$1.recommendCommands(firstUnknownCommand, handlerKeys);
  2686. }
  2687. }
  2688. if (completionCommand &&
  2689. ~argv._.indexOf(completionCommand) &&
  2690. !requestCompletions) {
  2691. if (exitProcess)
  2692. setBlocking(true);
  2693. self.showCompletionScript();
  2694. self.exit(0);
  2695. }
  2696. }
  2697. else if (command$1.hasDefaultCommand() && !skipDefaultCommand) {
  2698. const innerArgv = command$1.runCommand(null, self, parsed);
  2699. return self._postProcess(innerArgv, populateDoubleDash);
  2700. }
  2701. if (requestCompletions) {
  2702. if (exitProcess)
  2703. setBlocking(true);
  2704. args = [].concat(args);
  2705. const completionArgs = args.slice(args.indexOf(`--${completion$1.completionKey}`) + 1);
  2706. completion$1.getCompletion(completionArgs, completions => {
  2707. (completions || []).forEach(completion => {
  2708. _logger.log(completion);
  2709. });
  2710. self.exit(0);
  2711. });
  2712. return self._postProcess(argv, !populateDoubleDash, _calledFromCommand);
  2713. }
  2714. if (!hasOutput) {
  2715. Object.keys(argv).forEach(key => {
  2716. if (key === helpOpt && argv[key]) {
  2717. if (exitProcess)
  2718. setBlocking(true);
  2719. skipValidation = true;
  2720. self.showHelp('log');
  2721. self.exit(0);
  2722. }
  2723. else if (key === versionOpt && argv[key]) {
  2724. if (exitProcess)
  2725. setBlocking(true);
  2726. skipValidation = true;
  2727. usage$1.showVersion();
  2728. self.exit(0);
  2729. }
  2730. });
  2731. }
  2732. if (!skipValidation && options.skipValidation.length > 0) {
  2733. skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true);
  2734. }
  2735. if (!skipValidation) {
  2736. if (parsed.error)
  2737. throw new YError(parsed.error.message);
  2738. if (!requestCompletions) {
  2739. self._runValidation(argv, aliases, {}, parsed.error);
  2740. }
  2741. }
  2742. }
  2743. catch (err) {
  2744. if (err instanceof YError)
  2745. usage$1.fail(err.message, err);
  2746. else
  2747. throw err;
  2748. }
  2749. return self._postProcess(argv, populateDoubleDash, _calledFromCommand);
  2750. };
  2751. self._postProcess = function (argv, populateDoubleDash, calledFromCommand = false) {
  2752. if (isPromise(argv))
  2753. return argv;
  2754. if (calledFromCommand)
  2755. return argv;
  2756. if (!populateDoubleDash) {
  2757. argv = self._copyDoubleDash(argv);
  2758. }
  2759. const parsePositionalNumbers = self.getParserConfiguration()['parse-positional-numbers'] ||
  2760. self.getParserConfiguration()['parse-positional-numbers'] === undefined;
  2761. if (parsePositionalNumbers) {
  2762. argv = self._parsePositionalNumbers(argv);
  2763. }
  2764. return argv;
  2765. };
  2766. self._copyDoubleDash = function (argv) {
  2767. if (!argv._ || !argv['--'])
  2768. return argv;
  2769. argv._.push.apply(argv._, argv['--']);
  2770. try {
  2771. delete argv['--'];
  2772. }
  2773. catch (_err) { }
  2774. return argv;
  2775. };
  2776. self._parsePositionalNumbers = function (argv) {
  2777. const args = argv['--'] ? argv['--'] : argv._;
  2778. for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
  2779. if (shim$1.Parser.looksLikeNumber(arg) &&
  2780. Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
  2781. args[i] = Number(arg);
  2782. }
  2783. }
  2784. return argv;
  2785. };
  2786. self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors, isDefaultCommand = false) {
  2787. if (parseErrors)
  2788. throw new YError(parseErrors.message);
  2789. validation$1.nonOptionCount(argv);
  2790. validation$1.requiredArguments(argv);
  2791. let failedStrictCommands = false;
  2792. if (strictCommands) {
  2793. failedStrictCommands = validation$1.unknownCommands(argv);
  2794. }
  2795. if (strict && !failedStrictCommands) {
  2796. validation$1.unknownArguments(argv, aliases, positionalMap, isDefaultCommand);
  2797. }
  2798. else if (strictOptions) {
  2799. validation$1.unknownArguments(argv, aliases, {}, false, false);
  2800. }
  2801. validation$1.customChecks(argv, aliases);
  2802. validation$1.limitedChoices(argv);
  2803. validation$1.implications(argv);
  2804. validation$1.conflicting(argv);
  2805. };
  2806. function guessLocale() {
  2807. if (!detectLocale)
  2808. return;
  2809. const locale = shim$1.getEnv('LC_ALL') ||
  2810. shim$1.getEnv('LC_MESSAGES') ||
  2811. shim$1.getEnv('LANG') ||
  2812. shim$1.getEnv('LANGUAGE') ||
  2813. 'en_US';
  2814. self.locale(locale.replace(/[.:].*/, ''));
  2815. }
  2816. self.help();
  2817. self.version();
  2818. return self;
  2819. }
  2820. const rebase = (base, dir) => shim$1.path.relative(base, dir);
  2821. function isYargsInstance(y) {
  2822. return !!y && typeof y._parseArgs === 'function';
  2823. }
  2824. var _a, _b;
  2825. const { readFileSync } = require('fs');
  2826. const { inspect } = require('util');
  2827. const { resolve } = require('path');
  2828. const y18n = require('y18n');
  2829. const Parser = require('yargs-parser');
  2830. var cjsPlatformShim = {
  2831. assert: {
  2832. notStrictEqual: assert.notStrictEqual,
  2833. strictEqual: assert.strictEqual,
  2834. },
  2835. cliui: require('cliui'),
  2836. findUp: require('escalade/sync'),
  2837. getEnv: (key) => {
  2838. return process.env[key];
  2839. },
  2840. getCallerFile: require('get-caller-file'),
  2841. getProcessArgvBin: getProcessArgvBin,
  2842. inspect,
  2843. mainFilename: (_b = (_a = require === null || require === void 0 ? void 0 : require.main) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : process.cwd(),
  2844. Parser,
  2845. path: require('path'),
  2846. process: {
  2847. argv: () => process.argv,
  2848. cwd: process.cwd,
  2849. execPath: () => process.execPath,
  2850. exit: (code) => {
  2851. process.exit(code);
  2852. },
  2853. nextTick: process.nextTick,
  2854. stdColumns: typeof process.stdout.columns !== 'undefined'
  2855. ? process.stdout.columns
  2856. : null,
  2857. },
  2858. readFileSync,
  2859. require: require,
  2860. requireDirectory: require('require-directory'),
  2861. stringWidth: require('string-width'),
  2862. y18n: y18n({
  2863. directory: resolve(__dirname, '../locales'),
  2864. updateFiles: false,
  2865. }),
  2866. };
  2867. const minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION
  2868. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  2869. : 10;
  2870. if (process && process.version) {
  2871. const major = Number(process.version.match(/v([^.]+)/)[1]);
  2872. if (major < minNodeVersion) {
  2873. throw Error(`yargs supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs#supported-nodejs-versions`);
  2874. }
  2875. }
  2876. const Parser$1 = require('yargs-parser');
  2877. const Yargs$1 = YargsWithShim(cjsPlatformShim);
  2878. var cjs = {
  2879. applyExtends,
  2880. cjsPlatformShim,
  2881. Yargs: Yargs$1,
  2882. argsert,
  2883. globalMiddlewareFactory,
  2884. isPromise,
  2885. objFilter,
  2886. parseCommand,
  2887. Parser: Parser$1,
  2888. processArgv,
  2889. rebase,
  2890. YError,
  2891. };
  2892. module.exports = cjs;