@blundergoat/gruff-ts 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,14 @@
1
- // Text, HTML, SARIF, hotspot, and dashboard renderers for the stable analysis report.
1
+ // Text, SARIF, hotspot, markdown, GitHub, and summary renderers for the stable analysis report.
2
+ // HTML output and dashboard chrome live in `report-html.ts` so this module stays under the
3
+ // `size.file-length` threshold; both files source `buildPillarRows` + `grade` from
4
+ // `pillar-summary.ts` so the cross-format Pillars table stays byte-aligned.
2
5
  import type { AnalysisReport, Finding, OutputFormat, Severity } from "./types.ts";
6
+ import { OUTPUT_VOLUME_HINT_THRESHOLD } from "./constants.ts";
7
+ import { countRuleSeverities } from "./findings-helpers.ts";
8
+ import { buildPillarRows, type PillarRow } from "./pillar-summary.ts";
3
9
  import { ruleDescriptors } from "./rules.ts";
4
-
5
- const CYCLOMATIC_BUCKETS = [
6
- { label: "21+", minimum: 21 },
7
- { label: "16-20", minimum: 16 },
8
- { label: "11-15", minimum: 11 },
9
- { label: "6-10", minimum: 6 },
10
- { label: "1-5", minimum: 1 },
11
- ] as const;
10
+ import { renderHtml } from "./report-html.ts";
11
+ import { severityGradeBreakdown } from "./scoring.ts";
12
12
 
13
13
  /*
14
14
  * Format dispatcher. `hotspot` is emitted inline (smallest schema) while every other format has a
@@ -180,13 +180,17 @@ function sarifLevel(severity: Severity): "error" | "warning" | "note" {
180
180
  * durable machine output should use `analyse --format=json` instead.
181
181
  */
182
182
  function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
183
- const pillarCounts = countBy(report.findings, (finding) => finding.pillar);
184
183
  const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
184
+ const pillarRows = buildPillarRows(report);
185
+ const breakdown = severityGradeBreakdown(report.findings);
185
186
  const lines = [
186
187
  `gruff-ts ${report.tool.version} summary`,
187
188
  `Path: ${pathLabel ?? report.run.projectRoot}`,
188
189
  ...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
189
- `Score: ${report.score.composite.toFixed(1)} (${report.score.grade})`,
190
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)})`,
191
+ ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
192
+ ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
193
+ ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
190
194
  `Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
191
195
  `Analysed files: ${report.paths.analysedFiles}`,
192
196
  ...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
@@ -194,31 +198,33 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
194
198
  if (report.diagnostics.length > 0) {
195
199
  lines.push("", "Diagnostics:", ...report.diagnostics.map(summaryDiagnosticLine));
196
200
  }
197
- lines.push("", "Per-pillar counts:");
198
- lines.push(...renderRankedCounts(pillarCounts, "No findings by pillar."));
201
+ lines.push("", ...renderPillarsBlock(pillarRows));
199
202
  lines.push("", `Top ${top} rules:`);
200
- lines.push(...renderRankedCounts(ruleCounts, "No rule findings.", top));
203
+ lines.push(...renderRankedRuleRows(report.findings, top));
201
204
  lines.push("", `Top ${top} file offenders:`);
202
205
  lines.push(
203
206
  ...(
204
207
  report.score.topOffenders.length === 0
205
208
  ? ["- No file offenders."]
206
- : report.score.topOffenders.slice(0, top).map((offender) => `- ${offender.filePath}: ${offender.findings} findings, score ${offender.score.toFixed(1)}`)
209
+ : report.score.topOffenders.slice(0, top).map((offender) => `- ${offender.filePath}: ${offender.findings} findings, quality ${offender.score.toFixed(1)}/100`)
207
210
  ),
208
211
  );
209
212
  return `${lines.join("\n")}\n`;
210
213
  }
211
214
 
212
215
  /*
213
- * Renders the stable public `gruff.summary.v1` JSON contract for the `summary --format=json` flow.
214
- * The schema shape (scope/score/findings/topRules/topOffenders) is part of that contract - downstream
215
- * CI integrations parse it, so field renames or removals are breaking changes for users.
216
+ * Renders the stable public `gruff.summary.v2` JSON contract for the `summary --format=json` flow.
217
+ * Phase 2 of the cross-port harmonisation replaces the flat `{pillar, count}` shape with rich
218
+ * per-pillar objects carrying grade, score, applicability, and per-severity counts (findings,
219
+ * advisory, warning, error). The schema-version string is bumped because downstream CI consumers
220
+ * parse this payload and the field-set is no longer compatible with v1; scope/score/topRules/
221
+ * topOffenders remain unchanged.
216
222
  */
217
223
  function renderSummaryJson(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
218
- const pillarCounts = countBy(report.findings, (finding) => finding.pillar);
219
224
  const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
225
+ const pillarRows = buildPillarRows(report);
220
226
  const payload = {
221
- schemaVersion: "gruff.summary.v1",
227
+ schemaVersion: "gruff.summary.v2",
222
228
  tool: report.tool,
223
229
  scope: {
224
230
  paths: pathLabel ?? report.run.projectRoot,
@@ -232,7 +238,17 @@ function renderSummaryJson(report: AnalysisReport, elapsedMs?: number, pathLabel
232
238
  score: report.score,
233
239
  findings: report.summary,
234
240
  baseline: report.baseline,
235
- pillars: renderRankedCountRows(pillarCounts),
241
+ pillars: pillarRows.map((row) => ({
242
+ pillar: row.pillar,
243
+ grade: row.grade,
244
+ score: row.score,
245
+ penalty: row.penalty,
246
+ applicable: row.isApplicable,
247
+ findings: row.findings,
248
+ advisory: row.advisory,
249
+ warning: row.warning,
250
+ error: row.error,
251
+ })),
236
252
  topRules: renderRankedCountRows(ruleCounts, top),
237
253
  topOffenders: report.score.topOffenders.slice(0, top),
238
254
  };
@@ -274,6 +290,73 @@ function countBy<T extends string>(findings: Finding[], keyFor: (finding: Findin
274
290
  return counts;
275
291
  }
276
292
 
293
+ /*
294
+ * Text renderer for the `Pillars` block in `gruff-ts summary`. Column widths are computed from the
295
+ * actual data (max pillar-name length, max digits per severity column) with a 3-char minimum value
296
+ * width so single-digit cells still leave visual breathing room before the next column. This
297
+ * matches the cross-port canonical byte-for-byte layout: leading "Pillars" header, 2-space row
298
+ * indent, pillar name padded to max-name-width + 1 space, single-letter grade, 1-space separator,
299
+ * score right-aligned in 6 chars with 2 decimals, then findings/advisory/warning/error cells
300
+ * separated by 3 spaces and trimmed of trailing whitespace on the final column.
301
+ */
302
+ function renderPillarsBlock(rows: PillarRow[]): string[] {
303
+ if (rows.length === 0) {
304
+ return ["Pillars", " (none)"];
305
+ }
306
+ const nameWidth = Math.max(...rows.map((row) => row.pillar.length));
307
+ const findingsWidth = Math.max(3, ...rows.map((row) => String(row.findings).length));
308
+ const advisoryWidth = Math.max(3, ...rows.map((row) => String(row.advisory).length));
309
+ const warningWidth = Math.max(3, ...rows.map((row) => String(row.warning).length));
310
+ const errorWidth = Math.max(3, ...rows.map((row) => String(row.error).length));
311
+ const lines = ["Pillars"];
312
+ for (const row of rows) {
313
+ const name = row.pillar.padEnd(nameWidth);
314
+ const score = row.score.toFixed(2).padStart(6);
315
+ const findingsCell = `findings=${String(row.findings).padEnd(findingsWidth)}`;
316
+ const advisoryCell = `advisory=${String(row.advisory).padEnd(advisoryWidth)}`;
317
+ const warningCell = `warning=${String(row.warning).padEnd(warningWidth)}`;
318
+ const errorCell = `error=${String(row.error).padEnd(errorWidth)}`;
319
+ const line = ` ${name} ${row.grade} ${score} ${findingsCell} ${advisoryCell} ${warningCell} ${errorCell}`.replace(/\s+$/, "");
320
+ lines.push(line);
321
+ }
322
+ return lines;
323
+ }
324
+
325
+ /*
326
+ * Enriched top-N rules renderer. Replaces the plain `- <ruleId>: <count>` form with a per-severity
327
+ * split plus the rule's one-line description, so an operator triaging 1000+ findings can see
328
+ * whether the top entry is one error or four hundred advisories at a glance. Description text is
329
+ * truncated to `DESCRIPTION_BODY_LIMIT` characters with an ellipsis so the row stays legible at 100
330
+ * columns. Sort order is preserved (count DESC, ruleId ASC) to keep the row-at-position-[0] stable.
331
+ */
332
+ function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
333
+ const severities = countRuleSeverities(findings);
334
+ if (severities.size === 0) {
335
+ return ["- No rule findings."];
336
+ }
337
+ const descriptions = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor.description]));
338
+ const limited = [...severities.entries()]
339
+ .sort(([leftKey, leftCounts], [rightKey, rightCounts]) => rightCounts.total - leftCounts.total || leftKey.localeCompare(rightKey))
340
+ .slice(0, limit ?? severities.size);
341
+ return limited.map(([ruleId, counts]) => {
342
+ const description = truncateDescription(descriptions.get(ruleId) ?? "");
343
+ return `- ${ruleId}: ${counts.total} (${counts.error} err / ${counts.warning} warn / ${counts.advisory} adv) - ${description}`;
344
+ });
345
+ }
346
+
347
+ /*
348
+ * 60-char description budget that keeps the rule-row line under ~100 columns even with the longest
349
+ * ruleId and severity-split. The trailing ellipsis is a single Unicode glyph so terminals that
350
+ * don't render `...` still see the truncation marker.
351
+ */
352
+ const DESCRIPTION_BODY_LIMIT = 60;
353
+
354
+ // Applies the description budget to a single rule's description so each rule row in the summary
355
+ // Top-N block fits on one terminal line. Returns the input unchanged when already short.
356
+ function truncateDescription(text: string): string {
357
+ return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
358
+ }
359
+
277
360
  function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText: string, limit?: number): string[] {
278
361
  if (counts.size === 0) {
279
362
  return [`- ${emptyText}`];
@@ -296,9 +379,13 @@ function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?:
296
379
  * sorted into the stable order, so piping into `grep` produces deterministic results.
297
380
  */
298
381
  function renderText(report: AnalysisReport): string {
382
+ const breakdown = severityGradeBreakdown(report.findings);
299
383
  const lines = [
300
384
  `gruff-ts ${report.tool.version}`,
301
- `Score: ${report.score.composite.toFixed(1)} (${report.score.grade}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
385
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
386
+ ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
387
+ ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
388
+ ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
302
389
  `Analysed files: ${report.paths.analysedFiles}`,
303
390
  ];
304
391
  if (report.diagnostics.length > 0) {
@@ -307,22 +394,72 @@ function renderText(report: AnalysisReport): string {
307
394
  if (report.findings.length > 0) {
308
395
  lines.push("", "Findings:", ...report.findings.map((finding) => `- [${finding.severity}] ${finding.filePath}:${finding.line ?? 1} ${finding.ruleId} - ${finding.message}`));
309
396
  }
397
+ if (report.findings.length >= OUTPUT_VOLUME_HINT_THRESHOLD) {
398
+ lines.push("", `Tip: ${report.findings.length} findings is more than a flat list usefully shows. Try \`gruff-ts summary --top=20\` for a per-rule digest.`);
399
+ }
310
400
  return `${lines.join("\n")}\n`;
311
401
  }
312
402
 
313
- // Truncates to 50 findings because Markdown previews (PR comments, READMEs) start mangling longer
314
- // tables. The stable JSON or HTML renderers stay the canonical full-fidelity output.
403
+ /*
404
+ * Markdown renderer for the `gruff.analysis.v2` report. Truncates to 50 findings because Markdown
405
+ * previews (PR comments, READMEs) start mangling longer tables; the JSON and HTML renderers stay
406
+ * the canonical full-fidelity output. Public contract / invariant: the Pillars table is inserted
407
+ * between the severity counts and the per-finding list so CI logs and PR comment previews see it
408
+ * first, and it shares its row data and sort order with the text/JSON/HTML pillar renderers via
409
+ * `buildPillarRows` so all four surfaces stay deterministic and byte-aligned across runs.
410
+ */
315
411
  function renderMarkdown(report: AnalysisReport): string {
412
+ const breakdown = severityGradeBreakdown(report.findings);
316
413
  return [
317
414
  "# gruff-ts report",
318
415
  "",
319
- `Score: **${report.score.composite.toFixed(1)} (${report.score.grade})**`,
416
+ `Composite: **${report.score.grade} (${report.score.composite.toFixed(1)})**`,
417
+ `- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
418
+ `- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
419
+ `- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
320
420
  "",
321
421
  `Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error.`,
422
+ "",
423
+ ...renderMarkdownPillarsTable(buildPillarRows(report)),
424
+ "",
322
425
  ...report.findings.slice(0, 50).map((finding) => `- \`${finding.ruleId}\` \`${finding.filePath}\`:${finding.line ?? 1} - ${finding.message}`),
323
426
  ].join("\n");
324
427
  }
325
428
 
429
+ /*
430
+ * Canonical 7-column Pillars table shared by the cross-port markdown contract. The header,
431
+ * separator (right-aligned numeric columns), and row format match the gruff-go markdown reporter
432
+ * byte-for-byte so downstream tooling (PR comment scrapers, dashboards parsing the markdown body)
433
+ * keys off a single shape. Row order is sourced from `buildPillarRows` (findings DESC, then pillar
434
+ * ASC); scores render with two decimals; pipes in pillar/grade cells are escaped so a future
435
+ * pillar/grade name containing `|` cannot break the table.
436
+ */
437
+ function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
438
+ const lines = [
439
+ "## Pillars",
440
+ "",
441
+ "| Pillar | Grade | Score | Findings | Advisory | Warning | Error |",
442
+ "| --- | --- | ---: | ---: | ---: | ---: | ---: |",
443
+ ];
444
+ if (rows.length === 0) {
445
+ lines.push("| _(none)_ | | | | | | |");
446
+ return lines;
447
+ }
448
+ for (const row of rows) {
449
+ lines.push(
450
+ `| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${row.score.toFixed(2)} | ${row.findings} | ${row.advisory} | ${row.warning} | ${row.error} |`,
451
+ );
452
+ }
453
+ return lines;
454
+ }
455
+
456
+ // Escapes the pipe character so a pillar/grade name containing `|` cannot terminate the table row.
457
+ // Markdown's table syntax has no other reserved cell characters - newlines are already impossible
458
+ // inside a single-line `lines.push` interpolation - so this single replacement is sufficient.
459
+ function escapeMarkdownCell(cell: string): string {
460
+ return cell.replaceAll("|", "\\|");
461
+ }
462
+
326
463
  // GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
327
464
  // must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
328
465
  function renderGithub(report: AnalysisReport): string {
@@ -337,382 +474,6 @@ function githubAnnotationPath(filePath: string): string {
337
474
  return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
338
475
  }
339
476
 
340
- // Extra metadata appended to dashboard-served HTML. Static-file consumers never see it because the
341
- // CLI calls `renderHtml` without this argument; only the dashboard route passes it in.
342
- interface DashboardRenderContext {
343
- projectRoot: string;
344
- scanPath: string;
345
- }
346
-
347
- /*
348
- * Self-contained HTML output (CSS inlined, no external assets) so reports can be archived or
349
- * emailed. The schema invariant: every Finding listed in the report must be reachable through
350
- * deep links - the on-page JS in `dashboardJs` relies on stable `data-path` attributes.
351
- */
352
- function renderHtml(report: AnalysisReport, dashboardContext?: DashboardRenderContext): string {
353
- const bodySections = [
354
- htmlMasthead(report),
355
- htmlDiagnostics(report),
356
- dashboardContext ? htmlDashboardContext(dashboardContext) : "",
357
- htmlVerdict(report),
358
- htmlPillars(report),
359
- htmlOffenders(report),
360
- htmlDistribution(report),
361
- htmlFindings(report),
362
- htmlFooter(report),
363
- ].join("\n");
364
- return `<!doctype html>
365
- <html lang="en-NZ">
366
- <head>
367
- <meta charset="utf-8">
368
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
369
- <title>gruff-ts report - ${escapeHtml(report.score.grade)}</title>
370
- <style>${htmlReportCss(report.diagnostics.length > 0)}</style>
371
- </head>
372
- <body>
373
- <main class="paper"><span class="corner-tr"></span><span class="corner-bl"></span>
374
- ${bodySections}
375
- </main>
376
- </body>
377
- </html>`;
378
- }
379
-
380
- // Top banner: path count, format, fail-on, schema version. The schemaVersion text is the
381
- // contract surface - operators eyeball it to confirm the report shape they expect.
382
- function htmlMasthead(report: AnalysisReport): string {
383
- const paths = report.paths.analysedFiles === 0 ? "." : `${report.paths.analysedFiles} analysed ${report.paths.analysedFiles === 1 ? "file" : "files"}`;
384
- return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code quality - inspection report</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
385
- }
386
-
387
- // Single key/value row. Both inputs are escaped - they reach this function as user-influenced
388
- // strings (paths, format names) and would otherwise enable injection in archived reports.
389
- function htmlMetaRow(label: string, metaValue: string): string {
390
- const escapedLabel = escapeHtml(label);
391
- const escapedValue = escapeHtml(metaValue);
392
- return `<div><span class="label">${escapedLabel}</span><span class="val">${escapedValue}</span></div>`;
393
- }
394
-
395
- // Diagnostics are parse/IO failures, not normal findings. HTML renders them before score sections
396
- // because partial scans must remain visibly incomplete; omitting empty diagnostics is the stable contract.
397
- function htmlDiagnostics(report: AnalysisReport): string {
398
- if (report.diagnostics.length === 0) {
399
- return "";
400
- }
401
- const diagnostics = report.diagnostics.map(htmlDiagnosticEntry).join("");
402
- return `<section class="diagnostics"><h2 class="section-head">diagnostics <span class="aside">run messages</span></h2><div class="diagnostic-list">${diagnostics}</div></section>`;
403
- }
404
-
405
- // HTML markup for one diagnostic entry. The `diagnostic-type`/`diagnostic-message`/`diagnostic-location`
406
- // span classes are part of the stable HTML report contract - the dashboard CSS and any downstream
407
- // scraping keys off them, so the structure here must stay invariant across renderer changes.
408
- function htmlDiagnosticEntry(diagnostic: AnalysisReport["diagnostics"][number]): string {
409
- const lineSuffix = diagnostic.line ? `:${diagnostic.line}` : "";
410
- const location = diagnostic.filePath
411
- ? `<span class="diagnostic-location">${escapeHtml(diagnostic.filePath)}${lineSuffix}</span>`
412
- : "";
413
- return `<div class="diagnostic"><span class="diagnostic-type">${escapeHtml(diagnostic.diagnosticType)}</span><span class="diagnostic-message">${escapeHtml(diagnostic.message)}</span>${location}</div>`;
414
- }
415
-
416
- // Dashboard-only banner that names the project root and scan path. Static reports never include
417
- // this; both inputs are user-controlled query parameters and are escaped before reaching HTML.
418
- function htmlDashboardContext(context: DashboardRenderContext): string {
419
- const escapedProjectRoot = escapeHtml(context.projectRoot);
420
- const escapedScanPath = escapeHtml(context.scanPath);
421
- return `<section class="dashboard-context"><h2 class="section-head">dashboard scan <span class="aside">local run</span></h2><div class="dashboard-context-grid"><div><span class="label">Project root</span><span class="val">${escapedProjectRoot}</span></div><div><span class="label">Path</span><span class="val">${escapedScanPath}</span></div></div></section>`;
422
- }
423
-
424
- /*
425
- * The grade stamp + four stat cards. The verdict shape is part of the stable visual contract that
426
- * the dashboard relies on for parity with static reports.
427
- */
428
- function htmlVerdict(report: AnalysisReport): string {
429
- const gradeCssClass = gradeClass(report.score.grade);
430
- const escapedGrade = escapeHtml(report.score.grade);
431
- const scoreText = report.score.composite.toFixed(1);
432
- const escapedSummary = escapeHtml(verdictSummary(report));
433
- const stats = `${htmlStat(String(report.summary.total), "findings", "")}${htmlStat(String(report.summary.error), "errors", "fail")}${htmlStat(String(report.summary.warning), "warnings", "warn")}${htmlStat(String(report.summary.advisory), "advisories", "note")}`;
434
- return `<section class="verdict"><div class="grade-stamp ${gradeCssClass}"><div class="grade-letter">${escapedGrade}</div><div class="grade-score">${scoreText} / 100</div></div><div class="verdict-body"><div class="verdict-headline">Inspection complete.<br><em>${escapedSummary}</em></div><div class="verdict-stats">${stats}</div></div></section>`;
435
- }
436
-
437
- // Headline sentence. Counts only warning/error findings - advisories are intentionally excluded
438
- // from the verdict text because they are below the stable "needs attention" threshold.
439
- function verdictSummary(report: AnalysisReport): string {
440
- const thresholdFindings = report.summary.warning + report.summary.error;
441
- if (thresholdFindings === 0) {
442
- return "No warning or error findings flagged.";
443
- }
444
- const pillars = new Set(report.findings.filter((finding) => finding.severity === "warning" || finding.severity === "error").map((finding) => finding.pillar));
445
- return `${thresholdFindings} ${thresholdFindings === 1 ? "finding" : "findings"} at warning or error severity across ${pillars.size} ${pillars.size === 1 ? "pillar" : "pillars"}.`;
446
- }
447
-
448
- // One stat card (number + label). `className` is a curated, non-escaped CSS class - callers must
449
- // not pass user input here or it would break the layout in archived reports.
450
- function htmlStat(number: string, label: string, className: string): string {
451
- const escapedClassName = escapeHtml(className);
452
- const escapedNumber = escapeHtml(number);
453
- const escapedLabel = escapeHtml(label);
454
- return `<div class="stat"><div class="num ${escapedClassName}">${escapedNumber}</div><div class="lbl">${escapedLabel}</div></div>`;
455
- }
456
-
457
- /*
458
- * Pillar score grid in the same order the analyser produced - the stable composite score is the
459
- * mean of these pillars (see `scoreReport`), so visual order matches the headline-grade derivation.
460
- */
461
- function htmlPillars(report: AnalysisReport): string {
462
- const items =
463
- report.score.pillars.length === 0
464
- ? '<div class="empty">No pillar findings.</div>'
465
- : report.score.pillars
466
- .map((pillar) => {
467
- const letter = grade(pillar.score);
468
- return `<div class="pillar"><div class="name">${escapeHtml(pillar.pillar)}</div><div class="grade ${gradeClass(letter)}">${letter}</div><div class="breakdown"><div class="row"><span class="key">score</span><span class="val">${pillar.score.toFixed(1)}</span></div><div class="row"><span class="key">findings</span><span class="val">${pillar.findings}</span></div></div></div>`;
469
- })
470
- .join("");
471
- return `<section class="pillars"><h2 class="section-head">pillar grades <span class="aside">weighted composite</span></h2><div class="pillar-grid">${items}</div></section>`;
472
- }
473
-
474
- // Top-10 offender table, ordered by ascending score (worst first). `scoreReport` returns the full
475
- // sorted list; summary and hotspot apply their own caps from the same source. The HTML report caps
476
- // at 10 rows so the visual layout stays stable regardless of project size - that 10 is the contract.
477
- function htmlOffenders(report: AnalysisReport): string {
478
- const rows =
479
- report.score.topOffenders.length === 0
480
- ? '<tr><td colspan="4">No offenders found.</td></tr>'
481
- : report.score.topOffenders
482
- .slice(0, 10)
483
- .map((file) => {
484
- const letter = grade(file.score);
485
- return `<tr><td class="file-path">${htmlLocation(file.filePath)}</td><td class="num">${file.score.toFixed(1)}</td><td class="num">${file.findings}</td><td class="num"><span class="grade-pill ${gradeClass(letter)}">${letter}</span></td></tr>`;
486
- })
487
- .join("");
488
- return `<section class="offenders"><h2 class="section-head">top offenders <span class="aside">sorted by score</span></h2><table class="offender-list"><thead><tr><th scope="col">file</th><th scope="col" class="num">score</th><th scope="col" class="num">findings</th><th scope="col" class="num">grade</th></tr></thead><tbody>${rows}</tbody></table></section>`;
489
- }
490
-
491
- /*
492
- * Histogram of cyclomatic-complexity buckets. The 5 fixed buckets are part of the stable visual
493
- * vocabulary maintainers learn over time - adding a new bucket would invalidate that mental model.
494
- */
495
- function htmlDistribution(report: AnalysisReport): string {
496
- const distribution = cyclomaticDistribution(report);
497
- const max = Math.max(1, ...Object.values(distribution));
498
- const bars = Object.entries(distribution)
499
- .map(([label, count]) => {
500
- const height = Math.max(4, Math.round((count / max) * 100));
501
- const className = label === "16-20" || label === "21+" ? " fail" : label === "11-15" ? " warn" : "";
502
- return `<div class="bar${className}" style="height:${height}%;"><span class="count">${count}</span></div>`;
503
- })
504
- .join("");
505
- const axis = Object.keys(distribution)
506
- .map((label) => `<span>${escapeHtml(label)}</span>`)
507
- .join("");
508
- return `<section class="chart-section"><h2 class="section-head">distribution <span class="aside">cyclomatic complexity</span></h2><p class="chart-summary">${escapeHtml(cyclomaticSummary(distribution))}</p><div class="chart-card"><div class="title">cyclomatic complexity - flagged functions</div><div class="histogram">${bars}</div><div class="histogram-axis">${axis}</div></div></section>`;
509
- }
510
-
511
- /*
512
- * Pre-seeded with zero counts for every bucket so the resulting record has a stable key order
513
- * in JSON dumps. Findings outside `complexity.cyclomatic` are ignored - see `cyclomaticFindingBucket`.
514
- */
515
- function cyclomaticDistribution(report: AnalysisReport): Record<string, number> {
516
- const distribution: Record<string, number> = { "1-5": 0, "6-10": 0, "11-15": 0, "16-20": 0, "21+": 0 };
517
- for (const finding of report.findings) {
518
- const bucket = cyclomaticFindingBucket(finding);
519
- if (bucket) {
520
- distribution[bucket] = (distribution[bucket] ?? 0) + 1;
521
- }
522
- }
523
- return distribution;
524
- }
525
-
526
- // Extracts the cyclomatic number from the finding message because the metadata schema doesn't
527
- // expose it as a top-level field - coupling the renderer to the message text is acceptable here
528
- // because the message format is itself part of the stable rule contract.
529
- function cyclomaticFindingBucket(finding: Finding): string | undefined {
530
- if (finding.ruleId !== "complexity.cyclomatic") {
531
- return undefined;
532
- }
533
- const match = finding.message.match(/cyclomatic complexity (\d+)/);
534
- const complexityValue = match?.[1] ? Number(match[1]) : undefined;
535
- return complexityValue === undefined ? undefined : cyclomaticBucket(complexityValue);
536
- }
537
-
538
- // Linear walk in descending-minimum order so the first match wins - required because `21+` and
539
- // `16-20` would otherwise both apply to a value of 25.
540
- function cyclomaticBucket(complexityValue: number): string | undefined {
541
- for (const bucket of CYCLOMATIC_BUCKETS) {
542
- if (complexityValue >= bucket.minimum) {
543
- return bucket.label;
544
- }
545
- }
546
- return undefined;
547
- }
548
-
549
- // One-line caption that quantifies how many functions exceed CC=10. The pluralisation handling
550
- // matters - "1 functions exceed" reads poorly enough that a reviewer would file it as a regression.
551
- function cyclomaticSummary(distribution: Record<string, number>): string {
552
- const moderate = distribution["11-15"] ?? 0;
553
- const high = distribution["16-20"] ?? 0;
554
- const severe = distribution["21+"] ?? 0;
555
- const exceeds = moderate + high + severe;
556
- return `${exceeds} ${exceeds === 1 ? "function" : "functions"} ${exceeds === 1 ? "exceeds" : "exceed"} CC 10 (${moderate} in 11-15, ${high} in 16-20, ${severe} at 21+).`;
557
- }
558
-
559
- // Caps the list at 250 entries because the inline-CSS report becomes painful to scroll past that.
560
- // The footer caveat shows "first 250 of N" so the truncation stable and visible.
561
- function htmlFindings(report: AnalysisReport): string {
562
- const findings =
563
- report.findings.length === 0
564
- ? '<div class="empty">No findings.</div>'
565
- : report.findings
566
- .slice(0, 250)
567
- .map(
568
- (finding) =>
569
- `<div class="finding"><div class="severity ${severityClass(finding.severity)}">${escapeHtml(finding.severity)}</div><div class="finding-body"><h3 class="rule">${escapeHtml(finding.ruleId)}</h3><div class="msg">${escapeHtml(finding.message)}</div><div class="loc"><code>${htmlLocation(finding.filePath, finding.line)}</code></div></div><div class="points"><b>${escapeHtml(finding.pillar)}</b></div></div>`,
570
- )
571
- .join("");
572
- const capped = report.findings.length > 250 ? ` <span class="aside">first 250 of ${report.findings.length}</span>` : ` <span class="aside">${report.findings.length} shown</span>`;
573
- return `<section class="findings"><h2 class="section-head">flagged findings${capped}</h2><div class="findings-list">${findings}</div></section>`;
574
- }
575
-
576
- /*
577
- * Page-bottom strip with tool version and schema string - those are the two stable identifiers a
578
- * reviewer can use to reproduce a historical report.
579
- */
580
- function htmlFooter(report: AnalysisReport): string {
581
- const escapedVersion = escapeHtml(report.tool.version);
582
- const escapedSchemaVersion = escapeHtml(report.schemaVersion);
583
- return `<footer class="footer"><div class="left">gruff-ts - v${escapedVersion}</div><div class="center">strong opinions, opinionated defaults</div><div class="right">schema - ${escapedSchemaVersion}</div></footer>`;
584
- }
585
-
586
- // Renders a keyboard-focusable location pill. `data-path` is what the dashboard JS keys off when
587
- // the user clicks to deep-link; both attributes go through `escapeHtml` because filePath is user-influenced.
588
- function htmlLocation(filePath: string, line?: number): string {
589
- const text = line === undefined ? filePath : `${filePath}:${line}`;
590
- return `<span class="loc-link" tabindex="0" data-path="${escapeHtml(text)}">${escapeHtml(text)}</span>`;
591
- }
592
-
593
- // CSS class suffix used by severity badges and grade letters. Returning a curated literal (never
594
- // arbitrary user text) is what keeps `htmlStat`/`htmlFinding` safe to interpolate without escaping.
595
- function severityClass(severity: Severity): string {
596
- return severity === "error" ? "fail" : severity === "warning" ? "warn" : "note";
597
- }
598
-
599
- // Constrains grade text to known CSS suffixes before interpolation. Unknown future grades degrade
600
- // to neutral styling instead of creating user-influenced class names.
601
- function gradeClass(gradeValue: string): string {
602
- const letter = gradeValue[0]?.toLowerCase() ?? "n";
603
- return ["a", "b", "c", "d", "f"].includes(letter) ? letter : "n";
604
- }
605
-
606
- // Single inline stylesheet for both static reports and dashboard-served pages. `shouldIncludeDiagnostics`
607
- // appends the diagnostic-section rules only when the report actually has them, keeping clean
608
- // reports leaner. Hand-maintained CSS - no preprocessor.
609
- function htmlReportCss(shouldIncludeDiagnostics: boolean): string {
610
- const baseCss = `:root{--ink:#0d0c0a;--ink-2:#161412;--ink-3:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--grade-a:#7fa15a;--grade-b:#b8b450;--grade-c:#d08c36;--grade-d:#c2552b;--grade-f:#8b2828;--advisory:#b5ab94;--serif:Georgia,'Iowan Old Style',serif;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box;margin:0;padding:0}html{background:var(--ink);scrollbar-gutter:stable}body{font-family:var(--mono);color:var(--paper);background:var(--ink);min-height:100vh;line-height:1.5;font-size:14px;padding:48px 32px}.paper{max-width:1180px;margin:0 auto 24px;background:var(--ink-2);border:1px solid var(--rule);position:relative;padding:56px 64px 48px;scrollbar-gutter:stable}.corner-tr,.corner-bl,.paper:before,.paper:after{content:'';position:absolute;width:22px;height:22px;border:1px solid var(--forge)}.paper:before{top:12px;left:12px;border-right:0;border-bottom:0}.paper:after{bottom:12px;right:12px;border-left:0;border-top:0}.corner-tr{top:12px;right:12px;border-left:0;border-bottom:0}.corner-bl{bottom:12px;left:12px;border-right:0;border-top:0}.masthead{display:grid;grid-template-columns:1fr auto;gap:32px;padding-bottom:28px;border-bottom:1px solid var(--rule);align-items:end}.wordmark{font-family:var(--serif);font-weight:900;font-size:96px;line-height:.85;color:var(--paper);font-style:italic}.wordmark:after{content:'-ts';color:var(--forge);font-style:normal;font-size:.45em;margin-left:.15em;vertical-align:super}.tagline{margin-top:12px;font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase}.meta{text-align:right;font-size:11px;color:var(--paper-dim);line-height:1.9}.label{color:var(--paper-mute);text-transform:uppercase;letter-spacing:0;margin-right:8px}.val{color:var(--paper)}.inspection-id{margin-top:10px;color:var(--forge);font-weight:700;font-size:12px;letter-spacing:0}.section-head{font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase;padding-bottom:16px;margin-bottom:20px;border-bottom:1px solid var(--rule);display:flex;justify-content:space-between;align-items:baseline;font-family:var(--mono);font-weight:500;line-height:1.5}.section-head:before{content:'>';margin-right:10px;color:var(--forge);font-family:var(--serif);font-size:14px;font-style:italic}.aside{color:var(--paper-mute);font-size:10px;letter-spacing:0}.verdict{display:grid;grid-template-columns:auto 1fr;gap:56px;padding:48px 0;border-bottom:1px solid var(--rule);align-items:center}.grade-stamp{width:220px;height:220px;border:3px solid currentColor;color:var(--grade-b);display:flex;flex-direction:column;align-items:center;justify-content:center;transform:rotate(-4deg)}.grade-stamp.a,.grade.a,.grade-pill.a{color:var(--grade-a)}.grade-stamp.b,.grade.b,.grade-pill.b{color:var(--grade-b)}.grade-stamp.c,.grade.c,.grade-pill.c{color:var(--grade-c)}.grade-stamp.d,.grade.d,.grade-pill.d{color:var(--grade-d)}.grade-stamp.f,.grade.f,.grade-pill.f{color:var(--grade-f)}.grade-letter{font-family:var(--serif);font-style:italic;font-weight:900;font-size:112px;line-height:1}.grade-score{font-size:13px;letter-spacing:0}.verdict-body{display:flex;flex-direction:column;gap:18px}.verdict-headline{font-family:var(--serif);font-style:italic;font-weight:600;font-size:38px;line-height:1.15}.verdict-headline em{color:var(--forge)}.verdict-stats{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid var(--rule);padding-top:20px}.stat{border-right:1px solid var(--rule);padding:0 18px}.stat:first-child{padding-left:0}.stat:last-child{border-right:0}.verdict-stats .num{font-family:var(--serif);font-weight:800;font-size:32px;line-height:1}.verdict-stats .num.warn{color:var(--grade-c)}.verdict-stats .num.fail{color:var(--grade-f)}.verdict-stats .num.note{color:var(--advisory)}.lbl{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-top:8px}.pillars,.offenders,.chart-section{padding:48px 0;border-bottom:1px solid var(--rule)}.pillar-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--rule);border:1px solid var(--rule)}.pillar{background:var(--ink-2);padding:24px 20px;display:flex;flex-direction:column;gap:14px}.pillar .name{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute)}.pillar .grade{font-family:var(--serif);font-weight:800;font-style:italic;font-size:52px;line-height:.9}.breakdown{font-size:11px;color:var(--paper-dim);line-height:1.7}.row{display:flex;justify-content:space-between;gap:8px}.key{color:var(--paper-mute)}table{width:100%;border-collapse:collapse;font-size:13px;table-layout:auto;font-family:var(--mono)}th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);font-weight:500;padding:12px 14px 12px 0;border-bottom:1px solid var(--rule)}th:last-child,td:last-child{padding-right:0}th.num,td.num{text-align:right;padding-left:18px}td{padding:14px 14px 14px 0;border-bottom:1px solid var(--ink-3);color:var(--paper-dim);font-size:13px;font-family:var(--mono);font-weight:500;line-height:1.4}td.num{color:var(--paper);font-variant-numeric:tabular-nums}.file-path{color:var(--paper);font-weight:500}.grade-pill{display:inline-block;font-family:var(--serif);font-style:italic;font-weight:800;font-size:18px;line-height:1;padding:4px 10px;border:1.5px solid currentColor;min-width:36px;text-align:center}.chart-summary{color:var(--paper-dim);font-size:12px;margin:-6px 0 18px}.chart-card{border:1px solid var(--rule);padding:24px;background:var(--ink-3)}.title{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-bottom:24px}.histogram{display:flex;align-items:flex-end;gap:6px;height:180px;padding-bottom:20px;border-bottom:1px solid var(--rule)}.bar{flex:1;background:var(--forge);position:relative;min-height:4px}.bar.warn{background:var(--grade-c)}.bar.fail{background:var(--grade-f)}.bar .count{position:absolute;top:-22px;left:50%;transform:translateX(-50%);font-size:11px}.histogram-axis{display:flex;gap:6px;margin-top:8px;font-size:10px;color:var(--paper-mute)}.histogram-axis span{flex:1;text-align:center}.findings{padding:48px 0}.finding{display:grid;grid-template-columns:auto 1fr auto;gap:24px;padding:18px 0;border-bottom:1px solid var(--ink-3);align-items:start}.severity{font-size:9px;text-transform:uppercase;letter-spacing:0;padding:4px 10px;border:1px solid currentColor;margin-top:2px;min-width:76px;text-align:center}.severity.fail{color:var(--grade-f)}.severity.warn{color:var(--grade-c)}.severity.note{color:var(--paper-mute)}.rule{font-size:10px;color:var(--forge);text-transform:uppercase;letter-spacing:0;margin-bottom:6px;font-family:var(--mono);font-weight:700;line-height:1.5}.msg{font-family:var(--serif);font-weight:500;font-size:17px;color:var(--paper);line-height:1.4}.loc{font-size:11px;color:var(--paper-mute);margin-top:8px}.loc code{color:var(--paper-dim);background:var(--ink-3);padding:1px 6px;border:1px solid var(--rule)}.loc-link{color:inherit;text-decoration:none}.loc-link:focus-visible{outline:2px solid var(--forge);outline-offset:3px}.points{font-size:10px;color:var(--paper-mute);text-align:right;letter-spacing:0;min-width:96px;padding-left:12px}.empty{color:var(--paper-dim);font-size:12px}.footer{margin-top:48px;padding-top:24px;border-top:1px solid var(--rule);display:grid;grid-template-columns:1fr auto 1fr;gap:24px;align-items:center;font-size:10px;color:var(--paper-mute);letter-spacing:0;text-transform:uppercase}.center{font-family:var(--serif);font-style:italic;font-size:13px;color:var(--paper-dim);text-transform:none;letter-spacing:0}.right{text-align:right}@media(max-width:900px){body{padding:16px}.paper{padding:28px 20px}.wordmark{font-size:64px}.masthead,.verdict{grid-template-columns:1fr}.meta{text-align:left}.grade-stamp{margin:0 auto}.pillar-grid{grid-template-columns:repeat(2,1fr)}.verdict-stats{grid-template-columns:repeat(2,1fr);gap:16px}.stat{border-right:0;padding:0}.verdict-headline{font-size:28px}.footer{grid-template-columns:1fr}.center,.right{text-align:left}}@media(max-width:560px){.pillar-grid{grid-template-columns:1fr}.finding{grid-template-columns:1fr}.points{text-align:left;padding-left:0}.verdict-stats{grid-template-columns:1fr}.histogram{height:140px}}`;
611
- const reportCss = `${baseCss}.dashboard-context{padding:28px 0;border-bottom:1px solid var(--rule)}.dashboard-context-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dashboard-context-grid>div{border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px}.dashboard-context .label{display:block;margin:0 0 6px}.dashboard-context .val{overflow-wrap:anywhere}@media(max-width:700px){.dashboard-context-grid{grid-template-columns:1fr}}@media(max-width:560px){.offender-list thead{display:none}.offender-list,.offender-list tbody,.offender-list tr,.offender-list td{display:block;width:100%}.offender-list tr{border-bottom:1px solid var(--ink-3);padding:10px 0}.offender-list td{border-bottom:0;padding:6px 0}.offender-list td.num{text-align:left;padding-left:0}}`;
612
- if (!shouldIncludeDiagnostics) {
613
- return reportCss;
614
- }
615
- return `${reportCss}.diagnostics{padding:28px 0 0}.diagnostic-list{display:grid;gap:10px}.diagnostic{display:grid;grid-template-columns:auto 1fr;gap:10px 14px;border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px;color:var(--paper-dim);font-size:12px}.diagnostic-type{text-transform:uppercase;letter-spacing:0;color:var(--forge);font-size:10px}.diagnostic-location{grid-column:2;color:var(--paper-mute);font-size:11px}`;
616
- }
617
-
618
- // Top-level dashboard chrome: iframe that loads the scan + a slide-out controls panel. The iframe
619
- // arrangement is what lets the dashboard reload scans without losing the control form state.
620
- function dashboardHomeHtml(projectRoot: string, scanPath: string): string {
621
- const initialScan = dashboardScanUrl(projectRoot, scanPath);
622
- return `<!doctype html>
623
- <html lang="en">
624
- <head>
625
- <meta charset="utf-8">
626
- <meta name="viewport" content="width=device-width, initial-scale=1">
627
- <title>gruff-ts dashboard</title>
628
- <style>${dashboardCss()}</style>
629
- </head>
630
- <body>
631
- <iframe class="report-frame" name="report-frame" title="gruff-ts report" src="${escapeHtml(initialScan)}"></iframe>
632
- <button class="controls-toggle" type="button" aria-expanded="false" aria-controls="controls-panel" title="Dashboard controls">&#9881;</button>
633
- <aside class="controls-panel" id="controls-panel" hidden>
634
- <header class="controls-head">
635
- <h1>Dashboard controls</h1>
636
- <p>local scan settings</p>
637
- </header>
638
- <form class="scan-form" data-scan-form action="/scan" method="get" target="report-frame">
639
- <label>Project root <input name="projectRoot" value="${escapeHtml(projectRoot)}" autocomplete="off"></label>
640
- <label>Paths <input name="path" value="${escapeHtml(scanPath)}" autocomplete="off"></label>
641
- <div class="scan-state"><span>Status</span><strong data-scan-status>Loading report</strong></div>
642
- <div class="actions">
643
- <button class="secondary" type="button" data-refresh>Refresh</button>
644
- <button type="submit">Run scan</button>
645
- </div>
646
- </form>
647
- </aside>
648
- <script>${dashboardJs()}</script>
649
- </body>
650
- </html>`;
651
- }
652
-
653
- // URLSearchParams handles encoding so the projectRoot/scanPath values are safe to embed in `src`.
654
- function dashboardScanUrl(projectRoot: string, scanPath: string): string {
655
- const params = new URLSearchParams({ projectRoot, path: scanPath });
656
- return `/scan?${params.toString()}`;
657
- }
658
-
659
- // Friendly failure page served when `renderDashboardScan` catches an analyser throw. All inputs
660
- // are escaped - `message` is the error text and could contain attacker-controlled file path fragments.
661
- function dashboardErrorHtml(message: string, projectRoot: string, scanPath: string): string {
662
- const escapedMessage = escapeHtml(message);
663
- const escapedProjectRoot = escapeHtml(projectRoot);
664
- const escapedScanPath = escapeHtml(scanPath);
665
- return `<!doctype html>
666
- <html lang="en-NZ">
667
- <head>
668
- <meta charset="utf-8">
669
- <meta name="viewport" content="width=device-width, initial-scale=1">
670
- <title>gruff-ts dashboard scan failed</title>
671
- <style>${dashboardCss()}</style>
672
- </head>
673
- <body class="error-page">
674
- <main class="scan-error">
675
- <h1>Scan failed</h1>
676
- <p>${escapedMessage}</p>
677
- <dl>
678
- <dt>Project root</dt><dd>${escapedProjectRoot}</dd>
679
- <dt>Paths</dt><dd>${escapedScanPath}</dd>
680
- </dl>
681
- </main>
682
- </body>
683
- </html>`;
684
- }
685
-
686
- // Inline stylesheet shared by the dashboard shell and its error page. Inlined (not linked) so the
687
- // dashboard works without separate asset routes - keeping it self-contained matters for offline use.
688
- function dashboardCss(): string {
689
- return `:root{color-scheme:dark;--ink:#0d0c0a;--ink-2:#161412;--panel:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--forge-dark:#b94402;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box}html,body{height:100%;margin:0;background:var(--ink);color:var(--paper);font-family:var(--mono);font-size:14px;line-height:1.5}.report-frame{position:fixed;inset:0;width:100%;height:100%;border:0;background:var(--ink)}.controls-toggle{position:fixed;top:18px;right:18px;z-index:3;width:44px;height:44px;border:1px solid rgba(232,93,4,.75);border-radius:8px;background:var(--forge);color:#170b05;font:700 22px/1 var(--mono);display:grid;place-items:center;cursor:pointer;box-shadow:0 16px 36px rgba(0,0,0,.38)}.controls-toggle:hover,.controls-toggle:focus-visible{background:#ff7a1a;outline:2px solid rgba(243,233,210,.75);outline-offset:3px}.controls-panel{position:fixed;z-index:2;top:74px;right:18px;width:min(420px,calc(100vw - 36px));max-height:calc(100vh - 92px);overflow:auto;background:rgba(31,28,25,.98);border:1px solid var(--rule);border-radius:8px;padding:20px;box-shadow:0 24px 70px rgba(0,0,0,.5)}[hidden]{display:none!important}.controls-head{border-bottom:1px solid var(--rule);padding-bottom:14px;margin-bottom:16px}.controls-head h1{margin:0;font-size:18px;font-weight:800}.controls-head p{margin:4px 0 0;color:var(--paper-mute);font-size:12px;text-transform:uppercase}.scan-form{display:grid;gap:14px}.scan-form label{display:grid;gap:6px;color:var(--paper-dim);font-size:12px;text-transform:uppercase}.scan-form input{width:100%;font:inherit;color:var(--paper);background:var(--ink-2);border:1px solid var(--rule);border-radius:6px;padding:10px 11px;min-width:0}.scan-form input:focus{outline:2px solid var(--forge);outline-offset:2px}.scan-state{display:flex;justify-content:space-between;gap:12px;border:1px solid var(--rule);background:var(--ink-2);border-radius:6px;padding:10px 11px;color:var(--paper-mute)}.scan-state strong{color:var(--paper);font-weight:700;text-align:right}.actions{display:grid;grid-template-columns:1fr 1fr;gap:10px}.actions button{font:inherit;border:1px solid var(--forge);border-radius:6px;padding:10px 12px;background:var(--forge);color:#170b05;font-weight:800;cursor:pointer}.actions button.secondary{background:transparent;color:var(--paper);border-color:var(--rule)}.actions button:disabled{opacity:.6;cursor:wait}.scan-error{max-width:720px;margin:8vh auto;padding:48px;background:var(--panel);border:1px solid var(--rule);color:var(--paper)}.scan-error h1{margin:0 0 16px;font-size:28px}.scan-error p{color:var(--paper-dim);overflow-wrap:anywhere}.scan-error dl{display:grid;grid-template-columns:auto 1fr;gap:8px 16px;margin:24px 0 0}.scan-error dt{color:var(--paper-mute);text-transform:uppercase}.scan-error dd{margin:0;overflow-wrap:anywhere}@media(max-width:560px){.controls-toggle{top:12px;right:12px}.controls-panel{top:64px;right:12px;width:calc(100vw - 24px);max-height:calc(100vh - 76px);padding:16px}.actions{grid-template-columns:1fr}.scan-error{margin:0;min-height:100vh;padding:28px 20px}.scan-error dl{grid-template-columns:1fr}}`;
690
- }
691
-
692
- // Inline `<script>` body served with the dashboard shell. Updates the URL via history.replaceState
693
- // so a maintainer can copy the current scan's URL and reproduce it later without re-typing controls.
694
- function dashboardJs(): string {
695
- return `const form=document.querySelector("[data-scan-form]");const frame=document.querySelector(".report-frame");const toggle=document.querySelector(".controls-toggle");const panel=document.querySelector(".controls-panel");const refresh=document.querySelector("[data-refresh]");const status=document.querySelector("[data-scan-status]");function setOpen(open){panel.hidden=!open;toggle.setAttribute("aria-expanded",String(open));if(open){const input=form.querySelector("input");if(input){input.focus();}}}function params(){return new URLSearchParams(new FormData(form));}function runScan(){const query=params();status.textContent="Scanning";refresh.disabled=true;form.querySelector("button[type=submit]").disabled=true;frame.src="/scan?"+query.toString();history.replaceState(null,"","/?"+query.toString());}toggle.addEventListener("click",()=>setOpen(panel.hidden));document.addEventListener("keydown",(event)=>{if(event.key==="Escape"){setOpen(false);}});form.addEventListener("submit",(event)=>{event.preventDefault();runScan();});refresh.addEventListener("click",runScan);frame.addEventListener("load",()=>{status.textContent="Ready";refresh.disabled=false;form.querySelector("button[type=submit]").disabled=false;});`;
696
- }
697
-
698
- // Composite-score → letter grade conversion. 90/80/70/60 boundaries are part of the stable rule
699
- // surface; changing them would shift every historical report grade and the headline on the dashboard.
700
- function grade(score: number): string {
701
- if (score >= 90) {
702
- return "A";
703
- }
704
- if (score >= 80) {
705
- return "B";
706
- }
707
- if (score >= 70) {
708
- return "C";
709
- }
710
- if (score >= 60) {
711
- return "D";
712
- }
713
- return "F";
714
- }
715
-
716
477
  // Three GitHub annotation levels - gruff's "advisory" collapses to "notice" because Actions has
717
478
  // no fourth tier and "notice" is the documented soft-warning level.
718
479
  function githubLevel(severity: Severity): "notice" | "warning" | "error" {
@@ -731,10 +492,4 @@ function escapeCommandProperty(propertyText: string): string {
731
492
  return escapeCommand(propertyText).replaceAll(":", "%3A").replaceAll(",", "%2C");
732
493
  }
733
494
 
734
- // Four-character HTML entity escape (`&`, `<`, `>`, `"`). `&` must be first so the other entities
735
- // don't get double-encoded; missing escapes here would enable script injection in archived reports.
736
- function escapeHtml(htmlText: string): string {
737
- return htmlText.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
738
- }
739
-
740
- export { dashboardErrorHtml, dashboardHomeHtml, grade, renderHtml, renderReport, renderSummary, renderSummaryJson };
495
+ export { renderReport, renderSummary, renderSummaryJson };