"use strict";

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

var _webpack = require("webpack");

const pluginName = 'prefetch-preload-chunk-plugin';
/**
 * NOTE: below functions are useable in webpack 5 as per day 28 Apr 2023
 * Please checkout for future changes
 * Here List of functions that take chunkId as Argument and return url without publicPath
 * `__webpack_require__.u(chunkId)`          -  return's JS script urlPath
 * `__webpack_require__.miniCssF(chunkId)`   -  return's CSS script urlPath
 * `__webpack_require__.miniI18nF(chunkId)`  -  return's I18N script urlPath
 *
 *
 * if url  has .undefined. then chunk or url not valid or that file nt available
 */

class ResourceHintsPlugin {
  constructor({
    publicPath
  }) {
    this.publicPathsTemplateObj = {
      js: publicPath,
      css: publicPath,
      i18n: publicPath
    };
  } // eslint-disable-next-line class-methods-use-this


  apply(compiler) {
    compiler.hooks.thisCompilation.tap(pluginName, compilation => {
      const enabledChunks = new WeakSet();

      const handler = (entryRuntimeChunk, set) => {
        if (enabledChunks.has(entryRuntimeChunk)) {
          return;
        }

        enabledChunks.add(entryRuntimeChunk);
        set.add(_webpack.RuntimeGlobals.getFullHash);
        set.add(_webpack.RuntimeGlobals.getChunkCssFilename);
        const {
          publicPathsTemplateObj
        } = this;
        compilation.addRuntimeModule(entryRuntimeChunk, // eslint-disable-next-line no-use-before-define
        new ResourceHintsRuntimePlugin(set, {
          compiler,
          chunk: entryRuntimeChunk,
          publicPathsTemplateObj
        }));
      };

      compilation.hooks.runtimeRequirementInTree.for(_webpack.RuntimeGlobals.ensureChunkHandlers).tap(pluginName, handler);
    });
  }

}

exports.default = ResourceHintsPlugin;

class ResourceHintsRuntimePlugin extends _webpack.RuntimeModule {
  constructor(compiler, {
    chunk,
    publicPathsTemplateObj
  }) {
    super('ResourceHintsRuntimePlugin loading', 10);
    this.compiler = compiler;
    this.publicPathsTemplateObj = publicPathsTemplateObj;
    this.chunk = chunk;
  }

  generate() {
    const {
      chunk
    } = this;
    const idNameMap = chunk.getChunkMaps().name;
    const nameIdMap = {};
    let needsMap = false; // eslint-disable-next-line no-restricted-syntax

    for (const key in idNameMap) {
      if (Object.prototype.hasOwnProperty.call(idNameMap, key)) {
        const value = idNameMap[key];
        nameIdMap[value] = key;

        if (key !== value) {
          needsMap = true;
        }
      }
    }

    const {
      js: jsPP = '',
      css: cssPP = '',
      i18n: i18nPP = ''
    } = this.publicPathsTemplateObj;
    return _webpack.Template.asString([`
      const preloadedChunks = {};
      function createLinkTag(href, rel) {
        let link = document.createElement("link");
        link.href = href;
        link.rel = rel;
        if(href.endsWith(".css")) {
          link.as="style";
        } else if (href.endsWith(".js")) {
          link.as="script";
        }
        document.head.appendChild(link);
      }
      function isValidUrl(url) {
        //return !url.includes(".undefined.");
        return url.indexOf(".undefined.") === -1;
      }
      function loadAsPreloadOrPrefetch(_chunkId, rel) {
        let chunkId = ${_webpack.RuntimeGlobals.require}.getChunkId(_chunkId);
        // ${_webpack.RuntimeGlobals.require}.e(chunkId);
        // return;
        if(__webpack_require__.O.j(chunkId) || preloadedChunks[chunkId]) {
          preloadedChunks[chunkId] = true;
          // console.log("skipped loadAsPreloadOrPrefetch", _chunkId, chunkId, rel);
          return;
        }
        const jsUrl = ${jsPP} + __webpack_require__.u(chunkId);
        const cssUrl = ${cssPP} + __webpack_require__.miniCssF(chunkId);
        const i18nUrl = ${i18nPP} + __webpack_require__.miniI18nF(chunkId);
        isValidUrl(jsUrl) && createLinkTag(jsUrl, rel);
        isValidUrl(cssUrl) && createLinkTag(cssUrl, rel);
        isValidUrl(i18nUrl) && createLinkTag(i18nUrl, rel);      
      }
      
      ${_webpack.RuntimeGlobals.require}.getChunkId = function getChunkId(chunkId) {
        ${needsMap ? `chunkId = ${JSON.stringify(nameIdMap)}[chunkId]||chunkId;` : ''}
        return chunkId;
      }
      // Prefetch a chunk (${pluginName})
      ${_webpack.RuntimeGlobals.require}.pfc = function prefetchChunk(chunkId) {
        loadAsPreloadOrPrefetch(chunkId, "prefetch");
      };

      // Preload a chunk (${pluginName})
      ${_webpack.RuntimeGlobals.require}.plc = function preloadChunk(chunkId) {
        loadAsPreloadOrPrefetch(chunkId, "preload");
      };
        ` // `// Prefetch a chunk (${pluginName})`,
    // `${RuntimeGlobals.require}.pfc = function prefetchChunk(chunkId) {`,
    // Template.indent([
    //   `chunkId = ${RuntimeGlobals.require}.getChunkId(chunkId)`,
    //   `${RuntimeGlobals.require}.e(chunkId);`
    // ]),
    // '};',
    // `// Preload a chunk (${pluginName})`,
    // `${RuntimeGlobals.require}.pfc = function prefetchChunk(chunkId) {`,
    // Template.indent([
    //   `chunkId = ${RuntimeGlobals.require}.getChunkId(chunkId)`,
    //   `${RuntimeGlobals.require}.e(chunkId);`
    // ]),
    // '};'
    ]);
  }

}