index.js 2.4 KB

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