"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var HtmlPreloadOrPrefetchPlugin_exports = {};
__export(HtmlPreloadOrPrefetchPlugin_exports, {
  HTMLPreloadOrPrefetchPlugin: () => HTMLPreloadOrPrefetchPlugin
});
module.exports = __toCommonJS(HtmlPreloadOrPrefetchPlugin_exports);
var import_lodash = require("lodash");
var import_helpers = require("./helpers");
var import_util = require("../util");
var import_url = require("../../url");
/**
 * @license
 * Copyright 2018 Google Inc.
 * https://github.com/vuejs/preload-webpack-plugin/blob/master/src/index.js
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const defaultOptions = {
  type: "async-chunks"
};
function filterResourceHints(resourceHints, scripts) {
  return resourceHints.filter(
    (resourceHint) => !scripts.find(
      (script) => script.attributes.src === resourceHint.attributes.href
    )
  );
}
function generateLinks(options, type, compilation, htmlPluginData, HTMLCount) {
  const extractedChunks = (0, import_helpers.extractChunks)({
    // @ts-expect-error compilation type mismatch
    compilation,
    includeType: options.type
  });
  const htmlChunks = (
    // Handle all chunks.
    options.type === "all-assets" || HTMLCount === 1 ? extractedChunks : extractedChunks.filter(
      (chunk) => (
        // TODO: Not yet supported in rspack, maybe we should implement it in another way
        // https://github.com/web-infra-dev/rspack/issues/3896
        (0, import_helpers.doesChunkBelongToHtml)({
          chunk,
          compilation,
          htmlPluginData,
          pluginOptions: options
        })
      )
    )
  );
  const allFiles = htmlChunks.reduce(
    (accumulated, chunk) => accumulated.concat([
      ...chunk.files,
      // sourcemap files are inside auxiliaryFiles in webpack5
      ...chunk.auxiliaryFiles || []
    ]),
    []
  );
  const uniqueFiles = new Set(allFiles);
  const filteredFiles = [...uniqueFiles].filter((file) => [/.map$/].every((regex) => !regex.test(file))).filter(
    (file) => !options.include || (typeof options.include === "function" ? options.include(file) : options.include.some((regex) => new RegExp(regex).test(file)))
  ).filter(
    (file) => !options.exclude || (typeof options.exclude === "function" ? !options.exclude(file) : options.exclude.every((regex) => !new RegExp(regex).test(file)))
  );
  const sortedFilteredFiles = filteredFiles.sort();
  const links = [];
  const publicPath = (0, import_util.getPublicPathFromCompiler)(compilation.compiler);
  for (const file of sortedFilteredFiles) {
    const href = (0, import_url.withPublicPath)(file, publicPath);
    const attributes = {
      href,
      rel: type
    };
    if (type === "preload") {
      attributes.as = (0, import_helpers.determineAsValue)({
        href,
        file
      });
      if (attributes.as === "font") {
        attributes.crossorigin = "";
      }
    }
    links.push({
      tagName: "link",
      attributes,
      voidTag: true,
      meta: {}
    });
  }
  return links;
}
class HTMLPreloadOrPrefetchPlugin {
  constructor(options, type, HtmlPlugin, HTMLCount) {
    this.resourceHints = [];
    this.options = {
      ...defaultOptions,
      ...typeof options === "boolean" ? {} : options
    };
    this.type = type;
    this.HtmlPlugin = HtmlPlugin;
    this.HTMLCount = HTMLCount;
  }
  apply(compiler) {
    compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
      this.HtmlPlugin.getHooks(compilation).beforeAssetTagGeneration.tap(
        `HTML${(0, import_lodash.upperFirst)(this.type)}Plugin`,
        (htmlPluginData) => {
          this.resourceHints = generateLinks(
            this.options,
            this.type,
            compilation,
            htmlPluginData,
            this.HTMLCount
          );
          return htmlPluginData;
        }
      );
      this.HtmlPlugin.getHooks(compilation).alterAssetTags.tap(
        `HTML${(0, import_lodash.upperFirst)(this.type)}Plugin`,
        (htmlPluginData) => {
          if (this.resourceHints) {
            htmlPluginData.assetTags.styles = [
              ...filterResourceHints(
                this.resourceHints,
                htmlPluginData.assetTags.scripts
              ),
              ...htmlPluginData.assetTags.styles
            ];
          }
          return htmlPluginData;
        }
      );
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  HTMLPreloadOrPrefetchPlugin
});
