// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import type { Range, SemVer } from "./types.ts";
import { satisfies } from "./satisfies.ts";
import { lessThan } from "./less_than.ts";

/**
 * Returns the lowest version in the list that satisfies the range, or `undefined` if
 * none of them do.
 *
 * @example Usage
 * ```ts
 * import { parse, parseRange, minSatisfying } from "@std/semver";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const versions = ["0.2.0", "1.2.3", "1.3.0", "2.0.0", "2.1.0"].map(parse);
 * const range = parseRange(">=1.0.0 <2.0.0");
 *
 * assertEquals(minSatisfying(versions, range), parse("1.2.3"));
 * ```
 *
 * @param versions The versions to check.
 * @param range The range of possible versions to compare to.
 * @returns The lowest version in versions that satisfies the range.
 */
export function minSatisfying(
  versions: SemVer[],
  range: Range,
): SemVer | undefined {
  let min;
  for (const version of versions) {
    if (!satisfies(version, range)) continue;
    min = min && lessThan(min, version) ? min : version;
  }
  return min;
}

// denoCacheMetadata={"headers":{"access-control-allow-origin":"*","age":"3720275","cache-control":"public, max-age=31536000, immutable","vary":"Origin","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","set-cookie":"__cf_bm=4Acfp0iuJKEHdLyUL76U7bu5.WUdEmjbCd68sSl7pLg-1785241875.1650794-1.0.1.1-Bw3bJlTIhxVvrF7AduRXcuKmZxbmHFi2uK3oYwQR4TXv1LxlzR52i5c0c38hoIP8g3MCeIkhOUz.d4ha66Wd_qldQZI7I.x2VdL2F8CWdyY4mwckcU4fI.UnB2IGNjyX; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","etag":"\"500453f57b5dc0869339be51e6d66351\"","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=Klj9%2BNsassZQuoLubIwhgm%2F0HxvxCJ3ADDbCqNgcn95WXzKw0zrOma%2BzPpspoAd2LDqdLieceKyDCuy%2FaXM1UbYInCksyKaEMENnUZYYYuJaHq9q5nGGlD0%3D\"}]}","server":"cloudflare","x-content-type-options":"nosniff","access-control-expose-headers":"*","content-length":"1164","alt-svc":"h3=\":443\"; ma=86400","cf-ray":"a223e657ca727db6-LAX","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-cache-status":"HIT","x-jsr-backend":"modules","content-type":"text/typescript","accept-ranges":"bytes"},"url":"https://jsr.io/@std/semver/0.224.3/min_satisfying.ts","time":1785241875}