"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 pluginStore_exports = {};
__export(pluginStore_exports, {
  createPluginStore: () => createPluginStore,
  initPlugins: () => initPlugins
});
module.exports = __toCommonJS(pluginStore_exports);
var import_logger = require("./logger");
function createPluginStore() {
  let plugins = [];
  const addPlugins = (newPlugins, options) => {
    const { before } = options || {};
    newPlugins.forEach((newPlugin) => {
      if (typeof newPlugin !== "object" || newPlugin === null) {
        throw new Error(
          `expect plugin instance is object, but got ${typeof newPlugin}.`
        );
      } else if (typeof newPlugin.setup !== "function") {
        throw new Error(
          `expect plugin.setup is function, but got ${typeof newPlugin}.`
        );
      }
      if (plugins.find((item) => item.name === newPlugin.name)) {
        import_logger.logger.warn(
          `Rsbuild plugin "${newPlugin.name}" registered multiple times.`
        );
      } else if (before) {
        const index = plugins.findIndex((item) => item.name === before);
        if (index === -1) {
          import_logger.logger.warn(`Plugin "${before}" does not exist.`);
          plugins.push(newPlugin);
        } else {
          plugins.splice(index, 0, newPlugin);
        }
      } else {
        plugins.push(newPlugin);
      }
    });
  };
  const removePlugins = (pluginNames) => {
    plugins = plugins.filter((plugin) => !pluginNames.includes(plugin.name));
  };
  const isPluginExists = (pluginName) => Boolean(plugins.find((plugin) => plugin.name === pluginName));
  return {
    get plugins() {
      return plugins;
    },
    addPlugins,
    removePlugins,
    isPluginExists
  };
}
const pluginDagSort = (plugins, key = "name", preKey = "pre", postKey = "post") => {
  let allLines = [];
  function getPluginByAny(q) {
    const target = plugins.find(
      (item) => typeof q === "string" ? item[key] === q : item[key] === q[key]
    );
    if (!target) {
      throw new Error(`plugin ${q} not existed`);
    }
    return target;
  }
  plugins.forEach((item) => {
    item[preKey]?.forEach((p) => {
      if (plugins.find((ap) => ap.name === p)) {
        allLines.push([getPluginByAny(p)[key], getPluginByAny(item)[key]]);
      }
    });
    item[postKey]?.forEach((pt) => {
      if (plugins.find((ap) => ap.name === pt)) {
        allLines.push([getPluginByAny(item)[key], getPluginByAny(pt)[key]]);
      }
    });
  });
  let zeroEndPoints = plugins.filter(
    (item) => !allLines.find((l) => l[1] === item[key])
  );
  const sortedPoint = [];
  while (zeroEndPoints.length) {
    const zep = zeroEndPoints.shift();
    sortedPoint.push(getPluginByAny(zep));
    allLines = allLines.filter((l) => l[0] !== getPluginByAny(zep)[key]);
    const restPoints = plugins.filter(
      (item) => !sortedPoint.find((sp) => sp[key] === item[key])
    );
    zeroEndPoints = restPoints.filter(
      // eslint-disable-next-line @typescript-eslint/no-loop-func
      (item) => !allLines.find((l) => l[1] === item[key])
    );
  }
  if (allLines.length) {
    const restInRingPoints = {};
    allLines.forEach((l) => {
      restInRingPoints[l[0]] = true;
      restInRingPoints[l[1]] = true;
    });
    throw new Error(
      `plugins dependencies has loop: ${Object.keys(restInRingPoints).join(
        ","
      )}`
    );
  }
  return sortedPoint;
};
async function initPlugins({
  pluginAPI,
  pluginStore
}) {
  (0, import_logger.debug)("init plugins");
  const plugins = pluginDagSort(pluginStore.plugins);
  const removedPlugins = plugins.reduce((ret, plugin) => {
    if (plugin.remove) {
      return ret.concat(plugin.remove);
    }
    return ret;
  }, []);
  for (const plugin of plugins) {
    if (removedPlugins.includes(plugin.name)) {
      continue;
    }
    await plugin.setup(pluginAPI);
  }
  (0, import_logger.debug)("init plugins done");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createPluginStore,
  initPlugins
});
