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

import { assertPath } from "./assert_path.ts";

export function stripSuffix(name: string, suffix: string): string {
  if (suffix.length >= name.length) {
    return name;
  }

  const lenDiff = name.length - suffix.length;

  for (let i = suffix.length - 1; i >= 0; --i) {
    if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) {
      return name;
    }
  }

  return name.slice(0, -suffix.length);
}

export function lastPathSegment(
  path: string,
  isSep: (char: number) => boolean,
  start = 0,
): string {
  let matchedNonSeparator = false;
  let end = path.length;

  for (let i = path.length - 1; i >= start; --i) {
    if (isSep(path.charCodeAt(i))) {
      if (matchedNonSeparator) {
        start = i + 1;
        break;
      }
    } else if (!matchedNonSeparator) {
      matchedNonSeparator = true;
      end = i + 1;
    }
  }

  return path.slice(start, end);
}

export function assertArgs(path: string, suffix: string) {
  assertPath(path);
  if (path.length === 0) return path;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string. Received ${JSON.stringify(suffix)}`,
    );
  }
}

// denoCacheMetadata={"headers":{"access-control-expose-headers":"*","accept-ranges":"bytes","access-control-allow-origin":"*","content-type":"text/typescript","etag":"\"efb377e6dda72c3c73b19e6afde57ed1\"","x-jsr-backend":"modules","x-robots-tag":"noindex","x-content-type-options":"nosniff","age":"1636554","vary":"Origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cf-cache-status":"HIT","server":"cloudflare","date":"Tue, 28 Jul 2026 12:31:15 GMT","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":"a223e6586c717db6-LAX","cross-origin-resource-policy":"cross-origin","set-cookie":"__cf_bm=AnJQCnywS8EtPC4AGOctklFsjd_XMwMc8970oGhuKYA-1785241875.2748518-1.0.1.1-OoTuL.T_aR1xM85kx8ajg1ePgeUMInY46.pNYeHmUbmqEu_4xjOscztTb6k7YfJS3bZz.yrV7d4WpnUz_zZf7Sd2z0RXTmzbpzTDeL6bqFFq1MtQdSib4eovE_52s4zx; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=sZufY%2B9F8YX1%2FWH%2B7X8DtPsfi4gvbNaYYLBMDvlt3asLXZbTnRG%2FMMa1zUJU8kNNomkdBw3abiFbZU1rE29o8rdq925n48lPxPQBiL9OKj8TzEXy1LOnXzM%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","content-length":"1262","cache-control":"public, max-age=31536000, immutable"},"url":"https://jsr.io/@std/path/0.224.0/_common/basename.ts","time":1785241875}