"use strict";

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

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

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

  return data;
}

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

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

  return data;
}

function _umiNotify() {
  const data = _interopRequireDefault(require("umi-notify"));

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

  return data;
}

var _getRouteManager = _interopRequireDefault(require("../getRouteManager"));

var _getFilesGenerator = _interopRequireDefault(require("../getFilesGenerator"));

var _replaceChunkMaps = _interopRequireDefault(require("../replaceChunkMaps"));

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

function _default(api) {
  const service = api.service,
        debug = api.debug,
        config = api.config,
        UmiError = api.UmiError,
        printUmiError = api.printUmiError;
  const cwd = service.cwd,
        paths = service.paths;
  api.registerCommand('build', {
    webpack: true,
    description: 'building for production'
  }, args => {
    const watch = args.w || args.watch;

    _umiNotify().default.onBuildStart({
      name: 'umi',
      version: 2
    });

    const RoutesManager = (0, _getRouteManager.default)(service);
    RoutesManager.fetchRoutes();
    return new Promise((resolve, reject) => {
      process.env.NODE_ENV = 'production';
      service.applyPlugins('onStart');

      service._applyPluginsAsync('onStartAsync').then(() => {
        service.rebuildTmpFiles = () => {
          filesGenerator.rebuild();
        };

        service.rebuildHTML = () => {
          service.applyPlugins('onHTMLRebuild');
        };

        const filesGenerator = (0, _getFilesGenerator.default)(service, {
          RoutesManager,
          mountElementId: config.mountElementId
        });
        filesGenerator.generate();

        function startWatch() {
          filesGenerator.watch();
          service.userConfig.setConfig(service.config);
          service.userConfig.watchWithDevServer();
        }

        if (process.env.HTML !== 'none') {
          const HtmlGeneratorPlugin = require('../getHtmlGeneratorPlugin').default(service); // move html-webpack-plugin to the head, so that
          // other plugins (like workbox-webpack-plugin)
          // which listen to `emit` event can detect assets


          service.webpackConfig.plugins.unshift(new HtmlGeneratorPlugin());
        }

        service._applyPluginsAsync('beforeBuildCompileAsync').then(() => {
          require('af-webpack/build').default({
            cwd,
            watch,
            // before: service.webpackConfig
            // now: [ service.webpackConfig, ... ] , for ssr or more configs
            webpackConfig: [service.webpackConfig, ...(service.ssrWebpackConfig ? [service.ssrWebpackConfig] : [])],

            // stats now is Array MultiStats
            // [ clientStats, ...otherStats ]
            onSuccess({
              stats
            }) {
              debug('Build success');

              if (watch) {
                startWatch();
              }

              if (process.env.RM_TMPDIR !== 'none' && !watch) {
                debug(`Clean tmp dir ${service.paths.tmpDirPath}`);

                _rimraf().default.sync(paths.absTmpDirPath);
              }

              if (service.ssrWebpackConfig) {
                // replace using manifest
                // __UMI_SERVER__.js/css => umi.${hash}.js/css
                const clientStat = Array.isArray(stats.stats) ? stats.stats[0] : stats;

                if (clientStat) {
                  (0, _replaceChunkMaps.default)(service, clientStat);
                }
              }

              service.applyPlugins('onBuildSuccess', {
                args: {
                  stats
                }
              });

              service._applyPluginsAsync('onBuildSuccessAsync', {
                args: {
                  stats
                }
              }).then(() => {
                debug('Build success end');

                _umiNotify().default.onBuildComplete({
                  name: 'umi',
                  version: 2
                }, {
                  err: null
                });

                resolve();
              });
            },

            // stats now is Array MultiStats
            // [ clientStats, ...otherStats ]
            onFail({
              err,
              stats
            }) {
              service.applyPlugins('onBuildFail', {
                args: {
                  err,
                  stats
                }
              });

              _umiNotify().default.onBuildComplete({
                name: 'umi',
                version: 2
              }, {
                err
              });

              printUmiError(new UmiError({
                message: err && err.message,
                context: {
                  err,
                  stats
                }
              }), {
                detailsOnly: true
              });
              reject(err);
            }

          });
        });
      });
    });
  });
}