using System.Text.Json; using System.Xml.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models.WritingSolver; using PlotLine.Services; internal static class WritingSolverSeoTests { private sealed class Repository(SolverGraph graph) : IWritingSolverRepository { public Task GetAsync() => Task.FromResult(graph); public Task PublishAsync(string json, string editor) => throw new NotSupportedException(); } private sealed class Host(string environment) : IWebHostEnvironment { public string EnvironmentName { get; set; } = environment; public string ApplicationName { get; set; } = "PlotLine"; public string ContentRootPath { get; set; } = Path.GetFullPath("PlotLine"); public string WebRootPath { get; set; } = Path.GetFullPath("PlotLine/wwwroot"); public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider(); public IFileProvider WebRootFileProvider { get; set; } = new NullFileProvider(); } public static void AuditPublication() { void Check(bool ok, string reason) { if (!ok) throw new Exception(reason); } var graph = WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json")); var editorial = new WritingProblemEditorial("PlotLine/Content/WritingSolver/Editorial/pages-v1.json"); var repo = new Repository(graph); var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["WritingSolver:EnableIndexing"] = "true" }).Build(); var host = new Host("Production"); var help = new HelpService(host); HashSet Sitemap(IConfiguration settings) { var result = (ContentResult)new SitemapController(help, settings, repo, editorial).Index().GetAwaiter().GetResult(); var xml = XDocument.Parse(result.Content!); XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; var urls = xml.Descendants(ns + "loc").Select(e => e.Value).ToList(); Check(urls.Count == urls.Distinct().Count(), "Duplicate sitemap URL."); Check(urls.All(u => new Uri(u).Query == "" && new Uri(u).Fragment == ""), "Sitemap contains journey/query/fragment state."); return urls.ToHashSet(); } var expected = graph.Solutions.Where(p => p.Active && p.Index).Select(p => PublicSeo.AbsoluteUrl(config, "/problem-solver/" + p.Slug)).ToHashSet(); Check(expected.Count == editorial.Catalog.Pages.Count, "Permanent editorial catalogue/publication eligibility diverged."); var urls = Sitemap(config); var actual = urls.Where(u => new Uri(u).AbsolutePath.StartsWith("/problem-solver/") && !new Uri(u).AbsolutePath.StartsWith("/problem-solver/browse")).ToHashSet(); Check(expected.SetEquals(actual), "Generated sitemap must contain exactly the eligible permanent diagnoses."); Check(urls.Contains(PublicSeo.AbsoluteUrl(config, "/problem-solver")), "Solver discovery missing from Production sitemap."); var titles = new HashSet(); var descriptions = new HashSet(); using var cache = new MemoryCache(new MemoryCacheOptions()); foreach (var solution in graph.Solutions.Where(p => p.Active && p.Index)) { var controller = new WritingProblemsController(repo, new EphemeralDataProtectionProvider(), config, new WritingSolverResultContext(cache), editorial) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } }; controller.Solution(solution.Slug).GetAwaiter().GetResult(); var title = controller.ViewData["SeoTitle"] as string; var description = controller.ViewData["SeoDescription"] as string; Check(!string.IsNullOrWhiteSpace(title) && titles.Add(title), "Missing/duplicate permanent title."); Check(!string.IsNullOrWhiteSpace(description) && descriptions.Add(description), "Missing/duplicate permanent description."); var canonical = PublicSeo.AbsoluteUrl(config, "/problem-solver/" + solution.Slug); Check((string?)controller.ViewData["CanonicalUrl"] == canonical, "Permanent canonical is not clean/stable."); Check((string?)controller.ViewData["Robots"] == "index, follow" && !controller.Response.Headers.ContainsKey("X-Robots-Tag"), "Production eligible page unexpectedly noindex."); Check(!string.IsNullOrWhiteSpace(controller.ViewData["OgTitle"] as string) && !string.IsNullOrWhiteSpace(controller.ViewData["OgDescription"] as string), "Missing Open Graph text."); var image = new Uri((string)controller.ViewData["OgImage"]!); Check(File.Exists(Path.Combine(host.WebRootPath, image.AbsolutePath.TrimStart('/'))), "Social image missing."); foreach (var json in (IEnumerable)controller.ViewData["StructuredData"]!) { using var doc = JsonDocument.Parse(json); var root = doc.RootElement; Check(root.GetProperty("@type").GetString() == "WebPage" && root.GetProperty("url").GetString() == canonical, "Unexpected structured identity/type."); Check(!string.IsNullOrWhiteSpace(root.GetProperty("description").GetString()), "Structured description missing."); } } var transient = new WritingProblemsController(repo, new EphemeralDataProtectionProvider(), config, new WritingSolverResultContext(cache), editorial) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } }; transient.Index(choose: true).GetAwaiter().GetResult(); Check((string?)transient.ViewData["Robots"] == "noindex, follow", "Validation-only journey URL must remain noindex."); var first = graph.Solutions.First(p => p.Active && p.Index); first.Index = false; Check(!Sitemap(config).Contains(PublicSeo.AbsoluteUrl(config, "/problem-solver/" + first.Slug)), "Unpublished index flag ignored by sitemap."); first.Index = true; first.Active = false; Check(!Sitemap(config).Contains(PublicSeo.AbsoluteUrl(config, "/problem-solver/" + first.Slug)), "Inactive diagnosis entered sitemap."); first.Active = true; var disabled = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["WritingSolver:EnableIndexing"] = "false" }).Build(); Check(!Sitemap(disabled).Any(u => new Uri(u).AbsolutePath.StartsWith("/problem-solver")), "Disabled Solver entered sitemap."); foreach (var environment in new[] { "Production", "Development" }) { using var services = new ServiceCollection().AddSingleton(new Host(environment)).BuildServiceProvider(); var app = new ApplicationBuilder(services); app.UseDevelopmentNoIndex(); app.Run(_ => Task.CompletedTask); var http = new DefaultHttpContext(); app.Build()(http).GetAwaiter().GetResult(); Check(http.Response.Headers.ContainsKey("X-Robots-Tag") == (environment == "Development"), "Global environment indexing boundary failed."); Check(PublicIndexing.Robots(environment, "index, follow") == (environment == "Development" ? "noindex, follow" : "index, follow"), "HTML environment policy failed."); Check(PublicIndexing.Robots(environment, "noindex, follow") == "noindex, follow", "Stateful noindex was weakened."); } } }