"use strict";

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

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

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

  return data;
}

function _resolve() {
  const data = _interopRequireDefault(require("resolve"));

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

  return data;
}

function _assert() {
  const data = _interopRequireDefault(require("assert"));

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

  return data;
}

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

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

  return data;
}

function _error() {
  const data = require("umi-core/lib/error");

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

  return data;
}

function _umiUtils() {
  const data = require("umi-utils");

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

  return data;
}

var _registerBabel = _interopRequireWildcard(require("./registerBabel"));

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

var _getCodeFrame = _interopRequireDefault(require("./utils/getCodeFrame"));

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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

const debug = require('debug')('umi-build-dev:getPlugin');

function _default(opts = {}) {
  const cwd = opts.cwd,
        _opts$plugins = opts.plugins,
        plugins = _opts$plugins === void 0 ? [] : _opts$plugins; // 内置插件

  const builtInPlugins = ['./plugins/commands/dev', './plugins/commands/build', './plugins/commands/inspect', './plugins/commands/test', './plugins/commands/help', './plugins/commands/generate', './plugins/commands/rm', './plugins/commands/config', ...(process.env.UMI_UI === 'none' ? [] : [require.resolve('umi-plugin-ui')]), './plugins/commands/block', './plugins/commands/version', './plugins/global-js', './plugins/global-css', './plugins/mountElementId', './plugins/mock', './plugins/proxy', './plugins/history', './plugins/afwebpack-config', './plugins/404', // 404 must after mock
  './plugins/targets', './plugins/importFromUmi'];
  const pluginsObj = [// builtIn 的在最前面
  ...builtInPlugins.map(p => {
    let opts;

    if (Array.isArray(p)) {
      /* eslint-disable prefer-destructuring */
      opts = p[1];
      p = p[0];
      /* eslint-enable prefer-destructuring */
    }

    const apply = require(p); // eslint-disable-line


    return {
      id: p.replace(/^.\//, 'built-in:'),
      apply: apply.default || apply,
      opts
    };
  }), ...getUserPlugins(process.env.UMI_PLUGINS ? process.env.UMI_PLUGINS.split(',') : [], {
    cwd
  }), ...getUserPlugins(plugins, {
    cwd
  })];
  debug(`plugins: \n${pluginsObj.map(p => `  ${p.id}`).join('\n')}`);
  return pluginsObj;
}

function pluginToPath(plugins, {
  cwd
}) {
  return (plugins || []).map(p => {
    (0, _assert().default)(Array.isArray(p) || typeof p === 'string', `Plugin config should be String or Array, but got ${_chalk().default.red(typeof p)}`);

    if (typeof p === 'string') {
      p = [p];
    }

    const _p = p,
          _p2 = _slicedToArray(_p, 2),
          path = _p2[0],
          opts = _p2[1];

    try {
      return [(0, _umiUtils().winPath)(_resolve().default.sync(path, {
        basedir: cwd
      })), opts];
    } catch (e) {
      throw new (_error().UmiError)({
        code: 'ERR_CORE_PLUGIN_RESOLVE_FAILED',
        message: `Plugin ${_chalk().default.underline.cyan(path)} can't be resolved`
      });
    }
  });
}

function getUserPlugins(plugins, {
  cwd
}) {
  const pluginPaths = pluginToPath(plugins, {
    cwd
  }); // 用户给的插件需要做 babel 转换

  if (pluginPaths.length) {
    (0, _registerBabel.addBabelRegisterFiles)(pluginPaths.map(p => p[0]), {
      cwd
    });
    (0, _registerBabel.default)({
      cwd
    });
  }

  return pluginPaths.map(p => {
    const _p3 = _slicedToArray(p, 2),
          path = _p3[0],
          opts = _p3[1];

    let apply;

    try {
      apply = require(path); // eslint-disable-line
    } catch (e) {
      throw new (_error().UmiError)({
        code: 'ERR_CORE_PLUGIN_INITIALIZE_FAILED',
        message: `Plugin ${_chalk().default.cyan.underline(path)} execute failed\n\n${_chalk().default.white((0, _getCodeFrame.default)(e, {
          cwd
        }))}`
      });
    }

    return {
      id: path.replace(makesureLastSlash(cwd), 'user:'),
      apply: apply.default || apply,
      opts
    };
  });
}

function resolveIdAndOpts({
  id,
  opts
}) {
  return {
    id,
    opts
  };
}

function toIdStr(plugins) {
  return plugins.map(p => p.id).join('^^');
}
/**
 * 返回结果：
 *   pluginsChanged: true | false
 *   optionChanged: [ 'a', 'b' ]
 */


function diffPlugins(newOption, oldOption, {
  cwd
}) {
  const newPlugins = getUserPlugins(newOption, {
    cwd
  }).map(resolveIdAndOpts);
  const oldPlugins = getUserPlugins(oldOption, {
    cwd
  }).map(resolveIdAndOpts);

  if (newPlugins.length !== oldPlugins.length) {
    return {
      pluginsChanged: true
    };
  } else if (toIdStr(newPlugins) !== toIdStr(oldPlugins)) {
    return {
      pluginsChanged: true
    };
  } else {
    return {
      optionChanged: newPlugins.filter((_, index) => {
        return !(0, _isEqual.default)(newPlugins[index].opts, oldPlugins[index].opts);
      })
    };
  }
}

function makesureLastSlash(path) {
  return path.slice(-1) === '/' ? path : `${path}/`;
}