| | | 1 | | using System.Text; |
| | | 2 | | using System.Text.RegularExpressions; |
| | | 3 | | using RoleRadar.Domain.Common; |
| | | 4 | | |
| | | 5 | | namespace RoleRadar.Domain.Notes; |
| | | 6 | | |
| | | 7 | | public sealed record ParsedImportSection( |
| | | 8 | | string SourceFileId, |
| | | 9 | | string HeadingPath, |
| | | 10 | | int OccurrenceIndex, |
| | | 11 | | int SectionOrderIndex, |
| | | 12 | | string Title, |
| | | 13 | | string Body, |
| | | 14 | | ProvenanceMarker Provenance, |
| | | 15 | | string BodyHash, |
| | | 16 | | string ImportKey); |
| | | 17 | | |
| | | 18 | | public static partial class MarkdownImportParser |
| | | 19 | | { |
| | 8 | 20 | | private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: t |
| | | 21 | | |
| | | 22 | | [GeneratedRegex(@"\[(stated|researched|inferred)(?:\s+(\d{4}-\d{2}-\d{2})(?:\s+([^\]]+?))?)?\]", RegexOptions.Compil |
| | | 23 | | private static partial Regex ProvenanceTagRegex(); |
| | | 24 | | |
| | | 25 | | public static bool ValidateUtf8(ReadOnlySpan<byte> bytes) |
| | | 26 | | { |
| | | 27 | | try |
| | | 28 | | { |
| | 74 | 29 | | _ = StrictUtf8.GetCharCount(bytes); |
| | 70 | 30 | | return true; |
| | | 31 | | } |
| | 4 | 32 | | catch (DecoderFallbackException) |
| | | 33 | | { |
| | 4 | 34 | | return false; |
| | | 35 | | } |
| | 74 | 36 | | } |
| | | 37 | | |
| | | 38 | | public static IReadOnlyList<ParsedImportSection> ParseBytes( |
| | | 39 | | string sourceFileId, |
| | | 40 | | byte[] bytes, |
| | | 41 | | string defaultDate) |
| | | 42 | | { |
| | 34 | 43 | | ArgumentNullException.ThrowIfNull(bytes); |
| | | 44 | | |
| | 34 | 45 | | if (!ValidateUtf8(bytes)) |
| | | 46 | | { |
| | 0 | 47 | | throw new DecoderFallbackException($"File '{sourceFileId}' contains invalid UTF-8 byte sequences."); |
| | | 48 | | } |
| | | 49 | | |
| | 34 | 50 | | var markdown = StrictUtf8.GetString(bytes); |
| | 34 | 51 | | return Parse(sourceFileId, markdown, defaultDate); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | public static IReadOnlyList<ParsedImportSection> Parse( |
| | | 55 | | string sourceFileId, |
| | | 56 | | string markdown, |
| | | 57 | | string defaultDate) |
| | | 58 | | { |
| | 64 | 59 | | ArgumentNullException.ThrowIfNull(sourceFileId); |
| | 64 | 60 | | ArgumentNullException.ThrowIfNull(markdown); |
| | | 61 | | |
| | 64 | 62 | | if (string.IsNullOrWhiteSpace(defaultDate) || !ProvenanceMarker.IsValidIsoDate(defaultDate)) |
| | | 63 | | { |
| | 0 | 64 | | throw new ArgumentException($"Default date '{defaultDate}' must be a valid ISO-8601 date in 'YYYY-MM-DD' for |
| | | 65 | | } |
| | | 66 | | |
| | 64 | 67 | | var normalizedSourceId = sourceFileId.Trim(); |
| | 64 | 68 | | var lines = SplitLines(markdown); |
| | | 69 | | |
| | 64 | 70 | | var headingLocations = FindSplitHeadings(markdown, lines); |
| | | 71 | | |
| | 64 | 72 | | var sections = new List<ParsedImportSection>(); |
| | 64 | 73 | | var headingPathOccurrences = new Dictionary<string, int>(StringComparer.Ordinal); |
| | 64 | 74 | | var bareHeadingCounter = 0; |
| | 64 | 75 | | var sectionOrderIndex = 0; |
| | | 76 | | |
| | 64 | 77 | | string? currentH1Path = null; |
| | | 78 | | |
| | 64 | 79 | | if (headingLocations.Count == 0) |
| | | 80 | | { |
| | 0 | 81 | | if (markdown.Length > 0) |
| | | 82 | | { |
| | 0 | 83 | | var prov = ExtractSectionProvenance(markdown, lines, 0, lines.Count, defaultDate); |
| | 0 | 84 | | var hash = Sha256Hasher.ComputeLowerHex(markdown); |
| | | 85 | | const string path = "$preamble"; |
| | 0 | 86 | | var importKey = $"{normalizedSourceId}#{path}#0"; |
| | | 87 | | |
| | 0 | 88 | | sections.Add(new ParsedImportSection( |
| | 0 | 89 | | SourceFileId: normalizedSourceId, |
| | 0 | 90 | | HeadingPath: path, |
| | 0 | 91 | | OccurrenceIndex: 0, |
| | 0 | 92 | | SectionOrderIndex: 0, |
| | 0 | 93 | | Title: "Preamble", |
| | 0 | 94 | | Body: markdown, |
| | 0 | 95 | | Provenance: prov, |
| | 0 | 96 | | BodyHash: hash, |
| | 0 | 97 | | ImportKey: importKey)); |
| | | 98 | | } |
| | | 99 | | |
| | 0 | 100 | | return sections; |
| | | 101 | | } |
| | | 102 | | |
| | | 103 | | // Check if there is preamble text before the first # or ## heading |
| | 64 | 104 | | var firstHeadingStart = headingLocations[0].StartCharIndex; |
| | 64 | 105 | | if (firstHeadingStart > 0) |
| | | 106 | | { |
| | 16 | 107 | | var preambleBody = markdown[..firstHeadingStart]; |
| | 16 | 108 | | var firstHeadingLineIndex = headingLocations[0].LineIndex; |
| | 16 | 109 | | var prov = ExtractSectionProvenance(markdown, lines, 0, firstHeadingLineIndex, defaultDate); |
| | 16 | 110 | | var hash = Sha256Hasher.ComputeLowerHex(preambleBody); |
| | | 111 | | const string path = "$preamble"; |
| | 16 | 112 | | var importKey = $"{normalizedSourceId}#{path}#0"; |
| | | 113 | | |
| | 16 | 114 | | sections.Add(new ParsedImportSection( |
| | 16 | 115 | | SourceFileId: normalizedSourceId, |
| | 16 | 116 | | HeadingPath: path, |
| | 16 | 117 | | OccurrenceIndex: 0, |
| | 16 | 118 | | SectionOrderIndex: sectionOrderIndex++, |
| | 16 | 119 | | Title: "Preamble", |
| | 16 | 120 | | Body: preambleBody, |
| | 16 | 121 | | Provenance: prov, |
| | 16 | 122 | | BodyHash: hash, |
| | 16 | 123 | | ImportKey: importKey)); |
| | | 124 | | } |
| | | 125 | | |
| | 3372 | 126 | | for (var i = 0; i < headingLocations.Count; i++) |
| | | 127 | | { |
| | 1622 | 128 | | var current = headingLocations[i]; |
| | 1622 | 129 | | var nextStart = (i + 1 < headingLocations.Count) |
| | 1622 | 130 | | ? headingLocations[i + 1].StartCharIndex |
| | 1622 | 131 | | : markdown.Length; |
| | | 132 | | |
| | 1622 | 133 | | var sectionBody = markdown[current.StartCharIndex..nextStart]; |
| | 1622 | 134 | | var nextLineIndex = (i + 1 < headingLocations.Count) |
| | 1622 | 135 | | ? headingLocations[i + 1].LineIndex |
| | 1622 | 136 | | : lines.Count; |
| | | 137 | | |
| | 1622 | 138 | | var prov = ExtractSectionProvenance(markdown, lines, current.LineIndex, nextLineIndex, defaultDate); |
| | | 139 | | |
| | | 140 | | string title; |
| | 1622 | 141 | | if (string.IsNullOrWhiteSpace(current.RawTitle)) |
| | | 142 | | { |
| | 14 | 143 | | bareHeadingCounter++; |
| | 14 | 144 | | title = $"(Untitled Heading #{bareHeadingCounter})"; |
| | | 145 | | } |
| | | 146 | | else |
| | | 147 | | { |
| | 1608 | 148 | | title = current.RawTitle; |
| | | 149 | | } |
| | | 150 | | |
| | 1622 | 151 | | var markerTitle = string.IsNullOrWhiteSpace(current.RawTitle) |
| | 1622 | 152 | | ? new string('#', current.Level) |
| | 1622 | 153 | | : $"{new string('#', current.Level)} {current.RawTitle}"; |
| | | 154 | | |
| | | 155 | | string headingPath; |
| | 1622 | 156 | | if (current.Level == 1) |
| | | 157 | | { |
| | 64 | 158 | | headingPath = markerTitle; |
| | 64 | 159 | | currentH1Path = headingPath; |
| | | 160 | | } |
| | | 161 | | else // Level == 2 |
| | | 162 | | { |
| | 1558 | 163 | | headingPath = currentH1Path is not null |
| | 1558 | 164 | | ? $"{currentH1Path} / {markerTitle}" |
| | 1558 | 165 | | : markerTitle; |
| | | 166 | | } |
| | | 167 | | |
| | 1622 | 168 | | if (!headingPathOccurrences.TryGetValue(headingPath, out var count)) |
| | | 169 | | { |
| | 1606 | 170 | | count = 0; |
| | | 171 | | } |
| | | 172 | | |
| | 1622 | 173 | | headingPathOccurrences[headingPath] = count + 1; |
| | 1622 | 174 | | var occurrenceIndex = count; |
| | | 175 | | |
| | 1622 | 176 | | var hash = Sha256Hasher.ComputeLowerHex(sectionBody); |
| | 1622 | 177 | | var importKey = $"{normalizedSourceId}#{headingPath}#{occurrenceIndex}"; |
| | | 178 | | |
| | 1622 | 179 | | sections.Add(new ParsedImportSection( |
| | 1622 | 180 | | SourceFileId: normalizedSourceId, |
| | 1622 | 181 | | HeadingPath: headingPath, |
| | 1622 | 182 | | OccurrenceIndex: occurrenceIndex, |
| | 1622 | 183 | | SectionOrderIndex: sectionOrderIndex++, |
| | 1622 | 184 | | Title: title, |
| | 1622 | 185 | | Body: sectionBody, |
| | 1622 | 186 | | Provenance: prov, |
| | 1622 | 187 | | BodyHash: hash, |
| | 1622 | 188 | | ImportKey: importKey)); |
| | | 189 | | } |
| | | 190 | | |
| | 64 | 191 | | return sections; |
| | | 192 | | } |
| | | 193 | | |
| | 42168 | 194 | | private sealed record LineInfo(int LineIndex, int StartCharIndex, int EndCharIndex, string Text, bool InFrontMatter) |
| | | 195 | | |
| | 17766 | 196 | | private sealed record HeadingLocation(int LineIndex, int Level, string RawTitle, int StartCharIndex); |
| | | 197 | | |
| | | 198 | | private static List<LineInfo> SplitLines(string markdown) |
| | | 199 | | { |
| | 64 | 200 | | var lines = new List<LineInfo>(); |
| | 64 | 201 | | var pos = 0; |
| | 64 | 202 | | var len = markdown.Length; |
| | 64 | 203 | | var lineIndex = 0; |
| | 64 | 204 | | var inFrontMatter = false; |
| | | 205 | | |
| | 10440 | 206 | | while (pos < len) |
| | | 207 | | { |
| | 10376 | 208 | | var lineStart = pos; |
| | 659204 | 209 | | while (pos < len && markdown[pos] != '\r' && markdown[pos] != '\n') |
| | | 210 | | { |
| | 648828 | 211 | | pos++; |
| | | 212 | | } |
| | | 213 | | |
| | 10376 | 214 | | var contentEnd = pos; |
| | 10376 | 215 | | if (pos < len) |
| | | 216 | | { |
| | 10372 | 217 | | if (markdown[pos] == '\r' && pos + 1 < len && markdown[pos + 1] == '\n') |
| | | 218 | | { |
| | 7922 | 219 | | pos += 2; |
| | | 220 | | } |
| | | 221 | | else |
| | | 222 | | { |
| | 2450 | 223 | | pos += 1; |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | 10376 | 227 | | var lineText = markdown[lineStart..contentEnd]; |
| | | 228 | | |
| | 10376 | 229 | | if (lineIndex == 0 && lineText.Trim() == "---") |
| | | 230 | | { |
| | 2 | 231 | | inFrontMatter = true; |
| | 2 | 232 | | lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: true)); |
| | 2 | 233 | | continue; |
| | | 234 | | } |
| | | 235 | | |
| | 10374 | 236 | | if (inFrontMatter) |
| | | 237 | | { |
| | 8 | 238 | | lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: true)); |
| | 8 | 239 | | if (lineText.Trim() == "---") |
| | | 240 | | { |
| | 2 | 241 | | inFrontMatter = false; |
| | | 242 | | } |
| | 2 | 243 | | continue; |
| | | 244 | | } |
| | | 245 | | |
| | 10366 | 246 | | lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: false)); |
| | | 247 | | } |
| | | 248 | | |
| | 64 | 249 | | return lines; |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static List<HeadingLocation> FindSplitHeadings(string markdown, List<LineInfo> lines) |
| | | 253 | | { |
| | 64 | 254 | | var headings = new List<HeadingLocation>(); |
| | 64 | 255 | | var inFence = false; |
| | 64 | 256 | | var fenceChar = '\0'; |
| | 64 | 257 | | var fenceLen = 0; |
| | | 258 | | |
| | 20880 | 259 | | foreach (var line in lines) |
| | | 260 | | { |
| | 10376 | 261 | | if (line.InFrontMatter) |
| | | 262 | | { |
| | | 263 | | continue; |
| | | 264 | | } |
| | | 265 | | |
| | 10366 | 266 | | var span = line.Text.AsSpan(); |
| | 10366 | 267 | | if (MarkdownSectionParser.TryUpdateFenceState(span, ref inFence, ref fenceChar, ref fenceLen)) |
| | | 268 | | { |
| | | 269 | | continue; |
| | | 270 | | } |
| | | 271 | | |
| | 10358 | 272 | | if (inFence) |
| | | 273 | | { |
| | | 274 | | continue; |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | // Indented code block: 4 or more leading spaces or tab |
| | 10350 | 278 | | if (IsIndentedCodeLine(span)) |
| | | 279 | | { |
| | | 280 | | continue; |
| | | 281 | | } |
| | | 282 | | |
| | 10346 | 283 | | if (TryParseAtxHeading(span, out var level, out var title)) |
| | | 284 | | { |
| | | 285 | | // We split ONLY on level 1 (#) and level 2 (##) |
| | 2016 | 286 | | if (level is 1 or 2) |
| | | 287 | | { |
| | 1622 | 288 | | headings.Add(new HeadingLocation(line.LineIndex, level, title, line.StartCharIndex)); |
| | | 289 | | } |
| | | 290 | | } |
| | | 291 | | } |
| | | 292 | | |
| | 64 | 293 | | return headings; |
| | | 294 | | } |
| | | 295 | | |
| | | 296 | | private static bool IsIndentedCodeLine(ReadOnlySpan<char> span) |
| | | 297 | | { |
| | 10350 | 298 | | if (span.IsEmpty) |
| | | 299 | | { |
| | 3810 | 300 | | return false; |
| | | 301 | | } |
| | | 302 | | |
| | 6540 | 303 | | if (span[0] == '\t') |
| | | 304 | | { |
| | 0 | 305 | | return true; |
| | | 306 | | } |
| | | 307 | | |
| | 6540 | 308 | | var spaces = 0; |
| | 6644 | 309 | | while (spaces < span.Length && span[spaces] == ' ') |
| | | 310 | | { |
| | 104 | 311 | | spaces++; |
| | | 312 | | } |
| | | 313 | | |
| | 6540 | 314 | | return spaces >= 4; |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | private static bool TryParseAtxHeading(ReadOnlySpan<char> span, out int level, out string title) |
| | | 318 | | { |
| | 10346 | 319 | | level = 0; |
| | 10346 | 320 | | title = string.Empty; |
| | | 321 | | |
| | 10346 | 322 | | var spaces = 0; |
| | 10434 | 323 | | while (spaces < span.Length && spaces < 3 && span[spaces] == ' ') |
| | | 324 | | { |
| | 88 | 325 | | spaces++; |
| | | 326 | | } |
| | | 327 | | |
| | 10346 | 328 | | var trimmedLeading = span[spaces..]; |
| | 10346 | 329 | | if (trimmedLeading.IsEmpty || trimmedLeading[0] != '#') |
| | | 330 | | { |
| | 7754 | 331 | | return false; |
| | | 332 | | } |
| | | 333 | | |
| | 2592 | 334 | | var hashes = 0; |
| | 7532 | 335 | | while (hashes < trimmedLeading.Length && trimmedLeading[hashes] == '#') |
| | | 336 | | { |
| | 4940 | 337 | | hashes++; |
| | | 338 | | } |
| | | 339 | | |
| | 2592 | 340 | | if (hashes is < 1 or > 6) |
| | | 341 | | { |
| | 0 | 342 | | return false; |
| | | 343 | | } |
| | | 344 | | |
| | 2592 | 345 | | var rest = trimmedLeading[hashes..]; |
| | 2592 | 346 | | if (!rest.IsEmpty && rest[0] != ' ' && rest[0] != '\t') |
| | | 347 | | { |
| | 576 | 348 | | return false; |
| | | 349 | | } |
| | | 350 | | |
| | 2016 | 351 | | level = hashes; |
| | | 352 | | |
| | 2016 | 353 | | var rawTitle = rest.Trim(); |
| | | 354 | | // Check for optional closing sequence of # preceded by space/tab |
| | 2016 | 355 | | var titleStr = StripTrailingClosingHashes(rawTitle); |
| | 2016 | 356 | | title = titleStr; |
| | 2016 | 357 | | return true; |
| | | 358 | | } |
| | | 359 | | |
| | | 360 | | private static string StripTrailingClosingHashes(ReadOnlySpan<char> span) |
| | | 361 | | { |
| | 2016 | 362 | | if (span.IsEmpty) |
| | | 363 | | { |
| | 14 | 364 | | return string.Empty; |
| | | 365 | | } |
| | | 366 | | |
| | 2002 | 367 | | var end = span.Length; |
| | 2002 | 368 | | while (end > 0 && (span[end - 1] == ' ' || span[end - 1] == '\t')) |
| | | 369 | | { |
| | 0 | 370 | | end--; |
| | | 371 | | } |
| | | 372 | | |
| | 2002 | 373 | | var trailingHashes = 0; |
| | 2002 | 374 | | while (end - trailingHashes > 0 && span[end - trailingHashes - 1] == '#') |
| | | 375 | | { |
| | 0 | 376 | | trailingHashes++; |
| | | 377 | | } |
| | | 378 | | |
| | 2002 | 379 | | if (trailingHashes > 0 && end - trailingHashes > 0 && (span[end - trailingHashes - 1] == ' ' || span[end - trail |
| | | 380 | | { |
| | 0 | 381 | | var beforeHashes = span[..(end - trailingHashes)].Trim(); |
| | 0 | 382 | | return beforeHashes.ToString(); |
| | | 383 | | } |
| | | 384 | | |
| | 2002 | 385 | | return span.Trim().ToString(); |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | private static ProvenanceMarker ExtractSectionProvenance( |
| | | 389 | | string markdown, |
| | | 390 | | List<LineInfo> lines, |
| | | 391 | | int startLineIndex, |
| | | 392 | | int endLineIndex, |
| | | 393 | | string defaultDate) |
| | | 394 | | { |
| | 1638 | 395 | | var inFence = false; |
| | 1638 | 396 | | var fenceChar = '\0'; |
| | 1638 | 397 | | var fenceLen = 0; |
| | | 398 | | |
| | 5436 | 399 | | for (var i = startLineIndex; i < endLineIndex && i < lines.Count; i++) |
| | | 400 | | { |
| | 2614 | 401 | | var line = lines[i]; |
| | 2614 | 402 | | if (line.InFrontMatter) |
| | | 403 | | { |
| | | 404 | | continue; |
| | | 405 | | } |
| | | 406 | | |
| | 2604 | 407 | | var span = line.Text.AsSpan(); |
| | 2604 | 408 | | if (MarkdownSectionParser.TryUpdateFenceState(span, ref inFence, ref fenceChar, ref fenceLen)) |
| | | 409 | | { |
| | | 410 | | continue; |
| | | 411 | | } |
| | | 412 | | |
| | 2596 | 413 | | if (inFence) |
| | | 414 | | { |
| | | 415 | | continue; |
| | | 416 | | } |
| | | 417 | | |
| | 2588 | 418 | | var match = ProvenanceTagRegex().Match(line.Text); |
| | 2588 | 419 | | if (match.Success) |
| | | 420 | | { |
| | 1534 | 421 | | var kind = ProvenanceKindExtensions.FromWireString(match.Groups[1].Value); |
| | 1534 | 422 | | var date = match.Groups[2].Success && !string.IsNullOrWhiteSpace(match.Groups[2].Value) |
| | 1534 | 423 | | ? match.Groups[2].Value.Trim() |
| | 1534 | 424 | | : defaultDate; |
| | 1534 | 425 | | var qualifier = match.Groups[3].Success && !string.IsNullOrWhiteSpace(match.Groups[3].Value) |
| | 1534 | 426 | | ? match.Groups[3].Value.Trim() |
| | 1534 | 427 | | : null; |
| | | 428 | | |
| | 1534 | 429 | | return new ProvenanceMarker(kind, date, qualifier); |
| | | 430 | | } |
| | | 431 | | } |
| | | 432 | | |
| | 104 | 433 | | return new ProvenanceMarker(ProvenanceKind.Inferred, defaultDate); |
| | | 434 | | } |
| | | 435 | | } |