import { valid, compare, gte } from 'semver';

function resolveSelectors(versionedSelectors, grafanaVersion = "latest") {
  const version = grafanaVersion.replace(/\-.*/, "");
  return resolveSelectorGroup(versionedSelectors, version);
}
function resolveSelectorGroup(group, grafanaVersion) {
  const result = {};
  for (const [key, value] of Object.entries(group)) {
    if (isVersionedSelectorGroup(value)) {
      result[key] = resolveSelectorGroup(value, grafanaVersion);
    } else {
      assertIsSemverValid(value, key);
      result[key] = resolveSelector(value, grafanaVersion);
    }
  }
  return result;
}
function isVersionedSelectorGroup(target) {
  if (typeof target === "object") {
    const [first] = Object.keys(target);
    return !valid(first);
  }
  return false;
}
function resolveSelector(versionedSelector, grafanaVersion) {
  let versionToUse;
  let versions = Object.keys(versionedSelector).sort(compare);
  if (grafanaVersion === "latest") {
    return versionedSelector[versions[versions.length - 1]];
  }
  for (const version of versions) {
    if (gte(grafanaVersion, version)) {
      versionToUse = version;
    }
  }
  if (!versionToUse) {
    versionToUse = versions[versions.length - 1];
  }
  return versionedSelector[versionToUse];
}
function assertIsSemverValid(versionedSelector, selectorName) {
  if (!Object.keys(versionedSelector).every((version) => valid(version))) {
    throw new Error(`Invalid semver version: '${selectorName}'`);
  }
}

export { resolveSelectors };
//# sourceMappingURL=resolver.mjs.map
