"use strict";

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

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

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

  return data;
}

function _webpack() {
  const data = _interopRequireDefault(require("webpack"));

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

  return data;
}

function _rimraf() {
  const data = _interopRequireDefault(require("rimraf"));

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

  return data;
}

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

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

  return data;
}

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

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

  return data;
}

function _FileSizeReporter() {
  const data = require("react-dev-utils/FileSizeReporter");

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

  return data;
}

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')('af-webpack:build'); // These sizes are pretty large. We'll warn for bundles exceeding them.


const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

function getOutputPath(webpackConfig) {
  return Array.isArray(webpackConfig) ? webpackConfig[0].output.path : webpackConfig.output.path;
}

function build(opts = {}) {
  const webpackConfig = opts.webpackConfig,
        _opts$cwd = opts.cwd,
        cwd = _opts$cwd === void 0 ? process.cwd() : _opts$cwd,
        onSuccess = opts.onSuccess,
        onFail = opts.onFail;
  (0, _assert().default)(webpackConfig, 'webpackConfig should be supplied.');
  (0, _assert().default)((0, _lodash().isPlainObject)(webpackConfig) || Array.isArray(webpackConfig), 'webpackConfig should be plain object or array.');
  const outputPath = getOutputPath(webpackConfig); // 清理 output path

  if (process.env.CLEAR_OUTPUT !== 'none') {
    debug(`Clean output path ${outputPath.replace(`${cwd}/`, '')}`);

    _rimraf().default.sync(outputPath);
  }

  debug('build start');
  (0, _webpack().default)(webpackConfig, (err, stats) => {
    debug('build done');

    if (err || stats.hasErrors()) {
      if (onFail) {
        onFail(getErrorInfo(err, stats));
      }

      const isWatch = (0, _lodash().isPlainObject)(webpackConfig) ? webpackConfig.watch : webpackConfig.some(config => config.watch);
      /* array */

      if (!process.env.UMI_TEST && !isWatch) {
        process.exit(1);
      }
    }

    console.log('File sizes after gzip:\n');
    (0, _FileSizeReporter().printFileSizesAfterBuild)(stats, {
      root: outputPath,
      sizes: {}
    }, outputPath, WARN_AFTER_BUNDLE_GZIP_SIZE, WARN_AFTER_CHUNK_GZIP_SIZE);
    console.log();

    if (onSuccess) {
      onSuccess({
        stats
      });
    }
  });
}

function getErrorInfo(err, stats) {
  if (err || !stats.stats) {
    return {
      err: err || stats.compilation && stats.compilation.errors && stats.compilation.errors[0],
      stats,
      rawStats: stats
    };
  }

  const _stats$stats = _slicedToArray(stats.stats, 1),
        curStats = _stats$stats[0];

  return {
    err: err || curStats.compilation && curStats.compilation.errors && curStats.compilation.errors[0],
    stats: curStats,
    rawStats: stats
  };
}