krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
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
//! # Head Management
//!
//! Per-route `<head>` metadata with deterministic merge semantics for
//! nested layout composition.
//!
//! ## Usage
//!
//! ```rust
//! use krab_core::head::HeadContext;
//!
//! let head = HeadContext::new()
//!     .title("Blog Post Title")
//!     .description("A great post about Rust")
//!     .canonical("/blog/my-post")
//!     .og_type("article")
//!     .meta("author", "Jane Doe")
//!     .link_stylesheet("/css/blog.css")
//!     .script_module("/js/blog.js");
//!
//! // In SSR, render the head tags
//! let tags = head.render_tags();
//! assert!(tags.contains("<title>Blog Post Title</title>"));
//! ```

use std::collections::HashMap;

// ── Head Tag Types ──────────────────────────────────────────────────────────

/// A single `<meta>` tag.
#[derive(Debug, Clone, PartialEq)]
pub struct MetaTag {
    /// The meta attribute key (e.g., "name", "property", "http-equiv").
    pub attr_type: MetaAttrType,
    /// The attribute key value (e.g., "description", "og:title").
    pub key: String,
    /// The content value.
    pub content: String,
}

/// The type of meta attribute.
#[derive(Debug, Clone, PartialEq)]
pub enum MetaAttrType {
    /// `<meta name="..." content="...">`
    Name,
    /// `<meta property="..." content="...">`
    Property,
    /// `<meta http-equiv="..." content="...">`
    HttpEquiv,
}

impl MetaTag {
    /// Render this meta tag to an HTML string.
    pub fn render(&self) -> String {
        let attr = match self.attr_type {
            MetaAttrType::Name => "name",
            MetaAttrType::Property => "property",
            MetaAttrType::HttpEquiv => "http-equiv",
        };
        format!(
            "<meta {}=\"{}\" content=\"{}\"/>",
            attr,
            html_escape(&self.key),
            html_escape(&self.content)
        )
    }
}

/// Whether `name` may be rendered as an `extra_attrs` attribute on a
/// [`LinkTag`] or [`ScriptTag`]: a valid HTML attribute name that is not an
/// event handler. `on*` names (ASCII case-insensitive — `onload`, `ONERROR`)
/// are dropped, because an escaped value is still executed as script there,
/// so attacker-influenced key/value pairs would otherwise be an XSS vector.
fn extra_attr_allowed(name: &str) -> bool {
    crate::is_valid_attr_name(name)
        && !name
            .get(..2)
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("on"))
}

/// A `<link>` tag.
#[derive(Debug, Clone, PartialEq)]
pub struct LinkTag {
    /// The `rel` attribute, for example `stylesheet` or `canonical`.
    pub rel: String,
    /// The `href` attribute.
    pub href: String,
    /// Further attributes by name, rendered in unspecified order. Names that
    /// are not valid HTML attribute names, and event-handler names starting
    /// with `on` (any case), are dropped; values are escaped.
    pub extra_attrs: HashMap<String, String>,
}

impl LinkTag {
    /// Render this link tag to an HTML string.
    pub fn render(&self) -> String {
        let mut attrs = format!(
            "rel=\"{}\" href=\"{}\"",
            html_escape(&self.rel),
            html_escape(&self.href)
        );
        for (key, value) in &self.extra_attrs {
            // Same rule as `ScriptTag`: escaping a name leaves spaces and `=`
            // intact, so an attacker-supplied key could open a second
            // attribute (`x onload=alert(1) y`). Invalid names are dropped.
            if !extra_attr_allowed(key) {
                continue;
            }
            attrs.push_str(&format!(" {}=\"{}\"", html_escape(key), html_escape(value)));
        }
        format!("<link {}/>", attrs)
    }
}

/// A `<script>` tag.
#[derive(Debug, Clone, PartialEq)]
pub struct ScriptTag {
    /// The `src` attribute, for an external script.
    pub src: Option<String>,
    /// Inline script body. Rendered as-is except that `</script` sequences
    /// are rewritten to `<\/script` so they cannot close the block early.
    pub inline_content: Option<String>,
    /// Adds `type="module"`.
    pub is_module: bool,
    /// Adds the `async` attribute.
    pub is_async: bool,
    /// Adds the `defer` attribute.
    pub is_defer: bool,
    /// Further attributes by name, rendered in unspecified order. Names that
    /// are not valid HTML attribute names, and event-handler names starting
    /// with `on` (any case), are dropped; values are escaped.
    pub extra_attrs: HashMap<String, String>,
}

/// Escape a JSON document for embedding inside an HTML `<script>` block.
///
/// `<`, `>` and `&` are rewritten to their `\uXXXX` JSON escapes. A JSON parser
/// reads those back as the original characters, so the document's meaning is
/// untouched, while the HTML tokenizer can no longer see a `</script>` sequence
/// to break out on. Without this, any user-supplied value reaching JSON-LD —
/// a product name, an article title — is a stored-XSS vector, and JSON-LD
/// exists precisely to carry that kind of dynamic data.
fn escape_json_for_script(json: &str) -> String {
    json.replace('<', "\\u003c")
        .replace('>', "\\u003e")
        .replace('&', "\\u0026")
}

/// Neutralise `</script` sequences in inline script source.
///
/// Inline JavaScript cannot be HTML-escaped without changing what it means, so
/// only the sequence that ends the block early is rewritten. `<\/script` is
/// identical to `</script` inside a JavaScript string or regular expression,
/// which is where that sequence legitimately appears. The match is
/// case-insensitive because the HTML tokenizer's is.
fn escape_inline_script(content: &str) -> String {
    // One implementation with `view!`'s own `<script>` rendering, so the two
    // cannot disagree about what is a breakout.
    crate::escape_raw_text("script", content)
}

impl ScriptTag {
    /// Render this script tag to an HTML string.
    pub fn render(&self) -> String {
        let mut attrs = String::new();
        if let Some(ref src) = self.src {
            attrs.push_str(&format!(" src=\"{}\"", html_escape(src)));
        }
        if self.is_module {
            attrs.push_str(" type=\"module\"");
        }
        if self.is_async {
            attrs.push_str(" async");
        }
        if self.is_defer {
            attrs.push_str(" defer");
        }
        for (key, value) in &self.extra_attrs {
            // Escaping a name is not enough — `html_escape` leaves spaces and
            // `=` intact, so an attacker-supplied key could still open a second
            // attribute. Invalid names are dropped, as in `Element::render`.
            if !extra_attr_allowed(key) {
                continue;
            }
            attrs.push_str(&format!(" {}=\"{}\"", html_escape(key), html_escape(value)));
        }
        if let Some(ref content) = self.inline_content {
            format!(
                "<script{}>{}</script>",
                attrs,
                escape_inline_script(content)
            )
        } else {
            format!("<script{}></script>", attrs)
        }
    }
}

// ── Head Context ────────────────────────────────────────────────────────────

/// Accumulated `<head>` metadata for a route, supporting merge semantics
/// across nested layouts.
///
/// ## Merge Rules
///
/// When a child route's `HeadContext` is merged into a parent layout's context:
///
/// - **`title`**: Child wins (overwrites parent).
/// - **`description`**: Child wins (overwrites parent).
/// - **`canonical`**: Child wins (overwrites parent).
/// - **`og_type`**: Child wins (overwrites parent).
/// - **`meta` tags**: Child tags with the same key overwrite parent; unique keys are appended.
/// - **`link` tags**: Appended (no deduplication).
/// - **`script` tags**: Appended (no deduplication).
/// - **`json_ld`**: Child wins (overwrites parent).
#[derive(Debug, Clone, Default)]
pub struct HeadContext {
    title_value: Option<String>,
    description_value: Option<String>,
    canonical_value: Option<String>,
    og_type_value: Option<String>,
    og_image_value: Option<String>,
    robots_value: Option<String>,
    charset: String,
    viewport: String,
    meta_tags: Vec<MetaTag>,
    link_tags: Vec<LinkTag>,
    script_tags: Vec<ScriptTag>,
    json_ld: Option<String>,
}

impl HeadContext {
    /// Create a new head context with sensible defaults.
    pub fn new() -> Self {
        Self {
            charset: "utf-8".to_string(),
            viewport: "width=device-width, initial-scale=1.0".to_string(),
            ..Default::default()
        }
    }

    // ── Builder Methods ─────────────────────────────────────────────────

    /// Set the page title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title_value = Some(title.into());
        self
    }

    /// Set the meta description.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description_value = Some(desc.into());
        self
    }

    /// Set the canonical URL.
    pub fn canonical(mut self, url: impl Into<String>) -> Self {
        self.canonical_value = Some(url.into());
        self
    }

    /// Set the OpenGraph type (e.g., "website", "article").
    pub fn og_type(mut self, og: impl Into<String>) -> Self {
        self.og_type_value = Some(og.into());
        self
    }

    /// Set the OpenGraph image URL.
    pub fn og_image(mut self, url: impl Into<String>) -> Self {
        self.og_image_value = Some(url.into());
        self
    }

    /// Set the robots directive.
    pub fn robots(mut self, directive: impl Into<String>) -> Self {
        self.robots_value = Some(directive.into());
        self
    }

    /// Add a `<meta name="..." content="...">` tag.
    pub fn meta(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
        self.meta_tags.push(MetaTag {
            attr_type: MetaAttrType::Name,
            key: name.into(),
            content: content.into(),
        });
        self
    }

    /// Add a `<meta property="..." content="...">` tag (OpenGraph).
    pub fn meta_property(
        mut self,
        property: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.meta_tags.push(MetaTag {
            attr_type: MetaAttrType::Property,
            key: property.into(),
            content: content.into(),
        });
        self
    }

    /// Add a stylesheet `<link>`.
    pub fn link_stylesheet(mut self, href: impl Into<String>) -> Self {
        self.link_tags.push(LinkTag {
            rel: "stylesheet".to_string(),
            href: href.into(),
            extra_attrs: HashMap::new(),
        });
        self
    }

    /// Add a preload `<link>`.
    pub fn link_preload(mut self, href: impl Into<String>, as_type: impl Into<String>) -> Self {
        let mut extra = HashMap::new();
        extra.insert("as".to_string(), as_type.into());
        self.link_tags.push(LinkTag {
            rel: "preload".to_string(),
            href: href.into(),
            extra_attrs: extra,
        });
        self
    }

    /// Add a generic `<link>` tag.
    pub fn link(mut self, rel: impl Into<String>, href: impl Into<String>) -> Self {
        self.link_tags.push(LinkTag {
            rel: rel.into(),
            href: href.into(),
            extra_attrs: HashMap::new(),
        });
        self
    }

    /// Add an external `<script>` tag.
    pub fn script(mut self, src: impl Into<String>) -> Self {
        self.script_tags.push(ScriptTag {
            src: Some(src.into()),
            inline_content: None,
            is_module: false,
            is_async: false,
            is_defer: true,
            extra_attrs: HashMap::new(),
        });
        self
    }

    /// Add a module `<script type="module">` tag.
    pub fn script_module(mut self, src: impl Into<String>) -> Self {
        self.script_tags.push(ScriptTag {
            src: Some(src.into()),
            inline_content: None,
            is_module: true,
            is_async: false,
            is_defer: false,
            extra_attrs: HashMap::new(),
        });
        self
    }

    /// Add an inline `<script>` tag.
    pub fn script_inline(mut self, content: impl Into<String>) -> Self {
        self.script_tags.push(ScriptTag {
            src: None,
            inline_content: Some(content.into()),
            is_module: false,
            is_async: false,
            is_defer: false,
            extra_attrs: HashMap::new(),
        });
        self
    }

    /// Set structured data (JSON-LD).
    pub fn json_ld(mut self, json: impl Into<String>) -> Self {
        self.json_ld = Some(json.into());
        self
    }

    // ── Merge ───────────────────────────────────────────────────────────

    /// Merge a child context into this parent context.
    ///
    /// Child scalar values (title, description, canonical, og_type) overwrite parent.
    /// Child meta tags with matching keys overwrite parent; unique keys are appended.
    /// Child link and script tags are appended.
    pub fn merge(mut self, child: &HeadContext) -> Self {
        // Scalars: child wins
        if child.title_value.is_some() {
            self.title_value = child.title_value.clone();
        }
        if child.description_value.is_some() {
            self.description_value = child.description_value.clone();
        }
        if child.canonical_value.is_some() {
            self.canonical_value = child.canonical_value.clone();
        }
        if child.og_type_value.is_some() {
            self.og_type_value = child.og_type_value.clone();
        }
        if child.og_image_value.is_some() {
            self.og_image_value = child.og_image_value.clone();
        }
        if child.robots_value.is_some() {
            self.robots_value = child.robots_value.clone();
        }
        if child.json_ld.is_some() {
            self.json_ld = child.json_ld.clone();
        }

        // Meta tags: a child tag replaces the parent tag with the same
        // attribute *and* key; anything else appends. Keyed on the pair because
        // `name="author"` and `property="author"` are different tags — keying
        // on the key alone let one silently replace the other.
        for child_tag in &child.meta_tags {
            if let Some(pos) = self
                .meta_tags
                .iter()
                .position(|t| t.attr_type == child_tag.attr_type && t.key == child_tag.key)
            {
                self.meta_tags[pos] = child_tag.clone();
            } else {
                self.meta_tags.push(child_tag.clone());
            }
        }

        // Links and scripts: append
        self.link_tags.extend(child.link_tags.iter().cloned());
        self.script_tags.extend(child.script_tags.iter().cloned());

        self
    }

    // ── Rendering ───────────────────────────────────────────────────────

    /// Render all accumulated head tags into an HTML string.
    ///
    /// The output is deterministic and suitable for SSR injection.
    pub fn render_tags(&self) -> String {
        let mut parts: Vec<String> = Vec::new();

        // Charset
        parts.push(format!(
            "<meta charset=\"{}\"/>",
            html_escape(&self.charset)
        ));

        // Viewport
        if !self.viewport.is_empty() {
            parts.push(format!(
                "<meta name=\"viewport\" content=\"{}\"/>",
                html_escape(&self.viewport)
            ));
        }

        // Title
        if let Some(ref title) = self.title_value {
            parts.push(format!("<title>{}</title>", html_escape(title)));
        }

        // Description
        if let Some(ref desc) = self.description_value {
            parts.push(format!(
                "<meta name=\"description\" content=\"{}\"/>",
                html_escape(desc)
            ));
        }

        // Canonical
        if let Some(ref canonical) = self.canonical_value {
            parts.push(format!(
                "<link rel=\"canonical\" href=\"{}\"/>",
                html_escape(canonical)
            ));
        }

        // Robots
        if let Some(ref robots) = self.robots_value {
            parts.push(format!(
                "<meta name=\"robots\" content=\"{}\"/>",
                html_escape(robots)
            ));
        }

        // OpenGraph
        if let Some(ref title) = self.title_value {
            parts.push(format!(
                "<meta property=\"og:title\" content=\"{}\"/>",
                html_escape(title)
            ));
        }
        if let Some(ref desc) = self.description_value {
            parts.push(format!(
                "<meta property=\"og:description\" content=\"{}\"/>",
                html_escape(desc)
            ));
        }
        if let Some(ref og_type) = self.og_type_value {
            parts.push(format!(
                "<meta property=\"og:type\" content=\"{}\"/>",
                html_escape(og_type)
            ));
        }
        if let Some(ref og_image) = self.og_image_value {
            parts.push(format!(
                "<meta property=\"og:image\" content=\"{}\"/>",
                html_escape(og_image)
            ));
        }
        if let Some(ref canonical) = self.canonical_value {
            parts.push(format!(
                "<meta property=\"og:url\" content=\"{}\"/>",
                html_escape(canonical)
            ));
        }

        // Custom meta tags
        for tag in &self.meta_tags {
            parts.push(tag.render());
        }

        // Link tags
        for tag in &self.link_tags {
            parts.push(tag.render());
        }

        // Script tags
        for tag in &self.script_tags {
            parts.push(tag.render());
        }

        // JSON-LD
        if let Some(ref json_ld) = self.json_ld {
            parts.push(format!(
                "<script type=\"application/ld+json\">{}</script>",
                escape_json_for_script(json_ld)
            ));
        }

        parts.join("\n")
    }

    /// Get the current title value, if set.
    pub fn get_title(&self) -> Option<&str> {
        self.title_value.as_deref()
    }

    /// Get the current description value, if set.
    pub fn get_description(&self) -> Option<&str> {
        self.description_value.as_deref()
    }

    /// Get the current canonical URL, if set.
    pub fn get_canonical(&self) -> Option<&str> {
        self.canonical_value.as_deref()
    }
}

// ── HTML Escaping ───────────────────────────────────────────────────────────

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn basic_head_rendering() {
        let head = HeadContext::new()
            .title("Test Page")
            .description("A test page description");

        let tags = head.render_tags();
        assert!(tags.contains("<title>Test Page</title>"));
        assert!(tags.contains("name=\"description\" content=\"A test page description\""));
        assert!(tags.contains("charset=\"utf-8\""));
        assert!(tags.contains("name=\"viewport\""));
    }

    #[test]
    fn canonical_and_og_tags() {
        let head = HeadContext::new()
            .title("Blog Post")
            .canonical("https://example.com/blog/post-1")
            .og_type("article")
            .og_image("https://example.com/img.jpg");

        let tags = head.render_tags();
        assert!(tags.contains("rel=\"canonical\" href=\"https://example.com/blog/post-1\""));
        assert!(tags.contains("og:type\" content=\"article\""));
        assert!(tags.contains("og:image\" content=\"https://example.com/img.jpg\""));
        assert!(tags.contains("og:url\" content=\"https://example.com/blog/post-1\""));
    }

    #[test]
    fn custom_meta_tags() {
        let head = HeadContext::new()
            .meta("author", "Jane Doe")
            .meta("theme-color", "#000000");

        let tags = head.render_tags();
        assert!(tags.contains("name=\"author\" content=\"Jane Doe\""));
        assert!(tags.contains("name=\"theme-color\" content=\"#000000\""));
    }

    #[test]
    fn link_and_script_tags() {
        let head = HeadContext::new()
            .link_stylesheet("/css/main.css")
            .script_module("/js/app.js")
            .script_inline("console.log('hello')");

        let tags = head.render_tags();
        assert!(tags.contains("rel=\"stylesheet\" href=\"/css/main.css\""));
        assert!(tags.contains("src=\"/js/app.js\" type=\"module\""));
        assert!(tags.contains("console.log('hello')"));
    }

    #[test]
    fn merge_child_overwrites_scalars() {
        let parent = HeadContext::new()
            .title("Parent Title")
            .description("Parent desc")
            .canonical("/parent");

        let child = HeadContext::new()
            .title("Child Title")
            .description("Child desc");

        let merged = parent.merge(&child);
        assert_eq!(merged.get_title(), Some("Child Title"));
        assert_eq!(merged.get_description(), Some("Child desc"));
        // Canonical stays from parent since child didn't set it
        assert_eq!(merged.get_canonical(), Some("/parent"));
    }

    #[test]
    fn merge_meta_tags_child_key_overwrites() {
        let parent = HeadContext::new()
            .meta("author", "Parent Author")
            .meta("theme-color", "#fff");

        let child = HeadContext::new()
            .meta("author", "Child Author")
            .meta("keywords", "rust,web");

        let merged = parent.merge(&child);
        let tags = merged.render_tags();
        assert!(tags.contains("name=\"author\" content=\"Child Author\""));
        assert!(!tags.contains("Parent Author"));
        assert!(tags.contains("name=\"theme-color\" content=\"#fff\""));
        assert!(tags.contains("name=\"keywords\" content=\"rust,web\""));
    }

    /// A crafted attribute name cannot open a second attribute on `<link>`.
    #[test]
    fn link_extra_attrs_drop_invalid_names() {
        let mut extra = HashMap::new();
        extra.insert("x onload=alert(1) y".to_string(), "v".to_string());
        extra.insert("crossorigin".to_string(), "anonymous".to_string());
        let html = LinkTag {
            rel: "preload".to_string(),
            href: "/a.css".to_string(),
            extra_attrs: extra,
        }
        .render();
        assert!(!html.contains("onload"), "{html}");
        assert!(html.contains(r#"crossorigin="anonymous""#), "{html}");
    }

    #[test]
    fn merge_keeps_name_and_property_tags_with_the_same_key_apart() {
        let parent = HeadContext::new().meta("author", "Name Author");
        let child = HeadContext::new().meta_property("author", "Property Author");

        let tags = parent.merge(&child).render_tags();
        assert!(
            tags.contains("name=\"author\" content=\"Name Author\""),
            "{tags}"
        );
        assert!(
            tags.contains("property=\"author\" content=\"Property Author\""),
            "{tags}"
        );
    }

    #[test]
    fn merge_appends_links_and_scripts() {
        let parent = HeadContext::new().link_stylesheet("/css/parent.css");

        let child = HeadContext::new()
            .link_stylesheet("/css/child.css")
            .script("/js/child.js");

        let merged = parent.merge(&child);
        let tags = merged.render_tags();
        assert!(tags.contains("/css/parent.css"));
        assert!(tags.contains("/css/child.css"));
        assert!(tags.contains("/js/child.js"));
    }

    #[test]
    fn json_ld_rendering() {
        let head =
            HeadContext::new().json_ld(r#"{"@context":"https://schema.org","@type":"Article"}"#);

        let tags = head.render_tags();
        assert!(tags.contains("application/ld+json"));
        assert!(tags.contains("@context"));
    }

    #[test]
    fn html_escaping_in_head() {
        let head = HeadContext::new().title("Page with \"quotes\" & <tags>");

        let tags = head.render_tags();
        assert!(tags.contains("&amp;"));
        assert!(tags.contains("&lt;tags&gt;"));
    }

    #[test]
    fn robots_directive() {
        let head = HeadContext::new().robots("noindex, nofollow");

        let tags = head.render_tags();
        assert!(tags.contains("name=\"robots\" content=\"noindex, nofollow\""));
    }

    #[test]
    fn preload_link() {
        let head = HeadContext::new().link_preload("/fonts/inter.woff2", "font");

        let tags = head.render_tags();
        assert!(tags.contains("rel=\"preload\""));
        assert!(tags.contains("href=\"/fonts/inter.woff2\""));
        assert!(tags.contains("as=\"font\""));
    }
}

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

    #[test]
    fn json_ld_cannot_close_its_own_script_block() {
        let hostile = r#"{"name":"</script><img src=x onerror=alert(1)>"}"#;

        let html = HeadContext::new().json_ld(hostile).render_tags();

        assert!(
            !html.contains("</script><img"),
            "JSON-LD broke out of its block: {html}"
        );
        assert!(html.contains(r"\u003c/script\u003e"));
        // Exactly one closing tag: the one this renderer emitted.
        assert_eq!(html.matches("</script>").count(), 1);
    }

    #[test]
    fn json_ld_escaping_preserves_the_document() {
        // `\uXXXX` is how JSON spells these characters, so a parser reads back
        // precisely what the caller passed.
        let escaped = escape_json_for_script(r#"{"a":"1 < 2 & 3 > 2"}"#);

        let parsed: serde_json::Value = serde_json::from_str(&escaped).expect("still valid JSON");
        assert_eq!(parsed["a"], "1 < 2 & 3 > 2");
    }

    #[test]
    fn inline_script_cannot_close_its_own_block() {
        let content = r#"const s = "</script><img src=x onerror=alert(1)>";"#;

        let out = escape_inline_script(content);

        assert!(!out.contains("</script>"), "breakout survived: {out}");
        assert!(out.contains(r"<\/script>"));
    }

    #[test]
    fn inline_script_escaping_is_case_insensitive_and_keeps_casing() {
        let out = escape_inline_script("a </ScRiPt> b");

        assert!(!out.to_ascii_lowercase().contains("</script"));
        assert!(out.contains(r"<\/ScRiPt>"), "casing not preserved: {out}");
    }

    #[test]
    fn inline_script_without_a_breakout_is_untouched() {
        let content = "const x = a < b && c > d;";

        assert_eq!(escape_inline_script(content), content);
    }

    #[test]
    fn script_attribute_name_that_would_open_a_second_attribute_is_dropped() {
        let mut extra = HashMap::new();
        extra.insert("x onload=alert(1)".to_string(), "v".to_string());
        extra.insert("data-ok".to_string(), "1".to_string());

        let html = ScriptTag {
            src: Some("/pkg/app.js".to_string()),
            inline_content: None,
            is_module: false,
            is_async: false,
            is_defer: false,
            extra_attrs: extra,
        }
        .render();

        assert!(
            !html.contains("onload"),
            "injected handler survived: {html}"
        );
        assert!(html.contains("data-ok=\"1\""));
    }

    /// A well-formed event-handler name is still script: `on*` extra
    /// attributes are dropped from `<link>` and `<script>`, in any case.
    #[test]
    fn event_handler_extra_attrs_are_dropped() {
        let extra: HashMap<String, String> = [
            ("onload", "alert(1)"),
            ("ONERROR", "alert(2)"),
            ("onClick", "alert(3)"),
            ("data-on", "kept"),
            ("nonce", "abc"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();

        let link = LinkTag {
            rel: "preload".to_string(),
            href: "/a.css".to_string(),
            extra_attrs: extra.clone(),
        }
        .render();
        let script = ScriptTag {
            src: Some("/pkg/app.js".to_string()),
            inline_content: None,
            is_module: false,
            is_async: false,
            is_defer: false,
            extra_attrs: extra,
        }
        .render();

        for html in [&link, &script] {
            assert!(!html.contains("alert"), "event handler survived: {html}");
            assert!(html.contains(r#"data-on="kept""#), "{html}");
            assert!(html.contains(r#"nonce="abc""#), "{html}");
        }
    }
}