Files
nvke/tools/check-docs-mdx
Pete MacKinnonandClaude Sonnet 4.6 00cd031220 ci: add Fern Docs CI required gate (#1279)
* ci: add Fern Docs CI required gate

Add a required-merge-gate workflow (fern-docs-ci.yml) that runs
python3 tools/check-docs-mdx, fern check, and fern docs md check on
every pull request that touches docs or fern/. The gate carries no
secrets and requires no FERN_TOKEN.

Also drop the Fern CLI version pin from api-docs.yml; both workflows
now use fern-api@latest.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

* ci(fern-docs-ci): always run, skip expensive steps when no docs changed

Without a required-check-aware path filter the workflow never posts a
status on non-docs PRs, which blocks merge if the check is required.
Remove the trigger-level paths: filter and use a changed-files step
inside the job to skip the Fern steps when no relevant paths changed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

* ci: add Fern Docs preview build and comment workflows

Adds the two-workflow split for PR previews per the fern-scripts skill:
- fern-docs-preview-build.yml: collects fern/ and docs/ sources in the
  PR context (no secrets), uploads as artifact
- fern-docs-preview-comment.yml: triggered by workflow_run, generates a
  Fern preview with DOCS_FERN_TOKEN and posts a 🌿 comment on the PR

Requires DOCS_FERN_TOKEN organization secret. Note: api-docs.yml uses
FERN_TOKEN; both need the same underlying Fern org token.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

* ci(fern-docs-preview): use FERN_TOKEN to match org convention

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

* ci(fern-docs-preview): fix preview ID collision and URL extraction

Use pr-{number} as the Fern preview --id instead of HEAD_REF, matching
the api-docs.yml convention and avoiding collisions between PRs that share
a branch name. Switch URL extraction from a look-behind regex requiring a
trailing paren to a simpler https:// grep matching Fern's actual output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

* ci(fern-docs-preview): harden comment workflow against artifact injection

- Validate pr_number is numeric before writing to GITHUB_OUTPUT
- Checkout fern/ from the base branch and replace the artifact copy so
  npx never runs in PR-controlled code (prevents .npmrc / package.json
  injection that could exfiltrate FERN_TOKEN)
- Validate preview URL is on buildwithfern.com before sending FERN_TOKEN
  in the page-links curl call
- Drop FERN_TOKEN from page-links env; the get-slug-for-file API call
  does not require it

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>

---------

Signed-off-by: Pete MacKinnon <mackinnon.pd@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-09 12:43:23 -04:00

198 lines
6.8 KiB
Python
Executable File

#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Check markdown under docs/ and fern/ for constructs that break Fern's MDX parser.
Fern compiles .md files through MDX, which rejects constructs that are valid
in plain markdown. Fenced code, inline code spans, YAML frontmatter and
{/* JSX comments */} are ignored.
Checks:
void-element Non-self-closing void HTML tag (<br>, <img ...>) [--fix]
autolink <https://...> autolink [--fix]
lt-digit Bare "<" followed by a digit (<100ms)
placeholder Bare ALL_CAPS placeholder in prose (<GPU_UUID>)
brace Unescaped "{" outside code (parsed as a JSX expression)
html-comment <!-- ... --> comment
Usage:
check-docs-mdx [--fix] [--exclude GLOB]... [PATH ...]
PATH defaults to whichever of docs/ and fern/ exist. --exclude takes an
fnmatch glob matched against each file's path (repeatable), e.g.
--exclude 'docs/design/*' --exclude '*/AGENTS.md'.
Exit codes: 0 clean, 1 findings, 2 usage error. Requires only python3 (stdlib).
"""
import argparse
import fnmatch
import re
import sys
from pathlib import Path
VOID_ELEMENTS = "img|br|hr|input|source|meta|link|area|base|col|embed|param|track|wbr"
VOID_RE = re.compile(rf"<(?:{VOID_ELEMENTS})(?=[\s/>])[^<>]*(?<!/)>")
AUTOLINK_RE = re.compile(r"<(https?://[^>\s]+)>")
LT_DIGIT_RE = re.compile(r"<\d")
PLACEHOLDER_RE = re.compile(r"<[A-Z][A-Z0-9_]+>")
BRACE_RE = re.compile(r"(?<!\\)\{")
COMMENT_RE = re.compile(r"<!--")
INLINE_CODE_RE = re.compile(r"(?<!`)(`+)(?!`).+?(?<!`)\1(?!`)")
FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
JSX_COMMENT_OPEN = "{/*"
JSX_COMMENT_CLOSE = "*/}"
SKIP_DIRS = {".git", "node_modules"}
def _blank_code(line):
return INLINE_CODE_RE.sub(lambda m: " " * len(m.group(0)), line)
def _strip_jsx_comments(line, in_comment):
out = []
while line:
if in_comment:
end = line.find(JSX_COMMENT_CLOSE)
if end == -1:
return "".join(out), True
line = line[end + len(JSX_COMMENT_CLOSE):]
in_comment = False
continue
start = line.find(JSX_COMMENT_OPEN)
if start == -1:
out.append(line)
break
out.append(line[:start])
line = line[start + len(JSX_COMMENT_OPEN):]
in_comment = True
return "".join(out), in_comment
def _fix_outside_code(line, regex, repl):
out, pos = [], 0
for m in INLINE_CODE_RE.finditer(line):
out.append(regex.sub(repl, line[pos:m.start()]))
out.append(m.group(0))
pos = m.end()
out.append(regex.sub(repl, line[pos:]))
return "".join(out)
def _fix_void(m):
return m.group(0)[:-1].rstrip() + " />"
def scan(path, fix):
text = path.read_text(encoding="utf-8")
lines = text.split("\n")
findings = []
fence = None
in_comment = False
start = 0
if lines and lines[0].strip() == "---":
for i in range(1, len(lines)):
if lines[i].strip() in ("---", "..."):
start = i + 1
break
for idx in range(start, len(lines)):
raw = lines[idx]
lineno = idx + 1
fm = FENCE_RE.match(raw)
if fence is None:
if fm and not (fm.group(1)[0] == "`" and "`" in fm.group(2)):
fence = (fm.group(1)[0], len(fm.group(1)))
continue
else:
if fm and fm.group(1)[0] == fence[0] and len(fm.group(1)) >= fence[1] and not fm.group(2).strip():
fence = None
continue
raw_no_code = _blank_code(raw)
scan_line, in_comment = _strip_jsx_comments(raw_no_code, in_comment)
for m in VOID_RE.finditer(scan_line):
findings.append((lineno, "void-element", f"non-self-closing void element {m.group(0)!r} (use <tag ... />)"))
for m in AUTOLINK_RE.finditer(scan_line):
findings.append((lineno, "autolink", f"autolink {m.group(0)!r} parses as JSX (use [url](url))"))
for m in LT_DIGIT_RE.finditer(scan_line):
findings.append((lineno, "lt-digit", "bare '<' before a digit parses as a tag (use &lt;)"))
for m in PLACEHOLDER_RE.finditer(scan_line):
findings.append((lineno, "placeholder", f"bare placeholder {m.group(0)!r} parses as a tag (wrap in backticks)"))
for m in BRACE_RE.finditer(scan_line):
findings.append((lineno, "brace", "unescaped '{' parses as a JSX expression (use \\{ or backticks)"))
for m in COMMENT_RE.finditer(scan_line):
findings.append((lineno, "html-comment", "HTML comment not valid in MDX (remove or use {/* ... */})"))
if fix and not in_comment and JSX_COMMENT_OPEN not in raw_no_code:
new = _fix_outside_code(raw, VOID_RE, _fix_void)
new = _fix_outside_code(new, AUTOLINK_RE, lambda m: f"[{m.group(1)}]({m.group(1)})")
lines[idx] = new
if fix:
new_text = "\n".join(lines)
if new_text != text:
path.write_text(new_text, encoding="utf-8")
return findings
def collect(paths, excludes):
files = []
for p in paths:
root = Path(p)
candidates = [root] if root.is_file() else sorted(root.rglob("*"))
for f in candidates:
if f.suffix not in (".md", ".mdx") or not f.is_file():
continue
if SKIP_DIRS & set(f.parts):
continue
posix = f.as_posix()
if any(fnmatch.fnmatch(posix, pat) for pat in excludes):
continue
files.append(f)
return files
def main():
ap = argparse.ArgumentParser(description="Check markdown for MDX-unsafe constructs")
ap.add_argument("paths", nargs="*", help="files or directories (default: docs fern)")
ap.add_argument("--fix", action="store_true", help="auto-fix void-element and autolink findings")
ap.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="skip files matching this fnmatch glob (repeatable)")
args = ap.parse_args()
paths = args.paths or [d for d in ("docs", "fern") if Path(d).is_dir()]
if not paths:
print("error: no PATH given and neither docs/ nor fern/ exists", file=sys.stderr)
return 2
for p in paths:
if not Path(p).exists():
print(f"error: {p} does not exist", file=sys.stderr)
return 2
total = 0
for f in collect(paths, args.exclude):
results = scan(f, args.fix)
if args.fix:
results = scan(f, False)
for lineno, kind, msg in results:
print(f"{f}:{lineno}: [{kind}] {msg}")
total += 1
if total:
print(f"\nMDX safety: {total} issue(s) found", file=sys.stderr)
return 1
print("OK: all doc files are MDX-safe")
return 0
if __name__ == "__main__":
sys.exit(main())