linkedName

tcmts.cli.files.linkedName · #zchj57gi · term · runs on the server

uses tcmts.cli.files.fileFormat, which uses node:path

The file in the codebase a page's link reaches, by its name (and the rest of the link: #anchor), or undefined for a link that isn't to such a file (a URL, the same page, code, somewhere outside the codebase).

import { dirSegment, fileFormat, fileLeaf } from "#codebase/tcmts/cli/files";

export function linkedName(fromName: string, target: string): { name: string; rest: string } | undefined {
  if (/^[a-z][a-z0-9+.-]*:|^\/|^#/i.test(target)) return undefined;
  const cut = target.search(/[#?]/);
  const file = cut < 0 ? target : target.slice(0, cut);
  if (!fileFormat(file)) return undefined;
  const segs = fromName.split(".").slice(0, -1);
  for (const s of file.split("/").slice(0, -1)) {
    if (s === "..") {
      if (!segs.length) return undefined;
      segs.pop();
    } else if (s && s !== "." && s !== "src") segs.push(dirSegment(s));
  }
  let leaf: string;
  try {
    leaf = fileLeaf(file);
  } catch {
    return undefined;
  }
  return { name: [...segs, leaf].join("."), rest: cut < 0 ? "" : target.slice(cut) };
}

uses

used by