index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Main entrypoint for libraries using yargs-parser in Node.js
  2. // CJS and ESM environments:
  3. import { format } from 'util';
  4. import { readFileSync } from 'fs';
  5. import { normalize, resolve } from 'path';
  6. import { camelCase, decamelize, looksLikeNumber } from './string-utils.js';
  7. import { YargsParser } from './yargs-parser.js';
  8. // See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
  9. // version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
  10. const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
  11. ? Number(process.env.YARGS_MIN_NODE_VERSION)
  12. : 10;
  13. if (process && process.version) {
  14. const major = Number(process.version.match(/v([^.]+)/)[1]);
  15. if (major < minNodeVersion) {
  16. 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`);
  17. }
  18. }
  19. // Creates a yargs-parser instance using Node.js standard libraries:
  20. const env = process ? process.env : {};
  21. const parser = new YargsParser({
  22. cwd: process.cwd,
  23. env: () => {
  24. return env;
  25. },
  26. format,
  27. normalize,
  28. resolve,
  29. // TODO: figure out a way to combine ESM and CJS coverage, such that
  30. // we can exercise all the lines below:
  31. require: (path) => {
  32. if (typeof require !== 'undefined') {
  33. return require(path);
  34. }
  35. else if (path.match(/\.json$/)) {
  36. return readFileSync(path, 'utf8');
  37. }
  38. else {
  39. throw Error('only .json config files are supported in ESM');
  40. }
  41. }
  42. });
  43. const yargsParser = function Parser(args, opts) {
  44. const result = parser.parse(args.slice(), opts);
  45. return result.argv;
  46. };
  47. yargsParser.detailed = function (args, opts) {
  48. return parser.parse(args.slice(), opts);
  49. };
  50. yargsParser.camelCase = camelCase;
  51. yargsParser.decamelize = decamelize;
  52. yargsParser.looksLikeNumber = looksLikeNumber;
  53. export default yargsParser;