index.cjs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. 'use strict';
  2. var util = require('util');
  3. var fs = require('fs');
  4. var path = require('path');
  5. function camelCase(str) {
  6. const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  7. if (!isCamelCase) {
  8. str = str.toLocaleLowerCase();
  9. }
  10. if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
  11. return str;
  12. }
  13. else {
  14. let camelcase = '';
  15. let nextChrUpper = false;
  16. const leadingHyphens = str.match(/^-+/);
  17. for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
  18. let chr = str.charAt(i);
  19. if (nextChrUpper) {
  20. nextChrUpper = false;
  21. chr = chr.toLocaleUpperCase();
  22. }
  23. if (i !== 0 && (chr === '-' || chr === '_')) {
  24. nextChrUpper = true;
  25. }
  26. else if (chr !== '-' && chr !== '_') {
  27. camelcase += chr;
  28. }
  29. }
  30. return camelcase;
  31. }
  32. }
  33. function decamelize(str, joinString) {
  34. const lowercase = str.toLocaleLowerCase();
  35. joinString = joinString || '-';
  36. let notCamelcase = '';
  37. for (let i = 0; i < str.length; i++) {
  38. const chrLower = lowercase.charAt(i);
  39. const chrString = str.charAt(i);
  40. if (chrLower !== chrString && i > 0) {
  41. notCamelcase += `${joinString}${lowercase.charAt(i)}`;
  42. }
  43. else {
  44. notCamelcase += chrString;
  45. }
  46. }
  47. return notCamelcase;
  48. }
  49. function looksLikeNumber(x) {
  50. if (x === null || x === undefined)
  51. return false;
  52. if (typeof x === 'number')
  53. return true;
  54. if (/^0x[0-9a-f]+$/i.test(x))
  55. return true;
  56. if (x.length > 1 && x[0] === '0')
  57. return false;
  58. return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  59. }
  60. function tokenizeArgString(argString) {
  61. if (Array.isArray(argString)) {
  62. return argString.map(e => typeof e !== 'string' ? e + '' : e);
  63. }
  64. argString = argString.trim();
  65. let i = 0;
  66. let prevC = null;
  67. let c = null;
  68. let opening = null;
  69. const args = [];
  70. for (let ii = 0; ii < argString.length; ii++) {
  71. prevC = c;
  72. c = argString.charAt(ii);
  73. if (c === ' ' && !opening) {
  74. if (!(prevC === ' ')) {
  75. i++;
  76. }
  77. continue;
  78. }
  79. if (c === opening) {
  80. opening = null;
  81. }
  82. else if ((c === "'" || c === '"') && !opening) {
  83. opening = c;
  84. }
  85. if (!args[i])
  86. args[i] = '';
  87. args[i] += c;
  88. }
  89. return args;
  90. }
  91. let mixin;
  92. class YargsParser {
  93. constructor(_mixin) {
  94. mixin = _mixin;
  95. }
  96. parse(argsInput, options) {
  97. const opts = Object.assign({
  98. alias: undefined,
  99. array: undefined,
  100. boolean: undefined,
  101. config: undefined,
  102. configObjects: undefined,
  103. configuration: undefined,
  104. coerce: undefined,
  105. count: undefined,
  106. default: undefined,
  107. envPrefix: undefined,
  108. narg: undefined,
  109. normalize: undefined,
  110. string: undefined,
  111. number: undefined,
  112. __: undefined,
  113. key: undefined
  114. }, options);
  115. const args = tokenizeArgString(argsInput);
  116. const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
  117. const configuration = Object.assign({
  118. 'boolean-negation': true,
  119. 'camel-case-expansion': true,
  120. 'combine-arrays': false,
  121. 'dot-notation': true,
  122. 'duplicate-arguments-array': true,
  123. 'flatten-duplicate-arrays': true,
  124. 'greedy-arrays': true,
  125. 'halt-at-non-option': false,
  126. 'nargs-eats-options': false,
  127. 'negation-prefix': 'no-',
  128. 'parse-numbers': true,
  129. 'parse-positional-numbers': true,
  130. 'populate--': false,
  131. 'set-placeholder-key': false,
  132. 'short-option-groups': true,
  133. 'strip-aliased': false,
  134. 'strip-dashed': false,
  135. 'unknown-options-as-args': false
  136. }, opts.configuration);
  137. const defaults = Object.assign(Object.create(null), opts.default);
  138. const configObjects = opts.configObjects || [];
  139. const envPrefix = opts.envPrefix;
  140. const notFlagsOption = configuration['populate--'];
  141. const notFlagsArgv = notFlagsOption ? '--' : '_';
  142. const newAliases = Object.create(null);
  143. const defaulted = Object.create(null);
  144. const __ = opts.__ || mixin.format;
  145. const flags = {
  146. aliases: Object.create(null),
  147. arrays: Object.create(null),
  148. bools: Object.create(null),
  149. strings: Object.create(null),
  150. numbers: Object.create(null),
  151. counts: Object.create(null),
  152. normalize: Object.create(null),
  153. configs: Object.create(null),
  154. nargs: Object.create(null),
  155. coercions: Object.create(null),
  156. keys: []
  157. };
  158. const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
  159. const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
  160. [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
  161. const key = typeof opt === 'object' ? opt.key : opt;
  162. const assignment = Object.keys(opt).map(function (key) {
  163. const arrayFlagKeys = {
  164. boolean: 'bools',
  165. string: 'strings',
  166. number: 'numbers'
  167. };
  168. return arrayFlagKeys[key];
  169. }).filter(Boolean).pop();
  170. if (assignment) {
  171. flags[assignment][key] = true;
  172. }
  173. flags.arrays[key] = true;
  174. flags.keys.push(key);
  175. });
  176. [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
  177. flags.bools[key] = true;
  178. flags.keys.push(key);
  179. });
  180. [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
  181. flags.strings[key] = true;
  182. flags.keys.push(key);
  183. });
  184. [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
  185. flags.numbers[key] = true;
  186. flags.keys.push(key);
  187. });
  188. [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
  189. flags.counts[key] = true;
  190. flags.keys.push(key);
  191. });
  192. [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
  193. flags.normalize[key] = true;
  194. flags.keys.push(key);
  195. });
  196. if (typeof opts.narg === 'object') {
  197. Object.entries(opts.narg).forEach(([key, value]) => {
  198. if (typeof value === 'number') {
  199. flags.nargs[key] = value;
  200. flags.keys.push(key);
  201. }
  202. });
  203. }
  204. if (typeof opts.coerce === 'object') {
  205. Object.entries(opts.coerce).forEach(([key, value]) => {
  206. if (typeof value === 'function') {
  207. flags.coercions[key] = value;
  208. flags.keys.push(key);
  209. }
  210. });
  211. }
  212. if (typeof opts.config !== 'undefined') {
  213. if (Array.isArray(opts.config) || typeof opts.config === 'string') {
  214. [].concat(opts.config).filter(Boolean).forEach(function (key) {
  215. flags.configs[key] = true;
  216. });
  217. }
  218. else if (typeof opts.config === 'object') {
  219. Object.entries(opts.config).forEach(([key, value]) => {
  220. if (typeof value === 'boolean' || typeof value === 'function') {
  221. flags.configs[key] = value;
  222. }
  223. });
  224. }
  225. }
  226. extendAliases(opts.key, aliases, opts.default, flags.arrays);
  227. Object.keys(defaults).forEach(function (key) {
  228. (flags.aliases[key] || []).forEach(function (alias) {
  229. defaults[alias] = defaults[key];
  230. });
  231. });
  232. let error = null;
  233. checkConfiguration();
  234. let notFlags = [];
  235. const argv = Object.assign(Object.create(null), { _: [] });
  236. const argvReturn = {};
  237. for (let i = 0; i < args.length; i++) {
  238. const arg = args[i];
  239. let broken;
  240. let key;
  241. let letters;
  242. let m;
  243. let next;
  244. let value;
  245. if (arg !== '--' && isUnknownOptionAsArg(arg)) {
  246. pushPositional(arg);
  247. }
  248. else if (arg.match(/---+(=|$)/)) {
  249. pushPositional(arg);
  250. continue;
  251. }
  252. else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
  253. m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
  254. if (m !== null && Array.isArray(m) && m.length >= 3) {
  255. if (checkAllAliases(m[1], flags.arrays)) {
  256. i = eatArray(i, m[1], args, m[2]);
  257. }
  258. else if (checkAllAliases(m[1], flags.nargs) !== false) {
  259. i = eatNargs(i, m[1], args, m[2]);
  260. }
  261. else {
  262. setArg(m[1], m[2]);
  263. }
  264. }
  265. }
  266. else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
  267. m = arg.match(negatedBoolean);
  268. if (m !== null && Array.isArray(m) && m.length >= 2) {
  269. key = m[1];
  270. setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
  271. }
  272. }
  273. else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
  274. m = arg.match(/^--?(.+)/);
  275. if (m !== null && Array.isArray(m) && m.length >= 2) {
  276. key = m[1];
  277. if (checkAllAliases(key, flags.arrays)) {
  278. i = eatArray(i, key, args);
  279. }
  280. else if (checkAllAliases(key, flags.nargs) !== false) {
  281. i = eatNargs(i, key, args);
  282. }
  283. else {
  284. next = args[i + 1];
  285. if (next !== undefined && (!next.match(/^-/) ||
  286. next.match(negative)) &&
  287. !checkAllAliases(key, flags.bools) &&
  288. !checkAllAliases(key, flags.counts)) {
  289. setArg(key, next);
  290. i++;
  291. }
  292. else if (/^(true|false)$/.test(next)) {
  293. setArg(key, next);
  294. i++;
  295. }
  296. else {
  297. setArg(key, defaultValue(key));
  298. }
  299. }
  300. }
  301. }
  302. else if (arg.match(/^-.\..+=/)) {
  303. m = arg.match(/^-([^=]+)=([\s\S]*)$/);
  304. if (m !== null && Array.isArray(m) && m.length >= 3) {
  305. setArg(m[1], m[2]);
  306. }
  307. }
  308. else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
  309. next = args[i + 1];
  310. m = arg.match(/^-(.\..+)/);
  311. if (m !== null && Array.isArray(m) && m.length >= 2) {
  312. key = m[1];
  313. if (next !== undefined && !next.match(/^-/) &&
  314. !checkAllAliases(key, flags.bools) &&
  315. !checkAllAliases(key, flags.counts)) {
  316. setArg(key, next);
  317. i++;
  318. }
  319. else {
  320. setArg(key, defaultValue(key));
  321. }
  322. }
  323. }
  324. else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
  325. letters = arg.slice(1, -1).split('');
  326. broken = false;
  327. for (let j = 0; j < letters.length; j++) {
  328. next = arg.slice(j + 2);
  329. if (letters[j + 1] && letters[j + 1] === '=') {
  330. value = arg.slice(j + 3);
  331. key = letters[j];
  332. if (checkAllAliases(key, flags.arrays)) {
  333. i = eatArray(i, key, args, value);
  334. }
  335. else if (checkAllAliases(key, flags.nargs) !== false) {
  336. i = eatNargs(i, key, args, value);
  337. }
  338. else {
  339. setArg(key, value);
  340. }
  341. broken = true;
  342. break;
  343. }
  344. if (next === '-') {
  345. setArg(letters[j], next);
  346. continue;
  347. }
  348. if (/[A-Za-z]/.test(letters[j]) &&
  349. /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
  350. checkAllAliases(next, flags.bools) === false) {
  351. setArg(letters[j], next);
  352. broken = true;
  353. break;
  354. }
  355. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  356. setArg(letters[j], next);
  357. broken = true;
  358. break;
  359. }
  360. else {
  361. setArg(letters[j], defaultValue(letters[j]));
  362. }
  363. }
  364. key = arg.slice(-1)[0];
  365. if (!broken && key !== '-') {
  366. if (checkAllAliases(key, flags.arrays)) {
  367. i = eatArray(i, key, args);
  368. }
  369. else if (checkAllAliases(key, flags.nargs) !== false) {
  370. i = eatNargs(i, key, args);
  371. }
  372. else {
  373. next = args[i + 1];
  374. if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
  375. next.match(negative)) &&
  376. !checkAllAliases(key, flags.bools) &&
  377. !checkAllAliases(key, flags.counts)) {
  378. setArg(key, next);
  379. i++;
  380. }
  381. else if (/^(true|false)$/.test(next)) {
  382. setArg(key, next);
  383. i++;
  384. }
  385. else {
  386. setArg(key, defaultValue(key));
  387. }
  388. }
  389. }
  390. }
  391. else if (arg.match(/^-[0-9]$/) &&
  392. arg.match(negative) &&
  393. checkAllAliases(arg.slice(1), flags.bools)) {
  394. key = arg.slice(1);
  395. setArg(key, defaultValue(key));
  396. }
  397. else if (arg === '--') {
  398. notFlags = args.slice(i + 1);
  399. break;
  400. }
  401. else if (configuration['halt-at-non-option']) {
  402. notFlags = args.slice(i);
  403. break;
  404. }
  405. else {
  406. pushPositional(arg);
  407. }
  408. }
  409. applyEnvVars(argv, true);
  410. applyEnvVars(argv, false);
  411. setConfig(argv);
  412. setConfigObjects();
  413. applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
  414. applyCoercions(argv);
  415. if (configuration['set-placeholder-key'])
  416. setPlaceholderKeys(argv);
  417. Object.keys(flags.counts).forEach(function (key) {
  418. if (!hasKey(argv, key.split('.')))
  419. setArg(key, 0);
  420. });
  421. if (notFlagsOption && notFlags.length)
  422. argv[notFlagsArgv] = [];
  423. notFlags.forEach(function (key) {
  424. argv[notFlagsArgv].push(key);
  425. });
  426. if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
  427. Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
  428. delete argv[key];
  429. });
  430. }
  431. if (configuration['strip-aliased']) {
  432. [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
  433. if (configuration['camel-case-expansion'] && alias.includes('-')) {
  434. delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
  435. }
  436. delete argv[alias];
  437. });
  438. }
  439. function pushPositional(arg) {
  440. const maybeCoercedNumber = maybeCoerceNumber('_', arg);
  441. if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
  442. argv._.push(maybeCoercedNumber);
  443. }
  444. }
  445. function eatNargs(i, key, args, argAfterEqualSign) {
  446. let ii;
  447. let toEat = checkAllAliases(key, flags.nargs);
  448. toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
  449. if (toEat === 0) {
  450. if (!isUndefined(argAfterEqualSign)) {
  451. error = Error(__('Argument unexpected for: %s', key));
  452. }
  453. setArg(key, defaultValue(key));
  454. return i;
  455. }
  456. let available = isUndefined(argAfterEqualSign) ? 0 : 1;
  457. if (configuration['nargs-eats-options']) {
  458. if (args.length - (i + 1) + available < toEat) {
  459. error = Error(__('Not enough arguments following: %s', key));
  460. }
  461. available = toEat;
  462. }
  463. else {
  464. for (ii = i + 1; ii < args.length; ii++) {
  465. if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
  466. available++;
  467. else
  468. break;
  469. }
  470. if (available < toEat)
  471. error = Error(__('Not enough arguments following: %s', key));
  472. }
  473. let consumed = Math.min(available, toEat);
  474. if (!isUndefined(argAfterEqualSign) && consumed > 0) {
  475. setArg(key, argAfterEqualSign);
  476. consumed--;
  477. }
  478. for (ii = i + 1; ii < (consumed + i + 1); ii++) {
  479. setArg(key, args[ii]);
  480. }
  481. return (i + consumed);
  482. }
  483. function eatArray(i, key, args, argAfterEqualSign) {
  484. let argsToSet = [];
  485. let next = argAfterEqualSign || args[i + 1];
  486. const nargsCount = checkAllAliases(key, flags.nargs);
  487. if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
  488. argsToSet.push(true);
  489. }
  490. else if (isUndefined(next) ||
  491. (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
  492. if (defaults[key] !== undefined) {
  493. const defVal = defaults[key];
  494. argsToSet = Array.isArray(defVal) ? defVal : [defVal];
  495. }
  496. }
  497. else {
  498. if (!isUndefined(argAfterEqualSign)) {
  499. argsToSet.push(processValue(key, argAfterEqualSign));
  500. }
  501. for (let ii = i + 1; ii < args.length; ii++) {
  502. if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
  503. (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
  504. break;
  505. next = args[ii];
  506. if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
  507. break;
  508. i = ii;
  509. argsToSet.push(processValue(key, next));
  510. }
  511. }
  512. if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
  513. (isNaN(nargsCount) && argsToSet.length === 0))) {
  514. error = Error(__('Not enough arguments following: %s', key));
  515. }
  516. setArg(key, argsToSet);
  517. return i;
  518. }
  519. function setArg(key, val) {
  520. if (/-/.test(key) && configuration['camel-case-expansion']) {
  521. const alias = key.split('.').map(function (prop) {
  522. return camelCase(prop);
  523. }).join('.');
  524. addNewAlias(key, alias);
  525. }
  526. const value = processValue(key, val);
  527. const splitKey = key.split('.');
  528. setKey(argv, splitKey, value);
  529. if (flags.aliases[key]) {
  530. flags.aliases[key].forEach(function (x) {
  531. const keyProperties = x.split('.');
  532. setKey(argv, keyProperties, value);
  533. });
  534. }
  535. if (splitKey.length > 1 && configuration['dot-notation']) {
  536. (flags.aliases[splitKey[0]] || []).forEach(function (x) {
  537. let keyProperties = x.split('.');
  538. const a = [].concat(splitKey);
  539. a.shift();
  540. keyProperties = keyProperties.concat(a);
  541. if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
  542. setKey(argv, keyProperties, value);
  543. }
  544. });
  545. }
  546. if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
  547. const keys = [key].concat(flags.aliases[key] || []);
  548. keys.forEach(function (key) {
  549. Object.defineProperty(argvReturn, key, {
  550. enumerable: true,
  551. get() {
  552. return val;
  553. },
  554. set(value) {
  555. val = typeof value === 'string' ? mixin.normalize(value) : value;
  556. }
  557. });
  558. });
  559. }
  560. }
  561. function addNewAlias(key, alias) {
  562. if (!(flags.aliases[key] && flags.aliases[key].length)) {
  563. flags.aliases[key] = [alias];
  564. newAliases[alias] = true;
  565. }
  566. if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
  567. addNewAlias(alias, key);
  568. }
  569. }
  570. function processValue(key, val) {
  571. if (typeof val === 'string' &&
  572. (val[0] === "'" || val[0] === '"') &&
  573. val[val.length - 1] === val[0]) {
  574. val = val.substring(1, val.length - 1);
  575. }
  576. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  577. if (typeof val === 'string')
  578. val = val === 'true';
  579. }
  580. let value = Array.isArray(val)
  581. ? val.map(function (v) { return maybeCoerceNumber(key, v); })
  582. : maybeCoerceNumber(key, val);
  583. if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
  584. value = increment();
  585. }
  586. if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
  587. if (Array.isArray(val))
  588. value = val.map((val) => { return mixin.normalize(val); });
  589. else
  590. value = mixin.normalize(val);
  591. }
  592. return value;
  593. }
  594. function maybeCoerceNumber(key, value) {
  595. if (!configuration['parse-positional-numbers'] && key === '_')
  596. return value;
  597. if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
  598. const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
  599. if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
  600. value = Number(value);
  601. }
  602. }
  603. return value;
  604. }
  605. function setConfig(argv) {
  606. const configLookup = Object.create(null);
  607. applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
  608. Object.keys(flags.configs).forEach(function (configKey) {
  609. const configPath = argv[configKey] || configLookup[configKey];
  610. if (configPath) {
  611. try {
  612. let config = null;
  613. const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
  614. const resolveConfig = flags.configs[configKey];
  615. if (typeof resolveConfig === 'function') {
  616. try {
  617. config = resolveConfig(resolvedConfigPath);
  618. }
  619. catch (e) {
  620. config = e;
  621. }
  622. if (config instanceof Error) {
  623. error = config;
  624. return;
  625. }
  626. }
  627. else {
  628. config = mixin.require(resolvedConfigPath);
  629. }
  630. setConfigObject(config);
  631. }
  632. catch (ex) {
  633. if (ex.name === 'PermissionDenied')
  634. error = ex;
  635. else if (argv[configKey])
  636. error = Error(__('Invalid JSON config file: %s', configPath));
  637. }
  638. }
  639. });
  640. }
  641. function setConfigObject(config, prev) {
  642. Object.keys(config).forEach(function (key) {
  643. const value = config[key];
  644. const fullKey = prev ? prev + '.' + key : key;
  645. if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
  646. setConfigObject(value, fullKey);
  647. }
  648. else {
  649. if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
  650. setArg(fullKey, value);
  651. }
  652. }
  653. });
  654. }
  655. function setConfigObjects() {
  656. if (typeof configObjects !== 'undefined') {
  657. configObjects.forEach(function (configObject) {
  658. setConfigObject(configObject);
  659. });
  660. }
  661. }
  662. function applyEnvVars(argv, configOnly) {
  663. if (typeof envPrefix === 'undefined')
  664. return;
  665. const prefix = typeof envPrefix === 'string' ? envPrefix : '';
  666. const env = mixin.env();
  667. Object.keys(env).forEach(function (envVar) {
  668. if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
  669. const keys = envVar.split('__').map(function (key, i) {
  670. if (i === 0) {
  671. key = key.substring(prefix.length);
  672. }
  673. return camelCase(key);
  674. });
  675. if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
  676. setArg(keys.join('.'), env[envVar]);
  677. }
  678. }
  679. });
  680. }
  681. function applyCoercions(argv) {
  682. let coerce;
  683. const applied = new Set();
  684. Object.keys(argv).forEach(function (key) {
  685. if (!applied.has(key)) {
  686. coerce = checkAllAliases(key, flags.coercions);
  687. if (typeof coerce === 'function') {
  688. try {
  689. const value = maybeCoerceNumber(key, coerce(argv[key]));
  690. ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
  691. applied.add(ali);
  692. argv[ali] = value;
  693. });
  694. }
  695. catch (err) {
  696. error = err;
  697. }
  698. }
  699. }
  700. });
  701. }
  702. function setPlaceholderKeys(argv) {
  703. flags.keys.forEach((key) => {
  704. if (~key.indexOf('.'))
  705. return;
  706. if (typeof argv[key] === 'undefined')
  707. argv[key] = undefined;
  708. });
  709. return argv;
  710. }
  711. function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
  712. Object.keys(defaults).forEach(function (key) {
  713. if (!hasKey(obj, key.split('.'))) {
  714. setKey(obj, key.split('.'), defaults[key]);
  715. if (canLog)
  716. defaulted[key] = true;
  717. (aliases[key] || []).forEach(function (x) {
  718. if (hasKey(obj, x.split('.')))
  719. return;
  720. setKey(obj, x.split('.'), defaults[key]);
  721. });
  722. }
  723. });
  724. }
  725. function hasKey(obj, keys) {
  726. let o = obj;
  727. if (!configuration['dot-notation'])
  728. keys = [keys.join('.')];
  729. keys.slice(0, -1).forEach(function (key) {
  730. o = (o[key] || {});
  731. });
  732. const key = keys[keys.length - 1];
  733. if (typeof o !== 'object')
  734. return false;
  735. else
  736. return key in o;
  737. }
  738. function setKey(obj, keys, value) {
  739. let o = obj;
  740. if (!configuration['dot-notation'])
  741. keys = [keys.join('.')];
  742. keys.slice(0, -1).forEach(function (key) {
  743. key = sanitizeKey(key);
  744. if (typeof o === 'object' && o[key] === undefined) {
  745. o[key] = {};
  746. }
  747. if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
  748. if (Array.isArray(o[key])) {
  749. o[key].push({});
  750. }
  751. else {
  752. o[key] = [o[key], {}];
  753. }
  754. o = o[key][o[key].length - 1];
  755. }
  756. else {
  757. o = o[key];
  758. }
  759. });
  760. const key = sanitizeKey(keys[keys.length - 1]);
  761. const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
  762. const isValueArray = Array.isArray(value);
  763. let duplicate = configuration['duplicate-arguments-array'];
  764. if (!duplicate && checkAllAliases(key, flags.nargs)) {
  765. duplicate = true;
  766. if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
  767. o[key] = undefined;
  768. }
  769. }
  770. if (value === increment()) {
  771. o[key] = increment(o[key]);
  772. }
  773. else if (Array.isArray(o[key])) {
  774. if (duplicate && isTypeArray && isValueArray) {
  775. o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
  776. }
  777. else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
  778. o[key] = value;
  779. }
  780. else {
  781. o[key] = o[key].concat([value]);
  782. }
  783. }
  784. else if (o[key] === undefined && isTypeArray) {
  785. o[key] = isValueArray ? value : [value];
  786. }
  787. else if (duplicate && !(o[key] === undefined ||
  788. checkAllAliases(key, flags.counts) ||
  789. checkAllAliases(key, flags.bools))) {
  790. o[key] = [o[key], value];
  791. }
  792. else {
  793. o[key] = value;
  794. }
  795. }
  796. function extendAliases(...args) {
  797. args.forEach(function (obj) {
  798. Object.keys(obj || {}).forEach(function (key) {
  799. if (flags.aliases[key])
  800. return;
  801. flags.aliases[key] = [].concat(aliases[key] || []);
  802. flags.aliases[key].concat(key).forEach(function (x) {
  803. if (/-/.test(x) && configuration['camel-case-expansion']) {
  804. const c = camelCase(x);
  805. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  806. flags.aliases[key].push(c);
  807. newAliases[c] = true;
  808. }
  809. }
  810. });
  811. flags.aliases[key].concat(key).forEach(function (x) {
  812. if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
  813. const c = decamelize(x, '-');
  814. if (c !== key && flags.aliases[key].indexOf(c) === -1) {
  815. flags.aliases[key].push(c);
  816. newAliases[c] = true;
  817. }
  818. }
  819. });
  820. flags.aliases[key].forEach(function (x) {
  821. flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
  822. return x !== y;
  823. }));
  824. });
  825. });
  826. });
  827. }
  828. function checkAllAliases(key, flag) {
  829. const toCheck = [].concat(flags.aliases[key] || [], key);
  830. const keys = Object.keys(flag);
  831. const setAlias = toCheck.find(key => keys.includes(key));
  832. return setAlias ? flag[setAlias] : false;
  833. }
  834. function hasAnyFlag(key) {
  835. const flagsKeys = Object.keys(flags);
  836. const toCheck = [].concat(flagsKeys.map(k => flags[k]));
  837. return toCheck.some(function (flag) {
  838. return Array.isArray(flag) ? flag.includes(key) : flag[key];
  839. });
  840. }
  841. function hasFlagsMatching(arg, ...patterns) {
  842. const toCheck = [].concat(...patterns);
  843. return toCheck.some(function (pattern) {
  844. const match = arg.match(pattern);
  845. return match && hasAnyFlag(match[1]);
  846. });
  847. }
  848. function hasAllShortFlags(arg) {
  849. if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
  850. return false;
  851. }
  852. let hasAllFlags = true;
  853. let next;
  854. const letters = arg.slice(1).split('');
  855. for (let j = 0; j < letters.length; j++) {
  856. next = arg.slice(j + 2);
  857. if (!hasAnyFlag(letters[j])) {
  858. hasAllFlags = false;
  859. break;
  860. }
  861. if ((letters[j + 1] && letters[j + 1] === '=') ||
  862. next === '-' ||
  863. (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
  864. (letters[j + 1] && letters[j + 1].match(/\W/))) {
  865. break;
  866. }
  867. }
  868. return hasAllFlags;
  869. }
  870. function isUnknownOptionAsArg(arg) {
  871. return configuration['unknown-options-as-args'] && isUnknownOption(arg);
  872. }
  873. function isUnknownOption(arg) {
  874. if (arg.match(negative)) {
  875. return false;
  876. }
  877. if (hasAllShortFlags(arg)) {
  878. return false;
  879. }
  880. const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
  881. const normalFlag = /^-+([^=]+?)$/;
  882. const flagEndingInHyphen = /^-+([^=]+?)-$/;
  883. const flagEndingInDigits = /^-+([^=]+?\d+)$/;
  884. const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
  885. return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
  886. }
  887. function defaultValue(key) {
  888. if (!checkAllAliases(key, flags.bools) &&
  889. !checkAllAliases(key, flags.counts) &&
  890. `${key}` in defaults) {
  891. return defaults[key];
  892. }
  893. else {
  894. return defaultForType(guessType(key));
  895. }
  896. }
  897. function defaultForType(type) {
  898. const def = {
  899. boolean: true,
  900. string: '',
  901. number: undefined,
  902. array: []
  903. };
  904. return def[type];
  905. }
  906. function guessType(key) {
  907. let type = 'boolean';
  908. if (checkAllAliases(key, flags.strings))
  909. type = 'string';
  910. else if (checkAllAliases(key, flags.numbers))
  911. type = 'number';
  912. else if (checkAllAliases(key, flags.bools))
  913. type = 'boolean';
  914. else if (checkAllAliases(key, flags.arrays))
  915. type = 'array';
  916. return type;
  917. }
  918. function isUndefined(num) {
  919. return num === undefined;
  920. }
  921. function checkConfiguration() {
  922. Object.keys(flags.counts).find(key => {
  923. if (checkAllAliases(key, flags.arrays)) {
  924. error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
  925. return true;
  926. }
  927. else if (checkAllAliases(key, flags.nargs)) {
  928. error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
  929. return true;
  930. }
  931. return false;
  932. });
  933. }
  934. return {
  935. aliases: Object.assign({}, flags.aliases),
  936. argv: Object.assign(argvReturn, argv),
  937. configuration: configuration,
  938. defaulted: Object.assign({}, defaulted),
  939. error: error,
  940. newAliases: Object.assign({}, newAliases)
  941. };
  942. }
  943. }
  944. function combineAliases(aliases) {
  945. const aliasArrays = [];
  946. const combined = Object.create(null);
  947. let change = true;
  948. Object.keys(aliases).forEach(function (key) {
  949. aliasArrays.push([].concat(aliases[key], key));
  950. });
  951. while (change) {
  952. change = false;
  953. for (let i = 0; i < aliasArrays.length; i++) {
  954. for (let ii = i + 1; ii < aliasArrays.length; ii++) {
  955. const intersect = aliasArrays[i].filter(function (v) {
  956. return aliasArrays[ii].indexOf(v) !== -1;
  957. });
  958. if (intersect.length) {
  959. aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
  960. aliasArrays.splice(ii, 1);
  961. change = true;
  962. break;
  963. }
  964. }
  965. }
  966. }
  967. aliasArrays.forEach(function (aliasArray) {
  968. aliasArray = aliasArray.filter(function (v, i, self) {
  969. return self.indexOf(v) === i;
  970. });
  971. const lastAlias = aliasArray.pop();
  972. if (lastAlias !== undefined && typeof lastAlias === 'string') {
  973. combined[lastAlias] = aliasArray;
  974. }
  975. });
  976. return combined;
  977. }
  978. function increment(orig) {
  979. return orig !== undefined ? orig + 1 : 1;
  980. }
  981. function sanitizeKey(key) {
  982. if (key === '__proto__')
  983. return '___proto___';
  984. return key;
  985. }
  986. const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
  987. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  988. : 10;
  989. if (process && process.version) {
  990. const major = Number(process.version.match(/v([^.]+)/)[1]);
  991. if (major < minNodeVersion) {
  992. throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
  993. }
  994. }
  995. const env = process ? process.env : {};
  996. const parser = new YargsParser({
  997. cwd: process.cwd,
  998. env: () => {
  999. return env;
  1000. },
  1001. format: util.format,
  1002. normalize: path.normalize,
  1003. resolve: path.resolve,
  1004. require: (path) => {
  1005. if (typeof require !== 'undefined') {
  1006. return require(path);
  1007. }
  1008. else if (path.match(/\.json$/)) {
  1009. return fs.readFileSync(path, 'utf8');
  1010. }
  1011. else {
  1012. throw Error('only .json config files are supported in ESM');
  1013. }
  1014. }
  1015. });
  1016. const yargsParser = function Parser(args, opts) {
  1017. const result = parser.parse(args.slice(), opts);
  1018. return result.argv;
  1019. };
  1020. yargsParser.detailed = function (args, opts) {
  1021. return parser.parse(args.slice(), opts);
  1022. };
  1023. yargsParser.camelCase = camelCase;
  1024. yargsParser.decamelize = decamelize;
  1025. yargsParser.looksLikeNumber = looksLikeNumber;
  1026. module.exports = yargsParser;