All files / apps/developer-portal/tools/collect docs.ts

97.7% Statements 85/87
87.3% Branches 55/63
100% Functions 15/15
100% Lines 69/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188                              1x 1x 1x   1x           1x 22x 22x   22x 83x   83x 81x 2x 79x     22x 19x       1x 1x           1x 8x   1x 19x 19x   15x   4x               1x 4x 4x   4x   4x   4x   2x   1x     1x 12x 10x 9x 8x 7x 6x   1x                 1x           1x 18x   6x   6x   6x     18x       18x             1x 12x   1x   12x             1x 4x         4x   13x   13x   12x   12x 13x     4x   12x   12x 12x   12x                           13x   15x   4x     12x      
import { access, readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import type { AuditMeta } from "#layers/snapshot/shared/types/AuditMeta.ts";
import type { DecisionOutcome, DecisionStatus } from "#layers/snapshot/shared/decisions.ts";
import type { DocKind } from "#layers/snapshot/shared/types/DocKind.ts";
import type { DocLink } from "#layers/snapshot/shared/types/DocLink.ts";
import type { DocPage } from "#layers/snapshot/shared/types/DocPage.ts";
import type { DocsArtifact } from "#layers/snapshot/shared/types/DocsArtifact.ts";
import { parseFindings } from "#layers/snapshot/shared/audits.ts";
import { DECISION_OUTCOMES, DECISION_STATUSES } from "#layers/snapshot/shared/decisions.ts";
import { frontmatterFields } from "../lib/decisions.ts";
import { WORKSPACE_ROOT } from "../lib/paths.ts";
import { git } from "../lib/run.ts";
 
// Excluding nested openers keeps failed link candidates from rescanning each other's text and href.
const LINK = /\[[^[\]]*\]\((?<href>[^()\s]+)(?:\s+"[^"]*")?\)/g;
const HEADING = /^#{1,3}[^\S\n]+\S.*$/gm;
const FENCE = /^\s*(`{3,}|~{3,})/;
// Match whole backtick runs so an unmatched delimiter cannot restart at each of its backticks.
const CODE_SPAN = /(?<!`)(`+)(?:[^`\n]|\n(?![^\S\n]*\n))+\1(?!`)/g;
 
/**
 * Every inline link's href outside code. A docs page that shows link syntax in a sample is
 * describing a link, not making one, and the remark plugin never sees it as one.
 */
export const hrefsIn = (source: string): string[] => {
    const prose: string[] = [];
    let fence: string | null = null;
 
    for (const line of source.split("\n")) {
        const marker = FENCE.exec(line)?.[1];
 
        if (fence === null && marker) fence = marker;
        else if (fence !== null && marker?.startsWith(fence) && line.trim() === marker)
            fence = null;
        else if (fence === null) prose.push(line);
    }
 
    return [...prose.join("\n").replace(CODE_SPAN, " ").matchAll(LINK)].map(
        (match) => match.groups?.href ?? "",
    );
};
 
const DECISION_PATH = /^docs\/decisions\/\d{4}-/;
const AUDIT_PATH = /^docs\/audits\/\d{4}-/;
 
/**
 * Anchors and external links are somebody else's problem; only repo-relative paths are resolvable.
 * A `<placeholder>` is an instruction to whoever copies the doc, not a link, so it is never flagged.
 */
const isRepoRelative = (href: string): boolean =>
    !/^(?:[a-z]+:|\/\/|#)/i.test(href) && !href.includes("<");
 
const exists = async (path: string): Promise<boolean> => {
    try {
        await access(path);
 
        return true;
    } catch {
        return false;
    }
};
 
/**
 * Resolves against the filesystem, not the route table: these files are read on GitHub first, where
 * a link to `./layers` or to `./vite.config.ts` is valid.
 */
const checkLink = async (fromFile: string, href: string): Promise<DocLink | null> => {
    const [target] = href.split("#");
    const path = target?.replace(/:\d+(?:-\d+)?$/, "");
 
    Iif (!path) return null;
 
    const absolute = resolve(dirname(resolve(WORKSPACE_ROOT, fromFile)), decodeURIComponent(path));
 
    if (await exists(absolute)) return null;
 
    if (await exists(`${absolute}.md`)) return null;
 
    return { href, resolved: absolute.slice(WORKSPACE_ROOT.length + 1) };
};
 
const kindOf = (path: string): DocKind => {
    if (DECISION_PATH.test(path)) return "decision";
    if (AUDIT_PATH.test(path)) return "audit";
    if (path.endsWith("CHANGELOG.md")) return "changelog";
    if (path.endsWith("CLAUDE.md")) return "agent";
    if (path.endsWith("SKILL.md")) return "skill";
    if (path.startsWith("docs/")) return "doc";
 
    return "readme";
};
 
interface DecisionMeta {
    status: DecisionStatus | null;
    decision: DecisionOutcome | null;
    supersededBy: string | null;
}
 
const NO_DECISION_META: DecisionMeta = { status: null, decision: null, supersededBy: null };
 
/**
 * An unrecognised `status`/`decision` value answers null instead of a guess, so a frontmatter typo
 * shows as a missing badge in the dashboard.
 */
export const decisionMetaOf = (path: string, source: string): DecisionMeta => {
    if (!DECISION_PATH.test(path)) return NO_DECISION_META;
 
    const fields = frontmatterFields(source);
 
    Iif (fields === null) return NO_DECISION_META;
 
    const status = (DECISION_STATUSES as readonly string[]).includes(fields.status ?? "")
        ? (fields.status as DecisionStatus)
        : null;
    const decision = (DECISION_OUTCOMES as readonly string[]).includes(fields.decision ?? "")
        ? (fields.decision as DecisionOutcome)
        : null;
 
    return {
        status,
        decision,
        supersededBy: decision === "superseded" ? (fields.supersededBy ?? null) : null,
    };
};
 
const auditMetaOf = (path: string, source: string): AuditMeta | null => {
    if (!AUDIT_PATH.test(path)) return null;
 
    const fields = frontmatterFields(source) ?? {};
 
    return {
        scope: fields.scope ?? null,
        commit: fields.commit ?? null,
        findings: parseFindings(source),
    };
};
 
export const collectDocs = async (generatedAt: string): Promise<DocsArtifact> => {
    const paths = (
        await git(["ls-files", "--cached", "--others", "--exclude-standard", "--", "*.md"])
    )
        .split("\n")
        .filter(Boolean);
    const read = await Promise.all(
        paths.map(async (path): Promise<DocPage | undefined> => {
            const absolute = resolve(WORKSPACE_ROOT, path);
 
            if (!(await exists(absolute))) return undefined;
 
            const source = await readFile(absolute, "utf8");
 
            const title = source.match(HEADING)?.[0]?.replace(/^#{1,3}\s+/, "");
            const checked = await Promise.all(
                hrefsIn(source)
                    .filter(isRepoRelative)
                    .map((href) => checkLink(path, href)),
            );
            const brokenLinks = checked.filter((link): link is DocLink => link !== null);
 
            const updatedAt = (await git(["log", "-1", "--format=%cI", "--", path])).trim();
            const decisionMeta = decisionMetaOf(path, source);
 
            return {
                path,
                kind: kindOf(path),
                title: title?.trim() ?? path,
                words: source.split(/\s+/).filter(Boolean).length,
                updatedAt: updatedAt || null,
                decisionStatus: decisionMeta.status,
                decisionOutcome: decisionMeta.decision,
                decisionSupersededBy: decisionMeta.supersededBy,
                audit: auditMetaOf(path, source),
                brokenLinks,
            };
        }),
    );
    const pages = read.filter((page): page is DocPage => page !== undefined);
 
    pages.sort((a, b) => a.path.localeCompare(b.path));
 
    return {
        generatedAt,
        pages,
        brokenLinkCount: pages.reduce((sum, page) => sum + page.brokenLinks.length, 0),
    };
};