"use strict";

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

var _uglifycss = _interopRequireDefault(require("uglifycss"));

var _webpack = require("webpack");

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

/* eslint-disable class-methods-use-this */
// import { RawSource } from 'webpack-sources';
const pluginName = 'UglifyCSSPlugin'; // TODO: Check for css minimizer plugin

class UglifyCSSPlugin {
  apply(compiler) {
    const {
      RawSource
    } = compiler.webpack.sources;
    compiler.hooks.compilation.tap(pluginName, compilation => {
      compilation.hooks.processAssets.tapAsync({
        name: pluginName,
        stage: _webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE
      }, assets => {
        Object.keys(assets).filter(filename => /\.css$/.test(filename)).forEach(filename => {
          try {
            let asset = assets[filename].source();

            if (typeof asset !== 'string') {
              asset = asset.toString();
            }

            const result = _uglifycss.default.processString(asset);

            compilation.updateAsset(filename, new RawSource(result));
          } catch (e) {
            compilation.errors.push(e);
          }
        });
      });
    });
  }

}

exports.default = UglifyCSSPlugin;