"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPlugins = getPlugins;
exports.getOnlyDefaultPlugins = getOnlyDefaultPlugins;
exports.cleanupPlugins = cleanupPlugins;
const file_hasher_1 = require("../../hasher/file-hasher");
const nx_json_1 = require("../../config/nx-json");
const internal_api_1 = require("./internal-api");
const workspace_root_1 = require("../../utils/workspace-root");
let currentPluginsConfigurationHash;
let loadedPlugins;
let pendingPluginsPromise;
let cleanup;
async function getPlugins() {
    const pluginsConfiguration = (0, nx_json_1.readNxJson)().plugins ?? [];
    const pluginsConfigurationHash = (0, file_hasher_1.hashObject)(pluginsConfiguration);
    // If the plugins configuration has not changed, reuse the current plugins
    if (loadedPlugins &&
        pluginsConfigurationHash === currentPluginsConfigurationHash) {
        return loadedPlugins;
    }
    // Cleanup current plugins before loading new ones
    if (cleanup) {
        cleanup();
    }
    pendingPluginsPromise ??= (0, internal_api_1.loadNxPlugins)(pluginsConfiguration, workspace_root_1.workspaceRoot);
    currentPluginsConfigurationHash = pluginsConfigurationHash;
    const [result, cleanupFn] = await pendingPluginsPromise;
    cleanup = cleanupFn;
    loadedPlugins = result;
    return result;
}
let loadedDefaultPlugins;
let cleanupDefaultPlugins;
let pendingDefaultPluginPromise;
async function getOnlyDefaultPlugins() {
    // If the plugins configuration has not changed, reuse the current plugins
    if (loadedDefaultPlugins) {
        return loadedPlugins;
    }
    // Cleanup current plugins before loading new ones
    if (cleanupDefaultPlugins) {
        cleanupDefaultPlugins();
    }
    pendingDefaultPluginPromise ??= (0, internal_api_1.loadNxPlugins)([], workspace_root_1.workspaceRoot);
    const [result, cleanupFn] = await pendingDefaultPluginPromise;
    cleanupDefaultPlugins = cleanupFn;
    loadedPlugins = result;
    return result;
}
function cleanupPlugins() {
    pendingPluginsPromise = undefined;
    pendingDefaultPluginPromise = undefined;
    cleanup();
    cleanupDefaultPlugins();
}
