Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 3x 3x 757x 38x 12x 12x 3x 3x 151x 1097x 79x 37x 37x 37x 37x 37x 151x 151x 72x 72x 72x 72x 79x 42x 42x 37x 11x 11x 37x 37x 11x 3x 38x 38x 38x 38x 715x 4x 4x 711x 38x 593x 593x 44x 44x 22x 22x 22x 487x 487x 487x 1x 486x 486x 372x 114x 114x 35x 79x 487x 39x 39x 39x 39x 39x 39x 39x 593x 593x 593x 106x 106x 106x 106x 106x 487x 487x 487x 487x 39x 45x 4x 41x 41x 41x 45x 45x 45x 45x 41x 41x 41x 377x 374x 56x 56x 318x 41x 38x 38x 38x 548x 548x 44x 44x 504x 443x 38x 12850x 12850x 12850x 12850x 40x 12850x 12850x 40x 40x 40x 40x 40x 40x 40x 40x 12850x 443x 443x 443x 12850x 12850x 40x 40x 40x 12810x 12810x 443x 40x 1458x 40x 1x 1x 1x 1x 1x 40x 40x 620x 620x 620x 580x 40x 40x 40x 40x 1548x 1548x 1548x 1508x 40x 40x 25x 25x 25x 93x 93x 68x 68x 25x 37x 37x 37x 37x 37x 468x 468x 443x 443x 443x 25x 25x 25x 11x 11x 14x 14x 14x 14x 25x 37x 25x 25x 1068x 1068x 25x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Aggregator/CleanArtifact
* @description Normalise a single analysis-artifact Markdown file so it can be
* merged into the aggregate document without producing duplicate banners,
* competing H1 headings, or broken relative links.
*
* Applied transformations (in order):
* 1. Strip leading YAML front-matter (`---\nā¦\n---\n`).
* 2. Strip ISMS/owner/classification banners (emoji rows, shields.io badges,
* `<p align="center">` blocks, and the separator `---` that usually
* follows them).
* 3. Remove the artifact's own H1; the aggregator owns the document outline.
* 4. Demote every remaining heading by one level (H2āH3, etc.) so the
* aggregate has a single H1.
* 5. Rewrite repo-relative links/images to absolute GitHub URLs so the
* published HTML is portable.
* 6. Deduplicate mermaid fence bodies on a per-document basis (caller-owned
* state) ā identical blocks are replaced with a reference comment.
*/
/** Hack23 repo slug used when building blob/raw URLs. */
const GITHUB_REPO = 'Hack23/euparliamentmonitor';
/** Default branch used in generated URLs. */
const GITHUB_BRANCH = 'main';
/**
* Build a GitHub blob URL for a repo-relative path.
*
* @param relPath - Repo-relative file path
* @returns Absolute `https://github.com/.../blob/main/...` URL
*/
export function githubBlobUrl(relPath: string): string {
return `https://github.com/${GITHUB_REPO}/blob/${GITHUB_BRANCH}/${relPath.replace(/\\/g, '/')}`;
}
/**
* Build a `raw.githubusercontent.com` URL for a repo-relative path.
*
* @param relPath - Repo-relative file path
* @returns Absolute raw-content URL
*/
export function githubRawUrl(relPath: string): string {
return `https://raw.githubusercontent.com/${GITHUB_REPO}/${GITHUB_BRANCH}/${relPath.replace(/\\/g, '/')}`;
}
/** Options controlling artifact cleanup. */
export interface CleanArtifactOptions {
/**
* Repo-relative path of the artifact being cleaned (e.g.
* `analysis/daily/2026-01-15/breaking-run1/intelligence/synthesis-summary.md`).
* Used to resolve relative links/images against.
*/
readonly artifactRelPath: string;
/**
* Shared set of mermaid-body hashes seen so far in the aggregate document.
* Identical blocks are replaced with a cross-reference comment; the caller
* owns the set so it persists across artifacts.
*/
readonly seenMermaidHashes?: Set<string>;
}
/** Result of {@link cleanArtifact}. */
export interface CleanArtifactResult {
/** Cleaned Markdown ready to be concatenated into the aggregate. */
readonly markdown: string;
/** Headings removed (for debugging/telemetry). */
readonly strippedH1s: number;
/** Banner/metadata lines removed. */
readonly strippedBannerLines: number;
/** Mermaid blocks deduplicated as a reference to a previous occurrence. */
readonly dedupedMermaidBlocks: number;
}
/**
* Strip YAML front-matter from the head of a Markdown document. Matches
* `---\n...\n---\n` *only* at position 0 ā quoted `---` dividers deeper in
* the document are left alone.
*
* @param md - Raw Markdown source
* @returns Markdown with the leading front-matter block removed
*/
export function stripFrontMatter(md: string): string {
if (!md.startsWith('---')) return md;
const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(md);
return match ? md.slice(match[0].length) : md;
}
/**
* Regex patterns identifying banner / document-owner / shields.io / center-pic
* lines that clutter the aggregate. All are line-level patterns; the caller
* applies them after front-matter strip.
*/
const BANNER_LINE_PATTERNS: readonly RegExp[] = [
/^\s*<p\s+align="center">/i,
/^\s*<\/p>\s*$/i,
/^\s*<img\s+[^>]*hack23\.com\/icon-/i,
/^\s*<h1\s+align="center">/i,
/^\s*<\/h1>\s*$/i,
/^\s*<a\s+href="#"><img\s+src="https:\/\/img\.shields\.io\//i,
/^\s*\*\*\s*š\s*Document Owner/i,
/^\s*\*\*\s*š\s*Review Cycle/i,
/^\s*\*\*\s*š¢\s*Owner/i,
/^\s*<strong>\s*(?:š|š|š¢)/i,
// Standalone center-aligned block closings
/^\s*<\/p>\s*$/,
];
/**
* Line-level matcher for a standalone horizontal rule. Used to drop the
* `---` separator that usually follows the banner block.
*/
const HR_LINE = /^\s*---\s*$/;
/**
* Return true when the line should be stripped as banner content.
*
* @param line - Single line of Markdown
* @returns `true` if the line matches any banner pattern
*/
function isBannerLine(line: string): boolean {
for (const p of BANNER_LINE_PATTERNS) {
if (p.test(line)) return true;
}
return false;
}
/**
* Drop banner/metadata blocks from the head of the document. Rules:
* - A run of banner lines (contiguous, or separated only by blank lines) is
* removed. A trailing `---` horizontal rule immediately after the banner
* run is also removed.
* - Stops scanning as soon as we hit a line that looks like real content
* (headings, prose, tables, fences) that isn't a banner or blank.
*
* @param md - Raw Markdown source
* @returns `{ md, lines }` ā stripped Markdown and count of removed lines
*/
export function stripBanners(md: string): { md: string; lines: number } {
const lines = md.split('\n');
let i = 0;
let bannerEnd = 0;
let stripped = 0;
while (i < lines.length) {
const line = lines[i] ?? '';
if (isBannerLine(line)) {
bannerEnd = i + 1;
stripped++;
i++;
continue;
}
if (line.trim() === '') {
// blank line ā keep scanning for more banner lines
i++;
continue;
}
// Real content reached ā but absorb a trailing HR if it immediately
// follows a banner run.
if (bannerEnd > 0 && HR_LINE.test(line)) {
bannerEnd = i + 1;
stripped++;
}
break;
}
if (bannerEnd === 0) return { md, lines: 0 };
return { md: lines.slice(bannerEnd).join('\n').replace(/^\n+/, ''), lines: stripped };
}
// REUSE-IgnoreStart
/**
* Matches an SPDX tag anywhere on a line, whether wrapped in HTML comments
* (SPDX-License-Identifier line inside `<!-- ... -->`), inline markdown
* emphasis (italic-wrapped SPDX-License-Identifier / SPDX-FileCopyrightText),
* or written bare. Used to purge artifact-level SPDX metadata before rendering
* so it doesn't leak into the aggregated HTML (where the REUSE tool would then
* parse the surrounding markup as part of the SPDX expression).
*/
// REUSE-IgnoreEnd
const SPDX_TAG_LINE =
/SPDX-(?:License-Identifier|FileCopyrightText|PackageName|PackageSupplier|PackageDownloadLocation)\b/;
// REUSE-IgnoreStart
/**
* Remove every line containing an SPDX tag from the Markdown source. The
* aggregated article HTML carries its own file-level SPDX header via
* `REUSE.toml`; per-artifact tags would otherwise surface as visible footer
* text (italic-wrapped SPDX tags rendered inside `<em>` / `</em></p>`) and
* trip the REUSE compliance scanner, which would parse the trailing markup
* as part of the SPDX expression.
*
* @param md - Raw Markdown source
* @returns `{ md, lines }` ā stripped Markdown and count of removed lines
*/
// REUSE-IgnoreEnd
export function stripSpdxTags(md: string): { md: string; lines: number } {
const lines = md.split('\n');
const kept: string[] = [];
let stripped = 0;
for (const line of lines) {
if (SPDX_TAG_LINE.test(line)) {
stripped++;
continue;
}
kept.push(line);
}
return { md: kept.join('\n'), lines: stripped };
}
/**
* Remove every H1 (`^# ` and the setext H1 form) and demote every other
* ATX heading by one level. Setext H2 (`----` underline) stays as H2 because
* converting it to H3 would require replacing the underline form.
*
* Skips changes inside fenced code blocks.
*
* @param md - Raw Markdown source
* @returns `{ md, h1Count }` ā transformed Markdown and number of H1s removed
*/
/**
* Track open/close of a fenced code block. Returns the updated fence state
* and the original line (unmodified). Centralising the state machine keeps
* callers simple and makes cognitive complexity linear.
*
* @param line - Current line of Markdown
* @param inFence - Whether the previous line was inside a fenced block
* @param fenceMarker - Opening marker for the current fence (or `""`)
* @returns `{ inFence, fenceMarker, matched }` reflecting the state after
* processing `line`; `matched` is `true` when the line itself is a
* fence boundary (and should therefore be passed through verbatim)
*/
function advanceFenceState(
line: string,
inFence: boolean,
fenceMarker: string
): { inFence: boolean; fenceMarker: string; matched: boolean } {
const fenceMatch = /^(\s*)(```+|~~~+)(.*)$/.exec(line);
if (!fenceMatch || !fenceMatch[2]) return { inFence, fenceMarker, matched: false };
const marker = fenceMatch[2];
if (!inFence) {
return { inFence: true, fenceMarker: marker, matched: true };
}
Eif (marker.startsWith(fenceMarker.charAt(0)) && marker.length >= fenceMarker.length) {
return { inFence: false, fenceMarker: '', matched: true };
}
return { inFence, fenceMarker, matched: true };
}
/**
* Transform one non-fence heading line: setext H1, ATX H1, or ATX H2-H6.
* Returns the processed output plus how many source lines it consumed and
* whether an H1 was removed.
*
* @param lines - All source lines (used to peek at the next line for setext)
* @param index - Zero-based index of the line under consideration
* @returns `{ output, consumed, h1Removed }` ā `consumed` is how many lines
* the caller should advance by (1 for ATX; 2 for setext H1; 0 when
* the line is not a heading at all)
*/
function processHeadingLine(
lines: readonly string[],
index: number
): { output: string | null; consumed: number; h1Removed: boolean } {
const line = lines[index] ?? '';
// Setext H1: current line has text, next line is `===+`
const nextLine = lines[index + 1] ?? '';
if (/^\s*=+\s*$/.test(nextLine) && /\S/.test(line)) {
return { output: null, consumed: 2, h1Removed: true };
}
const atx = /^(\s*)(#{1,6})(\s.*)$/.exec(line);
if (!atx || !atx[2]) {
return { output: line, consumed: 1, h1Removed: false };
}
const level = atx[2].length;
if (level === 1) {
return { output: null, consumed: 1, h1Removed: true };
}
const demoted = level === 6 ? '######' : '#'.repeat(level + 1);
return {
output: `${atx[1] ?? ''}${demoted}${atx[3] ?? ''}`,
consumed: 1,
h1Removed: false,
};
}
/**
* Remove every H1 (`^# ` and the setext H1 form) and demote every other
* ATX heading by one level. Setext H2 (`----` underline) stays as H2 because
* converting it to H3 would require replacing the underline form.
*
* Skips changes inside fenced code blocks.
*
* @param md - Raw Markdown source
* @returns `{ md, h1Count }` ā transformed Markdown and number of H1s removed
*/
export function demoteHeadings(md: string): { md: string; h1Count: number } {
const lines = md.split('\n');
const out: string[] = [];
let inFence = false;
let fenceMarker = '';
let h1Count = 0;
let i = 0;
while (i < lines.length) {
const line = lines[i] ?? '';
const fence = advanceFenceState(line, inFence, fenceMarker);
if (fence.matched || inFence) {
inFence = fence.inFence;
fenceMarker = fence.fenceMarker;
out.push(line);
i++;
continue;
}
const result = processHeadingLine(lines, i);
if (result.h1Removed) h1Count++;
if (result.output !== null) out.push(result.output);
i += result.consumed;
}
return { md: out.join('\n'), h1Count };
}
/**
* Resolve a relative link target against the artifact's directory and
* return an absolute GitHub URL.
*
* @param target - Original link target (e.g. `../templates/foo.md`)
* @param artifactRelPath - Repo-relative path of the artifact
* @param raw - When true, produce a raw.githubusercontent URL (for images)
* @returns Absolute URL (or the original target for anchors/absolute links)
*/
export function resolveLink(target: string, artifactRelPath: string, raw: boolean): string {
// Preserve absolute URLs, anchors, mailto/tel, and protocol-relative
if (
/^[a-z][a-z0-9+.-]*:\/\//i.test(target) ||
target.startsWith('//') ||
target.startsWith('#') ||
target.startsWith('mailto:') ||
target.startsWith('tel:') ||
target.startsWith('data:')
) {
return target;
}
const artifactDir = artifactRelPath.split('/').slice(0, -1).join('/');
// Split off an optional `#fragment` or `?query` suffix for re-attachment.
const suffixMatch = /[#?].*$/.exec(target);
const suffix = suffixMatch ? suffixMatch[0] : '';
const bare = suffix ? target.slice(0, -suffix.length) : target;
const resolved = posixResolve(artifactDir, bare);
const url = raw ? githubRawUrl(resolved) : githubBlobUrl(resolved);
return `${url}${suffix}`;
}
/**
* POSIX path-resolve over `/`-separated strings. Mirrors `path.posix.resolve`
* on a virtual absolute root so we don't depend on `path` for pure string ops.
*
* @param baseDir - Directory portion of the base path (POSIX separators)
* @param rel - Relative path to resolve against `baseDir`
* @returns Resolved path with `.` / `..` segments collapsed
*/
function posixResolve(baseDir: string, rel: string): string {
const parts = `${baseDir}/${rel}`.split('/');
const stack: string[] = [];
for (const part of parts) {
if (part === '' || part === '.') continue;
if (part === '..') {
stack.pop();
continue;
}
stack.push(part);
}
return stack.join('/');
}
/**
* Rewrite `[text](relative.md)` and `` links to GitHub URLs.
*
* @param md - Markdown source (may contain fenced code blocks, left untouched)
* @param artifactRelPath - Repo-relative path of the artifact
* @returns Markdown with every non-fence-local link rewritten
*/
export function rewriteLinks(md: string, artifactRelPath: string): string {
const lines = md.split('\n');
let inFence = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? '';
if (/^\s*(```+|~~~+)/.test(line)) {
inFence = !inFence;
continue;
}
if (inFence) continue;
lines[i] = rewriteLinksInLine(line, artifactRelPath);
}
return lines.join('\n');
}
/**
* Rewrite every `[text](target)` occurrence in a single non-fenced line.
* Uses a manual scanner instead of a global regex to avoid catastrophic
* backtracking on nested brackets.
*
* @param line - One line of Markdown, outside any fenced code block
* @param artifactRelPath - Repo-relative path of the source artifact
* @returns Line with every local `.md` target rewritten to a GitHub URL
*/
/**
* Attempt to parse a Markdown link starting at `line[index]`. Returns
* `null` when no valid `[text](target)` / `` link is present.
*
* @param line - Source line being scanned
* @param index - Zero-based index of the candidate `[` or `!`
* @param artifactRelPath - Repo-relative path of the source artifact
* @returns `{ replacement, nextIndex }` when a link was rewritten, else `null`
*/
function tryParseLinkAt(
line: string,
index: number,
artifactRelPath: string
): { replacement: string; nextIndex: number } | null {
const ch = line.charAt(index);
const isImage = ch === '!' && line.charAt(index + 1) === '[';
const isLink = ch === '[';
if (!isImage && !isLink) return null;
const start = isImage ? index + 1 : index;
const closeText = findMatchingBracket(line, start);
Iif (closeText === -1 || line.charAt(closeText + 1) !== '(') return null;
const openParen = closeText + 1;
const closeParen = findMatchingParen(line, openParen);
Iif (closeParen === -1) return null;
const label = line.slice(start, closeText + 1);
const rawTarget = line.slice(openParen + 1, closeParen).trim();
const { target, title } = splitTargetAndTitle(rawTarget);
const newTarget = resolveLink(target, artifactRelPath, isImage);
const replacement = (isImage ? '!' : '') + label + '(' + newTarget + title + ')';
return { replacement, nextIndex: closeParen + 1 };
}
/**
* Rewrite every `[text](target)` occurrence in a single non-fenced line.
* Uses a manual scanner instead of a global regex to avoid catastrophic
* backtracking on nested brackets.
*
* @param line - One line of Markdown, outside any fenced code block
* @param artifactRelPath - Repo-relative path of the source artifact
* @returns Line with every local `.md` target rewritten to a GitHub URL
*/
function rewriteLinksInLine(line: string, artifactRelPath: string): string {
let out = '';
let i = 0;
while (i < line.length) {
const parsed = tryParseLinkAt(line, i, artifactRelPath);
if (parsed) {
out += parsed.replacement;
i = parsed.nextIndex;
continue;
}
out += line.charAt(i);
i++;
}
return out;
}
/**
* Split a raw Markdown link target into its URL and optional `"title"`
* suffix. Uses a linear scanner instead of a regex to avoid catastrophic
* backtracking on pathological input.
*
* @param raw - Raw contents between the parentheses of a Markdown link
* @returns `{ target, title }` where `title` is `""` when absent, or the
* leading whitespace + `"..."` suffix when present
*/
function splitTargetAndTitle(raw: string): { target: string; title: string } {
let i = 0;
while (i < raw.length && !/\s/.test(raw.charAt(i))) i++;
if (i === raw.length) return { target: raw, title: '' };
const target = raw.slice(0, i);
const rest = raw.slice(i);
// Accept only exactly-matched `"..."` title; otherwise treat whole thing
// as part of the target so we don't silently drop content.
const trimmed = rest.trimStart();
Eif (
trimmed.length >= 2 &&
trimmed.charAt(0) === '"' &&
trimmed.charAt(trimmed.length - 1) === '"'
) {
return { target, title: rest };
}
return { target: raw, title: '' };
}
/**
* Index of the matching `]` for a `[` at position `start`, or `-1` if none.
*
* @param line - Line being scanned
* @param start - Zero-based index of the opening `[`
* @returns Zero-based index of the matching `]`, or `-1`
*/
function findMatchingBracket(line: string, start: number): number {
let depth = 0;
for (let i = start; i < line.length; i++) {
const ch = line.charAt(i);
Iif (ch === '\\') {
i++;
continue;
}
if (ch === '[') depth++;
else if (ch === ']') {
depth--;
Eif (depth === 0) return i;
}
}
return -1;
}
/**
* Index of the matching `)` for a `(` at position `start`, or `-1` if none.
*
* @param line - Line being scanned
* @param start - Zero-based index of the opening `(`
* @returns Zero-based index of the matching `)`, or `-1`
*/
function findMatchingParen(line: string, start: number): number {
let depth = 0;
for (let i = start; i < line.length; i++) {
const ch = line.charAt(i);
Iif (ch === '\\') {
i++;
continue;
}
if (ch === '(') depth++;
else if (ch === ')') {
depth--;
Eif (depth === 0) return i;
}
}
return -1;
}
/**
* Deduplicate identical mermaid fence blocks by body hash. The caller owns
* the `seen` Set so dedup state persists across artifacts in the same
* aggregate.
*
* When a duplicate is found the fence is replaced with a single-line HTML
* comment pointing at the earlier occurrence. Non-mermaid fences are left
* untouched.
*
* @param md - Markdown source that may contain mermaid fences
* @param seen - Shared set of mermaid-body hashes (caller-owned)
* @returns `{ md, deduped }` ā cleaned Markdown and count of replacements
*/
/**
* Scan forward from `start` to find the body and closing fence of a
* mermaid block whose opening was detected on `lines[start - 1]`.
*
* @param lines - Source lines
* @param start - Index of the first body line after the opening fence
* @returns `{ body, closeIndex }` ā body lines and index of the closing
* fence (or `lines.length` if no closing fence is present)
*/
function scanMermaidBody(
lines: readonly string[],
start: number
): { body: string[]; closeIndex: number } {
const body: string[] = [];
let j = start;
while (j < lines.length) {
const candidate = lines[j] ?? '';
if (/^\s*```+\s*$/.test(candidate)) break;
body.push(candidate);
j++;
}
return { body, closeIndex: j };
}
/**
* Deduplicate identical mermaid fence blocks by body hash. The caller owns
* the `seen` Set so dedup state persists across artifacts in the same
* aggregate.
*
* When a duplicate is found the fence is replaced with a single-line HTML
* comment pointing at the earlier occurrence. Non-mermaid fences are left
* untouched.
*
* @param md - Markdown source that may contain mermaid fences
* @param seen - Shared set of mermaid-body hashes (caller-owned)
* @returns `{ md, deduped }` ā cleaned Markdown and count of replacements
*/
export function dedupMermaid(md: string, seen: Set<string>): { md: string; deduped: number } {
const lines = md.split('\n');
const out: string[] = [];
let deduped = 0;
let i = 0;
while (i < lines.length) {
const line = lines[i] ?? '';
if (!/^\s*```+\s*mermaid\s*$/i.test(line)) {
out.push(line);
i++;
continue;
}
const { body, closeIndex } = scanMermaidBody(lines, i + 1);
const hash = hashString(body.join('\n').trim());
if (seen.has(hash)) {
out.push(
`<!-- mermaid block deduplicated: identical to earlier occurrence (hash=${hash}) -->`
);
deduped++;
} else {
seen.add(hash);
out.push(line);
out.push(...body);
Eif (closeIndex < lines.length) out.push(lines[closeIndex] ?? '');
}
i = closeIndex + 1;
}
return { md: out.join('\n'), deduped };
}
/**
* 32-bit FNV-1a hash rendered as hex. Not cryptographic ā used only to
* identify identical mermaid bodies within one aggregate document. The
* surface is entirely derived from committed repo content.
*
* @param input - String to hash
* @returns 8-character lowercase hex digest
*/
function hashString(input: string): string {
let h = 0x811c9dc5;
for (let i = 0; i < input.length; i++) {
h ^= input.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, '0');
}
/**
* Apply all cleanup passes and return the normalised Markdown plus
* simple counters for telemetry/tests.
*
* @param source - Raw Markdown contents of the artifact file
* @param options - Cleanup options (artifact path, shared mermaid dedup set)
* @returns {@link CleanArtifactResult} with the normalised Markdown
*/
export function cleanArtifact(source: string, options: CleanArtifactOptions): CleanArtifactResult {
const seen = options.seenMermaidHashes ?? new Set<string>();
let md = stripFrontMatter(source);
md = stripSpdxTags(md).md;
const { md: mdAfterBanners, lines: strippedBannerLines } = stripBanners(md);
md = mdAfterBanners;
const { md: mdAfterHeadings, h1Count } = demoteHeadings(md);
md = mdAfterHeadings;
md = rewriteLinks(md, options.artifactRelPath);
const { md: mdAfterMermaid, deduped } = dedupMermaid(md, seen);
md = mdAfterMermaid;
// Collapse excessive blank lines to at most 2 consecutive blanks
md = md.replace(/\n{3,}/g, '\n\n').trimEnd() + '\n';
return {
markdown: md,
strippedH1s: h1Count,
strippedBannerLines,
dedupedMermaidBlocks: deduped,
};
}
|