import fs from "fs";
import path from "path";
function canonicalURL(url, base) {
  let pathname = url.replace(/\/index.html$/, "");
  pathname = pathname.replace(/\/1\/?$/, "");
  if (!path.extname(pathname))
    pathname = pathname.replace(/(\/+)?$/, "/");
  pathname = pathname.replace(/\/+/g, "/");
  return new URL(pathname, base);
}
async function getPackageJSON(projectRoot) {
  const possibleLocs = new Set(["./package.json"]);
  for (const possibleLoc of possibleLocs) {
    const packageJSONLoc = new URL(possibleLoc, projectRoot);
    if (fs.existsSync(packageJSONLoc)) {
      return JSON.parse(await fs.promises.readFile(packageJSONLoc, "utf8"));
    }
  }
}
function parseNpmName(spec) {
  if (!spec || spec[0] === "." || spec[0] === "/")
    return void 0;
  let scope;
  let name = "";
  let parts = spec.split("/");
  if (parts[0][0] === "@") {
    scope = parts[0];
    name = parts.shift() + "/";
  }
  name += parts.shift();
  let subpath = parts.length ? `./${parts.join("/")}` : void 0;
  return {
    scope,
    name,
    subpath
  };
}
function codeFrame(src, loc) {
  if (!loc)
    return "";
  const lines = src.replace(/\r\n/g, "\n").split("\n");
  const visibleLines = [];
  for (let n = -2; n <= 2; n++) {
    if (lines[loc.line + n])
      visibleLines.push(loc.line + n);
  }
  let gutterWidth = 0;
  for (const lineNo of visibleLines) {
    let w = `> ${lineNo}`;
    if (w.length > gutterWidth)
      gutterWidth = w.length;
  }
  let output = "";
  for (const lineNo of visibleLines) {
    const isFocusedLine = lineNo === loc.line - 1;
    output += isFocusedLine ? "> " : "  ";
    output += `${lineNo + 1} | ${lines[lineNo]}
`;
    if (isFocusedLine)
      output += `${[...new Array(gutterWidth)].join(" ")}  | ${[...new Array(loc.column)].join(" ")}^
`;
  }
  return output;
}
export {
  canonicalURL,
  codeFrame,
  getPackageJSON,
  parseNpmName
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL2NvcmUvdXRpbC50cyJdLAogICJtYXBwaW5ncyI6ICJBQUNBO0FBQ0E7Q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