nornir 0.3.0

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Document export: render assembled markdown to PDF / HTML via typst.
//!
//! Pipeline:
//!   .md file(s) → pulldown-cmark events → typst markup string
//!                  → typst-as-lib engine (with embedded template + fonts)
//!                  → typst::Document
//!                  → typst_pdf / typst_html bytes
//!
//! No shellout. No JS. 100% Rust. The default template (`assets/typst/report.typ`)
//! is embedded at compile time via `rust-embed`. Future: allow `--template PATH`
//! to override, and a future opt-in path can skip the markdown front-end entirely
//! and let users author in typst directly.
//!
//! See also: [`crate::docs::sections`] — the section assembler that fills in
//! `<!-- nornir:gen:start:NAME -->` blocks. Run `assemble_file` first, then
//! `export()`.
//!
//! Cargo feature: `docs-export`.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};
use rust_embed::RustEmbed;
use typst::foundations::{Bytes, Dict, IntoValue};
use typst_as_lib::typst_kit_options::TypstKitFontOptions;
use typst_as_lib::TypstEngine;

#[derive(RustEmbed)]
#[folder = "assets/typst/"]
struct TemplateAssets;

/// Output formats supported by the exporter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DocFormat {
    /// Portable Document Format (typst-rendered).
    Pdf,
    /// HTML (typst-rendered single-file).
    Html,
    /// Raw markdown passthrough (no transformation).
    Md,
}

impl DocFormat {
    pub fn parse(s: &str) -> Result<Self> {
        match s.to_ascii_lowercase().as_str() {
            "pdf" => Ok(Self::Pdf),
            "html" => Ok(Self::Html),
            "md" | "markdown" => Ok(Self::Md),
            other => Err(anyhow!("unknown doc format: {other}")),
        }
    }
    pub fn extension(self) -> &'static str {
        match self {
            Self::Pdf => "pdf",
            Self::Html => "html",
            Self::Md => "md",
        }
    }
}

/// Which typst compilation target a translated body is destined for.
///
/// The markdown→typst translation is mostly shared, but a few constructs
/// differ between the paged (PDF/SVG) target and the experimental HTML
/// target — e.g. a thematic break is a `#line()` on a page but an
/// `<hr>` element in HTML, and the latter rejects layout primitives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
    /// Paged document (PDF/SVG) — the default, fully supported path.
    Paged,
    /// HTML document (experimental in typst 0.14). Best-effort.
    Html,
}

/// What goes into the template header.
#[derive(Debug, Clone)]
pub struct ExportMeta {
    pub title: String,
    pub version: String,
    pub generated: String,
}

/// Render `markdown` (already assembled by [`crate::docs::sections`]) to `format`.
/// Returns raw bytes.
///
/// - `image_cache_dir`: if `Some`, remote images referenced from the markdown
///   are downloaded (via `ureq` + rustls), cached on disk, and embedded into
///   the typst document. Pass `None` to skip remote fetches (placeholder text
///   is rendered instead).
/// - `root`: if `Some`, a typst filesystem root is mounted at that directory so
///   *local* images (e.g. `.nornir/assets/depgraph.svg`) resolve and embed.
///   Local image links are interpreted as project-root-relative (typically the
///   repo root). Pass `None` when the document references no local images.
pub fn export(
    markdown: &str,
    meta: &ExportMeta,
    format: DocFormat,
    image_cache_dir: Option<&Path>,
    root: Option<&Path>,
) -> Result<Vec<u8>> {
    match format {
        DocFormat::Md => Ok(markdown.as_bytes().to_vec()),
        DocFormat::Pdf => render_pdf(markdown, meta, image_cache_dir, root),
        DocFormat::Html => render_html(markdown, meta, image_cache_dir, root),
    }
}

fn render_pdf(
    markdown: &str,
    meta: &ExportMeta,
    image_cache_dir: Option<&Path>,
    root: Option<&Path>,
) -> Result<Vec<u8>> {
    let (engine, inputs) =
        build_engine(markdown, meta, image_cache_dir, root, Target::Paged)?;
    let doc: typst::layout::PagedDocument = engine
        .compile_with_input(inputs)
        .output
        .map_err(|err| anyhow!("typst compile failed: {:?}", err))?;
    let options = Default::default();
    typst_pdf::pdf(&doc, &options).map_err(|e| anyhow!("typst pdf export failed: {:?}", e))
}

/// HTML output via the **typst** engine (experimental in typst 0.14).
///
/// Uses the HTML-safe `web.typ` template and typst's `Target::Html`. This is
/// the low-priority path — if the experimental exporter rejects a construct,
/// the error is surfaced to the caller rather than silently producing a
/// half-rendered page.
fn render_html(
    markdown: &str,
    meta: &ExportMeta,
    image_cache_dir: Option<&Path>,
    root: Option<&Path>,
) -> Result<Vec<u8>> {
    let (engine, inputs) =
        build_engine_with_template(markdown, meta, image_cache_dir, root, Target::Html, "web.typ")?;
    let doc: typst_html::HtmlDocument = engine
        .compile_with_input(inputs)
        .output
        .map_err(|err| anyhow!("typst html compile failed: {:?}", err))?;
    let html = typst_html::html(&doc)
        .map_err(|err| anyhow!("typst html serialization failed: {:?}", err))?;
    Ok(html.into_bytes())
}

/// Build a typst engine + inputs for the default `report.typ` (paged) template.
fn build_engine(
    markdown: &str,
    meta: &ExportMeta,
    image_cache_dir: Option<&Path>,
    root: Option<&Path>,
    target: Target,
) -> Result<(typst_as_lib::TypstEngine<typst_as_lib::TypstTemplateMainFile>, Dict)> {
    build_engine_with_template(markdown, meta, image_cache_dir, root, target, "report.typ")
}

/// Build a typst engine + inputs from an embedded template by file name.
/// Mounts (a) any downloaded remote images as virtual `/img/...` files and
/// (b) a real filesystem root (when `root` is `Some`) so local `#image()`
/// paths resolve off disk.
fn build_engine_with_template(
    markdown: &str,
    meta: &ExportMeta,
    image_cache_dir: Option<&Path>,
    root: Option<&Path>,
    target: Target,
    template_name: &str,
) -> Result<(typst_as_lib::TypstEngine<typst_as_lib::TypstTemplateMainFile>, Dict)> {
    let template = TemplateAssets::get(template_name)
        .ok_or_else(|| anyhow!("bundled typst template missing: {template_name}"))?;
    let template_src = std::str::from_utf8(&template.data)
        .context("template not utf-8")?
        .to_owned();

    let mut images = ImageResolver::new(image_cache_dir);
    let body_typst = md_to_typst_with(markdown, &mut images, target);

    let mut builder = TypstEngine::builder()
        .main_file(template_src)
        .search_fonts_with(
            TypstKitFontOptions::default()
                .include_system_fonts(false)
                .include_embedded_fonts(true),
        );
    // Mount all downloaded image bytes as virtual files at `/img/<hash>.<ext>`.
    if !images.assets.is_empty() {
        let pairs: Vec<(&str, Bytes)> = images
            .assets
            .iter()
            .map(|(path, bytes)| (path.as_str(), Bytes::new(bytes.clone())))
            .collect();
        builder = builder.with_static_file_resolver(pairs);
    }
    // Mount a real filesystem root so local `#image("/...")` links resolve.
    if let Some(r) = root {
        builder = builder.with_file_system_resolver(r.to_path_buf());
    }
    let engine = builder.build();

    let mut inputs = Dict::new();
    inputs.insert("title".into(), meta.title.clone().into_value());
    inputs.insert("version".into(), meta.version.clone().into_value());
    inputs.insert("generated".into(), meta.generated.clone().into_value());
    inputs.insert("body".into(), body_typst.into_value());

    Ok((engine, inputs))
}

// ---------- Image fetcher ----------

/// Downloads remote markdown images into a local cache and tracks them
/// so the typst engine can serve them via its in-memory file resolver.
pub struct ImageResolver {
    cache_dir: Option<PathBuf>,
    /// virtual_path → bytes (mounted into the typst World).
    assets: HashMap<String, Vec<u8>>,
}

impl ImageResolver {
    fn new(cache_dir: Option<&Path>) -> Self {
        Self {
            cache_dir: cache_dir.map(|p| p.to_path_buf()),
            assets: HashMap::new(),
        }
    }

    /// Returns the typst-side virtual path for `url`, downloading + caching
    /// if necessary. Returns `None` when the URL is remote but no cache dir
    /// was configured, or when the download fails.
    fn resolve(&mut self, url: &str) -> Option<String> {
        if !(url.starts_with("http://") || url.starts_with("https://")) {
            // Local URL — typst will read it from the source-relative path.
            // We don't intercept these.
            return None;
        }
        let cache_dir = self.cache_dir.as_ref()?;
        if std::fs::create_dir_all(cache_dir).is_err() {
            return None;
        }
        let ext = guess_image_ext(url);
        let key = url_hash(url);
        let file_name = format!("{key}.{ext}");
        let disk_path = cache_dir.join(&file_name);

        // Already mounted this run (under any extension we picked)?
        let early_virtual = format!("/img/{file_name}");
        if self.assets.contains_key(&early_virtual) {
            return Some(early_virtual);
        }

        // Disk cache hit?
        let raw_bytes = if let Ok(b) = std::fs::read(&disk_path) {
            b
        } else {
            match fetch_url(url) {
                Ok(b) => {
                    let _ = std::fs::write(&disk_path, &b);
                    b
                }
                Err(_) => return None,
            }
        };

        // Sniff actual format. Transcode to WebP only when it's a win:
        //   - PNG → lossless WebP (typically 20–40% smaller).
        //   - JPEG → keep JPEG. Pure-Rust WebP encoder is lossless-only,
        //     so re-encoding photos would *inflate* the file. Lossy WebP
        //     needs the C libwebp crate, which violates the no-C-deps rule.
        //   - GIF → lossless WebP (single frame; animation is dropped,
        //     which is fine for static docs).
        //   - SVG / unknown → passthrough.
        let real_ext = sniff_image_ext(&raw_bytes).unwrap_or(ext);
        let (final_ext, final_bytes) = match real_ext {
            "png" | "gif" => match transcode_to_webp(&raw_bytes) {
                Some(b) if b.len() < raw_bytes.len() => ("webp", b),
                _ => (real_ext, raw_bytes),
            },
            other => (other, raw_bytes),
        };
        let final_name = format!("{key}.{final_ext}");
        if final_ext == "webp" {
            let webp_path = cache_dir.join(&final_name);
            if !webp_path.exists() {
                let _ = std::fs::write(&webp_path, &final_bytes);
            }
        }
        let virtual_path = format!("/img/{final_name}");
        if self.assets.contains_key(&virtual_path) {
            return Some(virtual_path);
        }
        self.assets.insert(virtual_path.clone(), final_bytes);
        Some(virtual_path)
    }
}

/// Best-effort transcode of PNG/JPEG/GIF bytes into WebP. Returns
/// `None` when the input is undecodable or the encode fails — caller
/// falls back to the original bytes.
fn transcode_to_webp(bytes: &[u8]) -> Option<Vec<u8>> {
    let img = image::load_from_memory(bytes).ok()?;
    let mut out = std::io::Cursor::new(Vec::with_capacity(bytes.len() / 2));
    img.write_to(&mut out, image::ImageFormat::WebP).ok()?;
    Some(out.into_inner())
}

/// Detect the image format from magic bytes. Returns `None` for unknown.
fn sniff_image_ext(bytes: &[u8]) -> Option<&'static str> {
    if bytes.len() >= 8 && &bytes[..8] == b"\x89PNG\r\n\x1a\n" {
        Some("png")
    } else if bytes.len() >= 3 && &bytes[..3] == b"\xff\xd8\xff" {
        Some("jpg")
    } else if bytes.len() >= 6 && (&bytes[..6] == b"GIF87a" || &bytes[..6] == b"GIF89a") {
        Some("gif")
    } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
        Some("webp")
    } else if bytes.len() >= 5 && (&bytes[..5] == b"<?xml" || &bytes[..4] == b"<svg") {
        Some("svg")
    } else {
        None
    }
}

fn fetch_url(url: &str) -> Result<Vec<u8>> {
    let resp = ureq::AgentBuilder::new()
        .timeout(std::time::Duration::from_secs(15))
        .user_agent("nornir-docs-export/0.1")
        .redirects(5)
        .build()
        .get(url)
        // Prefer WebP — many CDNs (Cloudflare, fastly, GitHub assets)
        // content-negotiate and hand us WebP directly, skipping the
        // local transcode.
        .set("Accept", "image/webp,image/png,image/jpeg,image/*;q=0.8,*/*;q=0.5")
        .call()
        .map_err(|e| anyhow!("fetch {url}: {e}"))?;
    if resp.status() / 100 != 2 {
        return Err(anyhow!("fetch {url}: HTTP {}", resp.status()));
    }
    let mut buf = Vec::with_capacity(64 * 1024);
    use std::io::Read;
    let mut reader = resp.into_reader().take(5 * 1024 * 1024);
    reader
        .read_to_end(&mut buf)
        .map_err(|e| anyhow!("read {url}: {e}"))?;
    Ok(buf)
}

fn url_hash(url: &str) -> String {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    url.hash(&mut h);
    format!("{:016x}", h.finish())
}

fn guess_image_ext(url: &str) -> &'static str {
    // Strip query string before sniffing extension.
    let path = url.split(['?', '#']).next().unwrap_or(url);
    let lower = path.to_ascii_lowercase();
    if lower.ends_with(".png") {
        "png"
    } else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
        "jpg"
    } else if lower.ends_with(".gif") {
        "gif"
    } else if lower.ends_with(".svg") {
        "svg"
    } else if lower.ends_with(".webp") {
        "webp"
    } else {
        // Typst supports PNG/JPEG/GIF/SVG/WebP; default to png — most asset
        // hosts return PNG for screenshots when no extension is given.
        "png"
    }
}

// ---------- Markdown → Typst translator ----------

/// Translate a markdown document into typst markup.
///
/// This is *not* a full converter — it handles every construct nornir
/// emits in its own generated sections plus the common subset (headings,
/// lists, code, links, emphasis, tables, blockquotes, images, horizontal
/// rules, line/paragraph breaks). Unknown HTML is passed through as a
/// raw block.
/// Translate markdown to typst markup with no image resolution
/// (remote URLs become placeholder text). Kept for tests + callers
/// that don't need image fetching.
pub fn md_to_typst(md: &str) -> String {
    let mut noop = ImageResolver::new(None);
    md_to_typst_with(md, &mut noop, Target::Paged)
}

/// Translate markdown to typst markup, routing remote images through
/// `images` (downloads + mounts them as virtual files). `target` selects
/// a handful of construct emissions that differ between the paged and HTML
/// backends (currently: the thematic break).
pub fn md_to_typst_with(md: &str, images: &mut ImageResolver, target: Target) -> String {
    use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_TABLES);
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    opts.insert(Options::ENABLE_TASKLISTS);

    let mut out = String::with_capacity(md.len() * 2);
    let mut list_stack: Vec<Option<u64>> = Vec::new();
    let mut in_code: Option<String> = None;
    let mut code_buf = String::new();
    // Suppress an image's alt-text run (`![alt](src)`): typst's `#image` takes
    // no alt body, so the alt would otherwise leak into the document as stray
    // text right after the image.
    let mut in_image = false;
    let mut table_cells: Vec<String> = Vec::new();
    let mut cell_buf: Option<String> = None;
    let mut link_url: Option<String> = None;

    let push = |out: &mut String, cell_buf: &mut Option<String>, s: &str| {
        if let Some(b) = cell_buf {
            b.push_str(s);
        } else {
            out.push_str(s);
        }
    };

    for ev in Parser::new_ext(md, opts) {
        match ev {
            Event::Start(Tag::Heading { level, .. }) => {
                let n = match level {
                    HeadingLevel::H1 => 1,
                    HeadingLevel::H2 => 2,
                    HeadingLevel::H3 => 3,
                    HeadingLevel::H4 => 4,
                    HeadingLevel::H5 => 5,
                    HeadingLevel::H6 => 6,
                };
                out.push('\n');
                for _ in 0..n {
                    out.push('=');
                }
                out.push(' ');
            }
            Event::End(TagEnd::Heading(_)) => out.push_str("\n\n"),

            Event::Start(Tag::Paragraph) => {}
            Event::End(TagEnd::Paragraph) => out.push_str("\n\n"),

            Event::Start(Tag::BlockQuote(_)) => out.push_str("#quote(block: true)[\n"),
            Event::End(TagEnd::BlockQuote(_)) => out.push_str("]\n\n"),

            Event::Start(Tag::CodeBlock(kind)) => {
                let lang = match kind {
                    CodeBlockKind::Fenced(l) => l.to_string(),
                    CodeBlockKind::Indented => String::new(),
                };
                in_code = Some(lang);
                code_buf.clear();
            }
            Event::End(TagEnd::CodeBlock) => {
                let lang = in_code.take().unwrap_or_default();
                // The body is buffered so we can size the typst raw fence longer
                // than any backtick run inside it — nornir's own docs embed
                // ``` fences and `code`, which would otherwise leave the raw
                // block "unclosed" for the typst parser.
                out.push_str(&typst_raw_block(&lang, &code_buf));
                code_buf.clear();
            }

            Event::Start(Tag::List(start)) => {
                list_stack.push(start);
                out.push('\n');
            }
            Event::End(TagEnd::List(_)) => {
                list_stack.pop();
                out.push('\n');
            }
            Event::Start(Tag::Item) => {
                let indent = "  ".repeat(list_stack.len().saturating_sub(1));
                out.push_str(&indent);
                match list_stack.last().copied().flatten() {
                    Some(_) => out.push_str("+ "),
                    None => out.push_str("- "),
                }
            }
            Event::End(TagEnd::Item) => out.push('\n'),

            Event::Start(Tag::Emphasis) => push(&mut out, &mut cell_buf, "_"),
            Event::End(TagEnd::Emphasis) => push(&mut out, &mut cell_buf, "_"),
            Event::Start(Tag::Strong) => push(&mut out, &mut cell_buf, "*"),
            Event::End(TagEnd::Strong) => push(&mut out, &mut cell_buf, "*"),
            Event::Start(Tag::Strikethrough) => push(&mut out, &mut cell_buf, "#strike[ "),
            Event::End(TagEnd::Strikethrough) => push(&mut out, &mut cell_buf, " ]"),

            Event::Start(Tag::Link { dest_url, .. }) => {
                link_url = Some(dest_url.to_string());
                push(&mut out, &mut cell_buf, "#link(\"");
                push(&mut out, &mut cell_buf, &escape_typst_str(&dest_url));
                push(&mut out, &mut cell_buf, "\")[");
            }
            Event::End(TagEnd::Link) => {
                link_url = None;
                push(&mut out, &mut cell_buf, "]");
            }

            Event::Start(Tag::Image { dest_url, title, .. }) => {
                let _ = title;
                in_image = true;
                let url = dest_url.to_string();
                let is_remote = url.starts_with("http://") || url.starts_with("https://");
                if is_remote {
                    match images.resolve(&url) {
                        Some(virt) => {
                            push(&mut out, &mut cell_buf, "#image(\"");
                            push(&mut out, &mut cell_buf, &escape_typst_str(&virt));
                            push(&mut out, &mut cell_buf, "\")");
                        }
                        None => {
                            push(&mut out, &mut cell_buf, "_[remote image omitted]_");
                        }
                    }
                } else {
                    let local = local_image_path(&url);
                    push(&mut out, &mut cell_buf, "#image(\"");
                    push(&mut out, &mut cell_buf, &escape_typst_str(&local));
                    push(&mut out, &mut cell_buf, "\")");
                }
            }
            Event::End(TagEnd::Image) => in_image = false,

            Event::Start(Tag::Table(aligns)) => {
                let cols = aligns.len().max(1);
                table_cells.clear();
                out.push_str(&format!("\n#table(\n  columns: {},\n", cols));
            }
            Event::End(TagEnd::Table) => {
                for c in table_cells.drain(..) {
                    out.push_str("  [");
                    out.push_str(&c);
                    out.push_str("],\n");
                }
                out.push_str(")\n\n");
            }
            Event::Start(Tag::TableHead) | Event::Start(Tag::TableRow) => {}
            Event::End(TagEnd::TableHead) | Event::End(TagEnd::TableRow) => {}
            Event::Start(Tag::TableCell) => {
                cell_buf = Some(String::new());
            }
            Event::End(TagEnd::TableCell) => {
                if let Some(b) = cell_buf.take() {
                    table_cells.push(b);
                }
            }

            Event::Text(t) => {
                if in_code.is_some() {
                    // Raw code body — buffered verbatim (fenced at End).
                    code_buf.push_str(&t);
                } else if in_image {
                    // Alt text — `#image` has no body; drop it.
                } else {
                    let _ = &link_url;
                    push(&mut out, &mut cell_buf, &escape_typst_text(&t));
                }
            }
            Event::Code(t) => {
                push(&mut out, &mut cell_buf, &typst_raw_inline(&t));
            }
            Event::Html(h) | Event::InlineHtml(h) => {
                // Skip nornir markers; pass other HTML through as comment.
                let s = h.to_string();
                if s.contains("nornir:gen:") || s.contains("nornir:generated") {
                    // section markers — already consumed by sections.rs
                    continue;
                }
                // Recover `<img src="…">` so logos/figures authored as raw HTML
                // (for git-host centering) still render in PDF/HTML. Local paths
                // are normalised to project-root form so the filesystem root
                // resolves them. Other raw HTML is dropped (typst has no DOM).
                if let Some(src) = extract_img_src(&s) {
                    let is_remote = src.starts_with("http://") || src.starts_with("https://");
                    let path = if is_remote {
                        images.resolve(&src)
                    } else {
                        Some(local_image_path(&src))
                    };
                    if let Some(p) = path {
                        let esc = escape_typst_str(&p);
                        match target {
                            // `#align` is a layout primitive — not in the HTML target.
                            Target::Paged => {
                                push(&mut out, &mut cell_buf, "\n#align(center, image(\"");
                                push(&mut out, &mut cell_buf, &esc);
                                push(&mut out, &mut cell_buf, "\", width: 70%))\n\n");
                            }
                            Target::Html => {
                                push(&mut out, &mut cell_buf, "\n#image(\"");
                                push(&mut out, &mut cell_buf, &esc);
                                push(&mut out, &mut cell_buf, "\")\n\n");
                            }
                        }
                    }
                }
            }
            Event::SoftBreak => push(&mut out, &mut cell_buf, " "),
            Event::HardBreak => push(&mut out, &mut cell_buf, " \\\n"),
            Event::Rule => match target {
                Target::Paged => {
                    out.push_str("\n#line(length: 100%, stroke: 0.4pt + gray)\n\n")
                }
                // Layout primitives aren't allowed in typst's HTML target; emit
                // a real `<hr>` element instead.
                Target::Html => out.push_str("\n#html.elem(\"hr\")\n\n"),
            },
            Event::FootnoteReference(_)
            | Event::TaskListMarker(_)
            | Event::InlineMath(_)
            | Event::DisplayMath(_) => {}
            Event::Start(_) | Event::End(_) => {}
        }
    }
    out
}

/// Longest run of consecutive backticks in `s`.
fn max_backtick_run(s: &str) -> usize {
    let mut max = 0;
    let mut cur = 0;
    for c in s.chars() {
        if c == '`' {
            cur += 1;
            max = max.max(cur);
        } else {
            cur = 0;
        }
    }
    max
}

/// Emit `content` as a typst *inline* raw span, choosing a backtick fence
/// longer than any run inside it (CommonMark rule), padding with spaces when
/// the content starts or ends with a backtick.
fn typst_raw_inline(content: &str) -> String {
    let fence = "`".repeat(max_backtick_run(content) + 1);
    if content.starts_with('`') || content.ends_with('`') {
        format!("{fence} {content} {fence}")
    } else {
        format!("{fence}{content}{fence}")
    }
}

/// Emit `content` as a typst *block* raw, with a fence (≥3 backticks) longer
/// than any run inside it, and the language tag glued to the opening fence.
fn typst_raw_block(lang: &str, content: &str) -> String {
    let fence = "`".repeat((max_backtick_run(content) + 1).max(3));
    let mut body = content.to_string();
    if !body.ends_with('\n') {
        body.push('\n');
    }
    format!("\n{fence}{lang}\n{body}{fence}\n\n")
}

/// Normalise a *local* markdown image path into a typst project-root path.
///
/// nornir emits local image links repo-root-relative (e.g.
/// `.nornir/assets/depgraph.svg`). typst resolves a leading-`/` path against
/// the mounted filesystem root, while a bare relative path is resolved against
/// the (virtual, in-memory) main file — which has no directory. So we strip a
/// `./` prefix and force a single leading `/`, making the path root-anchored.
fn local_image_path(url: &str) -> String {
    let trimmed = url.strip_prefix("./").unwrap_or(url);
    format!("/{}", trimmed.trim_start_matches('/'))
}

/// Best-effort extraction of the first `src="…"` (or `src='…'`) attribute from
/// a raw HTML `<img …>` chunk. Returns `None` when the chunk has no `<img>`.
fn extract_img_src(html: &str) -> Option<String> {
    let lower = html.to_ascii_lowercase();
    if !lower.contains("<img") {
        return None;
    }
    let at = lower.find("src=")? + 4;
    let rest = &html[at..];
    let quote = rest.chars().next()?;
    if quote != '"' && quote != '\'' {
        return None;
    }
    let end = rest[1..].find(quote)?;
    Some(rest[1..1 + end].to_string())
}

fn escape_typst_text(s: &str) -> String {
    // Escape typst's active characters in text context.
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' | '#' | '$' | '*' | '_' | '`' | '<' | '>' | '@' | '[' | ']' => {
                out.push('\\');
                out.push(c);
            }
            // A `/` only needs escaping when it would start a typst comment
            // (`//` line comment or `/*` block comment) — otherwise the comment
            // swallows the rest of the line, including any open `*`/`_`/`[`
            // delimiter, yielding "unclosed delimiter". Common in plain-text
            // URLs (`https://…`). Lone slashes (paths) are left untouched.
            '/' if matches!(chars.peek().copied(), Some('/') | Some('*')) => {
                out.push('\\');
                out.push('/');
            }
            _ => out.push(c),
        }
    }
    out
}

fn escape_typst_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            _ => out.push(c),
        }
    }
    out
}

// --------- High-level "render this repo" convenience ----------

/// Read `<repo_root>/README.md`, build [`ExportMeta`] from the crate's
/// `Cargo.toml`, and render to `format`. The README must already have been
/// assembled via [`crate::docs::sections::assemble_file`].
pub fn export_repo(repo_root: &Path, format: DocFormat) -> Result<Vec<u8>> {
    let md_path = repo_root.join("README.md");
    let md = std::fs::read_to_string(&md_path)
        .with_context(|| format!("read {}", md_path.display()))?;
    let meta = read_meta(repo_root)?;
    let cache_dir = repo_root.join(".nornir/cache/images");
    // Mount the repo root so local `.nornir/assets/…` images resolve and embed.
    export(&md, &meta, format, Some(&cache_dir), Some(repo_root))
}

fn read_meta(repo_root: &Path) -> Result<ExportMeta> {
    let cargo_toml = repo_root.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml)
        .with_context(|| format!("read {}", cargo_toml.display()))?;
    let parsed: toml::Value = toml::from_str(&content)?;
    let pkg = parsed
        .get("package")
        .or_else(|| parsed.get("workspace").and_then(|w| w.get("package")));
    let dir_name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("project")
        .to_string();
    let (title, version) = if let Some(p) = pkg {
        let name = p
            .get("name")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| dir_name.clone());
        let version = p
            .get("version")
            .and_then(|v| v.as_str())
            .unwrap_or("0.0.0")
            .to_string();
        (name, version)
    } else {
        (dir_name, "0.0.0".to_string())
    };
    let generated = chrono::Utc::now().format("%Y-%m-%d").to_string();
    Ok(ExportMeta {
        title,
        version,
        generated,
    })
}

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

    #[test]
    fn md_to_typst_basic() {
        let md = "# Title\n\nSome *bold* text and `code`.\n\n- one\n- two\n";
        let out = md_to_typst(md);
        assert!(out.contains("= Title"));
        assert!(out.contains("`code`"));
        assert!(out.contains("- one"));
    }

    #[test]
    fn md_to_typst_table() {
        let md = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        let out = md_to_typst(md);
        assert!(out.contains("#table("));
        assert!(out.contains("columns: 2"));
    }

    #[test]
    fn md_to_typst_link() {
        let md = "see [docs](https://example.com)";
        let out = md_to_typst(md);
        assert!(out.contains("#link(\"https://example.com\")"));
    }

    #[test]
    fn md_to_typst_code_fence() {
        let md = "```rust\nfn main() {}\n```\n";
        let out = md_to_typst(md);
        assert!(out.contains("```rust"));
        assert!(out.contains("fn main() {}"));
    }

    #[test]
    fn format_parse() {
        assert_eq!(DocFormat::parse("pdf").unwrap(), DocFormat::Pdf);
        assert_eq!(DocFormat::parse("HTML").unwrap(), DocFormat::Html);
        assert_eq!(DocFormat::parse("md").unwrap(), DocFormat::Md);
        assert!(DocFormat::parse("xml").is_err());
    }

    #[test]
    fn md_to_typst_remote_image_placeholder_without_cache() {
        let md = "![alt](https://example.com/x.png)\n";
        let out = md_to_typst(md);
        assert!(
            out.contains("remote image omitted"),
            "expected placeholder, got: {out}"
        );
    }

    #[test]
    fn md_to_typst_local_image_root_anchored() {
        // Local image links are normalised to project-root paths so the
        // mounted filesystem root resolves them.
        let out = md_to_typst("![alt](.nornir/assets/logo.png)\n");
        assert!(out.contains("#image(\"/.nornir/assets/logo.png\")"), "got: {out}");
        let out2 = md_to_typst("![alt](./assets/logo.png)\n");
        assert!(out2.contains("#image(\"/assets/logo.png\")"), "got: {out2}");
    }

    #[test]
    fn html_img_block_becomes_centered_image() {
        let md = "<p align=\"center\"><img src=\".nornir/assets/logo.webp\" width=\"720\" /></p>\n";
        let out = md_to_typst(md);
        assert!(out.contains("#align(center, image(\"/.nornir/assets/logo.webp\""), "got: {out}");
    }

    #[test]
    fn extract_img_src_handles_quotes() {
        assert_eq!(extract_img_src("<img src=\"a/b.png\">").as_deref(), Some("a/b.png"));
        assert_eq!(extract_img_src("<img class=x src='c.svg' />").as_deref(), Some("c.svg"));
        assert_eq!(extract_img_src("<p>no image</p>"), None);
    }

    #[test]
    fn md_passthrough() {
        let md = "hello";
        let meta = ExportMeta {
            title: "t".into(),
            version: "0".into(),
            generated: "g".into(),
        };
        let out = export(md, &meta, DocFormat::Md, None, None).unwrap();
        assert_eq!(out, b"hello");
    }

    #[test]
    fn url_in_text_does_not_open_typst_comment() {
        // A plain-text URL (`https://…`) carries `//`, which typst reads as a
        // line comment — it would swallow a following close delimiter and yield
        // "unclosed delimiter". The translator must escape the comment-starting
        // slash. Regression: znippy-inbox.md `**https://…**` sank the doc-book.
        // Escaping the first slash of `//` breaks the line-comment: typst then
        // sees an escaped literal `/` (`\/`) followed by a lone `/`. The
        // `emphasised_url_compiles_to_pdf` test is the end-to-end guarantee.
        let out = md_to_typst("**https://codeberg.org/nordisk/znippy**\n");
        assert!(out.contains("https:\\//codeberg.org"), "comment-start slash not escaped: {out}");
        // A lone slash (the common path case) is left untouched.
        let path = md_to_typst("see a/b/c here\n");
        assert!(path.contains("a/b/c"), "lone slashes should not be escaped: {path}");
        // `/*` never survives as a literal adjacency (the existing `*` escape
        // already breaks it into `/\*`), so no block comment opens.
        let blk = md_to_typst("a /* b\n");
        assert!(!blk.contains("/*"), "bare /* would open a block comment: {blk}");
    }

    #[test]
    fn emphasised_url_compiles_to_pdf() {
        // Full pipeline: the offending construct must actually compile under
        // typst now (previously: TypstSource "unclosed delimiter").
        let md = "# moved\n\n**https://codeberg.org/nordisk/znippy**\n";
        let meta = ExportMeta {
            title: "t".into(),
            version: "0".into(),
            generated: "g".into(),
        };
        let out = export(md, &meta, DocFormat::Pdf, None, None).expect("pdf compile");
        assert!(!out.is_empty());
    }

    #[test]
    fn html_render_smoke() {
        // HTML is the low-priority, experimental typst target. Assert only
        // that it produces non-empty HTML carrying the body text — the exact
        // tag structure is typst's to decide and may change between versions.
        let md = "# H\n\ntext\n";
        let meta = ExportMeta {
            title: "T".into(),
            version: "1".into(),
            generated: "g".into(),
        };
        let out = export(md, &meta, DocFormat::Html, None, None).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert!(s.contains('H'), "expected heading text in html, got: {s}");
        assert!(s.to_ascii_lowercase().contains("<html"), "expected html doc, got: {s}");
    }
}