apply-extends.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.applyExtends = void 0;
  4. const fs = require("fs");
  5. const path = require("path");
  6. const yerror_1 = require("./yerror");
  7. let previouslyVisitedConfigs = [];
  8. function checkForCircularExtends(cfgPath) {
  9. if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
  10. throw new yerror_1.YError(`Circular extended configurations: '${cfgPath}'.`);
  11. }
  12. }
  13. function getPathToDefaultConfig(cwd, pathToExtend) {
  14. return path.resolve(cwd, pathToExtend);
  15. }
  16. function mergeDeep(config1, config2) {
  17. const target = {};
  18. function isObject(obj) {
  19. return obj && typeof obj === 'object' && !Array.isArray(obj);
  20. }
  21. Object.assign(target, config1);
  22. for (const key of Object.keys(config2)) {
  23. if (isObject(config2[key]) && isObject(target[key])) {
  24. target[key] = mergeDeep(config1[key], config2[key]);
  25. }
  26. else {
  27. target[key] = config2[key];
  28. }
  29. }
  30. return target;
  31. }
  32. function applyExtends(config, cwd, mergeExtends = false) {
  33. let defaultConfig = {};
  34. if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
  35. if (typeof config.extends !== 'string')
  36. return defaultConfig;
  37. const isPath = /\.json|\..*rc$/.test(config.extends);
  38. let pathToDefault = null;
  39. if (!isPath) {
  40. try {
  41. pathToDefault = require.resolve(config.extends);
  42. }
  43. catch (err) {
  44. // most likely this simply isn't a module.
  45. }
  46. }
  47. else {
  48. pathToDefault = getPathToDefaultConfig(cwd, config.extends);
  49. }
  50. // maybe the module uses key for some other reason,
  51. // err on side of caution.
  52. if (!pathToDefault && !isPath)
  53. return config;
  54. if (!pathToDefault)
  55. throw new yerror_1.YError(`Unable to find extended config '${config.extends}' in '${cwd}'.`);
  56. checkForCircularExtends(pathToDefault);
  57. previouslyVisitedConfigs.push(pathToDefault);
  58. defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends);
  59. delete config.extends;
  60. defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault), mergeExtends);
  61. }
  62. previouslyVisitedConfigs = [];
  63. return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config);
  64. }
  65. exports.applyExtends = applyExtends;