// 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 { greaterThan } from "./greater_than.ts";

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

// denoCacheMetadata={"headers":{"x-jsr-backend":"modules","cf-cache-status":"HIT","content-length":"1175","etag":"\"15be53fdb475a4daea09af9ac931726d\"","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","set-cookie":"__cf_bm=u1JS1QUgZv_RQjV0KVfukhHpw95JlgEMV4XoSELioNk-1785241875.1636753-1.0.1.1-V6NkVH4tzJGHx8m08GeaXHsIp1ITyyV784G_u7d4jam.ayoWp925_ZodXTZl3rjt4SeTDW2Tg3BggE4gxMBssuamnvjG3omVGMsoj3IACfktRAlh5JO3zlQ0cIA3.VRk; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","x-content-type-options":"nosniff","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=%2Bx7bmMHISNPeV3Yp%2B58lbahRVoMhP4prYNfsNKArhD8pxmjb%2BOs%2FSAAB5dU3muCqS815LS%2FMuZmYwR4UPivznuEZbZv%2FAKkOob7EXkADpFYOX8fi5aSjyi0%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","age":"608576","cross-origin-resource-policy":"cross-origin","content-type":"text/typescript","access-control-allow-origin":"*","vary":"Origin","x-robots-tag":"noindex","cf-ray":"a223e657ca717db6-LAX","date":"Tue, 28 Jul 2026 12:31:15 GMT","accept-ranges":"bytes","access-control-expose-headers":"*","server":"cloudflare","cache-control":"public, max-age=31536000, immutable","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';"},"url":"https://jsr.io/@std/semver/0.224.3/max_satisfying.ts","time":1785241875}