import { getModules } from "../lib/modules/registry.js";
let cachedRegistry = null;
let cachedModulesRef = null;
function buildRegistry(modules) {
  const enabledModuleIds = modules.map((mod) => mod.id);
  const enabledModuleSet = new Set(enabledModuleIds);
  const featureToModule = /* @__PURE__ */ new Map();
  const prefixToModule = /* @__PURE__ */ new Map();
  for (const mod of modules) {
    const features = mod.features;
    if (!Array.isArray(features)) continue;
    for (const feature of features) {
      if (!feature || typeof feature.id !== "string" || !feature.id) continue;
      const declared = typeof feature.module === "string" && feature.module.length > 0 ? feature.module : mod.id;
      featureToModule.set(feature.id, declared);
      const dot = feature.id.indexOf(".");
      if (dot > 0) {
        const prefix = feature.id.slice(0, dot);
        if (!prefixToModule.has(prefix)) prefixToModule.set(prefix, declared);
      }
    }
  }
  return { enabledModuleIds, enabledModuleSet, featureToModule, prefixToModule };
}
function getRegistry() {
  try {
    const modules = getModules();
    if (cachedRegistry && cachedModulesRef === modules) return cachedRegistry;
    cachedModulesRef = modules;
    cachedRegistry = buildRegistry(modules);
    return cachedRegistry;
  } catch {
    return null;
  }
}
function getOwningModuleId(featureId) {
  const registry = getRegistry();
  if (registry) {
    const direct = registry.featureToModule.get(featureId);
    if (direct) return direct;
    if (featureId.endsWith(".*")) {
      const prefix = featureId.slice(0, -2);
      const fromPrefix = registry.prefixToModule.get(prefix);
      if (fromPrefix) return fromPrefix;
      return prefix;
    }
  }
  const dot = featureId.indexOf(".");
  return dot === -1 ? featureId : featureId.slice(0, dot);
}
function getEnabledModuleIds() {
  const registry = getRegistry();
  return registry ? [...registry.enabledModuleIds] : [];
}
function filterGrantsByEnabledModules(granted) {
  const registry = getRegistry();
  if (!registry) return [...granted];
  const { enabledModuleIds, enabledModuleSet, prefixToModule } = registry;
  const result = [];
  for (const grant of granted) {
    if (grant === "*") {
      for (const id of enabledModuleIds) result.push(`${id}.*`);
      for (const [prefix, owningModule] of prefixToModule) {
        if (!enabledModuleSet.has(prefix) && enabledModuleSet.has(owningModule)) {
          result.push(`${prefix}.*`);
        }
      }
      continue;
    }
    if (enabledModuleSet.has(getOwningModuleId(grant))) result.push(grant);
  }
  return result;
}
export {
  filterGrantsByEnabledModules,
  getEnabledModuleIds,
  getOwningModuleId
};
//# sourceMappingURL=enabledModulesRegistry.js.map
