// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import type { Range } from "./types.ts";
import { parseRange } from "./parse_range.ts";

/**
 * Parses the given range string and returns a Range object. If the range string
 * is invalid, `undefined` is returned.
 *
 * @example Usage
 * ```ts
 * import { tryParseRange } from "@std/semver";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(tryParseRange(">=1.2.3 <1.2.4"), [
 *  [
 *    { operator: ">=", major: 1, minor: 2, patch: 3, prerelease: [], build: [] },
 *    { operator: "<", major: 1, minor: 2, patch: 4, prerelease: [], build: [] },
 *  ],
 * ]);
 * ```
 *
 * @param range The range string
 * @returns A Range object if valid otherwise `undefined`
 */
export function tryParseRange(
  range: string,
): Range | undefined {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return parseRange(range);
  } catch {
    return undefined;
  }
}

// denoCacheMetadata={"headers":{"cf-cache-status":"HIT","cf-ray":"a223e657ca8c7db6-LAX","content-length":"1050","set-cookie":"__cf_bm=zppT9uLb8rzqS8aqnpCFrN7U7BpiGf5yOQXSA5ivUPo-1785241875.170789-1.0.1.1-s5zZ9LXOEnQVPjDx_8OVzwKrBVy2BBowNc0zf3BGyBkz4OdrIwzahJD9YDrYZ20SpVLw.vy.Z7nJ_wCzNDzBbCyN_TYtifxZNEzEwuBKVrAKWgJZWS3aqJiCZncTNf_i; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Tue, 28 Jul 2026 12:31:15 GMT","access-control-expose-headers":"*","alt-svc":"h3=\":443\"; ma=86400","vary":"Origin","server":"cloudflare","etag":"\"d3117b4a448cf64bf8227cfaa7d19119\"","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';","x-robots-tag":"noindex","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=qK19fWOvw6gHId%2FS1FnjmLX0jtQ3VxdwFOyD13muhUvFvFsB%2FMGF%2FXMQPLfBHbodG4YYQV6hOk3WXa%2FaLNMyee7AWbSO8VK1DbfrA626uma7baWQ8yrQhRM%3D\"}]}","content-type":"text/typescript","age":"3116065","cross-origin-resource-policy":"cross-origin","access-control-allow-origin":"*","accept-ranges":"bytes","x-content-type-options":"nosniff","cache-control":"public, max-age=31536000, immutable","x-jsr-backend":"modules"},"url":"https://jsr.io/@std/semver/0.224.3/try_parse_range.ts","time":1785241875}