"use strict";

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

var _webpack = require("webpack");

/* eslint-disable class-methods-use-this */
function checkSmapFilePattern(assetName) {
  return /\.js$/.test(assetName) && !/\.i18n\.js$/.test(assetName) || /\.js\.map$/.test(assetName) && !/\.i18n\.js\.map$/.test(assetName);
}

function skipRuntimeFiles(assetName) {
  return !assetName.includes('[locale]');
}

const pluginName = 'SplitSourceMapPlugin'; // Purpose:

/**
 * we want build that can load files source map and without sourcemap at the same time,
 * or can be mentioned as so single build need to support two different clients that one for fast load and one for debugging.
 */

class SourceMapPlugin {
  apply(compiler) {
    const {
      RawSource
    } = compiler.webpack.sources;
    compiler.hooks.thisCompilation.tap(pluginName, compilation => {
      compilation.hooks.processAssets.tap({
        name: pluginName,
        stage: _webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
      }, assets => {
        Object.keys(assets).forEach(assetName => {
          const assetCode = assets[assetName].source();

          if (checkSmapFilePattern(assetName) && skipRuntimeFiles(assetName)) {
            compilation.renameAsset(assetName, `smap/${assetName}`);

            if (!/\.map$/.test(assetName)) {
              compilation.emitAsset(assetName, new RawSource(assetCode));
            }
          }
        });
      });
      compilation.hooks.processAssets.tap({
        name: pluginName,
        stage: _webpack.Compilation.PROCESS_ASSETS_STAGE_DERIVED // additionalAssets: true

      }, assets => {
        Object.keys(assets).forEach(assetName => {
          if (assetName.includes('runtime') && skipRuntimeFiles(assetName)) {
            const runtimeAssetCode = assets[assetName].source();
            const newAssetName = `smap/${assetName}`;
            compilation.emitAsset(newAssetName, new RawSource(runtimeAssetCode));
          }

          ;
        });
      });
    });
  }

}

exports.SourceMapPlugin = SourceMapPlugin;