"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    return data;
  };

  return data;
}

function _requireindex() {
  const data = _interopRequireDefault(require("requireindex"));

  _requireindex = function _requireindex() {
    return data;
  };

  return data;
}

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function _chalk() {
    return data;
  };

  return data;
}

function _didyoumean() {
  const data = _interopRequireDefault(require("didyoumean"));

  _didyoumean = function _didyoumean() {
    return data;
  };

  return data;
}

function _lodash() {
  const data = require("lodash");

  _lodash = function _lodash() {
    return data;
  };

  return data;
}

function _signale() {
  const data = _interopRequireDefault(require("signale"));

  _signale = function _signale() {
    return data;
  };

  return data;
}

function _getUserConfig() {
  const data = _interopRequireWildcard(require("umi-core/lib/getUserConfig"));

  _getUserConfig = function _getUserConfig() {
    return data;
  };

  return data;
}

var _watch = require("./getConfig/watch");

var _isEqual = _interopRequireDefault(require("./isEqual"));

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }

class UserConfig {
  static getConfig(opts = {}) {
    const cwd = opts.cwd,
          service = opts.service;
    return (0, _getUserConfig().default)({
      cwd,
      defaultConfig: service.applyPlugins('modifyDefaultConfig', {
        initialValue: {}
      })
    });
  }

  constructor(service) {
    this.service = service;
    this.configFailed = false;
    this.config = null;
    this.file = null;
    this.relativeFile = null;
    this.watch = _watch.watch;
    this.unwatch = _watch.unwatch;
    this.initConfigPlugins();
  }

  initConfigPlugins() {
    const map = (0, _requireindex().default)((0, _path().join)(__dirname, 'getConfig/configPlugins'));
    let plugins = Object.keys(map).filter(key => !key.includes('.test.')).map(key => {
      return map[key].default;
    });
    plugins = this.service.applyPlugins('_registerConfig', {
      initialValue: plugins
    });
    this.plugins = plugins.map(p => p(this));
  }

  printError(messages) {
    if (this.service.printError) this.service.printError(messages);
  }

  getConfig(opts = {}) {
    const _this$service = this.service,
          paths = _this$service.paths,
          cwd = _this$service.cwd;
    const force = opts.force,
          setConfig = opts.setConfig;
    const defaultConfig = this.service.applyPlugins('modifyDefaultConfig', {
      initialValue: {}
    });
    const file = (0, _getUserConfig().getConfigFile)(cwd);
    this.file = file;

    if (!file) {
      return defaultConfig;
    } // 强制读取，不走 require 缓存


    if (force) {
      (0, _getUserConfig().cleanConfigRequireCache)(cwd);
    }

    let config = null;
    const relativeFile = file.replace(`${paths.cwd}/`, '');
    this.relativeFile = relativeFile;

    const onError = (e, file) => {
      const msg = `配置文件 "${file.replace(`${paths.cwd}/`, '')}" 解析出错，请检查语法。
\r\n${e.toString()}`;
      this.printError(msg);
      throw e;
    };

    config = (0, _getUserConfig().getConfigByConfigFile)(file, {
      defaultConfig,
      onError
    });
    config = this.service.applyPlugins('_modifyConfig', {
      initialValue: config
    }); // Validate

    var _iterator = _createForOfIteratorHelper(this.plugins),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        const plugin = _step.value;
        const name = plugin.name,
              validate = plugin.validate;

        if (config[name] && validate) {
          try {
            plugin.validate.call({
              cwd
            }, config[name]);
          } catch (e) {
            // 校验出错后要把值设到缓存的 config 里，确保 watch 判断时才能拿到正确的值
            if (setConfig) {
              setConfig(config);
            }

            this.printError(e.message);
            throw new Error(`配置 ${name} 校验失败, ${e.message}`);
          }
        }
      } // 找下不匹配的 name

    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    const pluginNames = this.plugins.map(p => p.name);
    Object.keys(config).forEach(key => {
      if (!pluginNames.includes(key)) {
        if (opts.setConfig) {
          opts.setConfig(config);
        }

        const affixmsg = `选择 "${pluginNames.join(', ')}" 中的一项`;
        const guess = (0, _didyoumean().default)(key, pluginNames);
        const midMsg = guess ? `你是不是想配置 "${guess}" ？ 或者` : '请';
        const msg = `"${relativeFile}" 中配置的 "${key}" 并非约定的配置项，${midMsg}${affixmsg}`;
        this.printError(msg);
        throw new Error(msg);
      }
    });
    return config;
  }

  setConfig(config) {
    this.config = config;
  }

  watchWithDevServer() {
    // 配置插件的监听
    var _iterator2 = _createForOfIteratorHelper(this.plugins),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        const plugin = _step2.value;

        if (plugin.watch) {
          plugin.watch();
        }
      } // 配置文件的监听

    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    this.watchConfigs((event, path) => {
      _signale().default.debug(`[${event}] ${path}`);

      try {
        const newConfig = this.getConfig({
          force: true,
          setConfig: newConfig => {
            this.config = newConfig;
          }
        }); // 从失败中恢复过来，需要 reload 一次

        if (this.configFailed) {
          this.configFailed = false;
          this.service.refreshBrowser();
        }

        const oldConfig = (0, _lodash().cloneDeep)(this.config);
        this.config = newConfig;

        var _iterator3 = _createForOfIteratorHelper(this.plugins),
            _step3;

        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            const plugin = _step3.value;
            const name = plugin.name;

            if (!(0, _isEqual.default)(newConfig[name], oldConfig[name])) {
              this.service.config[name] = newConfig[name];
              this.service.applyPlugins('onConfigChange', {
                args: {
                  newConfig
                }
              });

              if (plugin.onChange) {
                plugin.onChange(newConfig, oldConfig);
              }
            }
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      } catch (e) {
        this.configFailed = true;
        console.error(_chalk().default.red(`watch handler failed, since ${e.message}`));
        console.error(e);
      }
    });
  }

  watchConfigs(handler) {
    const cwd = this.service.cwd;
    const watcher = this.watch('CONFIG_FILES', (0, _getUserConfig().getConfigPaths)(cwd));

    if (watcher) {
      watcher.on('all', handler);
    }
  }

}

var _default = UserConfig;
exports.default = _default;