larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
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
//! Reads a post file: its frontmatter, and its body as HTML with an anchor on every heading.
//!
//! Rendered bodies are cached by the file's path, modification time and size, so editing a post is
//! seen on the next request and an unchanged one is never rendered twice.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};

use comrak::nodes::{Node, NodeHtmlBlock, NodeValue};
use comrak::{Arena, Options, format_html, parse_document};
use regex::{Captures, Regex};
use serde::Serialize;
use serde_json::{Map, Value};

use crate::conditionals;
use crate::config::{HtmlInput, MarkdownSettings};
use crate::support;
use crate::{Error, yaml};

static FRONTMATTER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s)\A---\r?\n(.*?)\r?\n---(?:\r?\n|\z)(.*)\z").expect("a valid pattern"));
static HEADING: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?is)<h2(\s[^>]*)?>(.*?)</h2>|<h3(\s[^>]*)?>(.*?)</h3>").expect("a valid pattern"));
static TAGS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<[^>]*>").expect("a valid pattern"));
static EXISTING_ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"\sid="([^"]+)""#).expect("a valid pattern"));
static ENTITY: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);").expect("a valid pattern"));
static EXTERNAL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:[A-Za-z][A-Za-z0-9+.-]*:)?//([^/?#]*)").expect("a valid pattern"));
static EXTERNAL_LINK: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"<!--larablog:external--><a href=").expect("a valid pattern"));

/// The GFM tag filter: these tags are shown as text even when the Markdown may carry HTML.
static DISALLOWED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)<(/?(?:title|textarea|style|xmp|iframe|noembed|noframes|script|plaintext))([\s/>]|$)")
        .expect("a valid pattern")
});
static UNSAFE_URL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^\s*(?:javascript|vbscript|file|data):").expect("a valid pattern"));

/// comrak writes a task-list checkbox as `<input type="checkbox" checked="" disabled="" />`;
/// CommonMark's GFM extension writes `<input checked="" disabled="" type="checkbox">`.
static TASK_CHECKBOX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"<input type="checkbox"((?: checked="")?) disabled="" />"#).expect("a valid pattern")
});
static OPENING_NEWLINE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(<!--larablog:if-published:[A-Za-z0-9_.-]+:[01]-->)\n").expect("a valid pattern"));

const EXTERNAL_MARK: &str = "<!--larablog:external-->";

/// An `h2` or `h3` of a body, with the id its anchor carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Heading {
    /// 2 or 3.
    pub level: u8,
    /// The `id` of the heading, unique within the post.
    pub id: String,
    /// Its text, without markup.
    pub text: String,
}

/// A rendered body: the HTML, with its condition markers still in it, and its headings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rendered {
    /// The HTML, as cached. [`Blog::resolve_links`](crate::Blog::resolve_links) finishes it on
    /// every visit.
    pub html: String,
    /// Every `h2` and `h3`, hidden ones included.
    pub headings: Vec<Heading>,
}

/// A rendered body and the modification time and size of the file it came from.
type Cached = ((u64, u64), Arc<Rendered>);

/// The CommonMark converter and the cache of rendered bodies.
pub struct Markdown {
    cache: Mutex<HashMap<PathBuf, Cached>>,
}

impl Default for Markdown {
    fn default() -> Self {
        Self::new()
    }
}

impl Markdown {
    /// An empty cache.
    pub fn new() -> Self {
        Self {
            cache: Mutex::new(HashMap::new()),
        }
    }

    /// The frontmatter and the raw body of a file's text.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::InvalidPost`] when the frontmatter is not valid YAML.
    pub fn split(content: &str) -> Result<(Map<String, Value>, String), Error> {
        let content = content.strip_prefix('\u{feff}').unwrap_or(content);

        let Some(found) = FRONTMATTER.captures(content) else {
            return Ok((Map::new(), content.to_owned()));
        };

        let meta = yaml::parse(&found[1])
            .map_err(|message| Error::InvalidPost(format!("The frontmatter is not valid YAML: {message}")))?;

        Ok((
            match meta {
                Value::Object(map) => map,
                _ => Map::new(),
            },
            found[2].to_owned(),
        ))
    }

    /// Render a file, from the cache when it has not changed.
    ///
    /// # Errors
    ///
    /// Fails when the file cannot be read or its frontmatter is not valid YAML.
    pub fn render(&self, file: &Path, caching: bool) -> Result<Arc<Rendered>, Error> {
        let signature = signature(file);

        if caching {
            let cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);

            if let Some((cached, rendered)) = cache.get(file)
                && *cached == signature
            {
                return Ok(Arc::clone(rendered));
            }
        }

        let content = std::fs::read_to_string(file).map_err(|error| Error::Io(file.to_path_buf(), error))?;
        let (_, body) = Self::split(&content)?;
        let config = laravel::config();
        let rendered = Arc::new(Self::convert(
            &body,
            &config.section::<crate::LarablogConfig>().markdown,
            &config.app.url,
        ));

        if caching {
            self.cache
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .insert(file.to_path_buf(), (signature, Arc::clone(&rendered)));
        }

        Ok(rendered)
    }

    /// Convert Markdown to HTML and give every `h2` and `h3` an anchor. `app_url` is the
    /// application's address: links to its host are not external.
    pub fn convert(markdown: &str, settings: &MarkdownSettings, app_url: &str) -> Rendered {
        anchor(&to_html(markdown, settings, app_url))
    }
}

fn signature(file: &Path) -> (u64, u64) {
    std::fs::metadata(file).map_or((0, 0), |metadata| {
        let modified = metadata
            .modified()
            .ok()
            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
            .map_or(0, |duration| u64::try_from(duration.as_nanos()).unwrap_or(0));

        (modified, metadata.len())
    })
}

fn options(settings: &MarkdownSettings) -> Options<'static> {
    let mut options = Options::default();

    options.extension.strikethrough = true;
    options.extension.table = true;
    options.extension.autolink = true;
    options.extension.tasklist = true;
    options.render.r#unsafe = settings.html_input == HtmlInput::Allow;
    options.render.escape = settings.html_input == HtmlInput::Escape;

    options
}

fn to_html(markdown: &str, settings: &MarkdownSettings, app_url: &str) -> String {
    let options = options(settings);
    let arena = Arena::new();
    let source = conditionals::rewrite(markdown);
    let root = parse_document(&arena, &source, &options);

    let app_host = host_of(app_url);

    for node in root.descendants() {
        let mut data = node.data_mut();

        if let NodeValue::HtmlBlock(block) = &data.value
            && is_marker(block.literal.trim())
        {
            let literal = block.literal.trim().to_owned();

            data.value = NodeValue::Raw(literal);
        } else if let NodeValue::HtmlBlock(NodeHtmlBlock { literal, .. }) | NodeValue::HtmlInline(literal) =
            &mut data.value
        {
            *literal = DISALLOWED.replace_all(literal, "&lt;$1$2").into_owned();
        } else if !settings.allow_unsafe_links
            && let NodeValue::Link(target) | NodeValue::Image(target) = &mut data.value
            && UNSAFE_URL.is_match(&target.url)
        {
            target.url.clear();
        }
    }

    hoist_list_items(&arena, root);

    if settings.external_links {
        mark_external_links(&arena, root, app_host.as_deref());
    }

    let mut html = String::new();

    format_html(root, &options, &mut html).expect("writing to a String does not fail");

    if settings.external_links {
        html = EXTERNAL_LINK
            .replace_all(&html, r#"<a rel="noopener noreferrer" target="_blank" href="#)
            .into_owned();
    }

    let html = TASK_CHECKBOX.replace_all(&html, r#"<input$1 disabled="" type="checkbox">"#);

    OPENING_NEWLINE
        .replace_all(&html, "$1")
        .replace("\n<!--larablog:endif-->", "<!--larablog:endif-->")
}

fn is_marker(text: &str) -> bool {
    text == conditionals::ENDIF || (text.starts_with("<!--larablog:if-published:") && text.ends_with("-->"))
}

fn marker_kind(node: Node<'_>) -> Option<bool> {
    match &node.data().value {
        NodeValue::Raw(text) if text == conditionals::ENDIF => Some(false),
        NodeValue::Raw(text) if text.starts_with("<!--larablog:if-published:") => Some(true),
        _ => None,
    }
}

/// A paragraph inside a condition keeps its `<p>` even in a tight list, as in the PHP package, where
/// the paragraph's grandparent is the list item and not the list.
fn keep_paragraphs<'a>(arena: &'a Arena<'a>, item: Node<'a>, everything: bool) {
    let tight = item
        .parent()
        .is_some_and(|list| matches!(&list.data().value, NodeValue::List(list) if list.tight));

    if !tight {
        return;
    }

    let mut depth = i32::from(everything);

    for child in item.children().collect::<Vec<_>>() {
        match marker_kind(child) {
            Some(true) => depth += 1,
            Some(false) => depth -= 1,
            None => {}
        }

        if depth > 0 && matches!(child.data().value, NodeValue::Paragraph) {
            child.prepend(arena.alloc(NodeValue::Raw("<p>".to_owned()).into()));
            child.append(arena.alloc(NodeValue::Raw("</p>".to_owned()).into()));
        }
    }
}

/// A list item whose only content is one condition is wrapped as a whole, so a hidden condition
/// leaves no empty bullet behind.
fn hoist_list_items<'a>(arena: &'a Arena<'a>, root: Node<'a>) {
    let items: Vec<Node<'a>> = root
        .descendants()
        .filter(|node| matches!(node.data().value, NodeValue::Item(_)))
        .collect();

    for item in items {
        let children: Vec<Node<'a>> = item.children().collect();
        let (Some(first), Some(last)) = (children.first(), children.last()) else {
            continue;
        };

        if children.len() < 2 || marker_kind(first) != Some(true) || marker_kind(last) != Some(false) {
            keep_paragraphs(arena, item, false);

            continue;
        }

        let mut depth = 0_i32;
        let mut sole = true;

        for (index, child) in children.iter().enumerate() {
            match marker_kind(child) {
                Some(true) => depth += 1,
                Some(false) => depth -= 1,
                None => {}
            }

            if depth == 0 && index + 1 < children.len() {
                sole = false;

                break;
            }
        }

        if !sole || depth != 0 {
            keep_paragraphs(arena, item, false);

            continue;
        }

        let opening = match &first.data().value {
            NodeValue::Raw(text) => text.clone(),
            _ => continue,
        };

        first.detach();
        last.detach();
        keep_paragraphs(arena, item, true);
        item.insert_before(arena.alloc(NodeValue::Raw(opening).into()));
        item.insert_after(arena.alloc(NodeValue::Raw(conditionals::ENDIF.to_owned()).into()));
    }
}

fn host_of(url: &str) -> Option<String> {
    EXTERNAL.captures(url).map(|found| authority_host(&found[1]))
}

fn authority_host(authority: &str) -> String {
    let without_user = authority.rsplit('@').next().unwrap_or(authority);
    let host = if without_user.starts_with('[') {
        without_user.split(']').next().unwrap_or(without_user)
    } else {
        without_user.split(':').next().unwrap_or(without_user)
    };

    host.to_ascii_lowercase()
}

/// Links to other hosts get `rel="noopener noreferrer"` and `target="_blank"`, as the
/// ExternalLink extension of CommonMark does. The mark is turned into the attributes after the
/// HTML is written, because a link node has nowhere to carry them.
fn mark_external_links<'a>(arena: &'a Arena<'a>, root: Node<'a>, internal: Option<&str>) {
    let links: Vec<Node<'a>> = root
        .descendants()
        .filter(|node| matches!(node.data().value, NodeValue::Link(_)))
        .collect();

    for link in links {
        let external = match &link.data().value {
            NodeValue::Link(target) => EXTERNAL
                .captures(&target.url)
                .map(|found| authority_host(&found[1]))
                .is_some_and(|host| Some(host.as_str()) != internal),
            _ => false,
        };

        if external {
            link.insert_before(arena.alloc(NodeValue::Raw(EXTERNAL_MARK.to_owned()).into()));
        }
    }
}

fn anchor(html: &str) -> Rendered {
    let mut headings: Vec<Heading> = Vec::new();
    let mut seen: HashMap<String, ()> = HashMap::new();

    let anchored = HEADING.replace_all(html, |found: &Captures<'_>| {
        let (level, attributes, inner) = match found.get(2) {
            Some(inner) => (2, found.get(1).map_or("", |m| m.as_str()), inner.as_str()),
            None => (
                3,
                found.get(3).map_or("", |m| m.as_str()),
                found.get(4).map_or("", |m| m.as_str()),
            ),
        };

        let text = decode_entities(&TAGS.replace_all(inner, "")).trim().to_owned();
        let mut attributes = attributes.to_owned();

        let id = if let Some(existing) = EXISTING_ID.captures(&attributes) {
            existing[1].to_owned()
        } else {
            let base = {
                let slug = support::slug(&text);

                if slug.is_empty() { "section".to_owned() } else { slug }
            };
            let mut id = base.clone();
            let mut number = 2;

            while seen.contains_key(&id) {
                id = format!("{base}-{number}");
                number += 1;
            }

            attributes.push_str(&format!(" id=\"{id}\""));

            id
        };

        seen.insert(id.clone(), ());
        headings.push(Heading { level, id, text });

        format!("<h{level}{attributes}>{inner}</h{level}>")
    });

    Rendered {
        html: anchored.into_owned(),
        headings,
    }
}

/// `html_entity_decode` for the entities a heading holds: the numeric ones and the usual names.
fn decode_entities(text: &str) -> String {
    ENTITY
        .replace_all(text, |found: &Captures<'_>| {
            let name = &found[1];

            if let Some(number) = name.strip_prefix('#') {
                let code = match number.strip_prefix(['x', 'X']) {
                    Some(hex) => u32::from_str_radix(hex, 16).ok(),
                    None => number.parse().ok(),
                };

                return code
                    .and_then(char::from_u32)
                    .map_or_else(|| found[0].to_owned(), |c| c.to_string());
            }

            match name {
                "amp" => "&",
                "lt" => "<",
                "gt" => ">",
                "quot" => "\"",
                "apos" => "'",
                "nbsp" => "\u{a0}",
                "copy" => "\u{a9}",
                "hellip" => "\u{2026}",
                "mdash" => "\u{2014}",
                "ndash" => "\u{2013}",
                "laquo" => "\u{ab}",
                "raquo" => "\u{bb}",
                _ => return found[0].to_owned(),
            }
            .to_owned()
        })
        .into_owned()
}