"use strict";

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

var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));

var _utils = require("../utils");

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

const MODULE_TYPE = 'css/mini-extract';

const isI18nFile = url => url.endsWith('.i18n.js');

const {
  app: {
    enableSMap
  }
} = (0, _utils.getOptions)();

class CdnChangePlugin {
  constructor(options) {
    this.i18nTemplate = options.i18nTemplate || '{{__I18N_CDN__}}';
    this.variableName = options.variableName || '__CSS_CDN__';
    this.cssTemplate = options.cssTemplate || '{{__CSS_CDN__}}';
    this.jsTemplate = options.jsTemplate || '{{__JS_CDN__}}';
  }

  getCssChunkObject(mainChunk) {
    const obj = {};

    for (const chunk of mainChunk.getAllAsyncChunks()) {
      for (const module of chunk.modulesIterable) {
        if (module.type === MODULE_TYPE) {
          obj[chunk.id] = 1;
          break;
        }
      }
    }

    return obj;
  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap('CdnChangePlugin', compilation => {
      compilation.mainTemplate.hooks.requireEnsure.tap('CdnChangePlugin', (source, chunk) => {
        const chunkMap = this.getCssChunkObject(chunk);

        if (Object.keys(chunkMap).length > 0) {
          return source.replace('__webpack_require__.p', `window['${this.variableName}']`);
        }
      });
    });
    compiler.hooks.make.tap('CdnChangePlugin', compilation => {
      _htmlWebpackPlugin.default.getHooks(compilation).beforeAssetTagGeneration.tapAsync('CdnChangePlugin', (data, cb) => {
        data.assets = Object.assign({}, data.assets, {
          css: data.assets.css.map(css => `${this.cssTemplate}${css}`),
          js: data.assets.js.map(js => {
            if (enableSMap && !isI18nFile(js)) {
              js = js.replace('js/', `{{--js-smap}}js/`); //eslint-disable-line
            }

            return `${isI18nFile(js) ? this.i18nTemplate : this.jsTemplate}${js}`;
          })
        });
        cb(null, data);
      });
    });
  }

}

var _default = CdnChangePlugin;
exports.default = _default;