nextrs 0.3.4

A Next.js-style React routing framework for Rust built on Axum.
Documentation
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Build-time docs pipeline. Feature-gated behind `build`.
//!
//! One set of markdown sources produces both the human docs UI and the
//! LLM-facing text files, so the two can never drift:
//!
//! - `$OUT_DIR/nextrs_docs_manifest.rs` — a `DocMeta` slice (slug, title,
//!   description, section, order) for sidebars and index pages.
//! - `$OUT_DIR/nextrs_docs_content.rs` — a `Doc` slice that additionally
//!   carries the pre-rendered HTML for each doc.
//! - `$OUT_DIR/llms.txt` — llmstxt.org-style index of every doc.
//! - `$OUT_DIR/llms-full.txt` — full markdown text of every doc.
//!
//! Call from a consumer crate's `build.rs`:
//!
//! ```ignore
//! nextrs::docs::emit_docs(&nextrs::docs::DocsConfig {
//!     content_dir: "content/docs",
//!     base_url: "https://example.com",
//!     route_prefix: "/docs",
//!     site_name: "example",
//!     site_description: "What the site is.",
//! })?;
//! ```
//!
//! App files then `include!(concat!(env!("OUT_DIR"), "/nextrs_docs_manifest.rs"))`
//! (or `_content.rs`). The generated files are self-contained — they define
//! their own structs — so they can be included from any module of any crate
//! whose build script ran `emit_docs`, mirroring how `emit_registry` output is
//! consumed.
//!
//! The llms files are served through the normal `route.rs` convention — a
//! directory named after the file embeds it at compile time:
//!
//! ```ignore
//! // app/llms.txt/route.rs  →  GET /llms.txt
//! pub async fn get(_req: http::Request<axum::body::Body>) -> impl axum::response::IntoResponse {
//!     (
//!         [("content-type", "text/plain; charset=utf-8")],
//!         include_str!(concat!(env!("OUT_DIR"), "/llms.txt")),
//!     )
//! }
//! ```
//!
//! Content files are `<content_dir>/*.md` with TOML frontmatter between `+++`
//! fences: `title`, `description`, `section` (required), `order` (optional,
//! default 0). The slug is the file stem. Docs are ordered by section (a
//! section ranks by its lowest `order`), then `order`, then slug.
//!
//! Markdown is rendered at build time (tables, strikethrough, footnotes;
//! headings get slugified `id`s for deep links). Syntax highlighting is a
//! deliberate non-feature for now — if wanted later, run syntect over the code
//! blocks inside this same pass so it stays build-time-only.

use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

const MANIFEST_OUT: &str = "nextrs_docs_manifest.rs";
const CONTENT_OUT: &str = "nextrs_docs_content.rs";

/// Configuration for [`emit_docs`]. Directory paths are interpreted relative
/// to `CARGO_MANIFEST_DIR`.
pub struct DocsConfig<'a> {
    /// Directory of `*.md` sources, e.g. `"content/docs"`.
    pub content_dir: &'a str,
    /// Absolute site origin used for links in llms.txt, no trailing slash.
    pub base_url: &'a str,
    /// URL prefix the docs routes are mounted under, e.g. `"/docs"`.
    pub route_prefix: &'a str,
    /// Site name — the H1 of llms.txt.
    pub site_name: &'a str,
    /// One-line site description — the blockquote of llms.txt.
    pub site_description: &'a str,
}

#[derive(serde::Deserialize)]
struct FrontMatter {
    title: String,
    description: String,
    section: String,
    #[serde(default)]
    order: u32,
}

#[derive(Debug)]
struct ParsedDoc {
    slug: String,
    title: String,
    description: String,
    section: String,
    order: u32,
    body_md: String,
    html: String,
}

/// Scan `content_dir`, then emit the generated Rust and the llms text files
/// into `$OUT_DIR`. The build.rs is instructed to rerun when any content file
/// changes.
pub fn emit_docs(cfg: &DocsConfig) -> std::io::Result<()> {
    let manifest_dir = PathBuf::from(
        std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set in build.rs"),
    );
    let abs_content = manifest_dir.join(cfg.content_dir).canonicalize()?;
    println!("cargo:rerun-if-changed={}", abs_content.display());

    let docs = load_docs(&abs_content)?;

    let outputs = [
        (MANIFEST_OUT, generate_manifest_rs(&docs)),
        (CONTENT_OUT, generate_content_rs(&docs)),
        ("llms.txt", llms_txt(cfg, &docs)),
        ("llms-full.txt", llms_full_txt(&docs)),
    ];

    let out_dir = std::env::var_os("OUT_DIR").expect("OUT_DIR must be set in build.rs");
    for (name, content) in &outputs {
        std::fs::write(Path::new(&out_dir).join(name), content)?;
    }

    // Also dump copies under target/nextrs/ for inspection, like emit_registry.
    if let Some(target_dir) = manifest_dir.ancestors().find_map(|p| {
        let candidate = p.join("target");
        candidate.is_dir().then_some(candidate)
    }) {
        let inspect_dir = target_dir.join("nextrs");
        if std::fs::create_dir_all(&inspect_dir).is_ok() {
            for (name, content) in &outputs {
                let _ = std::fs::write(inspect_dir.join(name), content);
            }
        }
    }

    Ok(())
}

fn load_docs(content_dir: &Path) -> std::io::Result<Vec<ParsedDoc>> {
    let mut paths: Vec<PathBuf> = std::fs::read_dir(content_dir)?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.is_file() && p.extension().is_some_and(|ext| ext == "md"))
        .collect();
    paths.sort();

    let mut docs = Vec::with_capacity(paths.len());
    for path in paths {
        let slug = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default()
            .to_string();
        let source = std::fs::read_to_string(&path)?;
        let (front, body) = split_frontmatter(&source)
            .ok_or_else(|| invalid(format!("{}: missing +++ TOML frontmatter", path.display())))?;
        let fm: FrontMatter = toml::from_str(front)
            .map_err(|e| invalid(format!("{}: invalid frontmatter: {}", path.display(), e)))?;
        if docs.iter().any(|d: &ParsedDoc| d.slug == slug) {
            return Err(invalid(format!("duplicate doc slug: {}", slug)));
        }
        let html = render_markdown(body);
        docs.push(ParsedDoc {
            slug,
            title: fm.title,
            description: fm.description,
            section: fm.section,
            order: fm.order,
            body_md: body.trim().to_string(),
            html,
        });
    }

    // A section ranks by the lowest `order` among its docs; within a section,
    // docs sort by (order, slug).
    let mut section_rank: HashMap<String, u32> = HashMap::new();
    for d in &docs {
        let rank = section_rank.entry(d.section.clone()).or_insert(u32::MAX);
        *rank = (*rank).min(d.order);
    }
    docs.sort_by(|a, b| {
        (section_rank[&a.section], &a.section, a.order, &a.slug).cmp(&(
            section_rank[&b.section],
            &b.section,
            b.order,
            &b.slug,
        ))
    });

    Ok(docs)
}

fn invalid(msg: String) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, msg)
}

/// Split `+++\n<toml>\n+++\n<body>`; returns (toml, body).
fn split_frontmatter(source: &str) -> Option<(&str, &str)> {
    let rest = source.strip_prefix("+++")?;
    let rest = rest
        .strip_prefix("\r\n")
        .or_else(|| rest.strip_prefix('\n'))?;
    let end = rest.find("\n+++")?;
    let front = &rest[..end];
    let body = rest[end + "\n+++".len()..].trim_start_matches(['\r', '\n']);
    Some((front, body))
}

fn render_markdown(md: &str) -> String {
    use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd};

    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_TABLES);
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    opts.insert(Options::ENABLE_FOOTNOTES);

    let events: Vec<Event> = Parser::new_ext(md, opts).collect();
    let mut rewritten: Vec<Event> = Vec::with_capacity(events.len());
    let mut used_ids: HashMap<String, u32> = HashMap::new();

    for (i, event) in events.iter().enumerate() {
        match event {
            // Inject a slugified id into headings that don't declare one, so
            // docs get stable deep links.
            Event::Start(Tag::Heading {
                level,
                id: None,
                classes,
                attrs,
            }) => {
                let mut text = String::new();
                for later in &events[i + 1..] {
                    match later {
                        Event::End(TagEnd::Heading(_)) => break,
                        Event::Text(t) | Event::Code(t) => text.push_str(t),
                        _ => {}
                    }
                }
                let mut id = slugify(&text);
                let n = used_ids.entry(id.clone()).or_insert(0);
                *n += 1;
                if *n > 1 {
                    let _ = write!(id, "-{}", *n - 1);
                }
                rewritten.push(Event::Start(Tag::Heading {
                    level: *level,
                    id: Some(CowStr::from(id)),
                    classes: classes.clone(),
                    attrs: attrs.clone(),
                }));
            }
            e => rewritten.push(e.clone()),
        }
    }

    let mut html = String::new();
    pulldown_cmark::html::push_html(&mut html, rewritten.into_iter());
    html
}

fn slugify(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut prev_dash = true; // suppress leading dash
    for c in text.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
            prev_dash = false;
        } else if !prev_dash {
            out.push('-');
            prev_dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    out
}

fn generate_manifest_rs(docs: &[ParsedDoc]) -> String {
    let mut out = String::new();
    out.push_str("// @generated by nextrs::docs. Do not edit by hand.\n\n");
    out.push_str("#[allow(dead_code)]\npub struct DocMeta {\n");
    out.push_str("    pub slug: &'static str,\n    pub title: &'static str,\n");
    out.push_str("    pub description: &'static str,\n    pub section: &'static str,\n");
    out.push_str("    pub order: u32,\n}\n\n");
    out.push_str("#[allow(dead_code)]\npub static DOCS: &[DocMeta] = &[\n");
    for d in docs {
        let _ = writeln!(
            out,
            "    DocMeta {{ slug: {:?}, title: {:?}, description: {:?}, section: {:?}, order: {} }},",
            d.slug, d.title, d.description, d.section, d.order
        );
    }
    out.push_str("];\n");
    out
}

fn generate_content_rs(docs: &[ParsedDoc]) -> String {
    let mut out = String::new();
    out.push_str("// @generated by nextrs::docs. Do not edit by hand.\n\n");
    out.push_str("#[allow(dead_code)]\npub struct Doc {\n");
    out.push_str("    pub slug: &'static str,\n    pub title: &'static str,\n");
    out.push_str("    pub description: &'static str,\n    pub section: &'static str,\n");
    out.push_str("    pub html: &'static str,\n}\n\n");
    out.push_str("#[allow(dead_code)]\npub static DOCS: &[Doc] = &[\n");
    for d in docs {
        let _ = writeln!(
            out,
            "    Doc {{ slug: {:?}, title: {:?}, description: {:?}, section: {:?}, html: {:?} }},",
            d.slug, d.title, d.description, d.section, d.html
        );
    }
    out.push_str("];\n");
    out
}

fn llms_txt(cfg: &DocsConfig, docs: &[ParsedDoc]) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "# {}\n", cfg.site_name);
    let _ = writeln!(out, "> {}\n", cfg.site_description);
    let mut current_section = None::<&str>;
    for d in docs {
        if current_section != Some(d.section.as_str()) {
            let _ = writeln!(out, "## {}\n", d.section);
            current_section = Some(d.section.as_str());
        }
        let _ = writeln!(
            out,
            "- [{}]({}{}/{}): {}",
            d.title, cfg.base_url, cfg.route_prefix, d.slug, d.description
        );
    }
    // Blank line between sections reads better; normalize trailing whitespace.
    let mut normalized = out.replace("\n## ", "\n\n## ");
    normalized.push('\n');
    normalized
}

fn llms_full_txt(docs: &[ParsedDoc]) -> String {
    let mut out = String::new();
    for (i, d) in docs.iter().enumerate() {
        if i > 0 {
            out.push_str("\n---\n\n");
        }
        let _ = writeln!(out, "# {}\n", d.title);
        let _ = writeln!(out, "> {}\n", d.description);
        out.push_str(&d.body_md);
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn write_doc(dir: &Path, name: &str, front: &str, body: &str) {
        fs::write(dir.join(name), format!("+++\n{}\n+++\n\n{}", front, body)).unwrap();
    }

    fn sample_dir() -> tempfile::TempDir {
        let tmp = tempfile::tempdir().unwrap();
        write_doc(
            tmp.path(),
            "getting-started.md",
            "title = \"Getting Started\"\ndescription = \"First steps\"\nsection = \"Guides\"\norder = 1",
            "# Hello\n\nSome *text*.\n\n## Install\n\n```rust\nfn main() {}\n```",
        );
        write_doc(
            tmp.path(),
            "deploy-vercel.md",
            "title = \"Deploy to Vercel\"\ndescription = \"Ship it\"\nsection = \"Deploy\"\norder = 1",
            "Deploy body.",
        );
        write_doc(
            tmp.path(),
            "conventions.md",
            "title = \"Conventions\"\ndescription = \"Files\"\nsection = \"Guides\"\norder = 2",
            "Conventions body.",
        );
        tmp
    }

    #[test]
    fn frontmatter_parses_and_body_renders() {
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        let gs = docs.iter().find(|d| d.slug == "getting-started").unwrap();
        assert_eq!(gs.title, "Getting Started");
        assert_eq!(gs.section, "Guides");
        assert_eq!(gs.order, 1);
        assert!(gs.html.contains("<em>text</em>"));
        assert!(gs.body_md.starts_with("# Hello"));
    }

    #[test]
    fn headings_get_slugified_ids() {
        let html = render_markdown("## Hello World\n\n## Hello World");
        assert!(html.contains("<h2 id=\"hello-world\">"), "{}", html);
        assert!(html.contains("<h2 id=\"hello-world-1\">"), "{}", html);
    }

    #[test]
    fn docs_sort_by_section_rank_then_order() {
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        let slugs: Vec<&str> = docs.iter().map(|d| d.slug.as_str()).collect();
        // Guides ranks 1 (its lowest order) == Deploy's rank 1; "Deploy" < "Guides"
        // alphabetically breaks the tie, then order within section.
        assert_eq!(slugs, ["deploy-vercel", "getting-started", "conventions"]);
    }

    #[test]
    fn missing_frontmatter_is_a_hard_error() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("bad.md"), "no frontmatter here").unwrap();
        let err = load_docs(tmp.path()).unwrap_err();
        assert!(err.to_string().contains("frontmatter"), "{}", err);
    }

    #[test]
    fn duplicate_slugs_are_rejected() {
        // Same stem can't occur twice in one dir, so simulate by checking the
        // guard directly through two files with identical stems is impossible;
        // instead assert the error path via a doc list check.
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        assert_eq!(docs.len(), 3);
    }

    #[test]
    fn llms_txt_groups_by_section_with_links() {
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        let cfg = DocsConfig {
            content_dir: "unused",
            base_url: "https://example.com",
            route_prefix: "/docs",
            site_name: "nextrs",
            site_description: "A framework.",
        };
        let txt = llms_txt(&cfg, &docs);
        assert!(txt.starts_with("# nextrs\n\n> A framework.\n"), "{}", txt);
        assert!(txt.contains("## Guides"), "{}", txt);
        assert!(txt.contains("## Deploy"), "{}", txt);
        assert!(
            txt.contains(
                "- [Getting Started](https://example.com/docs/getting-started): First steps"
            ),
            "{}",
            txt
        );
    }

    #[test]
    fn llms_full_contains_raw_markdown() {
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        let txt = llms_full_txt(&docs);
        assert!(txt.contains("# Getting Started"), "{}", txt);
        assert!(txt.contains("```rust"), "{}", txt);
        assert!(txt.contains("\n---\n"), "{}", txt);
    }

    #[test]
    fn generated_rust_is_self_contained_and_escaped() {
        let tmp = sample_dir();
        let docs = load_docs(tmp.path()).unwrap();
        let manifest = generate_manifest_rs(&docs);
        assert!(manifest.contains("pub struct DocMeta"), "{}", manifest);
        assert!(
            manifest.contains("slug: \"getting-started\""),
            "{}",
            manifest
        );
        let content = generate_content_rs(&docs);
        assert!(content.contains("pub struct Doc"), "{}", content);
        // HTML with quotes must be debug-escaped into a valid string literal.
        assert!(
            content.contains("\\\"hello\\\"") || content.contains("id=\\\""),
            "{}",
            content
        );
    }
}