Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
13.4 KB
Raw Blame
// @vitest-environment node
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { remarkHeading } from "fumadocs-core/mdx-plugins";
import remarkGfm from "remark-gfm";
import remarkMdx from "remark-mdx";
import remarkParse from "remark-parse";
import { unified } from "unified";
import { describe, expect, it } from "vitest";
import { i18n, type Lang } from "./i18n";

// CommonMark does not parse a Markdown link whose destination contains
// unescaped spaces (for example `[…](/issues#透過 AI 代理建立)`), so the raw
// `[label](url)` text renders verbatim on the page. CJK headings often mix in
// English terms with spaces, making hand-written anchors easy to break.
//
// Parsing with the same remark-mdx + GFM pipeline fumadocs-mdx uses:
//   1. Any `](` left inside a plain text node is unrendered Markdown link
//      syntax the reader will see. Code blocks and inline code are separate
//      node types and are excluded.
//   2. Any internal link with a `#anchor` fragment is checked against the
//      target page's heading IDs (generated by fumadocs's `remarkHeading`
//      plugin, including `[#custom-id]` overrides) and explicit JSX `id="..."`
//      attributes, covering both in-page and cross-page links.

type JsxAttribute = {
  type?: string;
  name?: string;
  value?: unknown;
};

type AstNode = {
  type: string;
  value?: string;
  url?: string;
  position?: { start?: { line?: number } };
  data?: { hProperties?: { id?: unknown } };
  attributes?: JsxAttribute[];
  children?: AstNode[];
};

type UnrenderedLink = {
  line: number;
  text: string;
};

type ParsedLink = {
  line: number;
  url: string;
};

type ParsedDoc = {
  file: string;
  lang: Lang;
  route: string;
  unrenderedLinks: UnrenderedLink[];
  anchorIds: Set<string>;
  links: ParsedLink[];
};

type BrokenAnchor = {
  file: string;
  line: number;
  url: string;
  reason: string;
};

const docsDir = path.resolve(__dirname, "../content/docs");
const nonDefaultLanguages = i18n.languages
  .filter((lang) => lang !== i18n.defaultLanguage)
  .sort((a, b) => b.length - a.length);

const processor = unified()
  .use(remarkParse)
  .use(remarkMdx)
  .use(remarkGfm)
  .use(remarkHeading, { generateToc: false });

function listMdxFiles(dir: string): string[] {
  return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) return listMdxFiles(full);
    return entry.name.endsWith(".mdx") ? [full] : [];
  });
}

function stripFrontmatter(source: string): string {
  const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(source);
  // Keep the line count so reported line numbers match the file.
  return match
    ? source.replace(match[0], "\n".repeat(match[0].split("\n").length - 1))
    : source;
}

function parseDocPath(relPath: string): { lang: Lang; route: string } {
  const posixPath = relPath.split(path.sep).join("/");
  let base = posixPath.replace(/\.mdx$/, "");
  let lang: Lang = i18n.defaultLanguage;

  for (const candidate of nonDefaultLanguages) {
    if (base.endsWith(`.${candidate}`)) {
      lang = candidate;
      base = base.slice(0, -(candidate.length + 1));
      break;
    }
  }

  let route: string;
  if (base === "index") {
    route = "/";
  } else if (base.endsWith("/index")) {
    route = `/${base.slice(0, -"/index".length)}`;
  } else {
    route = `/${base}`;
  }

  return { lang, route };
}

function analyzeMdx(source: string): {
  unrenderedLinks: UnrenderedLink[];
  anchorIds: Set<string>;
  links: ParsedLink[];
} {
  const tree = processor.parse(stripFrontmatter(source));
  processor.runSync(tree);

  const unrenderedLinks: UnrenderedLink[] = [];
  const anchorIds = new Set<string>();
  const links: ParsedLink[] = [];

  const walk = (node: AstNode) => {
    if (
      node.type === "text" &&
      typeof node.value === "string" &&
      node.value.includes("](")
    ) {
      const startLine = node.position?.start?.line ?? 0;
      const lines = node.value.split(/\r?\n/);
      lines.forEach((lineText, offset) => {
        if (lineText.includes("](")) {
          unrenderedLinks.push({
            line: startLine > 0 ? startLine + offset : 0,
            text: lineText.trim(),
          });
        }
      });
    }

    if (
      node.type === "heading" &&
      typeof node.data?.hProperties?.id === "string"
    ) {
      anchorIds.add(node.data.hProperties.id);
    }

    if (
      (node.type === "mdxJsxFlowElement" ||
        node.type === "mdxJsxTextElement") &&
      Array.isArray(node.attributes)
    ) {
      for (const attr of node.attributes) {
        if (
          attr.type === "mdxJsxAttribute" &&
          attr.name === "id" &&
          typeof attr.value === "string" &&
          attr.value.length > 0
        ) {
          anchorIds.add(attr.value);
        }
      }
    }

    if (node.type === "link" && typeof node.url === "string") {
      links.push({
        line: node.position?.start?.line ?? 0,
        url: node.url,
      });
    }

    if (Array.isArray(node.children)) {
      node.children.forEach(walk);
    }
  };

  walk(tree as unknown as AstNode);
  return { unrenderedLinks, anchorIds, links };
}

function findUnrenderedLinks(source: string): UnrenderedLink[] {
  return analyzeMdx(source).unrenderedLinks;
}

function isLang(value: string): value is Lang {
  return (i18n.languages as readonly string[]).includes(value);
}

function pageKey(lang: Lang, route: string): string {
  return `${lang}:${route}`;
}

function resolveAnchorTarget(
  doc: ParsedDoc,
  url: string,
): { targetLang: Lang; targetRoute: string; rawHash: string } | null {
  if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//")) return null;

  const hashIndex = url.indexOf("#");
  if (hashIndex === -1) return null;

  const rawHash = url.slice(hashIndex + 1);
  if (!rawHash) return null;

  const rawPath = url.slice(0, hashIndex).split("?")[0] ?? "";
  let targetLang: Lang = doc.lang;
  let targetRoute = doc.route;

  if (rawPath) {
    if (rawPath.startsWith("/")) {
      const segments = rawPath.split("/").filter(Boolean);
      const first = segments[0];
      if (first && isLang(first)) {
        targetLang = first;
        const rest = segments.slice(1).join("/");
        targetRoute = rest ? `/${rest}` : "/";
      } else {
        targetRoute = rawPath === "/" ? "/" : rawPath.replace(/\/+$/, "");
      }
    } else {
      const baseDir =
        doc.route === "/" ? "/" : path.posix.dirname(doc.route);
      targetRoute = path.posix.resolve(baseDir, rawPath).replace(/\/+$/, "") || "/";
    }
  }

  return { targetLang, targetRoute, rawHash };
}

function findBrokenAnchors(
  doc: ParsedDoc,
  docsByKey: Map<string, ParsedDoc>,
): BrokenAnchor[] {
  const broken: BrokenAnchor[] = [];

  for (const { line, url } of doc.links) {
    const resolved = resolveAnchorTarget(doc, url);
    if (!resolved) continue;

    const { targetLang, targetRoute, rawHash } = resolved;
    const target =
      docsByKey.get(pageKey(targetLang, targetRoute)) ??
      docsByKey.get(pageKey(i18n.defaultLanguage, targetRoute));

    if (!target) {
      broken.push({
        file: doc.file,
        line,
        url,
        reason: `target page not found (${targetLang}:${targetRoute})`,
      });
      continue;
    }

    let decodedHash = rawHash;
    try {
      decodedHash = decodeURIComponent(rawHash);
    } catch {
      // Keep rawHash when percent-encoding is invalid so it fails matching below.
    }

    if (!target.anchorIds.has(decodedHash) && !target.anchorIds.has(rawHash)) {
      broken.push({
        file: doc.file,
        line,
        url,
        reason: `anchor "#${decodedHash}" not found in ${target.file}`,
      });
    }
  }

  return broken;
}

describe("findUnrenderedLinks", () => {
  it("flags links whose anchor contains spaces", () => {
    expect(
      findUnrenderedLinks(
        "- [透過 AI 代理建立任務](/issues#透過 AI 代理建立)的操作完成或失敗;",
      ),
    ).toEqual([
      {
        line: 1,
        text: "[透過 AI 代理建立任務](/issues#透過 AI 代理建立)的操作完成或失敗;",
      },
    ]);

    expect(
      findUnrenderedLinks(
        "見[AI 代理執行的臨時令牌](/auth-tokens#AI 代理執行的臨時令牌)。",
      ),
    ).toEqual([
      {
        line: 1,
        text: "見[AI 代理執行的臨時令牌](/auth-tokens#AI 代理執行的臨時令牌)。",
      },
    ]);
  });

  it("flags unrendered links inside GFM tables, JSX components, and formatted labels", () => {
    const mdx = [
      "---",
      "title: Shortcuts",
      "---",
      "",
      "| Col | Description |",
      "|---|---|",
      "| **評論與聊天** | 說明。<br />見[給正在執行的 AI 代理插話](/mentioning-agents#給正在執行的 AI 代理插話)。 |",
      "",
      "<Callout>",
      "See [**bold label**](/issues#with spaces) here.",
      "</Callout>",
    ].join("\n");

    expect(findUnrenderedLinks(mdx)).toEqual([
      {
        line: 7,
        text: "見[給正在執行的 AI 代理插話](/mentioning-agents#給正在執行的 AI 代理插話)。",
      },
      {
        line: 10,
        text: "](/issues#with spaces) here.",
      },
    ]);
  });

  it("reports the exact line inside a multi-line paragraph", () => {
    const mdx = [
      "---",
      "title: Test",
      "---",
      "",
      "First line of paragraph",
      "Second line with [broken](/issues#foo bar)",
      "Third line of paragraph",
    ].join("\n");

    expect(findUnrenderedLinks(mdx)).toEqual([
      {
        line: 6,
        text: "Second line with [broken](/issues#foo bar)",
      },
    ]);
  });

  it("accepts valid links", () => {
    const mdx = [
      "- [透過 AI 代理建立任務](/issues#透過-ai-代理建立)的操作完成或失敗;",
      "- [Updating CLI](/daemon-runtimes#updating-cli)",
      "- [External](https://example.com/docs#section)",
    ].join("\n");

    expect(findUnrenderedLinks(mdx)).toEqual([]);
  });

  it("ignores ]( inside inline code and fenced code blocks", () => {
    const mdx = [
      "Use `[label](/issues#with spaces)` as a broken example.",
      "",
      "```md",
      "[broken](/issues#透過 AI 代理建立)",
      "```",
    ].join("\n");

    expect(findUnrenderedLinks(mdx)).toEqual([]);
  });
});

describe("findBrokenAnchors", () => {
  function buildDocs(entries: Record<string, string>): Map<string, ParsedDoc> {
    const map = new Map<string, ParsedDoc>();
    for (const [file, source] of Object.entries(entries)) {
      const { lang, route } = parseDocPath(file);
      const parsed = analyzeMdx(source);
      map.set(pageKey(lang, route), {
        file,
        lang,
        route,
        ...parsed,
      });
    }
    return map;
  }

  it("accepts valid in-page, cross-page, custom-id, and JSX-id anchors", () => {
    const docs = buildDocs({
      "issues.zh-Hant.mdx": [
        "## 透過 AI 代理建立",
        "### 自訂錨點 [#custom-anchor]",
        "<Accordion title=\"Details\" id=\"accordion-id\" />",
        "",
        "See [same page](#透過-ai-代理建立) and [custom](#custom-anchor) and [jsx](#accordion-id).",
      ].join("\n"),
      "inbox.zh-Hant.mdx": [
        "See [create via agent](/issues#透過-ai-代理建立).",
        "See [custom](/issues#custom-anchor).",
        "See [jsx](/issues#accordion-id).",
        "See [external](https://example.com#not-checked).",
      ].join("\n"),
    });

    for (const doc of docs.values()) {
      expect(findBrokenAnchors(doc, docs)).toEqual([]);
    }
  });

  it("flags missing in-page anchors and missing cross-page targets", () => {
    const docs = buildDocs({
      "issues.mdx": [
        "## Overview",
        "",
        "See [bad in-page](#does-not-exist).",
        "See [bad cross-page](/missing-page#overview).",
      ].join("\n"),
      "inbox.mdx": "See [wrong anchor](/issues#wrong-heading).\n",
    });

    const issuesDoc = docs.get("en:/issues")!;
    const inboxDoc = docs.get("en:/inbox")!;

    expect(findBrokenAnchors(issuesDoc, docs)).toEqual([
      {
        file: "issues.mdx",
        line: 3,
        url: "#does-not-exist",
        reason: 'anchor "#does-not-exist" not found in issues.mdx',
      },
      {
        file: "issues.mdx",
        line: 4,
        url: "/missing-page#overview",
        reason: "target page not found (en:/missing-page)",
      },
    ]);

    expect(findBrokenAnchors(inboxDoc, docs)).toEqual([
      {
        file: "inbox.mdx",
        line: 1,
        url: "/issues#wrong-heading",
        reason: 'anchor "#wrong-heading" not found in issues.mdx',
      },
    ]);
  });
});

describe("docs content", () => {
  const files = listMdxFiles(docsDir);
  const parsedDocs: ParsedDoc[] = files.map((file) => {
    const rel = path.relative(docsDir, file);
    const { lang, route } = parseDocPath(rel);
    return {
      file: rel,
      lang,
      route,
      ...analyzeMdx(readFileSync(file, "utf8")),
    };
  });
  const docsByKey = new Map<string, ParsedDoc>(
    parsedDocs.map((doc) => [pageKey(doc.lang, doc.route), doc]),
  );

  it("finds the docs pages", () => {
    expect(parsedDocs.length).toBeGreaterThan(0);
  });

  it.each(parsedDocs.map((doc) => [doc.file, doc] as const))(
    "%s has no unrendered markdown links",
    (_name, doc) => {
      expect(
        doc.unrenderedLinks.map((hit) => ({ file: doc.file, ...hit })),
      ).toEqual([]);
    },
  );

  it.each(parsedDocs.map((doc) => [doc.file, doc] as const))(
    "%s has valid internal anchors",
    (_name, doc) => {
      expect(findBrokenAnchors(doc, docsByKey)).toEqual([]);
    },
  );
});