Skip to main content

rto_render/
docs.rs

1//! The documentation-site renderer: ADR markdown → themed HTML pages, produced
2//! deterministically so CI diffs are meaningful. Replaces the shell
3//! `md2html.awk` stopgap with a real `CommonMark` parser (`pulldown-cmark`),
4//! fixing the whole class of hand-rolled-parser bugs (backtick runs, tables,
5//! heading edge cases) we hit before.
6//!
7//! Page chrome (theme, nav, back-link, footer) matches the previous site so the
8//! switch is drop-in. This module is pure string generation; the `roteiro`
9//! binary owns walking `docs/adr` and copying static assets.
10
11use std::collections::BTreeMap;
12use std::fmt::Write as _;
13
14use pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag, TagEnd, html};
15
16/// A rendered ADR: its title (for the index) and the full themed HTML page.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RenderedAdr {
19    /// The ADR title (first `# ` heading, or the fallback passed to
20    /// [`render_adr`]).
21    pub title: String,
22    /// The complete HTML document.
23    pub html: String,
24}
25
26/// Where each source document is **actually published**: the file the site
27/// serves, keyed by the source markdown's file name.
28///
29/// [`rewrite_doc_link`] used to derive a link's target from the link's own
30/// spelling — `../BUILD_PLAN_V2.md` → `../BUILD_PLAN_V2.html` — which is correct
31/// only while every document is served under its own stem. Site pages ended
32/// that: a page is published as its declared `site-page:` slug, and a slug is
33/// URL-safe by construction (`[a-z0-9-]+`), so `docs/BUILD_PLAN_V2.md` is served
34/// as `build-plan-v2.html`. The rewrite then pointed four correct repository
35/// links at a page that is never emitted — issue #446, live on roteiro.dev.
36///
37/// So the served name is *looked up* rather than guessed. The renderer is handed
38/// the index of what the site emits, which is the only thing that knows the
39/// answer.
40///
41/// Keyed by file name rather than by full path because the site mirrors the
42/// repository's layout — `docs/*.md` at the root, `docs/adr/*.md` under `adr/` —
43/// so a link's directory hops are already correct and only the final segment can
44/// differ. A file name claimed by two published documents is recorded as
45/// **ambiguous** and left unrewritten: guessing which one a link meant is how a
46/// link silently points at the wrong page, which is worse than the 404 it
47/// replaces.
48#[derive(Debug, Default, Clone, PartialEq, Eq)]
49pub struct PublishedPages(BTreeMap<String, Option<String>>);
50
51impl PublishedPages {
52    /// An empty index: every `.md` link falls back to its own stem.
53    #[must_use]
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    /// Record that `source_file` (a markdown file name, e.g. `BUILD_PLAN_V2.md`)
59    /// is served as `served_as` (e.g. `build-plan-v2.html`).
60    ///
61    /// A second, differing claim on one file name makes it ambiguous; see the
62    /// type's documentation for why that is left unrewritten.
63    pub fn publish(&mut self, source_file: &str, served_as: &str) {
64        self.0
65            .entry(source_file.to_owned())
66            .and_modify(|slot| {
67                if slot.as_deref() != Some(served_as) {
68                    *slot = None;
69                }
70            })
71            .or_insert_with(|| Some(served_as.to_owned()));
72    }
73
74    /// The file `source_file` is served as, or `None` when it is unknown or
75    /// ambiguous.
76    fn served(&self, source_file: &str) -> Option<&str> {
77        self.0.get(source_file)?.as_deref()
78    }
79}
80
81/// Where a link that leaves the site points instead: the repository's own web
82/// view, at the commit the site was built from.
83///
84/// The Build Plan cites code as evidence for its claims — `[sync](../crates/…
85/// /sync.rs)` — which is correct in a checkout and dead on roteiro.dev, because
86/// `render docs` publishes documents and not source. Six such links were live on
87/// the site (issue #456). This is the answer chosen for them: keep the link's
88/// affordance and move its target to the one place the file is actually served.
89///
90/// # Pinned to a commit, not to a branch
91///
92/// `blob` carries a sha (`…/blob/<sha>`), not `…/blob/main`. GitHub serves a
93/// blob by sha forever, so the link keeps resolving after the file is renamed or
94/// deleted; a `main` link 404s on the next rename, and this is a *retired* plan
95/// whose citations describe the code as it stood, so drifting them onto today's
96/// `main` would be wrong even when it resolved. It is also the rule the vault
97/// renderer already ships (`source_blob_base` + `head_commit_id`), and one repo
98/// with two answers to "which commit does a source link mean" is its own defect.
99///
100/// The cost is stated rather than hidden: a site rendered from a commit that was
101/// never pushed yields links the host has never heard of. That is a local
102/// preview, not the published site — the Website workflow renders from a commit
103/// GitHub already has.
104///
105/// # No mappable origin
106///
107/// Construction goes through [`SourceBase::new`], which yields `None` when the
108/// caller has no blob base to offer — no `origin` remote, or a remote whose URL
109/// does not map to a web view. Links are then left exactly as they are: still
110/// correct in a checkout, still dead on the site. That is deliberate and is the
111/// least-bad of the three: refusing to render would break `render docs` in any
112/// repository without an `origin` (every test fixture, every fresh `git init`),
113/// and demoting the link to plain text would destroy information to hide a
114/// problem the reader can otherwise route around.
115///
116/// # Can the class recur?
117///
118/// Not while a base exists: the rule is structural, not a list of the six links
119/// that were found. *Any* link climbing above the site root is re-aimed, so a new
120/// citation added to any rendered document is handled the day it is written, and
121/// `a_link_out_of_the_site_goes_to_the_repository` is what fails if that stops.
122///
123/// It recurs silently in exactly one case — a site rendered where no base can be
124/// derived — and nothing catches that, because the output is the *authored* link
125/// and there is no rendered-site link gate (issue #459) to notice. That case is
126/// the one the deploy does not hit: the Website workflow checks out with an
127/// `origin` on `github.com`, and `without_an_origin_remote_a_source_link_is_left_as_authored`
128/// pins the behaviour rather than the absence of a gate.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct SourceBase {
131    /// Web blob base, no trailing slash — e.g.
132    /// `https://github.com/owner/repo/blob/<sha>`.
133    blob: String,
134    /// The rendered document's own directory, repository-relative and with no
135    /// trailing slash: `docs`, `docs/adr`, `website/pages`. A link is resolved
136    /// against this to get the path the repository serves.
137    dir: String,
138}
139
140impl SourceBase {
141    /// A source base for a document at repository-relative directory `dir`,
142    /// served from `blob`. `None` when `blob` is `None` — see the type's
143    /// documentation for why that leaves links alone rather than failing.
144    #[must_use]
145    pub fn new(blob: Option<&str>, dir: &str) -> Option<Self> {
146        Some(Self {
147            blob: blob?.trim_end_matches('/').to_owned(),
148            dir: dir.trim_matches('/').to_owned(),
149        })
150    }
151
152    /// The web URL for `path` — a link written relative to this document —
153    /// carrying `frag` through unchanged (`#L12` is a GitHub line anchor, and
154    /// the site has no better guess than the author's).
155    ///
156    /// `None` when `path` climbs out of the repository altogether, which no base
157    /// can name.
158    fn blob_url(&self, path: &str, frag: Option<&str>) -> Option<String> {
159        let joined = format!("{}/{}", self.dir, path);
160        let (up, segs) = resolve_relative(&joined);
161        if up > 0 || segs.is_empty() {
162            return None;
163        }
164        let repo_path = segs.join("/");
165        Some(match frag {
166            Some(frag) => format!("{}/{repo_path}#{frag}", self.blob),
167            None => format!("{}/{repo_path}", self.blob),
168        })
169    }
170}
171
172/// One page in the site navigation bar: where it goes and what it is called.
173///
174/// Built by the caller from the authored site pages (`rto_spec::site_nav` puts
175/// them in order), and passed to [`render_site_page`] whole so every page emits
176/// the *same* bar. A per-page bar assembled independently is a bar that can
177/// disagree with itself, which is how a page ends up unreachable from its
178/// neighbours.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct NavEntry {
181    /// Root-relative href (e.g. `modes.html`, or `./` for the landing page).
182    pub href: String,
183    /// Short label shown in the bar.
184    pub label: String,
185}
186
187/// An entry in the ADR/docs index page.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct IndexEntry {
190    /// Relative href (e.g. `0001-….html`).
191    pub href: String,
192    /// Display title.
193    pub title: String,
194}
195
196/// Convert `CommonMark` `md` to an HTML fragment (GitHub tables + strikethrough,
197/// and Roteiro `[[wiki-links]]` resolved). Resolves ADR links relative to the
198/// ADR directory; use [`render_doc`] for root-level pages.
199///
200/// A fragment renderer has no site to be a part of, so it carries neither
201/// [`PublishedPages`] nor [`SourceBase`]: a `.md` link is rewritten to its own
202/// stem, which is right for an ADR and a guess for anything published under a
203/// slug, and a link out of the site is left alone.
204#[must_use]
205pub fn markdown_to_html(md: &str) -> String {
206    render_markdown(md, "", &PublishedPages::new(), None, 0)
207}
208
209/// Render `md` to HTML: resolve `[[wiki-links]]` (ADR links use `adr_prefix` as
210/// their href prefix), rewrite ordinary `[…](*.md)` links to their rendered
211/// `.html` targets and links out of the site to `source`, then run `CommonMark`
212/// with GitHub tables/strikethrough. `depth` is the page's own depth below the
213/// site root; see [`rewrite_doc_link`].
214fn render_markdown(
215    md: &str,
216    adr_prefix: &str,
217    pages: &PublishedPages,
218    source: Option<&SourceBase>,
219    depth: usize,
220) -> String {
221    let pre = rewrite_wiki_links(md, adr_prefix);
222    let ids = heading_ids(&pre);
223    let mut next_id = 0usize;
224    // Rewrite link destinations pointing at local Markdown files to the HTML the
225    // site actually serves (e.g. `adr/0001-….md` → `adr/0001-….html`), and give
226    // every heading a stable `id` so it can be linked to.
227    let parser = Parser::new_ext(&pre, options()).map(|event| match event {
228        Event::Start(Tag::Link {
229            link_type,
230            dest_url,
231            title,
232            id,
233        }) => Event::Start(Tag::Link {
234            link_type,
235            dest_url: rewrite_doc_link(&dest_url, pages, source, depth)
236                .map_or(dest_url, CowStr::from),
237            title,
238            id,
239        }),
240        Event::Start(Tag::Heading {
241            level,
242            classes,
243            attrs,
244            ..
245        }) => {
246            let id = ids.get(next_id).cloned().map(CowStr::from);
247            next_id += 1;
248            Event::Start(Tag::Heading {
249                level,
250                id,
251                classes,
252                attrs,
253            })
254        }
255        other => other,
256    });
257    let mut out = String::new();
258    html::push_html(&mut out, parser);
259    out
260}
261
262/// The `CommonMark` dialect the whole site is parsed with — [`rto_graph`]'s, not
263/// a copy of it.
264///
265/// This used to build its own `Options` with the same three flags. It was the
266/// same set by agreement rather than by construction, which is the arrangement
267/// [`rto_graph::markdown_dialect`] exists to end: a different option set is a
268/// different language, and two parsers that disagree about it do not fail — they
269/// quietly disagree about where a heading's text ends, which is the defect #469
270/// was. That crate could not finish the consolidation while this file was held
271/// open by the work in #456/#457/#508; this is the remaining half.
272///
273/// What the dialect buys *this* renderer, and why the heading-attribute flag in
274/// particular is load-bearing here: **heading attributes are how a URL outlives a
275/// restructure.** A page split out of the old single-page site keeps the anchor
276/// the old page published — the heading declares `{#modes}` and lands at
277/// `#modes` — instead of silently becoming whatever the new heading text happens
278/// to slugify to. External links point at those anchors and cannot be updated, so
279/// the alternative is not a tidier URL; it is a dead one.
280fn options() -> Options {
281    // Keep this body a single delegation. It is the shape that invites a
282    // "just for rendering" flag, and the shape where adding one leaves nothing
283    // to notice it by — the duplicate that used to sit here is gone, so a
284    // divergence introduced now is invisible rather than merely unnoticed.
285    //
286    // A flag this renderer sets and `rto-graph`'s extractors do not is a flag
287    // that changes what a heading's text *is* on one surface and not the other.
288    // That is the #469 defect again, with the evidence removed.
289    //
290    // So a renderer-only flag belongs in `markdown_dialect` or nowhere, and "or
291    // nowhere" is not rhetoric: the claim that some future flag cannot reach
292    // heading text is an argument, not an observation, and an argument belongs
293    // in `rto-graph` beside the flag it licenses, where every surface reads it.
294    //
295    // `the_dialect_is_not_extended_here` fails if this body grows a flag.
296    rto_graph::markdown_dialect()
297}
298
299/// The `id` for every heading in `md`, in document order.
300///
301/// An explicit `{#anchor}` wins; otherwise the id is [`rto_graph::slugify`] of
302/// the heading text. Both branches go through [`rto_graph::heading_id_from`] —
303/// the *same* function `rto_spec` builds the section's node key with, for ADRs,
304/// blueprints and site pages alike — so an authored link to `site:modes#offline`
305/// lands on the heading the graph says it does.
306///
307/// That sentence used to be here and was only half true: this honoured an
308/// explicit `{#anchor}` and `rto_spec` slugified the heading text regardless, so
309/// a heading that declared its own address had one id in the page and a
310/// different key in the graph (#524). The claim is now enforced by construction
311/// rather than asserted in prose, which is the difference that matters.
312///
313/// The two **document-level** rules — a heading whose id would be empty
314/// (`## ###`) falls back to its position, and a repeat gets a `-2`, `-3`, …
315/// suffix — used to stay here, on the argument that only a renderer emits
316/// elements and so only a renderer can have two share an `id`. They are in
317/// [`rto_graph::headings`] now, because that argument was wrong in its
318/// consequence: `rto_spec` did neither, so `## A {#same}` / `## B {#same}`
319/// rendered two anchors and upserted into **one** graph node (#629).
320///
321/// Computed from a *first parse* rather than a line scan: heading text can be
322/// spread over several inline events, and `#` inside a fenced block is not a
323/// heading at all. Parsing twice costs a document-sized pass and cannot be wrong
324/// about what the renderer will see, because it is the same parser — and now
325/// literally the same call, so "the same parser" has stopped being a claim.
326///
327/// # This rule is not GitHub's, and deliberately stays that way
328///
329/// A document in `docs/` is read in two places under two slug rules: GitHub
330/// renders `**v0.10.x**` as `v010x` and this renders it as `v0-10-x`, so an
331/// anchor hand-written against one is dead in the other. That is real, and it is
332/// the *second* half of issue #457 — the six anchors that issue found were dead
333/// under **both** rules, because the heading text had changed under them.
334///
335/// It is not fixed by aligning this rule to GitHub's, and that is not a
336/// deferral. [`rto_graph::slugify`] is the *one* rule, shared on purpose:
337/// `rto_spec` builds every section node key with it (`adr:0001#design`,
338/// `site:modes#offline-mode`) and this builds the matching `id`, which is the
339/// only reason a `[[doc#section]]` wiki-link resolves through one and lands
340/// through the other. Re-keying it to GitHub's would re-key every section node in
341/// the graph and break every authored wiki-link `roteiro check` gates — to fix
342/// anchors in one retired document. rustdoc is a *third* rule already in play,
343/// so there is no single rule to converge on in any case.
344///
345/// Note what does **not** protect this: #397's guard (`doc_anchor_fragments.rs`)
346/// replicates rustdoc's rule in its own private `slugify` and never calls
347/// [`rto_graph::slugify`], so changing this rule would not have made it fail. It
348/// is not a guard on this code path, and treating it as one was the mistake worth
349/// recording here.
350///
351/// So the divergence is left, documented, and the affected anchors were given
352/// explicit ids that neither rule touches (see `docs/BUILD_PLAN.md`). **Nothing
353/// currently checks an intra-document anchor** in either rendering — not
354/// `roteiro check`, not this crate. Issue #459 is where that check belongs.
355fn heading_ids(md: &str) -> Vec<String> {
356    // Keep this body a single delegation, for the reason [`options`] gives about
357    // the dialect. This used to parse the document itself and own two rules the
358    // graph did not have — the `section-N` fallback for a heading that names
359    // nothing, and the `-2` suffix for one whose id is taken. Owning them here
360    // was justified on the grounds that only a renderer emits elements and so
361    // only a renderer can have two share an `id`. What it actually produced was
362    // #629: this emitted `same` and `same-2` while `rto_spec` keyed both sections
363    // `same` and upserted one over the other, so the graph's surviving node named
364    // a place the page addressed as something else.
365    //
366    // Both rules live in `rto_graph::headings` now, applied over **every** level
367    // — which is the half a local dedup cannot reproduce, because `rto_spec`
368    // records only `##` and `# Same` before `## Same` still pushes the h2 to
369    // `same-2` here.
370    rto_graph::headings(md).into_iter().map(|h| h.id).collect()
371}
372
373/// Split a relative path into the number of hops it takes **above** its own
374/// directory and the segments that remain, resolving `.` and `..` the way a
375/// browser and a filesystem both do.
376///
377/// `../crates/x.rs` is `(1, ["crates", "x.rs"])`; `adr/../guide.md` is
378/// `(0, ["guide.md"])`. The hop count is the whole escape test in
379/// [`rewrite_doc_link`]: a link that climbs further than the page sits below the
380/// site root is a link to something outside the site.
381fn resolve_relative(path: &str) -> (usize, Vec<&str>) {
382    let mut up = 0usize;
383    let mut segs: Vec<&str> = Vec::new();
384    for seg in path.split('/') {
385        match seg {
386            "" | "." => {}
387            ".." => {
388                if segs.pop().is_none() {
389                    up += 1;
390                }
391            }
392            s => segs.push(s),
393        }
394    }
395    (up, segs)
396}
397
398/// Rewrite a relative link so it points at what the **site** serves, preserving
399/// any `#fragment`. Returns `None` for external, protocol-relative, `mailto:`,
400/// pure-anchor and root-relative links, and for anything the site already serves
401/// under the spelling the link uses — all of which are left unchanged.
402///
403/// `depth` is how far below the site root the page being rendered sits: 0 for a
404/// root-level page, 1 for an ADR under `adr/`. It is supplied by the entry point
405/// rather than by the caller, because the entry point is the thing that knows.
406///
407/// Two rewrites live here, and the order between them is the interesting part:
408///
409/// * a `.md` link is aimed at the page the site publishes it as
410///   ([`PublishedPages`]) — checked **first**, so a document that happens to be
411///   reached by a path climbing out of its own directory still lands on its
412///   published page rather than being treated as unpublished (issue #446);
413/// * a link that climbs above the site root and is *not* published is aimed at
414///   the repository's web view ([`SourceBase`]) — issue #456.
415fn rewrite_doc_link(
416    dest: &str,
417    pages: &PublishedPages,
418    source: Option<&SourceBase>,
419    depth: usize,
420) -> Option<String> {
421    if dest.starts_with("http://")
422        || dest.starts_with("https://")
423        || dest.starts_with("//")
424        || dest.starts_with("mailto:")
425        || dest.starts_with('#')
426        || dest.starts_with('/')
427    {
428        return None;
429    }
430    let (path, frag) = dest
431        .split_once('#')
432        .map_or((dest, None), |(p, f)| (p, Some(f)));
433    // Only the final segment can differ between the repository and the site, so
434    // the link's own directory hops are kept verbatim; see [`PublishedPages`].
435    let (dir, file) = path.rsplit_once('/').map_or(("", path), |(d, f)| (d, f));
436    // `strip_suffix` rather than `ends_with`: the extension is matched exactly as
437    // it is written, which is the rule every document in this repository follows.
438    let is_markdown = path.strip_suffix(".md").is_some();
439    let sep = if dir.is_empty() { "" } else { "/" };
440
441    // A page the site publishes, under the name it publishes it as (issue #446).
442    // First, so a document reached by a path that climbs out of its own
443    // directory still lands on its page rather than being read as unpublished.
444    if let Some(served) = is_markdown.then(|| pages.served(file)).flatten() {
445        return Some(match frag {
446            Some(frag) => format!("{dir}{sep}{served}#{frag}"),
447            None => format!("{dir}{sep}{served}"),
448        });
449    }
450
451    // Not published, and climbing above the site root: no rewrite *within* the
452    // site can make this resolve, so hand it to the repository (issue #456).
453    // When there is no base to hand it to, fall through — everything below is
454    // the behaviour that predates this, unchanged, so a repository with no
455    // mappable `origin` renders exactly the site it rendered before.
456    if resolve_relative(path).0 > depth
457        && let Some(url) = source.and_then(|s| s.blob_url(path, frag))
458    {
459        return Some(url);
460    }
461
462    if !is_markdown {
463        return None;
464    }
465    // Unknown or ambiguous: fall back to the stem rewrite this has always done,
466    // which is right for every ADR (each is served under its own stem) and no
467    // worse than before for anything else.
468    let served = format!("{}.html", file.trim_end_matches(".md"));
469    Some(match frag {
470        Some(frag) => format!("{dir}{sep}{served}#{frag}"),
471        None => format!("{dir}{sep}{served}"),
472    })
473}
474
475/// Render one ADR markdown document to a themed HTML page. Leading YAML
476/// frontmatter is stripped; the title is the first `# ` heading, or `fallback`
477/// if there is none. ADR `[[…]]` links resolve to sibling ADR pages.
478///
479/// An ADR page is served one directory below the site root (`adr/`), which is
480/// the `1` below: a `../…` link from an ADR still lands inside the site, and only
481/// a second hop leaves it. See [`SourceBase`] for `source`.
482#[must_use]
483pub fn render_adr(
484    markdown: &str,
485    fallback_title: &str,
486    pages: &PublishedPages,
487    source: Option<&SourceBase>,
488) -> RenderedAdr {
489    let body = strip_frontmatter(markdown);
490    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
491    let content = render_markdown(body, "", pages, source, 1);
492    let nav = "<p class=\"nav\"><a href=\"../\">← Roteiro home</a> · \
493               <a href=\"./\">All ADRs</a> · <a href=\"../build-plan.html\">Build Plan</a></p>";
494    let html = page(&format!("{title} — Roteiro"), "../", nav, &content);
495    RenderedAdr { title, html }
496}
497
498/// Render a root-level "lifetime doc" (e.g. the Build Plan) to a themed page.
499/// Its `[[docs/adr/…]]` links resolve into the `adr/` subdirectory.
500///
501/// The page is served *at* the site root — the `0` below — so any `../…` link
502/// leaves the site; see [`SourceBase`] for where those go.
503#[must_use]
504pub fn render_doc(
505    markdown: &str,
506    fallback_title: &str,
507    pages: &PublishedPages,
508    source: Option<&SourceBase>,
509) -> RenderedAdr {
510    let body = strip_frontmatter(markdown);
511    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
512    let content = render_markdown(body, "adr/", pages, source, 0);
513    let nav = "<p class=\"nav\"><a href=\"./\">← Roteiro home</a> · \
514               <a href=\"adr/\">ADRs</a></p>";
515    let html = page(&format!("{title} — Roteiro"), "./", nav, &content);
516    RenderedAdr { title, html }
517}
518
519/// Render one **site page** — a document that declared itself published — to a
520/// themed root-level page carrying the site navigation bar.
521///
522/// `nav` is the whole bar, in order; `current_href` is this page's own entry,
523/// which is marked `aria-current="page"` and rendered unlinked so the reader can
524/// see where they are. A `current_href` that matches nothing in `nav` simply
525/// yields a bar with nothing marked, which is what a preview of an unlisted page
526/// should look like rather than an error.
527///
528/// The title is the first `# ` heading, or `fallback_title`. `[[docs/adr/…]]`
529/// links resolve into the `adr/` subdirectory, exactly as they do for the Build
530/// Plan: a site page is a root-level document.
531#[must_use]
532pub fn render_site_page(
533    markdown: &str,
534    fallback_title: &str,
535    nav: &[NavEntry],
536    current_href: &str,
537    pages: &PublishedPages,
538    source: Option<&SourceBase>,
539) -> RenderedAdr {
540    let body = strip_frontmatter(markdown);
541    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
542    let content = render_markdown(body, "adr/", pages, source, 0);
543    let bar = render_nav(nav, current_href);
544    let html = page(&format!("{title} — Roteiro"), "./", &bar, &content);
545    RenderedAdr { title, html }
546}
547
548/// The site navigation bar: one link per page, the current one marked.
549///
550/// Plain anchors in a `<nav>`, styled by `website/public/style.css`. No script:
551/// the explorer is deliberately vendored with no build step (ADR-0010), and a
552/// navigation bar that needs JavaScript to be a navigation bar would be the
553/// first thing on this site that does.
554#[must_use]
555pub fn render_nav(nav: &[NavEntry], current_href: &str) -> String {
556    let mut out = String::from("<nav class=\"sitenav\">");
557    for entry in nav {
558        if entry.href == current_href {
559            let _ = write!(
560                out,
561                "<span aria-current=\"page\">{}</span>",
562                escape_html(&entry.label)
563            );
564        } else {
565            let _ = write!(
566                out,
567                "<a href=\"{}\">{}</a>",
568                escape_attr(&entry.href),
569                escape_html(&entry.label)
570            );
571        }
572    }
573    out.push_str("</nav>");
574    out
575}
576
577/// The marker whose contents [`replace_site_nav`] owns.
578const SITENAV_OPEN: &str = "<nav class=\"sitenav\">";
579
580/// Replace the `<nav class="sitenav">…</nav>` block in a **hand-written** page
581/// with the bar the renderer computes, returning `None` when the page carries no
582/// such block.
583///
584/// # Why this exists
585///
586/// `website/public/index.html` is the one page of roteiro.dev nothing renders —
587/// it is copied verbatim — and it used to carry a *hand-maintained copy* of the
588/// list the renderer derives from `site-order` (issue #508). Adding
589/// `docs/SERVING.md` appeared in every rendered page's bar automatically and had
590/// to be typed into the landing page by hand.
591///
592/// The failure that made it worth removing rather than remembering is silent and
593/// points the wrong way: a new page is published, reachable, and linked from
594/// every page **except the front one**. Nothing errors and `roteiro check`
595/// passes, because everything that is there resolves.
596///
597/// **That is also why no link auditor could have caught it, and why none will
598/// catch the next one of its shape.** The defect is a link that does *not*
599/// exist; auditing what is there cannot find what is missing. This removes the
600/// possibility instead — after this, the landing page has no independent list to
601/// disagree with. What still guards the seam is
602/// `the_landing_page_carries_the_bar_the_renderer_emits`, which now checks that
603/// the replacement *happened*: a landing page whose marker was renamed away
604/// keeps its stale bar silently, and that test is what fails.
605///
606/// # Why `None` rather than an error
607///
608/// A landing page with no `sitenav` is not claiming a bar, and a site is allowed
609/// not to have one — every `render docs` fixture writes a one-line `index.html`.
610/// The caller leaves such a page alone.
611#[must_use]
612pub fn replace_site_nav(html: &str, nav: &[NavEntry], current_href: &str) -> Option<String> {
613    let open = html.find(SITENAV_OPEN)?;
614    let close = html[open..].find("</nav>")? + open + "</nav>".len();
615    let mut out = String::with_capacity(html.len());
616    out.push_str(&html[..open]);
617    out.push_str(&render_nav(nav, current_href));
618    out.push_str(&html[close..]);
619    Some(out)
620}
621
622/// Render the docs index: any `lifetime` docs (Build Plan, …) then the ADRs.
623#[must_use]
624pub fn render_adr_index(lifetime: &[IndexEntry], entries: &[IndexEntry]) -> String {
625    let mut list = String::new();
626    if !lifetime.is_empty() {
627        list.push_str("<h1>Documentation</h1><ul>");
628        for e in lifetime {
629            let _ = write!(
630                list,
631                "<li><a href=\"{}\">{}</a></li>",
632                escape_attr(&e.href),
633                escape_html(&e.title)
634            );
635        }
636        list.push_str("</ul>");
637    }
638    list.push_str("<h1>Architecture Decision Records</h1><ul>");
639    for e in entries {
640        let _ = write!(
641            list,
642            "<li><a href=\"{}\">{}</a></li>",
643            escape_attr(&e.href),
644            escape_html(&e.title)
645        );
646    }
647    list.push_str("</ul>");
648    let nav = "<p class=\"nav\"><a href=\"../\">← Roteiro home</a></p>";
649    page("Documentation — Roteiro", "../", nav, &list)
650}
651
652/// Rewrite Roteiro `[[wiki-links]]` into Markdown, honouring code spans/fences:
653/// `[[docs/adr/<slug>.md]]` (optionally `#section`) becomes a link to that ADR
654/// page (`<adr_prefix><slug>.html`); any other `[[…]]` (code/file references,
655/// for which the site has no page) becomes inline code so it renders cleanly
656/// instead of leaking literal brackets.
657fn rewrite_wiki_links(md: &str, adr_prefix: &str) -> String {
658    let mut out = String::new();
659    let mut in_fence = false;
660    for line in md.lines() {
661        let trimmed = line.trim_start();
662        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
663            in_fence = !in_fence;
664            out.push_str(line);
665            out.push('\n');
666            continue;
667        }
668        if in_fence {
669            out.push_str(line);
670            out.push('\n');
671            continue;
672        }
673        rewrite_line_outside_code(line, adr_prefix, &mut out);
674        out.push('\n');
675    }
676    out
677}
678
679/// Rewrite wiki-links in one line, leaving `CommonMark` inline code spans
680/// untouched. A code span opens with a run of *n* backticks and closes with the
681/// next run of *exactly* *n* backticks; anything between (including `[[…]]`
682/// examples) is emitted verbatim. Backtick runs with no matching close are
683/// literal text and do not shield what follows.
684fn rewrite_line_outside_code(line: &str, adr_prefix: &str, out: &mut String) {
685    let bytes = line.as_bytes();
686    let mut text_start = 0;
687    let mut i = 0;
688    while i < bytes.len() {
689        if bytes[i] != b'`' {
690            i += 1;
691            continue;
692        }
693        let run_start = i;
694        while i < bytes.len() && bytes[i] == b'`' {
695            i += 1;
696        }
697        let run = i - run_start;
698        if let Some(rel) = find_closing_run(&bytes[i..], run) {
699            // Text before the opening delimiter is ordinary prose.
700            rewrite_wiki_in(&line[text_start..run_start], adr_prefix, out);
701            let code_end = i + rel + run;
702            out.push_str(&line[run_start..code_end]); // span, delimiters included
703            i = code_end;
704            text_start = i;
705        }
706        // No close → treat the run as literal text; keep it in the pending
707        // buffer (rewrite_wiki_in leaves backticks alone) and keep scanning.
708    }
709    rewrite_wiki_in(&line[text_start..], adr_prefix, out);
710}
711
712/// Byte offset (within `bytes`) of the next backtick run of *exactly* `run`
713/// backticks, or `None`. Longer or shorter runs are skipped, per `CommonMark`.
714fn find_closing_run(bytes: &[u8], run: usize) -> Option<usize> {
715    let mut i = 0;
716    while i < bytes.len() {
717        if bytes[i] != b'`' {
718            i += 1;
719            continue;
720        }
721        let start = i;
722        while i < bytes.len() && bytes[i] == b'`' {
723            i += 1;
724        }
725        if i - start == run {
726            return Some(start);
727        }
728    }
729    None
730}
731
732/// Rewrite every `[[…]]` in one non-code text segment.
733fn rewrite_wiki_in(seg: &str, adr_prefix: &str, out: &mut String) {
734    let mut rest = seg;
735    while let Some(open) = rest.find("[[") {
736        out.push_str(&rest[..open]);
737        let after = &rest[open + 2..];
738        if let Some(close) = after.find("]]") {
739            out.push_str(&wiki_target(&after[..close], adr_prefix));
740            rest = &after[close + 2..];
741        } else {
742            out.push_str("[[");
743            rest = after;
744        }
745    }
746    out.push_str(rest);
747}
748
749/// Resolve one wiki-link's inner text to Markdown.
750fn wiki_target(inner: &str, adr_prefix: &str) -> String {
751    let inner = inner.trim();
752    let path = inner.split_once('#').map_or(inner, |(p, _)| p.trim());
753    if let Some(rest) = path.strip_prefix("docs/adr/")
754        && let Some(stem) = rest.strip_suffix(".md")
755    {
756        return format!("[{}]({adr_prefix}{stem}.html)", adr_label(stem));
757    }
758    // Code/file reference — the site has no page for it; show it as code.
759    format!("`{inner}`")
760}
761
762/// A display label for an ADR filename stem: `0001-build-…` → `ADR-0001`.
763fn adr_label(stem: &str) -> String {
764    let digits: String = stem.chars().take_while(char::is_ascii_digit).collect();
765    if digits.is_empty() {
766        stem.to_owned()
767    } else {
768        format!("ADR-{digits}")
769    }
770}
771
772/// Wrap body HTML in the themed page chrome. `root` is the relative path to the
773/// site root (e.g. `"../"` for pages under `adr/`).
774fn page(title: &str, root: &str, nav: &str, body: &str) -> String {
775    format!(
776        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
777         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
778         <link rel=\"icon\" href=\"{root}favicon.svg\" type=\"image/svg+xml\">\
779         <link rel=\"icon\" href=\"{root}favicon.ico\" type=\"image/x-icon\" sizes=\"16x16 32x32 48x48\">\
780         <link rel=\"apple-touch-icon\" href=\"{root}apple-touch-icon.png\">\
781         <link rel=\"stylesheet\" href=\"{root}style.css\">\
782         <title>{title}</title></head><body>\
783         {nav}{body}\
784         <p class=\"backlink\"><a href=\"{root}\">← Back to roteiro.dev</a></p>\
785         <footer>Dual-licensed MIT OR Apache-2.0 · The Roteiro Project Team · <a href=\"https://discord.gg/bxgj4w6KM\">Discord</a></footer>\
786         </body></html>",
787        title = escape_html(title),
788    )
789}
790
791/// Strip a leading `---`-delimited YAML frontmatter block.
792fn strip_frontmatter(text: &str) -> &str {
793    let Some(rest) = text.strip_prefix("---\n") else {
794        return text;
795    };
796    match rest.find("\n---\n") {
797        Some(end) => &rest[end + 5..],
798        None => rest.strip_suffix("\n---").unwrap_or(text),
799    }
800}
801
802/// The visible text of the document's first level-1 heading — what the reader
803/// sees in the rendered `<h1>` — or `None` when the document has none.
804///
805/// Read from a **parse**, for the same reason [`heading_ids`] is: the heading's
806/// raw line is source, not text. A line scan cannot tell `{#modes}` (a heading
807/// attribute this renderer deliberately enables, see [`options`]) from the words
808/// of the heading, so it read `# The five ways to run it {#modes}` back as a
809/// title and put the markup in the `<title>` element of every page moved by the
810/// site split — issue #460, live on roteiro.dev. The `<h1>` on the same page was
811/// already right, because that side went through the parser.
812///
813/// The fix is *not* a second place that knows how to strip `{#…}`. A rule
814/// spelled out twice is a rule that can disagree with itself, and this one
815/// already disagrees once: the anchor is markup to the parser and text to the
816/// scanner. Asking the parser removes the second opinion rather than aligning
817/// it, and carries the rest of the dialect along for free — a fenced `# …` is
818/// not a title, a setext underline is one, and inline markup (`` `code` ``,
819/// emphasis, a link label) contributes its text and not its punctuation.
820///
821/// The parse stops at the first `</h1>`; nothing walks the rest of the document.
822fn first_heading(body: &str) -> Option<String> {
823    let mut text: Option<String> = None;
824    for event in Parser::new_ext(body, options()) {
825        match event {
826            Event::Start(Tag::Heading {
827                level: HeadingLevel::H1,
828                ..
829            }) => text = Some(String::new()),
830            // Only accumulates once an H1 has opened; a code span is part of the
831            // heading's text, exactly as it is for the heading's id.
832            Event::Text(t) | Event::Code(t) => {
833                if let Some(text) = text.as_mut() {
834                    text.push_str(&t);
835                }
836            }
837            Event::End(TagEnd::Heading(HeadingLevel::H1)) => break,
838            _ => {}
839        }
840    }
841    // An empty `#` heading names nothing, so it defers to the caller's fallback
842    // rather than rendering `<title> — Roteiro</title>`.
843    text.map(|t| t.trim().to_owned()).filter(|t| !t.is_empty())
844}
845
846fn escape_html(s: &str) -> String {
847    s.replace('&', "&amp;")
848        .replace('<', "&lt;")
849        .replace('>', "&gt;")
850}
851
852fn escape_attr(s: &str) -> String {
853    escape_html(s).replace('"', "&quot;")
854}
855
856#[cfg(test)]
857mod tests {
858    use super::{
859        IndexEntry, NavEntry, PublishedPages, SourceBase, escape_html, heading_ids,
860        markdown_to_html, options, render_adr, render_adr_index, render_doc, render_markdown,
861        render_nav, render_site_page, replace_site_nav,
862    };
863
864    /// The site index most tests do not exercise: with it empty, a `.md` link
865    /// falls back to its own stem, which is what every assertion below predates.
866    fn no_pages() -> PublishedPages {
867        PublishedPages::new()
868    }
869
870    fn nav() -> Vec<NavEntry> {
871        vec![
872            NavEntry {
873                href: "./".into(),
874                label: "Home".into(),
875            },
876            NavEntry {
877                href: "modes.html".into(),
878                label: "Modes & Co".into(),
879            },
880        ]
881    }
882
883    #[test]
884    fn markdown_renders_headings_and_tables() {
885        let html = markdown_to_html("# Title\n\n| a | b |\n|---|---|\n| 1 | 2 |\n");
886        assert!(html.contains("<h1 id=\"title\">Title</h1>"), "{html}");
887        assert!(html.contains("<table>"));
888        assert!(html.contains("<td>1</td>"));
889    }
890
891    #[test]
892    fn adr_wiki_links_become_sibling_page_links() {
893        // An ADR-to-ADR wiki link resolves to the sibling .html; a code/file
894        // reference becomes inline code; both stop leaking literal `[[ ]]`.
895        let md = "See [[docs/adr/0001-build-roteiro.md]] and \
896                  [[crates/rto-graph/src/store.rs#Store]] here.\n";
897        let html = markdown_to_html(md);
898        assert!(
899            html.contains("<a href=\"0001-build-roteiro.html\">ADR-0001</a>"),
900            "ADR wiki-link → sibling page: {html}"
901        );
902        assert!(
903            html.contains("<code>crates/rto-graph/src/store.rs#Store</code>"),
904            "code reference → inline code: {html}"
905        );
906        assert!(
907            !html.contains("[["),
908            "no literal wiki brackets leak: {html}"
909        );
910    }
911
912    #[test]
913    fn wiki_links_inside_code_are_left_literal() {
914        // A documented example of the syntax, in backticks or a fence, must not
915        // be rewritten.
916        let inline = markdown_to_html("use `[[docs/adr/0001-x.md]]` in prose\n");
917        assert!(
918            inline.contains("<code>[[docs/adr/0001-x.md]]</code>"),
919            "{inline}"
920        );
921        let fenced = markdown_to_html("```\n[[docs/adr/0001-x.md]]\n```\n");
922        assert!(
923            fenced.contains("[[docs/adr/0001-x.md]]"),
924            "fence literal: {fenced}"
925        );
926    }
927
928    #[test]
929    fn multi_backtick_code_spans_are_honoured() {
930        // A tight double-backtick span (`` ``…`` ``) and the Build Plan's
931        // nested-backtick example must both survive verbatim — the previous
932        // single-backtick split rewrote the wiki-link inside them.
933        let tight = markdown_to_html("say ``[[docs/adr/0001-x.md]]`` please\n");
934        assert!(
935            tight.contains("<code>[[docs/adr/0001-x.md]]</code>"),
936            "{tight}"
937        );
938        assert!(!tight.contains("<a "), "no link inside code span: {tight}");
939
940        let nested = markdown_to_html("its `` `[[path#Symbol]]` `` example\n");
941        assert!(
942            nested.contains("<code>`[[path#Symbol]]`</code>"),
943            "{nested}"
944        );
945        assert!(
946            !nested.contains("<a "),
947            "no link inside nested span: {nested}"
948        );
949
950        // An unterminated run is literal and does not shield a later real link.
951        let stray = markdown_to_html("a ` stray tick then [[docs/adr/0001-x.md]]\n");
952        assert!(
953            stray.contains("<a href=\"0001-x.html\">ADR-0001</a>"),
954            "unterminated backtick must not shield: {stray}"
955        );
956    }
957
958    #[test]
959    fn markdown_md_links_are_rewritten_to_html() {
960        // Ordinary `[text](path.md)` links must point at the rendered `.html`,
961        // preserving fragments; external and anchor links are left alone.
962        let html = markdown_to_html(
963            "See [ADR-1](adr/0001-x.md) and [§2](adr/0001-x.md#context) and \
964             [home](https://x.dev) and [top](#intro).\n",
965        );
966        assert!(html.contains("href=\"adr/0001-x.html\""), "{html}");
967        assert!(html.contains("href=\"adr/0001-x.html#context\""), "{html}");
968        assert!(
969            html.contains("href=\"https://x.dev\""),
970            "external unchanged: {html}"
971        );
972        assert!(html.contains("href=\"#intro\""), "anchor unchanged: {html}");
973        assert!(!html.contains(".md\""), "no raw .md hrefs remain: {html}");
974    }
975
976    #[test]
977    fn render_doc_links_adrs_into_subdir() {
978        // A root-level lifetime doc (Build Plan) resolves ADR links into `adr/`.
979        let r = render_doc(
980            "# Build Plan\n\nGoverned by [[docs/adr/0001-x.md]].\n",
981            "Build Plan",
982            &no_pages(),
983            None,
984        );
985        assert_eq!(r.title, "Build Plan");
986        assert!(
987            r.html.contains("<a href=\"adr/0001-x.html\">ADR-0001</a>"),
988            "root doc → adr/ prefix: {}",
989            r.html
990        );
991        // Root-level chrome: assets/back-link relative to site root.
992        assert!(r.html.contains("href=\"./style.css\""));
993        // Full favicon set — root-relative from the site root.
994        assert!(r.html.contains("href=\"./favicon.svg\""));
995        assert!(r.html.contains("href=\"./favicon.ico\""));
996        assert!(
997            r.html
998                .contains("rel=\"apple-touch-icon\" href=\"./apple-touch-icon.png\"")
999        );
1000    }
1001
1002    const ADR: &str = "---\nadr-id: \"0001\"\nstatus: Accepted\n---\n\n# ADR-0001: Example\n\n## Context\n\nSome `code` and a [link](https://x).\n";
1003
1004    #[test]
1005    fn render_adr_strips_frontmatter_and_themes() {
1006        let r = render_adr(ADR, "fallback", &no_pages(), None);
1007        assert_eq!(r.title, "ADR-0001: Example");
1008        // Frontmatter is gone; heading + section rendered.
1009        assert!(!r.html.contains("adr-id"));
1010        assert!(
1011            r.html
1012                .contains("<h1 id=\"adr-0001-example\">ADR-0001: Example</h1>")
1013        );
1014        // The section anchor matches the section's node key (`adr:0001#context`),
1015        // so a link through the graph lands on the heading in the browser.
1016        assert!(r.html.contains("<h2 id=\"context\">Context</h2>"));
1017        assert!(r.html.contains("<code>code</code>"));
1018        // Themed chrome present.
1019        assert!(
1020            r.html
1021                .contains("<link rel=\"stylesheet\" href=\"../style.css\">")
1022        );
1023        // Full favicon set (SVG + `.ico` fallback for browsers without SVG-favicon
1024        // support, e.g. Safari) — root-relative from a sub-page.
1025        assert!(r.html.contains("href=\"../favicon.svg\""));
1026        assert!(r.html.contains("href=\"../favicon.ico\""));
1027        assert!(
1028            r.html
1029                .contains("rel=\"apple-touch-icon\" href=\"../apple-touch-icon.png\"")
1030        );
1031        assert!(r.html.contains("← Roteiro home"));
1032        assert!(r.html.contains("← Back to roteiro.dev"));
1033        assert!(r.html.starts_with("<!doctype html>"));
1034    }
1035
1036    #[test]
1037    fn render_adr_falls_back_without_h1() {
1038        let r = render_adr(
1039            "no frontmatter, no heading\n",
1040            "slug-name",
1041            &no_pages(),
1042            None,
1043        );
1044        assert_eq!(r.title, "slug-name");
1045    }
1046
1047    #[test]
1048    fn index_lists_entries_and_escapes() {
1049        let entries = [
1050            IndexEntry {
1051                href: "0001-x.html".into(),
1052                title: "First & <best>".into(),
1053            },
1054            IndexEntry {
1055                href: "0002-y.html".into(),
1056                title: "Second".into(),
1057            },
1058        ];
1059        let lifetime = [IndexEntry {
1060            href: "../build-plan.html".into(),
1061            title: "Build Plan".into(),
1062        }];
1063        let html = render_adr_index(&lifetime, &entries);
1064        assert!(html.contains("<a href=\"../build-plan.html\">Build Plan</a>"));
1065        assert!(html.contains("<a href=\"0001-x.html\">First &amp; &lt;best&gt;</a>"));
1066        assert!(html.contains("<a href=\"0002-y.html\">Second</a>"));
1067        // First entry precedes second (order preserved).
1068        assert!(html.find("0001-x").unwrap() < html.find("0002-y").unwrap());
1069        // Lifetime docs listed before the ADRs.
1070        assert!(html.find("build-plan").unwrap() < html.find("0001-x").unwrap());
1071    }
1072
1073    #[test]
1074    fn an_explicit_anchor_survives_the_split_that_moved_its_section() {
1075        // The hazard this mechanism exists for. The old single-page site
1076        // published `#modes`, `#crossrepo`, `#remote-tier` — short, hand-chosen
1077        // ids that no heading text slugifies to. External links point at them and
1078        // cannot be updated, so a page that inherits a section must be able to
1079        // inherit its anchor verbatim.
1080        let html = markdown_to_html(
1081            "## The five ways to run it {#modes}\n\n## Cross-repo: a hub and its spokes {#crossrepo}\n",
1082        );
1083        assert!(
1084            html.contains("<h2 id=\"modes\">The five ways to run it</h2>"),
1085            "{html}"
1086        );
1087        assert!(
1088            html.contains("<h2 id=\"crossrepo\">Cross-repo: a hub and its spokes</h2>"),
1089            "{html}"
1090        );
1091        // The attribute is markup, not part of the heading's text.
1092        assert!(!html.contains("{#"), "no literal attribute leaks: {html}");
1093    }
1094
1095    #[test]
1096    fn generated_anchors_match_the_graph_s_section_keys_and_stay_unique() {
1097        // `rto_spec` builds `<doc>#<slugify(heading)>` section keys from the same
1098        // function, so a link that resolves in the graph lands on the heading.
1099        let html = markdown_to_html("## Install & build\n\n## Install & build\n\n## ###\n");
1100        assert!(html.contains("id=\"install-build\""), "{html}");
1101        // A repeat is suffixed rather than duplicated: two elements sharing an
1102        // `id` makes one of them unreachable.
1103        assert!(html.contains("id=\"install-build-2\""), "{html}");
1104        // A heading that slugifies to nothing still gets a usable anchor.
1105        assert!(html.contains("id=\"section-3\""), "{html}");
1106    }
1107
1108    #[test]
1109    fn inline_code_counts_as_heading_text() {
1110        // The old page's headings look like `What <code>init</code> sets up`.
1111        // Dropping the code span would slugify only the prose around it and give
1112        // the section an anchor nobody would guess.
1113        let html = markdown_to_html("### What `init` sets up\n");
1114        assert!(
1115            html.contains("<h3 id=\"what-init-sets-up\">"),
1116            "code span is part of the heading's text: {html}"
1117        );
1118    }
1119
1120    #[test]
1121    fn a_hash_inside_a_fence_is_not_a_heading() {
1122        // The id list is computed from a real parse, so fenced content cannot
1123        // shift every subsequent heading's anchor by one.
1124        let html = markdown_to_html("```\n## Not a heading\n```\n\n## Real\n");
1125        assert!(html.contains("<h2 id=\"real\">Real</h2>"), "{html}");
1126    }
1127
1128    #[test]
1129    fn a_heading_s_anchor_never_reaches_the_title() {
1130        // Issue #460, live on roteiro.dev: every page the site split moved
1131        // carries `{#…}` on its H1, and the title was read off the raw line.
1132        let r = render_site_page(
1133            "---\nsite-page: modes\n---\n\n# The five ways to run it {#modes}\n\nBody.\n",
1134            "fallback",
1135            &nav(),
1136            "modes.html",
1137            &no_pages(),
1138            None,
1139        );
1140        // The heading was always right; the title is the side that was wrong.
1141        assert!(
1142            r.html
1143                .contains("<h1 id=\"modes\">The five ways to run it</h1>"),
1144            "{}",
1145            r.html
1146        );
1147        assert_eq!(r.title, "The five ways to run it");
1148        assert!(
1149            r.html
1150                .contains("<title>The five ways to run it — Roteiro</title>"),
1151            "{}",
1152            r.html
1153        );
1154        // The most-seen string a page has: the tab, the bookmark, the search
1155        // result, the social preview. Nothing of the attribute survives anywhere.
1156        assert!(
1157            !r.html.contains("{#"),
1158            "no literal attribute leaks: {}",
1159            r.html
1160        );
1161    }
1162
1163    #[test]
1164    fn the_same_holds_for_an_adr_and_for_a_root_level_doc() {
1165        // One extractor serves all three renderers, so all three are checked:
1166        // a fix that reached only the page the issue named would leave the ADR
1167        // index quoting `{#…}` back at the reader.
1168        let adr = render_adr("# ADR-0001: Example {#adr1}\n", "slug", &no_pages(), None);
1169        assert_eq!(adr.title, "ADR-0001: Example");
1170        assert!(
1171            adr.html
1172                .contains("<title>ADR-0001: Example — Roteiro</title>"),
1173            "{}",
1174            adr.html
1175        );
1176        let doc = render_doc(
1177            "# Roteiro — Build Plan {#plan}\n",
1178            "Build Plan",
1179            &no_pages(),
1180            None,
1181        );
1182        assert_eq!(doc.title, "Roteiro — Build Plan");
1183        assert!(!doc.html.contains("{#"), "{}", doc.html);
1184    }
1185
1186    #[test]
1187    fn a_title_that_legitimately_spells_the_anchor_syntax_keeps_it() {
1188        // The other half of the rule, and the reason the fix is a parse and not
1189        // a strip: `{#…}` is an attribute only where the dialect says it is, and
1190        // a rule spelled out by hand does not know where that is. Inside a code
1191        // span it is prose, and a stripper blind to code spans mangles a page
1192        // whose subject *is* this syntax — which is most of the pages that
1193        // document it.
1194        let coded = render_doc(
1195            "# Why `{#anchor}` outlives a restructure\n",
1196            "fallback",
1197            &no_pages(),
1198            None,
1199        );
1200        assert_eq!(coded.title, "Why {#anchor} outlives a restructure");
1201        assert!(
1202            coded
1203                .html
1204                .contains("<title>Why {#anchor} outlives a restructure — Roteiro</title>"),
1205            "{}",
1206            coded.html
1207        );
1208        // Mid-heading and uncoded, it is still prose: an attribute block is
1209        // trailing or it is nothing.
1210        let mid = render_doc(
1211            "# Anchors are written {#id}, in prose\n",
1212            "fallback",
1213            &no_pages(),
1214            None,
1215        );
1216        assert_eq!(mid.title, "Anchors are written {#id}, in prose");
1217    }
1218
1219    #[test]
1220    fn the_title_and_the_heading_never_disagree() {
1221        // The invariant underneath #460, stated directly. Where the attribute
1222        // block ends is the dialect's call, not this module's — braces the
1223        // parser eats are gone from *both* surfaces, braces it keeps are on
1224        // both. Reading the title from the same parse is what makes that true by
1225        // construction rather than by two rules that happen to match today.
1226        for md in [
1227            "# The five ways to run it {#modes}\n",
1228            "# Why `{#anchor}` outlives a restructure\n",
1229            "# Anchors are written {#id}, in prose\n",
1230            "# Install & build {#build}\n",
1231            "# What `init` sets up\n",
1232            "# Sets like {#1, #2}\n",
1233        ] {
1234            let r = render_doc(md, "fallback", &no_pages(), None);
1235            let inner = r
1236                .html
1237                .split_once("<h1")
1238                .and_then(|(_, rest)| rest.split_once('>'))
1239                .and_then(|(_, rest)| rest.split_once("</h1>"))
1240                .map(|(text, _)| text.to_owned())
1241                .unwrap_or_default();
1242            // The heading carries inline markup (`<code>`, emphasis); the title
1243            // is the words inside it. Dropping the tags — and nothing else, so
1244            // entities still have to match — is what makes them comparable.
1245            let mut heading = String::new();
1246            let mut depth = 0usize;
1247            for c in inner.chars() {
1248                match c {
1249                    '<' => depth += 1,
1250                    '>' => depth = depth.saturating_sub(1),
1251                    _ if depth == 0 => heading.push(c),
1252                    _ => {}
1253                }
1254            }
1255            assert_eq!(
1256                heading,
1257                escape_html(&r.title),
1258                "title and heading disagree for {md:?}: {}",
1259                r.html
1260            );
1261        }
1262    }
1263
1264    #[test]
1265    fn the_title_is_the_heading_the_reader_sees() {
1266        // Inline markup contributes its text, not its punctuation — the same
1267        // rule the heading's own id already follows.
1268        let code = render_doc("# What `init` sets up\n", "fallback", &no_pages(), None);
1269        assert_eq!(code.title, "What init sets up");
1270        // A line scan called this document's title `Not a title`; the parser
1271        // knows a fenced hash is not a heading at all.
1272        let fenced = render_doc(
1273            "```\n# Not a title\n```\n\n# The real one\n",
1274            "fallback",
1275            &no_pages(),
1276            None,
1277        );
1278        assert_eq!(fenced.title, "The real one");
1279        // And a heading spelled the other way is still a heading: the page shows
1280        // an `<h1>`, so the tab has to show its words rather than the file stem.
1281        let setext = render_doc("Underlined\n==========\n", "fallback", &no_pages(), None);
1282        assert!(
1283            setext.html.contains("<h1 id=\"underlined\">"),
1284            "{}",
1285            setext.html
1286        );
1287        assert_eq!(setext.title, "Underlined");
1288    }
1289
1290    #[test]
1291    fn a_document_with_no_h1_falls_back_and_the_fallback_is_used_verbatim() {
1292        // The fallback is the caller's string, not markdown: it is never parsed,
1293        // so it cannot be stripped and cannot leak markup it does not contain.
1294        // Callers pass a file stem or a declared slug.
1295        let none = render_site_page(
1296            "---\nsite-page: modes\n---\n\nNo heading at all.\n",
1297            "The five ways to run it",
1298            &nav(),
1299            "modes.html",
1300            &no_pages(),
1301            None,
1302        );
1303        assert_eq!(none.title, "The five ways to run it");
1304        assert!(
1305            none.html
1306                .contains("<title>The five ways to run it — Roteiro</title>"),
1307            "{}",
1308            none.html
1309        );
1310        // An H1 with nothing in it names nothing, so it defers to the fallback
1311        // rather than emitting `<title> — Roteiro</title>`.
1312        let empty = render_doc("#\n\nBody.\n", "build-plan", &no_pages(), None);
1313        assert_eq!(empty.title, "build-plan");
1314        // A lower heading is not the document's title.
1315        let sub = render_doc("## Only a section {#s}\n", "build-plan", &no_pages(), None);
1316        assert_eq!(sub.title, "build-plan");
1317    }
1318
1319    #[test]
1320    fn a_site_page_carries_the_bar_with_itself_marked() {
1321        let r = render_site_page(
1322            "---\nsite-page: modes\n---\n\n# The five ways to run it\n\nSee [[docs/adr/0019-remote.md]].\n",
1323            "fallback",
1324            &nav(),
1325            "modes.html",
1326            &no_pages(),
1327            None,
1328        );
1329        assert_eq!(r.title, "The five ways to run it");
1330        // Frontmatter is chrome for the graph, not content for the reader.
1331        assert!(!r.html.contains("site-page"), "{}", r.html);
1332        // The current page is unlinked and marked; its neighbour is a link.
1333        assert!(
1334            r.html
1335                .contains("<span aria-current=\"page\">Modes &amp; Co</span>"),
1336            "{}",
1337            r.html
1338        );
1339        assert!(r.html.contains("<a href=\"./\">Home</a>"), "{}", r.html);
1340        // A root-level page: assets and ADR links resolve from the site root.
1341        assert!(r.html.contains("href=\"./style.css\""), "{}", r.html);
1342        assert!(
1343            r.html
1344                .contains("<a href=\"adr/0019-remote.html\">ADR-0019</a>"),
1345            "{}",
1346            r.html
1347        );
1348    }
1349
1350    #[test]
1351    fn the_bar_is_plain_anchors_and_escapes_its_labels() {
1352        let bar = render_nav(&nav(), "nothing.html");
1353        assert!(bar.starts_with("<nav class=\"sitenav\">"), "{bar}");
1354        // Nothing marked when the current page is not in the bar — a preview of
1355        // an unlisted page, not an error.
1356        assert!(!bar.contains("aria-current"), "{bar}");
1357        assert!(bar.contains("Modes &amp; Co"), "escaped label: {bar}");
1358        // No script: the site has no build step and this must not introduce one.
1359        assert!(!bar.contains("<script"), "{bar}");
1360    }
1361
1362    #[test]
1363    fn a_link_resolves_to_the_page_the_site_actually_serves() {
1364        // Issue #446: four ADRs link `../BUILD_PLAN_V2.md`, which is correct in
1365        // the repository. Published under a `site-page:` slug, that document is
1366        // served as `build-plan-v2.html` — so rewriting the link to its own stem
1367        // aims it at a page that is never emitted.
1368        let mut pages = PublishedPages::new();
1369        pages.publish("BUILD_PLAN_V2.md", "build-plan-v2.html");
1370        let html = render_markdown("See [V2](../BUILD_PLAN_V2.md).\n", "", &pages, None, 0);
1371        assert!(
1372            html.contains("href=\"../build-plan-v2.html\""),
1373            "served name, and the link's own hop kept: {html}"
1374        );
1375        // A fragment survives the substitution.
1376        let frag = render_markdown("[s](../BUILD_PLAN_V2.md#stage-21)\n", "", &pages, None, 0);
1377        assert!(
1378            frag.contains("href=\"../build-plan-v2.html#stage-21\""),
1379            "{frag}"
1380        );
1381        // An unpublished document still falls back to its stem, unchanged.
1382        let other = render_markdown("[x](../REVIEW_CHECKLIST.md)\n", "", &pages, None, 0);
1383        assert!(
1384            other.contains("href=\"../REVIEW_CHECKLIST.html\""),
1385            "{other}"
1386        );
1387    }
1388
1389    #[test]
1390    fn a_file_name_two_documents_claim_is_left_alone() {
1391        // Guessing which one a link meant would silently point it at the wrong
1392        // page — worse than the 404 the lookup exists to remove.
1393        let mut pages = PublishedPages::new();
1394        pages.publish("GUIDE.md", "guide.html");
1395        pages.publish("GUIDE.md", "other-guide.html");
1396        let html = render_markdown("[g](GUIDE.md)\n", "", &pages, None, 0);
1397        assert!(html.contains("href=\"GUIDE.html\""), "unrewritten: {html}");
1398        // Re-publishing the *same* target is not a conflict.
1399        let mut same = PublishedPages::new();
1400        same.publish("GUIDE.md", "guide.html");
1401        same.publish("GUIDE.md", "guide.html");
1402        let html = render_markdown("[g](GUIDE.md)\n", "", &same, None, 0);
1403        assert!(html.contains("href=\"guide.html\""), "{html}");
1404    }
1405
1406    #[test]
1407    fn the_dialect_is_not_extended_here() {
1408        // `options` exists to hold renderer-specific rationale, not to add
1409        // flags. This reads as a tautology against the body as written, and that
1410        // is exactly its job: it has no failure mode until someone gives the
1411        // body one, and that single edit is the only thing the comment beside it
1412        // can ask against rather than prevent.
1413        //
1414        // Note what it pins — the *dialect*, not the shape of the body. A
1415        // rewrite that still yields this option set is harmless and keeps
1416        // passing; every divergence that would change what a heading's text is
1417        // fails. That is the invariant worth holding, and it is a wider one than
1418        // "stay a single delegation".
1419        assert_eq!(options(), rto_graph::markdown_dialect());
1420    }
1421
1422    #[test]
1423    fn the_heading_id_rule_is_not_reimplemented_here() {
1424        // The counterpart of the test directly above, and the same argument:
1425        // `heading_ids` exists to hold this file's rationale about ids, not a
1426        // second copy of the rule. This reads as a tautology against the body as
1427        // written, which is exactly its job — it has no failure mode until
1428        // someone gives the body one.
1429        //
1430        // The fixture **contains the difference** rather than being a plain
1431        // document: a repeat, a claim an `h1` already took, and a heading that
1432        // names nothing. A local copy re-grown here would have to get all three
1433        // right to pass, and the one that used to be here got the second wrong —
1434        // it counted all levels while `rto_spec` counted `##` only, which is
1435        // what #629 was.
1436        let md = "# Same\n\n## Same\n\n## Dup\n\n## Dup\n\n### ###\n";
1437        assert_eq!(
1438            heading_ids(md),
1439            rto_graph::headings(md)
1440                .into_iter()
1441                .map(|h| h.id)
1442                .collect::<Vec<_>>()
1443        );
1444        // Agreement is necessary and not sufficient: two implementations that
1445        // both dropped the dedup would satisfy the assertion above. So pin what
1446        // the shared rule answers, once, here.
1447        assert_eq!(
1448            heading_ids(md),
1449            ["same", "same-2", "dup", "dup-2", "section-5"]
1450        );
1451    }
1452
1453    /// A source base for a document in `dir`, at a fixed sha.
1454    fn source(dir: &str) -> SourceBase {
1455        SourceBase::new(Some("https://github.com/o/r/blob/abc123"), dir).expect("base")
1456    }
1457
1458    #[test]
1459    fn a_link_out_of_the_site_goes_to_the_repository() {
1460        // Issue #456: the Build Plan cites code as evidence — correct in a
1461        // checkout, dead on the site, which publishes documents and not source.
1462        let base = source("docs");
1463        let html = render_markdown(
1464            "[sync](../crates/rto-graph/src/sync.rs) and [wf](../.github/workflows/website.yml)\n",
1465            "adr/",
1466            &no_pages(),
1467            Some(&base),
1468            0,
1469        );
1470        assert!(
1471            html.contains(
1472                "href=\"https://github.com/o/r/blob/abc123/crates/rto-graph/src/sync.rs\""
1473            ),
1474            "resolved against the document's own directory: {html}"
1475        );
1476        assert!(
1477            html.contains(
1478                "href=\"https://github.com/o/r/blob/abc123/.github/workflows/website.yml\""
1479            ),
1480            "a dotted directory is a directory, not a `.` segment: {html}"
1481        );
1482        // A line anchor is the author's, and travels.
1483        let frag = render_markdown(
1484            "[l](../crates/roteiro/src/init.rs#L12)\n",
1485            "adr/",
1486            &no_pages(),
1487            Some(&base),
1488            0,
1489        );
1490        assert!(
1491            frag.contains("blob/abc123/crates/roteiro/src/init.rs#L12\""),
1492            "{frag}"
1493        );
1494    }
1495
1496    #[test]
1497    fn a_link_that_stays_inside_the_site_is_left_alone() {
1498        // The whole discrimination is the hop count: `ask.html` and `adr/` are
1499        // written *for* the site and are correct there, so rewriting them to the
1500        // repository would break links that work today.
1501        let base = source("docs");
1502        let html = render_markdown(
1503            "[a](ask.html), [d](adr/), [s](./style.css) and [r](/abs.html)\n",
1504            "adr/",
1505            &no_pages(),
1506            Some(&base),
1507            0,
1508        );
1509        assert!(!html.contains("github.com"), "none rewritten: {html}");
1510        for href in [
1511            "\"ask.html\"",
1512            "\"adr/\"",
1513            "\"./style.css\"",
1514            "\"/abs.html\"",
1515        ] {
1516            assert!(html.contains(href), "{href} kept verbatim: {html}");
1517        }
1518    }
1519
1520    #[test]
1521    fn an_adr_may_climb_one_level_and_still_be_inside_the_site() {
1522        // An ADR page is served at `adr/<slug>.html`, so `../x` lands at the site
1523        // root. Treating that as an escape would send every ADR's back-link to
1524        // GitHub. The second hop does leave.
1525        let base = source("docs/adr");
1526        let inside = render_markdown("[b](../build-plan.html)\n", "", &no_pages(), Some(&base), 1);
1527        assert!(!inside.contains("github.com"), "{inside}");
1528        let outside = render_markdown("[c](../../Cargo.toml)\n", "", &no_pages(), Some(&base), 1);
1529        assert!(
1530            outside.contains("href=\"https://github.com/o/r/blob/abc123/Cargo.toml\""),
1531            "{outside}"
1532        );
1533    }
1534
1535    #[test]
1536    fn a_published_page_beats_the_escape_rule() {
1537        // Order matters: #446's lookup runs first, so a document reached by a
1538        // path that climbs out of its own directory still lands on the page the
1539        // site publishes it as, rather than being handed to the repository.
1540        let mut pages = PublishedPages::new();
1541        pages.publish("BUILD_PLAN_V2.md", "build-plan-v2.html");
1542        let base = source("website/pages");
1543        let html = render_markdown(
1544            "[v2](../../docs/BUILD_PLAN_V2.md)\n",
1545            "adr/",
1546            &pages,
1547            Some(&base),
1548            0,
1549        );
1550        assert!(
1551            html.contains("href=\"../../docs/build-plan-v2.html\""),
1552            "still the site's page: {html}"
1553        );
1554        assert!(!html.contains("github.com"), "{html}");
1555    }
1556
1557    #[test]
1558    fn without_a_source_base_the_link_is_left_as_authored() {
1559        // No `origin`, or one that maps to no web view. Leaving the link is the
1560        // deliberate choice: it stays correct in a checkout, and a rewrite that
1561        // silently produced a broken URL would be worse than the link it replaced.
1562        assert_eq!(SourceBase::new(None, "docs"), None);
1563        let html = render_markdown(
1564            "[s](../crates/rto-graph/src/sync.rs)\n",
1565            "adr/",
1566            &no_pages(),
1567            None,
1568            0,
1569        );
1570        assert!(
1571            html.contains("href=\"../crates/rto-graph/src/sync.rs\""),
1572            "{html}"
1573        );
1574    }
1575
1576    #[test]
1577    fn the_bar_on_the_landing_page_is_replaced_rather_than_maintained() {
1578        // Issue #508. The stale copy is overwritten wholesale, so there is no
1579        // second list left to drift out of `site-order`.
1580        let stale = "<h1>Roteiro</h1>\n<nav class=\"sitenav\">\n<a href=\"old.html\">Old</a>\n\
1581                     </nav>\n<p>after</p>\n";
1582        let out = replace_site_nav(stale, &nav(), "./").expect("marker found");
1583        assert!(
1584            !out.contains("old.html"),
1585            "the hand-written list is gone: {out}"
1586        );
1587        assert!(
1588            out.contains("<a href=\"modes.html\">Modes &amp; Co</a>"),
1589            "the computed bar took its place: {out}"
1590        );
1591        assert!(
1592            out.starts_with("<h1>Roteiro</h1>\n") && out.ends_with("<p>after</p>\n"),
1593            "only the bar is touched: {out}"
1594        );
1595        // A page that claims no bar is left alone rather than failing: every
1596        // `render docs` fixture writes a one-line landing page.
1597        assert_eq!(replace_site_nav("<h1>Home</h1>\n", &nav(), "./"), None);
1598    }
1599
1600    #[test]
1601    fn site_pages_render_deterministically() {
1602        let md = "---\nsite-page: a\n---\n\n# A\n\n## S\n";
1603        assert_eq!(
1604            render_site_page(md, "f", &nav(), "a.html", &no_pages(), None),
1605            render_site_page(md, "f", &nav(), "a.html", &no_pages(), None)
1606        );
1607    }
1608
1609    #[test]
1610    fn rendering_is_deterministic() {
1611        assert_eq!(
1612            render_adr(ADR, "f", &no_pages(), None),
1613            render_adr(ADR, "f", &no_pages(), None)
1614        );
1615    }
1616}