"use strict";

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

var _path = _interopRequireDefault(require("path"));

var _fs = _interopRequireDefault(require("fs"));

var _webpack = _interopRequireDefault(require("webpack"));

var _caseSensitivePathsWebpackPlugin = _interopRequireDefault(require("case-sensitive-paths-webpack-plugin"));

var _webpackBundleAnalyzer = require("webpack-bundle-analyzer");

var _lodashWebpackPlugin = _interopRequireDefault(require("lodash-webpack-plugin"));

var _miniCssExtractPlugin = _interopRequireDefault(require("mini-css-extract-plugin"));

var _I18nSplitPlugin = _interopRequireDefault(require("../plugins/I18nSplitPlugin"));

var _copyWebpackPlugin = _interopRequireDefault(require("copy-webpack-plugin"));

var _VariableConversionCollector = _interopRequireDefault(require("../plugins/VariableConversionCollector"));

var _SelectorPlugin = _interopRequireDefault(require("../plugins/SelectorPlugin"));

var _EventsHandlingPlugin = require("../plugins/EventsHandlingPlugin");

var _plugins = require("../plugins");

var _CustomAttributePlugin = require("../plugins/CustomAttributePlugin");

var _RtlCssPlugin = require("../plugins/RtlSplitPlugin/RtlCssPlugin");

var _CssOrderControlPlugin = _interopRequireDefault(require("../plugins/CssOrderControlPlugin"));

var _configHtmlWebpackPlugins = require("./configHtmlWebpackPlugins");

var _StatsPlugin = _interopRequireDefault(require("../plugins/StatsPlugin"));

var _EfcResourceCleanupPlugin = _interopRequireDefault(require("../plugins/EfcResourceCleanupPlugin"));

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

// eslint-disable-next-line no-unused-vars
const getProdPlugins = (options, publicPath = '') => {
  let {
    enableChunkHash
  } = options.app;
  const {
    generateHtml,
    manifestFileName,
    bundleAnalyze,
    optimize,
    publicPaths,
    patterns,
    hasEFC: prevOptionForEnableEFC,
    enableSMapHook,
    tpFolder,
    folder,
    outputFolder,
    context,
    exclude,
    enableSMap,
    server: {
      mode
    },
    hasShadowDOM,
    cssVariableReplacementConfig,
    plugins: pluginObject,
    // exclude,
    selectorWeightConfig,
    resourceHints,
    serviceWorker,
    htmlTemplate,
    customAttributes,
    tpHashMapping,
    cdnMapping,
    crossorigin
  } = options.app;
  const {
    inject,
    minify: minifyHtmlOptions,
    customScriptLoadingStrategey
  } = htmlTemplate;
  const {
    i18n
  } = options;
  const {
    enableRTLSplit,
    cssOrderControler
  } = options.css;
  const {
    hasEFC: newOptionForEnableEFC,
    nameScope: efcNameSpace,
    templateFilePath,
    localeAttr: efcLocaleAttr
  } = options.efc;
  const {
    enable: enableStats,
    options: statsOptions,
    excludeKeys: statsOutputExcludeKeys,
    fileName: statsFileName
  } = options.stats;
  const hasEFC = newOptionForEnableEFC || prevOptionForEnableEFC;
  const hashTempalate = enableChunkHash ? '.[chunkhash:20]_' : '';
  const cssLTRFileNameTempalte = `css/[name]${hashTempalate}${enableRTLSplit ? '.ltr' : ''}.css`;
  const cssRTLFileNameTempalte = `css/[name]${hashTempalate}.rtl.css`;
  const isDevelopment = mode === 'prod' || mode === 'dev' || mode === 'dev-no-warn';
  enableChunkHash = !isDevelopment && enableChunkHash;
  const pluginsArr = [new _caseSensitivePathsWebpackPlugin.default(), new _webpack.default.IgnorePlugin(/^\.\/locale$/, /moment$/), new _webpack.default.DefinePlugin({
    __TEST__: false,
    __DEVELOPMENT__: false,
    __LOCAL_PRODUCTION__: isDevelopment,
    __DOCS__: false,
    'process.env': {
      NODE_ENV: JSON.stringify('production')
    },
    __SERVER__: false
  }), new _miniCssExtractPlugin.default({
    // ignoreOrder: true,
    filename: cssLTRFileNameTempalte,
    chunkFilename: cssLTRFileNameTempalte
  }), new _plugins.ResourceHintsPlugin(options.resourceHints), new _plugins.MinifyPlugin()];

  if (enableRTLSplit) {
    pluginsArr.push(new _RtlCssPlugin.RtlCssPlugin({
      templateLabel: options.css.templateLabel,
      disableMiniFiySelector: options.css.disableMiniFiySelector,
      dirVarName: options.css.dirVarName,
      // config: {},
      // sourcemap: true,
      filename: cssRTLFileNameTempalte
    }));
  }

  const i18nManifestFileName = 'i18n-manifest.json';
  /**
   * NOTE:
   *  this file name ext .i18n.js added
   *  Because, in service worker they maintain cache as file name based
   *  So, to make differce we added .i18n.js ext.
   */

  const i18nFileNameTemplate = 'i18n-chunk/[locale]/[name].[chunkhash].i18n.js';
  const i18nPublicPath = Array.isArray(publicPaths) && !cdnMapping.isCdnEnabled ? publicPaths['4'] : ''; // const  i18nFileNameTemplate = 'i18n-chunk/[locale]/[name].[contentHash]_.js';
  // const  i18nFileNameTemplate = 'i18n-chunk/[locale]/[name]_.js';

  if (i18n.chunkSplitEnable) {
    pluginsArr.push(new _I18nSplitPlugin.default({
      jsResource: i18n.jsResource,
      localeVarName: i18n.localeVarName,
      jsonpFunc: i18n.jsonpFunc,
      disableDefault: i18n.disableDefault,
      publicPath: i18nPublicPath,
      i18nManifestFileName,
      // template: (object, locale) => `window.loadI18n(${JSON.stringify(object)}, ${JSON.stringify(locale)})`,
      filenameTemplate: i18nFileNameTemplate,
      propertiesFolder: i18n.propertiesFolder
    }));
  } else {
    const i18nPath = _path.default.join(process.cwd(), context, 'i18n');

    if (_fs.default.existsSync(i18nPath)) {
      pluginsArr.push(new _copyWebpackPlugin.default([{
        from: `${i18nPath}/`,
        to: enableChunkHash ? './i18n/[name].[hash:20]_.[ext]' : './i18n/[name]_.[ext]',
        toType: 'template'
      }]));
    }
  }

  tpFolder && pluginsArr.push(new _copyWebpackPlugin.default([{
    from: `${_path.default.join(process.cwd(), context, tpFolder)}/`,
    to: `./${tpFolder}/`,
    toType: 'dir'
  }]));
  generateHtml && (0, _configHtmlWebpackPlugins.configHtmlWebpackPlugins)(pluginsArr, {
    enableChunkHash,
    folder,
    inject,
    minify: minifyHtmlOptions,
    customScriptLoadingStrategey,
    crossorigin,
    hasEFC
  });

  if (hasEFC) {
    pluginsArr.push(new _plugins.EFCPlugin({
      isDevelopment,
      serverUrl: publicPath,
      i18nFileNameTemplate,
      templateFilePath,
      i18nManifestFileName,
      entryPointName: 'efc',
      // outputFile: 'zohodesk-efc-sdk-latest.js',
      nameScope: efcNameSpace,
      localeAttr: efcLocaleAttr,
      cdnVariableName: cdnMapping.isCdnEnabled ? cdnMapping.variableName : null
    }));
  }

  pluginsArr.push(new _plugins.I18NInjectIntoIndexPlugin({
    // Because we  will handle cdn url in CdnChangePlugin
    publicPath: cdnMapping.isCdnEnabled ? '' : i18nPublicPath,
    isDevelopment,
    templateLabel: i18n.templateLabel || '{{--user-locale}}',
    i18nFileNameTemplate,
    i18nManifestFileName,
    mainChunkName: 'main'
  }));

  if (publicPaths && !isDevelopment && !cdnMapping.isCdnEnabled) {
    const {
      callback
    } = publicPaths;
    pluginsArr.push(callback ? new _plugins.PublicPathCallbackPlugin({
      callback
    }) : new _plugins.PublicPathChangePlugin({
      publicPaths,
      resourceHints
    }));
  }

  if (cdnMapping.isCdnEnabled) {
    pluginsArr.push(new _plugins.CdnChangePlugin(cdnMapping));
  }

  pluginsArr.push(new _lodashWebpackPlugin.default({
    collections: true,
    shorthands: true
  }));
  hasShadowDOM && pluginsArr.push(new _plugins.ShadowDOMSupportPlugin());

  if (!isDevelopment) {
    enableSMap && enableSMapHook && pluginsArr.push(new _plugins.SourceMapHookPlugin());
    optimize && pluginsArr.push(new _plugins.OptimizeJSPlugin());
    pluginsArr.push(new _plugins.ManifestPlugin({
      fileName: manifestFileName
    }));

    if (bundleAnalyze) {
      pluginsArr.push(new _webpackBundleAnalyzer.BundleAnalyzerPlugin({
        analyzerMode: 'static',
        generateStatsFile: false,
        openAnalyzer: false,
        statsOptions: enableStats ? null : {
          source: false,
          normal: true,
          chunks: false,
          chunkGroups: false,
          module: false,
          assets: true,
          assetsSort: 'name'
        }
      })); // plugins.push(new ReportGeneratePlugin());
    }

    if (tpHashMapping && tpHashMapping.length > 0) {
      pluginsArr.push(new _plugins.TPHashMappingPlugin({
        fileMappings: tpHashMapping,
        tpFolder: `${_path.default.join(process.cwd(), context, tpFolder)}/`
      }));
    }
  }

  if (!isDevelopment && serviceWorker.enableSw) {
    const {
      filePath,
      fileName = 'sw.js',
      exitPath = '/',
      replaceText = '@@'
    } = serviceWorker;

    if (!filePath) {
      throw new Error('File Path required for service worker plugin');
    }

    pluginsArr.push(new _plugins.ServiceWorkerPlugin({
      filePath: _path.default.join(process.cwd(), filePath),
      i18nFileNameTemplate,
      fileName: fileName,
      exitPath: _path.default.join(outputFolder, exitPath),
      replaceText,
      publicPaths
    }));
  }

  if (pluginObject.cssVariableReplacement) {
    pluginsArr.push(new _VariableConversionCollector.default({
      cssVariableReplacementConfig,
      patterns
    }));
  }

  if (pluginObject.selectorWeight) {
    pluginsArr.push(new _SelectorPlugin.default({
      selectorWeightConfig,
      exclude: exclude.selectorWeight,
      patterns
    }));
  } // plugins.push(new VariableConversionCollector({}));


  cssOrderControler.enable && pluginsArr.push(new _CssOrderControlPlugin.default(cssOrderControler));
  customAttributes.enable && pluginsArr.push(new _CustomAttributePlugin.CustomAttributePlugin(customAttributes));
  customAttributes.enable && pluginsArr.push(new _EfcResourceCleanupPlugin.default(Object.assign({}, customAttributes, {
    globalCacheObj: context
  })));
  enableStats && pluginsArr.push(new _StatsPlugin.default({
    statsOptions,
    statsOutputExcludeKeys,
    statsFileName
  }));
  pluginsArr.push(new _EventsHandlingPlugin.EventsHandlingPlugin());
  return pluginsArr;
};

var _default = getProdPlugins;
exports.default = _default;