ASF-injectie 1/5: HtmlMarkerEditor (regio's, data-blok, ld+json, inline waarden, script-escaping) met tests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:03:52 +01:00
co-authored by Claude Sonnet 5.5
parent ab50d7dfba
commit 7d66944019
2 changed files with 251 additions and 0 deletions
@@ -0,0 +1,147 @@
using FluentAssertions;
using SlpModularCms.Core.Hosting.Website;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting.Website;
public class HtmlMarkerEditorTests
{
[Theory]
[InlineData("<p>plain</p>", false)]
[InlineData("<!--SLP:OFFERINGS-HTML-->", false)]
[InlineData("<div><!--CMS:DATA--></div>", true)]
[InlineData("<span data-cms-price=\"newborn\">x</span>", true)]
public void HasMarkers_RecognisesOnlyTheCmsMarkers(string html, bool expected)
=> HtmlMarkerEditor.HasMarkers(html).Should().Be(expected);
// ---- regions ----
[Fact]
public void Region_ContentBetweenTheMarkersIsReplaced_AndTheMarkersStay()
{
var html = "<div><!--CMS:OFFERINGS-HTML--><ul><li>baked</li></ul><!--/CMS:OFFERINGS-HTML--></div>";
HtmlMarkerEditor.ReplaceRegion(html, "CMS:OFFERINGS-HTML", "<ul><li>live</li></ul>")
.Should().Be("<div><!--CMS:OFFERINGS-HTML--><ul><li>live</li></ul><!--/CMS:OFFERINGS-HTML--></div>");
}
[Fact]
public void Region_MayBeEmptied_AndEveryPairOnThePageIsReplaced()
{
var html = "<!--CMS:BANNER-TOP-HTML-->a<!--/CMS:BANNER-TOP-HTML-->|<!--CMS:BANNER-TOP-HTML-->b\nc<!--/CMS:BANNER-TOP-HTML-->";
HtmlMarkerEditor.ReplaceRegion(html, "CMS:BANNER-TOP-HTML", string.Empty)
.Should().Be("<!--CMS:BANNER-TOP-HTML--><!--/CMS:BANNER-TOP-HTML-->|<!--CMS:BANNER-TOP-HTML--><!--/CMS:BANNER-TOP-HTML-->");
}
[Fact]
public void Region_WithoutItsClosingMarker_IsLeftAlone()
{
var html = "<!--CMS:OFFERINGS-HTML-->baked";
HtmlMarkerEditor.ReplaceRegion(html, "CMS:OFFERINGS-HTML", "x").Should().Be(html);
}
[Fact]
public void Region_ReplacementIsLiteral_NoRegexSubstitutionIsApplied()
{
var html = "<!--CMS:A-->old<!--/CMS:A-->";
HtmlMarkerEditor.ReplaceRegion(html, "CMS:A", "$1 ${open} $& \\n").Should().Be("<!--CMS:A-->$1 ${open} $& \\n<!--/CMS:A-->");
}
// ---- data block ----
[Fact]
public void DataBlock_MarkerAndBakedBlockAreReplacedByTheLiveBlock()
{
var html = "<head><!--CMS:DATA-->\n <script type=\"application/json\" id=\"cms-data\">{\"a\":1}</script></head>";
HtmlMarkerEditor.ReplaceDataBlock(html, "CMS:DATA", "cms-data", "<script id=\"cms-data\">LIVE</script>")
.Should().Be("<head><script id=\"cms-data\">LIVE</script></head>");
}
[Fact]
public void DataBlock_WithoutABakedBlock_TheMarkerAloneIsReplaced()
{
HtmlMarkerEditor.ReplaceDataBlock("<body><!--CMS:DATA--><p>x</p></body>", "CMS:DATA", "cms-data", "<script>LIVE</script>")
.Should().Be("<body><script>LIVE</script><p>x</p></body>");
}
[Fact]
public void DataBlock_AScriptWithAnotherIdIsNotTouched()
{
var html = "<!--CMS:DATA--><script type=\"application/json\" id=\"other\">{}</script>";
HtmlMarkerEditor.ReplaceDataBlock(html, "CMS:DATA", "cms-data", "<script>LIVE</script>")
.Should().Be("<script>LIVE</script><script type=\"application/json\" id=\"other\">{}</script>");
}
// ---- ld+json ----
private const string Marker = "CMS:OFFER-JSON-LD";
[Fact]
public void JsonLd_TheEditedJsonReplacesTheBlock_AndTheMarkerGoes()
{
var html = "<head><!--CMS:OFFER-JSON-LD slug=\"newborn\"--><script type=\"application/ld+json\">{\"a\":1}</script></head>";
string? seen = null;
var result = HtmlMarkerEditor.EditJsonLd(html, Marker, (slug, json) => { seen = slug + "|" + json; return "{\"b\":2}"; });
seen.Should().Be("newborn|{\"a\":1}");
result.Should().Be("<head><script type=\"application/ld+json\">{\"b\":2}</script></head>");
}
[Fact]
public void JsonLd_WhenTheEditReturnsNull_MarkerAndBlockStayExactlyAsBaked()
{
var html = "<!--CMS:OFFER-JSON-LD slug=\"newborn\"--><script type=\"application/ld+json\">{\"a\":1}</script>";
HtmlMarkerEditor.EditJsonLd(html, Marker, (_, _) => null).Should().Be(html);
}
[Theory]
[InlineData("<!--CMS:OFFER-JSON-LD slug=\"New Born\"--><script type=\"application/ld+json\">{}</script>")]
[InlineData("<!--CMS:OFFER-JSON-LD slug=\"newborn\"--><p>no block</p><script type=\"application/ld+json\">{}</script>")]
[InlineData("<!--CMS:OFFER-JSON-LD slug=\"newborn\"--><script type=\"text/javascript\">{}</script>")]
public void JsonLd_AMarkerNotInTheAgreedShape_IsNeverCalled(string html)
{
var called = false;
HtmlMarkerEditor.EditJsonLd(html, Marker, (_, _) => { called = true; return "x"; }).Should().Be(html);
called.Should().BeFalse();
}
// ---- inline values ----
[Fact]
public void Inline_TheTextOfASimpleSpanIsReplaced()
{
var html = "<p>vanaf <span data-cms-price=\"newborn\">€ 185</span> en <span data-cms-price=\"gezin\">€ 175</span></p>";
HtmlMarkerEditor.ReplaceInlineValues(html, "data-cms-price", slug => slug == "newborn" ? "€&nbsp;190" : null)
.Should().Be("<p>vanaf <span data-cms-price=\"newborn\">€&nbsp;190</span> en <span data-cms-price=\"gezin\">€ 175</span></p>");
}
[Fact]
public void Inline_ANestedSpanOrAnotherAttributeIsNotTouched()
{
var html = "<span data-cms-price=\"a\"><b>€ 1</b></span><span class=\"x\" data-cms-price=\"b\">€ 2</span>";
HtmlMarkerEditor.ReplaceInlineValues(html, "data-cms-price", _ => "NEW").Should().Be(html);
}
// ---- escaping ----
[Fact]
public void EscapeForScript_CannotCloseTheElement_AndKeepsTheJsonValueIntact()
{
var json = "{\"t\":\"</script><b>&\u2028\u2029\"}";
var escaped = HtmlMarkerEditor.EscapeForScript(json);
escaped.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028").And.NotContain("\u2029");
System.Text.Json.JsonDocument.Parse(escaped).RootElement.GetProperty("t").GetString().Should().Be("</script><b>&\u2028\u2029");
}
}
@@ -0,0 +1,104 @@
using System.Text.RegularExpressions;
namespace SlpModularCms.Core.Hosting.Website;
/// <summary>
/// The small, strict text edits a website page accepts from the CMS host. Every edit finds its marker by an exact
/// pattern and leaves the page alone when the pattern does not match: a marker that is missing, malformed or not in
/// the agreed place is never "repaired". All methods are pure (text in, text out).
/// </summary>
/// <remarks>
/// The marker formats are a contract with the website build (see aidlc-docs/features/asf-host-injection/plan.md):
/// <list type="bullet">
/// <item><c>&lt;!--CMS:X--&gt;…&lt;!--/CMS:X--&gt;</c>: a region whose content the host replaces (the fallback in between is the baked content).</item>
/// <item><c>&lt;!--CMS:DATA--&gt;</c> directly followed by the baked <c>&lt;script type="application/json" id="cms-data"&gt;</c> block.</item>
/// <item><c>&lt;!--CMS:OFFER-JSON-LD slug="x"--&gt;</c> directly before a <c>&lt;script type="application/ld+json"&gt;</c> block.</item>
/// <item><c>&lt;span data-cms-price="x"&gt;text&lt;/span&gt;</c>: a simple, not nested span whose text the host replaces.</item>
/// </list>
/// </remarks>
public static class HtmlMarkerEditor
{
private const RegexOptions Options = RegexOptions.Singleline | RegexOptions.CultureInvariant;
private static readonly TimeSpan MatchTimeout = TimeSpan.FromSeconds(2);
/// <summary>Whether the page mentions any CMS marker at all (a cheap check before any real work).</summary>
public static bool HasMarkers(string html) =>
html.Contains("<!--CMS:", StringComparison.Ordinal)
|| html.Contains("data-cms-price=", StringComparison.Ordinal);
/// <summary>
/// Replaces the content between <c>&lt;!--name--&gt;</c> and <c>&lt;!--/name--&gt;</c> (every pair on the page).
/// The markers themselves stay. An opening marker without its closing marker is left alone.
/// </summary>
public static string ReplaceRegion(string html, string name, string content)
{
var pattern = "(?<open><!--" + Regex.Escape(name) + "-->)(?<inner>.*?)(?<close><!--/" + Regex.Escape(name) + "-->)";
return Regex.Replace(html, pattern, m => m.Groups["open"].Value + content + m.Groups["close"].Value, Options, MatchTimeout);
}
/// <summary>
/// Replaces <c>&lt;!--markerName--&gt;</c> plus the baked <c>&lt;script … id="blockId"&gt;…&lt;/script&gt;</c> block that
/// directly follows it by <paramref name="newBlock"/> (marker and old block both go). Without such a block, the
/// marker alone is replaced.
/// </summary>
public static string ReplaceDataBlock(string html, string markerName, string blockId, string newBlock)
{
var pattern = "<!--" + Regex.Escape(markerName) + "-->(?:\\s*<script\\b[^>]*\\bid=\"" + Regex.Escape(blockId) + "\"[^>]*>.*?</script>)?";
return Regex.Replace(html, pattern, _ => newBlock, Options, MatchTimeout);
}
/// <summary>
/// For every <c>&lt;!--markerName slug="x"--&gt;</c> directly before a <c>&lt;script type="application/ld+json"&gt;</c>
/// block: calls <paramref name="edit"/> with the slug and the JSON text. A returned text replaces the JSON and the
/// marker is removed; null leaves marker and block exactly as they were (used when the edit cannot be made, so the
/// baked page is served).
/// </summary>
public static string EditJsonLd(string html, string markerName, Func<string, string, string?> edit)
{
var pattern = "<!--" + Regex.Escape(markerName) + "\\s+slug=\"(?<slug>[a-z0-9-]+)\"\\s*-->\\s*" +
"(?<open><script\\b[^>]*type=\"application/ld\\+json\"[^>]*>)(?<json>.*?)</script>";
return Regex.Replace(html, pattern, m =>
{
var edited = edit(m.Groups["slug"].Value, m.Groups["json"].Value);
return edited is null ? m.Value : m.Groups["open"].Value + edited + "</script>";
}, Options, MatchTimeout);
}
/// <summary>
/// Replaces the text of every simple <c>&lt;span {attribute}="slug"&gt;text&lt;/span&gt;</c> by what
/// <paramref name="textFor"/> returns for the slug (already HTML-encoded by the caller); null leaves the span alone.
/// </summary>
public static string ReplaceInlineValues(string html, string attribute, Func<string, string?> textFor)
{
var pattern = "(?<open><span\\s+" + Regex.Escape(attribute) + "=\"(?<slug>[a-z0-9-]+)\">)(?<inner>[^<]*)(?<close></span>)";
return Regex.Replace(html, pattern, m =>
{
var text = textFor(m.Groups["slug"].Value);
return text is null ? m.Value : m.Groups["open"].Value + text + m.Groups["close"].Value;
}, Options, MatchTimeout);
}
/// <summary>
/// Makes JSON safe to put inside a <c>&lt;script&gt;</c> element: <c>&lt;</c>, <c>&gt;</c>, <c>&amp;</c>, U+2028 and
/// U+2029 become <c>\uXXXX</c> escapes (still the same JSON string values), so the text can never close the element
/// or be read as markup.
/// </summary>
public static string EscapeForScript(string json)
{
var builder = new System.Text.StringBuilder(json.Length + 16);
foreach (var c in json)
{
switch (c)
{
case '<': builder.Append("\\u003C"); break;
case '>': builder.Append("\\u003E"); break;
case '&': builder.Append("\\u0026"); break;
case '\u2028': builder.Append("\\u2028"); break;
case '\u2029': builder.Append("\\u2029"); break;
default: builder.Append(c); break;
}
}
return builder.ToString();
}
}