// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import type { Comparator, Range } from "./types.ts";
import { OPERATORS } from "./_constants.ts";
import { ALL, NONE } from "./constants.ts";
import { isSemVer } from "./is_semver.ts";

function isComparator(value: unknown): value is Comparator {
  if (
    value === null || value === undefined || Array.isArray(value) ||
    typeof value !== "object"
  ) return false;
  if (value === NONE || value === ALL) return true;
  const { operator } = value as Comparator;
  return (
    (operator === undefined ||
      OPERATORS.includes(operator)) &&
    isSemVer(value)
  );
}

/**
 * Does a deep check on the object to determine if its a valid range.
 *
 * Objects with extra fields are still considered valid if they have at
 * least the correct fields.
 *
 * Adds a type assertion if true.
 *
 * @example Usage
 * ```ts
 * import { isRange } from "@std/semver/is-range";
 * import { assert, assertFalse } from "@std/assert";
 *
 * const range = [[{ major: 1, minor: 2, patch: 3 }]];
 * assert(isRange(range));
 * assertFalse(isRange({}));
 * ```
 * @param value The value to check if its a valid Range
 * @returns True if its a valid Range otherwise false.
 */
export function isRange(value: unknown): value is Range {
  return Array.isArray(value) &&
    value.every((r) => Array.isArray(r) && r.every((c) => isComparator(c)));
}

// denoCacheMetadata={"headers":{"age":"3116065","content-type":"text/typescript","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';","cf-ray":"a223e657ca8d7db6-LAX","cross-origin-resource-policy":"cross-origin","access-control-allow-origin":"*","access-control-expose-headers":"*","x-jsr-backend":"modules","set-cookie":"__cf_bm=cIjUwXg2iir9VDHVKVAToaH6MDOl5.DOrLBlkAhecE4-1785241875.1710088-1.0.1.1-Pg0E7QynGVSBpPHFfPvHTqeyiR9oT0_tTnTOWpbpeFt0ZelRBTVMcIptujsDI2yQfOxQAFA0PjXX8IKpSf1cietlrjRZCst859G3VjPUPj1kElzvUYpgOAUtPFvnjG8C; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","x-robots-tag":"noindex","content-length":"1445","date":"Tue, 28 Jul 2026 12:31:15 GMT","alt-svc":"h3=\":443\"; ma=86400","vary":"Origin","accept-ranges":"bytes","etag":"\"302d99f67591f106984039a887bb446c\"","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","x-content-type-options":"nosniff","cf-cache-status":"HIT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=jmM6cYpsZLjJyxRQ38hlvpfTnWGK5cQRq7pIzm1vY3OvtLla6WGqLizWgmuSpeyspr%2BkIftL7B9dkJcADp0MG44Rq6t3cPCWGydd%2FyEW0s9JlZYsb6FRUP4%3D\"}]}"},"url":"https://jsr.io/@std/semver/0.224.3/is_range.ts","time":1785241875}