repometry 0.5.0 → 0.6.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.
Files changed (115) hide show
  1. package/README.md +35 -17
  2. package/package.json +1 -1
  3. package/target/main/resources/report/json/comparison-v1.schema.json +6 -6
  4. package/target/main/resources/report/json/file-metrics-v1.schema.json +7 -6
  5. package/target/main/resources/report/json/pull-review-v1.schema.json +5 -5
  6. package/target/main/resources/report/json/report-v2.schema.json +197 -10
  7. package/target/main/resources/report/json/repository-summary-v1.schema.json +161 -14
  8. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +518 -6
  9. package/target/main/resources/viewer/styles.css +5 -0
  10. package/target/main/ts/api/git/changes.d.ts +1 -1
  11. package/target/main/ts/api/git/changes.js +3 -3
  12. package/target/main/ts/api/git/commit-metadata.js +6 -4
  13. package/target/main/ts/api/git/git.d.ts +1 -1
  14. package/target/main/ts/api/git/git.js +4 -4
  15. package/target/main/ts/api/git/inspection-source.d.ts +1 -1
  16. package/target/main/ts/api/git/inspection-source.js +3 -3
  17. package/target/main/ts/api/git/local.d.ts +1 -1
  18. package/target/main/ts/api/git/local.js +4 -4
  19. package/target/main/ts/api/worker/remote-executor.d.ts +1 -1
  20. package/target/main/ts/api/worker/remote-executor.js +2 -2
  21. package/target/main/ts/api/worker/worker-protocol.d.ts +2 -2
  22. package/target/main/ts/api/worker/worker-protocol.js +8 -8
  23. package/target/main/ts/api/worker/worker.d.ts +1 -1
  24. package/target/main/ts/api/worker/worker.js +4 -4
  25. package/target/main/ts/cli/main.js +4 -3
  26. package/target/main/ts/cli/reporting.d.ts +1 -1
  27. package/target/main/ts/cli/reporting.js +1 -1
  28. package/target/main/ts/compose/analysis-files.d.ts +13 -0
  29. package/target/main/ts/compose/analysis-files.js +95 -0
  30. package/target/main/ts/compose/analysis-imports.d.ts +7 -0
  31. package/target/main/ts/compose/analysis-imports.js +34 -0
  32. package/target/main/ts/compose/analysis-report.d.ts +5 -0
  33. package/target/main/ts/compose/analysis-report.js +78 -0
  34. package/target/main/ts/compose/analysis-repository.d.ts +6 -0
  35. package/target/main/ts/compose/analysis-repository.js +61 -0
  36. package/target/main/ts/compose/analysis-results.d.ts +38 -0
  37. package/target/main/ts/compose/analysis-results.js +78 -0
  38. package/target/main/ts/compose/analysis-sources.d.ts +73 -0
  39. package/target/main/ts/compose/analysis-sources.js +47 -0
  40. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -2
  41. package/target/main/ts/compose/analyze-snapshot.js +19 -250
  42. package/target/main/ts/compose/diff-coverage.d.ts +2 -0
  43. package/target/main/ts/compose/diff-coverage.js +6 -4
  44. package/target/main/ts/compose/inspect.js +8 -5
  45. package/target/main/ts/compose/languages.d.ts +29 -0
  46. package/target/main/ts/compose/languages.js +87 -0
  47. package/target/main/ts/compose/sources.js +14 -12
  48. package/target/main/ts/core/engine/manifest.d.ts +2 -2
  49. package/target/main/ts/core/engine/manifest.js +25 -5
  50. package/target/main/ts/core/engine/plan.d.ts +2 -4
  51. package/target/main/ts/core/engine/plan.js +13 -15
  52. package/target/main/ts/core/engine/plugin.d.ts +2 -1
  53. package/target/main/ts/core/model/clone-source.d.ts +1 -0
  54. package/target/main/ts/core/model/clone-source.js +1 -0
  55. package/target/main/ts/core/model/code-structure.d.ts +2 -0
  56. package/target/main/ts/core/model/code-structure.js +6 -0
  57. package/target/main/ts/core/model/language.d.ts +10 -0
  58. package/target/main/ts/core/model/language.js +6 -0
  59. package/target/main/ts/core/model/measurement.d.ts +7 -6
  60. package/target/main/ts/core/model/measurement.js +17 -6
  61. package/target/main/ts/core/model/plugin-data.d.ts +3 -0
  62. package/target/main/ts/core/model/quality-summary.js +5 -4
  63. package/target/main/ts/core/model/report.d.ts +1 -2
  64. package/target/main/ts/core/model/report.js +0 -1
  65. package/target/main/ts/core/model/snapshot.d.ts +0 -2
  66. package/target/main/ts/core/model/snapshot.js +0 -6
  67. package/target/main/ts/core/usecases/compare.js +61 -17
  68. package/target/main/ts/core/usecases/inspect.js +2 -2
  69. package/target/main/ts/plugin.d.ts +3 -2
  70. package/target/main/ts/plugin.js +1 -1
  71. package/target/main/ts/plugins/duplication/duplication.js +10 -4
  72. package/target/main/ts/plugins/language-js/babel-provider.js +8 -2
  73. package/target/main/ts/plugins/language-js/extensions.d.ts +3 -0
  74. package/target/main/ts/plugins/language-js/extensions.js +4 -0
  75. package/target/main/ts/plugins/language-js/js-security.js +3 -2
  76. package/target/main/ts/report/html/app/viewer-data.d.ts +1 -1
  77. package/target/main/ts/report/html/app/viewer-data.js +2 -29
  78. package/target/main/ts/report/html/app/viewer-metric-registry.js +7 -7
  79. package/target/main/ts/report/html/app/viewer-overview-cards.js +8 -2
  80. package/target/main/ts/report/html/app/viewer-route.d.ts +2 -2
  81. package/target/main/ts/report/html/app/viewer-route.js +3 -3
  82. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +6 -1
  83. package/target/main/ts/report/html/app/viewer-trend-data.js +6 -2
  84. package/target/main/ts/report/html/app/viewer.js +3 -3
  85. package/target/main/ts/report/html/site/export-site.d.ts +3 -4
  86. package/target/main/ts/report/html/site/export-site.js +24 -41
  87. package/target/main/ts/report/html/site/exported-server.js +2 -1
  88. package/target/main/ts/report/html/site/local-server.d.ts +1 -1
  89. package/target/main/ts/report/html/site/local-server.js +13 -19
  90. package/target/main/ts/report/html/site/projects.js +8 -17
  91. package/target/main/ts/report/json/projections/commit-summary.d.ts +2 -2
  92. package/target/main/ts/report/json/projections/commit-summary.js +18 -19
  93. package/target/main/ts/report/json/projections/file-metrics.js +31 -24
  94. package/target/main/ts/report/json/projections/inspection-context.js +10 -1
  95. package/target/main/ts/report/json/projections/inspection-details.d.ts +1 -1
  96. package/target/main/ts/report/json/projections/inspection-details.js +2 -2
  97. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  98. package/target/main/ts/report/json/projections/metric-values.js +15 -5
  99. package/target/main/ts/report/json/store/pull-review-store.js +1 -2
  100. package/target/main/ts/report/json/validation/report.d.ts +1 -1
  101. package/target/main/ts/report/json/validation/report.js +10 -8
  102. package/target/main/ts/report/json/validation/summary-validation.js +1 -3
  103. package/target/main/ts/report/json/wire/file-metrics-model.d.ts +2 -0
  104. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +0 -5
  105. package/target/main/ts/report/json/wire/public-history-model.d.ts +0 -6
  106. package/target/main/ts/report/json/wire/public-history-model.js +0 -1
  107. package/target/main/ts/report.d.ts +2 -3
  108. package/target/main/ts/report.js +1 -2
  109. package/target/main/resources/report/json/inspection-context-v1.schema.json +0 -172
  110. package/target/main/resources/report/json/public-history-v1.schema.json +0 -50
  111. package/target/main/resources/report/json/quality-history-v1.schema.json +0 -51
  112. package/target/main/resources/report/json/report-v1.schema.json +0 -65
  113. package/target/main/resources/report/json/viewer-details-v1.schema.json +0 -346
  114. package/target/main/ts/report/json/projections/public-history.d.ts +0 -4
  115. package/target/main/ts/report/json/projections/public-history.js +0 -17
@@ -2,7 +2,7 @@ import { isDeepStrictEqual } from 'node:util';
2
2
  import { isRecord } from '../engine/plugin.js';
3
3
  import { normalizeFindingIgnore, partitionFindings } from '../model/finding-ignore.js';
4
4
  import { reportSchema } from '../model/report.js';
5
- import { digest, isSourcePath } from '../model/snapshot.js';
5
+ import { digest } from '../model/snapshot.js';
6
6
  import { normalizeExclusions, sourceExclusionMatcher } from '../profile/exclusions.js';
7
7
  export async function executeInspection(options, ports) {
8
8
  const excludedPaths = normalizeExclusions(options.exclude ?? []);
@@ -28,7 +28,7 @@ export async function executeInspection(options, ports) {
28
28
  appliedConfig: { ...findings.appliedConfig, findingIgnore: ignore },
29
29
  ...(findings.findings === undefined ? {} : partitionFindings(findings.findings, ignore)) };
30
30
  const result = snapshot.subject.kind === 'commit' && ports.recordChurn
31
- ? await ports.recordChurn(filtered, root, snapshot.files.filter(file => isSourcePath(file.path)).map(file => file.path)) : filtered;
31
+ ? await ports.recordChurn(filtered, root, snapshot.files.map(file => file.path)) : filtered;
32
32
  await source.save(result);
33
33
  return result;
34
34
  }
@@ -1,9 +1,10 @@
1
1
  export { pluginApi } from './core/engine/plugin.js';
2
2
  export type { DataContract, InspectionInputs, Operation, Plugin, PluginConfigSchema, Product, RuleDescriptor } from './core/engine/plugin.js';
3
- export type { FileClaims, LegacyPlugin, MetricDescriptor, MetricScope, PluginKind, ProductDeclaration } from './core/engine/plugin.js';
3
+ export type { FileClaims, MetricDescriptor, MetricScope, PluginKind, ProductDeclaration } from './core/engine/plugin.js';
4
4
  export type { OperationCache, OperationCacheOptions } from './core/engine/operation-cache.js';
5
- export { codeStructure } from './core/model/code-structure.js';
5
+ export { codeStructure, codeStructures } from './core/model/code-structure.js';
6
6
  export type { CodeStructure, FunctionComplexity, StructuralCheck, StructuralObservation } from './core/model/code-structure.js';
7
+ export type { LanguageDisplay, ProvidedLanguage } from './core/model/language.js';
7
8
  export type { Candidate, CloneSource } from './core/model/clone-source.js';
8
9
  export { sourceFile, sourceFiles } from './core/model/snapshot.js';
9
10
  export type { InventoryFile, SourceFile, SourceSnapshot } from './core/model/source.js';
@@ -1,5 +1,5 @@
1
1
  export { pluginApi } from './core/engine/plugin.js';
2
- export { codeStructure } from './core/model/code-structure.js';
2
+ export { codeStructure, codeStructures } from './core/model/code-structure.js';
3
3
  export { sourceFile, sourceFiles } from './core/model/snapshot.js';
4
4
  export { measurements } from './core/model/measurement.js';
5
5
  export { findingResult } from './core/model/finding.js';
@@ -5,7 +5,7 @@ import { definitions } from '../../core/model/measurement.js';
5
5
  import { isCloneSource } from '../../core/model/clone-source.js';
6
6
  import { duplicationSettings } from '../../core/profile/maintainability.js';
7
7
  const cloneSources = {
8
- id: 'repometry.clone-sources-babel/v1',
8
+ id: 'repometry.clone-sources/v1',
9
9
  accepts: (value) => Array.isArray(value) && value.every(isCloneSource),
10
10
  };
11
11
  export const duplication = {
@@ -22,8 +22,14 @@ export const duplication = {
22
22
  };
23
23
  export const duplicationInput = cloneSources;
24
24
  function detectClones(sources) {
25
- const byFingerprint = new Map();
26
- for (const { path, candidates } of sources) {
25
+ const schemes = new Map();
26
+ for (const { path, candidates, scheme } of sources) {
27
+ const name = scheme ?? 'babel-syntax';
28
+ let byFingerprint = schemes.get(name);
29
+ if (!byFingerprint) {
30
+ byFingerprint = new Map();
31
+ schemes.set(name, byFingerprint);
32
+ }
27
33
  for (const candidate of candidates) {
28
34
  const occurrences = byFingerprint.get(candidate.similar);
29
35
  const occurrence = { ...candidate, path };
@@ -33,7 +39,7 @@ function detectClones(sources) {
33
39
  byFingerprint.set(candidate.similar, [occurrence]);
34
40
  }
35
41
  }
36
- const groups = [...byFingerprint.values()].filter(group => group.length > 1)
42
+ const groups = [...schemes.values()].flatMap(byFingerprint => [...byFingerprint.values()].filter(group => group.length > 1))
37
43
  .sort((left, right) => right[0].nodes - left[0].nodes || comparePaths(left[0].similar, right[0].similar));
38
44
  const matched = new Map(sources.map(source => [source.path, []]));
39
45
  const findings = [];
@@ -3,11 +3,12 @@ import { extname } from 'node:path';
3
3
  import { parse } from '@babel/parser';
4
4
  import { pluginApi } from '../../core/engine/plugin.js';
5
5
  import { codeStructure } from '../../core/model/code-structure.js';
6
- import { physicalLines, sourceExtensions, sourceFile, utf8 } from '../../core/model/snapshot.js';
6
+ import { physicalLines, sourceFile, utf8 } from '../../core/model/snapshot.js';
7
7
  import { cloneCandidates } from './clone-candidates.js';
8
8
  import { classifyLines } from './code-lines.js';
9
9
  import { functionFacts } from './function-facts.js';
10
10
  import { structuralObservations } from './structural-observations.js';
11
+ import { javaScriptExtensions, jsTsExtensions, typeScriptExtensions } from './extensions.js';
11
12
  const require = createRequire(import.meta.url);
12
13
  export const parserDefaults = { sourceType: 'unambiguous', errorRecovery: false, attachComment: false };
13
14
  export const babelTypes = { '@babel/types': require('@babel/types/package.json').version };
@@ -16,7 +17,12 @@ export const babelProvider = {
16
17
  version: '1.0.0',
17
18
  api: pluginApi,
18
19
  kinds: ['language'],
19
- claims: { extensions: sourceExtensions, languages: ['javascript', 'typescript'] },
20
+ claims: { extensions: jsTsExtensions, languages: ['javascript', 'typescript'] },
21
+ providesLanguages: [
22
+ { id: 'javascript', label: 'JavaScript', color: '#f1e05a', extensions: javaScriptExtensions },
23
+ { id: 'typescript', label: 'TypeScript', color: '#3178c6', extensions: typeScriptExtensions },
24
+ ],
25
+ settings: parserDefaults,
20
26
  produces: [{ contract: codeStructure.id, persistence: 'transient' }],
21
27
  tools: { '@babel/parser': require('@babel/parser/package.json').version },
22
28
  operations: [{
@@ -0,0 +1,3 @@
1
+ export declare const javaScriptExtensions: readonly ['.js', '.mjs', '.cjs', '.jsx'];
2
+ export declare const typeScriptExtensions: readonly ['.ts', '.mts', '.cts', '.tsx'];
3
+ export declare const jsTsExtensions: readonly [".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"];
@@ -0,0 +1,4 @@
1
+ export const javaScriptExtensions = ['.js', '.mjs', '.cjs', '.jsx'];
2
+ export const typeScriptExtensions = ['.ts', '.mts', '.cts', '.tsx'];
3
+ export const jsTsExtensions = [...javaScriptExtensions, ...typeScriptExtensions];
4
+ //# sourceMappingURL=extensions.js.map
@@ -3,7 +3,8 @@ import { extname } from 'node:path';
3
3
  import { parse } from '@babel/parser';
4
4
  import { pluginApi } from '../../core/engine/plugin.js';
5
5
  import { findingResult } from '../../core/model/finding.js';
6
- import { sourceExtensions, sourceFile, utf8 } from '../../core/model/snapshot.js';
6
+ import { sourceFile, utf8 } from '../../core/model/snapshot.js';
7
+ import { jsTsExtensions } from './extensions.js';
7
8
  import { babelTypes, parserDefaults } from './babel-provider.js';
8
9
  import { children } from './function-facts.js';
9
10
  const require = createRequire(import.meta.url);
@@ -42,7 +43,7 @@ export const jsSecurity = {
42
43
  version: '1.0.0',
43
44
  api: pluginApi,
44
45
  kinds: ['security'],
45
- claims: { extensions: sourceExtensions },
46
+ claims: { extensions: jsTsExtensions },
46
47
  produces: [{ contract: findingResult.id, persistence: 'report' }],
47
48
  tools: { '@babel/parser': require('@babel/parser/package.json').version, ...babelTypes },
48
49
  rules: jsSecurityRules,
@@ -7,7 +7,7 @@ export interface ViewerData {
7
7
  readonly reports: readonly PublicHistoryEntry[];
8
8
  readonly quality: QualityHistory['reports'];
9
9
  readonly context: Record<string, InspectionContext>;
10
- readonly counts?: Record<string, InspectionCounts | undefined>;
10
+ readonly counts: Record<string, InspectionCounts | undefined>;
11
11
  readonly pullReviewCount?: number;
12
12
  /** The branch whose first-parent history the commits are, when the configuration names it. */
13
13
  readonly branch?: string;
@@ -1,6 +1,6 @@
1
+ // The viewer's data: the repository summary, which lists every inspected commit, and each commit's inspection on demand.
1
2
  import { unpackJson } from '../../json/wire/compact-json.js';
2
3
  import { summarySchema } from '../../json/wire/summary-model.js';
3
- import { compareHistoryEntries, historySchema } from '../../json/wire/public-history-model.js';
4
4
  import { sourceLocator } from './viewer-source.js';
5
5
  const shaPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
6
6
  export class ViewerSummaryChanged extends Error {
@@ -11,8 +11,6 @@ export class ViewerSummaryChanged extends Error {
11
11
  }
12
12
  export async function loadViewerData(mode) {
13
13
  const summary = await readSummary();
14
- if (!summary)
15
- return legacyViewerData(mode);
16
14
  const counts = Object.fromEntries(summary.commits.map(commit => [commit.sha, commit.counts]));
17
15
  const details = new Map(summary.commits.map(commit => [commit.sha, commit.detail]));
18
16
  return {
@@ -47,8 +45,6 @@ export async function loadViewerData(mode) {
47
45
  }
48
46
  async function readSummary(cache) {
49
47
  const response = await fetch('./summary.json', { cache });
50
- if (response.status === 404)
51
- return null;
52
48
  if (!response.ok)
53
49
  throw new Error('Could not load the repository summary');
54
50
  const data = await response.json();
@@ -57,6 +53,7 @@ async function readSummary(cache) {
57
53
  throw new Error('Unsupported repository summary');
58
54
  return data;
59
55
  }
56
+ /** A commit's inspection, where the summary's path names one: `inspection/` when served locally, `details/` in an export. */
60
57
  async function readInspection(path, sha, mode) {
61
58
  const prefix = `${mode === 'local' ? 'inspection' : 'details'}/${sha}-`;
62
59
  const allowed = path.startsWith(prefix) && /^[a-f0-9]{64}\.json$/.test(path.slice(prefix.length));
@@ -70,30 +67,6 @@ async function readInspection(path, sha, mode) {
70
67
  return null;
71
68
  }
72
69
  }
73
- async function legacyViewerData(mode) {
74
- const [history, quality, saved, localContext] = await Promise.all([
75
- readOptional('./history.json'),
76
- readOptional('./quality-history.json'),
77
- mode === 'local' ? null : readOptional('./details.json'),
78
- mode === 'local' ? readOptional('./inspection-context.json') : null,
79
- ]);
80
- if (history?.schema !== historySchema || !Array.isArray(history.reports))
81
- throw new Error('Unsupported history format');
82
- const bundle = saved?.schema === 'urn:repometry:schema:viewer-details:1' ? saved : null;
83
- const context = localContext ?? bundle?.context ?? {};
84
- const reports = [...history.reports].sort(compareHistoryEntries);
85
- return {
86
- reports, context, quality: quality?.schema === 'urn:repometry:schema:quality-history:1' ? quality.reports : {},
87
- async loadDetails(sha) {
88
- if (!shaPattern.test(sha))
89
- return null;
90
- const inspection = mode === 'local'
91
- ? await readOptional(`./details/${sha}.json`)
92
- : bundle?.inspections[sha];
93
- return inspection ? { schema: 'urn:repometry:schema:viewer-inspection:1', sha, context: context[sha], inspection } : null;
94
- },
95
- };
96
- }
97
70
  async function readOptional(path) {
98
71
  try {
99
72
  const response = await fetch(path);
@@ -1,11 +1,11 @@
1
1
  /** Repometry's metrics keep short query words; every other key comes from the descriptor's id. */
2
2
  const builtinKeys = {
3
- 'repometry.cyclomatic-babel/v1': 'complexity',
4
- 'repometry.cognitive-babel/v1': 'cognitive',
5
- 'repometry.code-lines-babel/v1': 'lines',
3
+ 'repometry.cyclomatic-complexity/v1': 'complexity',
4
+ 'repometry.cognitive-complexity/v1': 'cognitive',
5
+ 'repometry.code-lines/v1': 'lines',
6
6
  'repometry.functions/v1': 'functions',
7
7
  'repometry.lcov-line-coverage/v1': 'coverage',
8
- 'repometry.duplicated-lines-babel/v1': 'duplication',
8
+ 'repometry.duplicated-lines/v1': 'duplication',
9
9
  'repometry.git-change-frequency/v1': 'changes',
10
10
  'repometry.lcov-branch-coverage/v1': 'branch-coverage',
11
11
  'repometry.lcov-covered-branches/v1': 'covered-branches',
@@ -16,9 +16,9 @@ const builtinKeys = {
16
16
  };
17
17
  /** The Repometry metrics the viewer draws from typed fields, with their own labels, columns and charts. */
18
18
  const handDrawn = new Set([
19
- 'repometry.physical-lines/v1', 'repometry.functions/v1', 'repometry.cyclomatic-babel/v1', 'repometry.cognitive-babel/v1',
20
- 'repometry.classes-babel/v1', 'repometry.code-lines-babel/v1', 'repometry.comment-lines-babel/v1',
21
- 'repometry.duplicated-lines-babel/v1', 'repometry.lcov-line-coverage/v1', 'repometry.lcov-covered-lines/v1',
19
+ 'repometry.physical-lines/v1', 'repometry.functions/v1', 'repometry.cyclomatic-complexity/v1', 'repometry.cognitive-complexity/v1',
20
+ 'repometry.classes/v1', 'repometry.code-lines/v1', 'repometry.comment-lines/v1',
21
+ 'repometry.duplicated-lines/v1', 'repometry.lcov-line-coverage/v1', 'repometry.lcov-covered-lines/v1',
22
22
  'repometry.lcov-coverable-lines/v1', 'repometry.git-change-frequency/v1',
23
23
  ]);
24
24
  /** Words that already mean something: query keys, Trends views and the series the viewer draws by hand. */
@@ -1,6 +1,6 @@
1
1
  import { byId, count, percent, quantity } from './viewer-dom.js';
2
2
  import { codeSmellCategories, securityCategories } from './viewer-files.js';
3
- import { formatMetric, metricValue, pluginSpec, securityGrades, securityRisks } from './viewer-metrics.js';
3
+ import { coverageGrade, formatMetric, metricValue, pluginSpec, securityGrades, securityRisks } from './viewer-metrics.js';
4
4
  import { href } from './viewer-route.js';
5
5
  /** Coverage kinds beyond lines, by their registry keys, in the words the Overview card uses for them. */
6
6
  const coverageKinds = [['branch-coverage', 'Branches'], ['function-coverage', 'Functions']];
@@ -68,7 +68,13 @@ export function renderInspection(report) {
68
68
  detailText('coverage-detail', 'No coverage report');
69
69
  else
70
70
  detailText('coverage-detail', `${percent(coverage)} of ${count(lines.total)} lines`, coverage < 1 ? uncoveredLink(report.sha) : undefined);
71
- byId('coverage-mark').replaceChildren(ring(coverage));
71
+ const mark = byId('coverage-mark');
72
+ mark.replaceChildren(ring(coverage));
73
+ // The ring is coloured by the grade the coverage badge gives it.
74
+ if (coverage === null)
75
+ delete mark.dataset.grade;
76
+ else
77
+ mark.dataset.grade = coverageGrade(coverage);
72
78
  renderCoverageKinds(report);
73
79
  }
74
80
  export function renderQuality(report, quality) {
@@ -25,8 +25,8 @@ export interface Route {
25
25
  }
26
26
  export declare function href(route: Route): string;
27
27
  export declare function isFilePage(page: Page): page is FilePage;
28
- /** Every page but pull requests reads the inspection's details, and the tabs need them where the summary has no counts. */
29
- export declare function needsDetails(page: Page, counted: boolean): boolean;
28
+ /** The pages that read the inspection's details; the summary's counts serve the rest. */
29
+ export declare function needsDetails(page: Page): boolean;
30
30
  /**
31
31
  * Reads the route from a location hash. A bare commit opens its Overview; an unknown commit reads as the newest one.
32
32
  * Components became a grouping of Metrics, so old links land there.
@@ -16,9 +16,9 @@ export function href(route) {
16
16
  export function isFilePage(page) {
17
17
  return page === 'metrics' || page === 'hotspots' || page === 'issues' || page === 'diagnostics';
18
18
  }
19
- /** Every page but pull requests reads the inspection's details, and the tabs need them where the summary has no counts. */
20
- export function needsDetails(page, counted) {
21
- return isFilePage(page) || page === 'overview' || page === 'settings' || !counted;
19
+ /** The pages that read the inspection's details; the summary's counts serve the rest. */
20
+ export function needsDetails(page) {
21
+ return isFilePage(page) || page === 'overview' || page === 'settings';
22
22
  }
23
23
  /**
24
24
  * Reads the route from a location hash. A bare commit opens its Overview; an unknown commit reads as the newest one.
@@ -9,6 +9,8 @@ export interface TrendData {
9
9
  readonly quality: Record<string, QualitySummary>;
10
10
  readonly context: Record<string, InspectionContext> | null;
11
11
  readonly compact: boolean;
12
+ /** How many pull request reviews are saved: changed-line coverage is a series only where there are some. */
13
+ readonly reviews?: number | undefined;
12
14
  /** Link to the Trends page for a commit, keeping or replacing the view and period. */
13
15
  readonly link: (sha: string, view?: TrendView, period?: Period) => string;
14
16
  }
@@ -24,7 +26,10 @@ export declare function isTrendView(value: string | null | undefined): value is
24
26
  export declare function isPeriod(value: string | null | undefined): value is Period;
25
27
  /** A metric's value at a commit, read with the commit's own quality summary and context. */
26
28
  export declare function trendValue(data: Pick<TrendData, 'quality' | 'context'>, report: PublicHistoryEntry, metric: Metric): number | null;
27
- /** Views that have data in this history, in display order; debt changes need remediation times. */
29
+ /**
30
+ * Views that have data in this history, in display order: debt changes need remediation times, and changed-line
31
+ * coverage needs saved pull request reviews.
32
+ */
28
33
  export declare function availableViews(data: TrendData): TrendView[];
29
34
  /** The whole curve by default; only a very long history opens on its last hundred inspections. */
30
35
  export declare function defaultPeriod(total: number): Period;
@@ -48,10 +48,14 @@ export function isPeriod(value) {
48
48
  export function trendValue(data, report, metric) {
49
49
  return metricValue(report, metric, data.quality[report.sha], data.context?.[report.sha]);
50
50
  }
51
- /** Views that have data in this history, in display order; debt changes need remediation times. */
51
+ /**
52
+ * Views that have data in this history, in display order: debt changes need remediation times, and changed-line
53
+ * coverage needs saved pull request reviews.
54
+ */
52
55
  export function availableViews(data) {
53
56
  const has = (metric) => data.reports.some(report => trendValue(data, report, metric) !== null);
54
- return groups().flatMap(([, views]) => views).filter(view => view === 'diff-coverage' || has(view === 'debt-changes' ? 'effort' : view));
57
+ const shown = (view) => view === 'diff-coverage' ? (data.reviews ?? 0) > 0 : has(view === 'debt-changes' ? 'effort' : view);
58
+ return groups().flatMap(([, views]) => views).filter(shown);
55
59
  }
56
60
  /** The whole curve by default; only a very long history opens on its last hundred inspections. */
57
61
  export function defaultPeriod(total) {
@@ -91,12 +91,12 @@ function start(data) {
91
91
  }
92
92
  function trendData() {
93
93
  return {
94
- reports, quality, context, compact: compact.matches,
94
+ reports, quality, context, compact: compact.matches, reviews: pullReviewCount,
95
95
  link: (sha, view, period) => href({ page: 'trends', sha, view, period }),
96
96
  };
97
97
  }
98
98
  function refreshTabs(page, sha, version, detail) {
99
- const row = counts?.[sha];
99
+ const row = counts[sha];
100
100
  const cachedDetail = cached.get(sha);
101
101
  if (row)
102
102
  updateTabs(page, row.findingCount, row.diagnosticCount);
@@ -208,7 +208,7 @@ function start(data) {
208
208
  if (page === 'overview')
209
209
  renderLead(reports, report, history, chartMetric, cached.get(report.sha));
210
210
  renderScannerContext(context?.[current.sha], report.sha);
211
- const detail = needsDetails(page, Boolean(counts)) ? selectedDetails(report.sha) : undefined;
211
+ const detail = needsDetails(page) ? selectedDetails(report.sha) : undefined;
212
212
  refreshTabs(page, report.sha, version, detail);
213
213
  if (page === 'overview')
214
214
  renderTrend(trendData(), report, chartMetric, compact.matches);
@@ -5,8 +5,6 @@ import type { PullReview } from '../../json/wire/pull-review-model.js';
5
5
  import type { Component } from '../../json/projections/components.js';
6
6
  export interface SiteOptions {
7
7
  readonly title?: string;
8
- /** `local` for `repometry view`, which serves details live; an export writes them as files. */
9
- readonly mode?: 'local' | 'private';
10
8
  readonly components?: readonly Component[];
11
9
  readonly pulls?: readonly PullReview[];
12
10
  readonly sources?: SourceLocator;
@@ -17,6 +15,7 @@ export interface SiteOptions {
17
15
  }
18
16
  /** A page without its footer, for reports published under someone else's name. */
19
17
  export declare function withoutFooter(html: string): string;
20
- export declare function siteFiles(reports: readonly Report[], { title, mode, components, pulls, sources, branch, readCommitMetadata, footer }?: SiteOptions, indexed?: readonly CommitSummary[]): Promise<Map<string, Buffer>>;
21
- export declare function siteSummary(rows: readonly CommitSummary[], { mode, components, pulls, sources, branch }: SiteOptions, details?: Map<string, string>): Buffer;
18
+ export declare function viewerAssets(rows: readonly CommitSummary[], { title, pulls, footer }: SiteOptions): Promise<Map<string, Buffer<ArrayBufferLike>>>;
19
+ export declare function siteFiles(reports: readonly Report[], options?: SiteOptions): Promise<Map<string, Buffer>>;
20
+ export declare function siteSummary(rows: readonly CommitSummary[], { components, pulls, sources, branch }: SiteOptions, inspectionPath?: (row: CommitSummary) => string | undefined): Buffer;
22
21
  export declare function exportSite(reader: ReportReader, destination: string, options?: SiteOptions): Promise<void>;
@@ -1,9 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { historySchema } from '../../json/wire/public-history-model.js';
5
4
  import { inspectionAsset } from '../../json/projections/inspection-details.js';
6
- import { isRecord } from '../../../core/engine/plugin.js';
5
+ import { validateSummaryIndex } from '../../json/validation/summary-validation.js';
7
6
  import { commitSummary, orderSummaries, repositorySummary, withCommitMetadata } from '../../json/projections/commit-summary.js';
8
7
  import { packJson } from '../../json/wire/compact-json.js';
9
8
  import { comparePaths, digest } from '../../../core/model/snapshot.js';
@@ -33,7 +32,7 @@ async function listAssets(directory, include) {
33
32
  export function withoutFooter(html) {
34
33
  return html.replace(/\n[ \t]*<footer class="site-footer">[\s\S]*?<\/footer>/, '');
35
34
  }
36
- export async function siteFiles(reports, { title = '', mode = 'private', components, pulls = [], sources, branch, readCommitMetadata, footer = true } = {}, indexed) {
35
+ export async function viewerAssets(rows, { title = '', pulls = [], footer = true }) {
37
36
  const files = new Map(await Promise.all((await listViewerAssets()).map(async ([name, source]) => {
38
37
  const bytes = await readFile(source);
39
38
  // The published viewer keeps its existing flat URLs for static hosts and open tabs.
@@ -43,42 +42,38 @@ export async function siteFiles(reports, { title = '', mode = 'private', compone
43
42
  return [name, contents];
44
43
  })));
45
44
  const index = files.get('index.html').toString('utf8')
46
- .replace('name="repometry-view" content="private"', `name="repometry-view" content="${mode}"`)
47
45
  .replace('name="repometry-project" content=""', () => `name="repometry-project" content="${escapeAttribute(title)}"`);
48
46
  files.set('index.html', Buffer.from(footer ? index : withoutFooter(index)));
49
- const commits = reports.filter(report => report.subject.kind === 'commit');
50
- const rows = orderSummaries(await withCommitMetadata(indexed ?? commits.map(commitSummary), readCommitMetadata));
51
- const publicRows = rows.map(({ quality, counts, detail, revision, profileDigest, profileBoundary, subject, author, tags, metrics, values, privateMetrics, ...history }) => ({ ...history, subject, author, tags }));
52
- const history = { schema: historySchema, reports: publicRows };
53
- const quality = { schema: 'urn:repometry:schema:quality-history:1',
54
- reports: Object.fromEntries(rows.map(row => [row.sha, row.quality])) };
55
- files.set('history.json', Buffer.from(`${JSON.stringify(history)}\n`));
56
- files.set('quality-history.json', Buffer.from(`${JSON.stringify(quality)}\n`));
57
47
  const latest = rows[0];
58
48
  for (const [name, data] of badges(latest, latest?.quality, latest?.counts?.security))
59
49
  files.set(name, data);
60
50
  files.set('pulls.json', Buffer.from(`${JSON.stringify({ schema: pullReviewsSchema, reviews: pulls })}\n`));
51
+ return files;
52
+ }
53
+ export async function siteFiles(reports, options = {}) {
54
+ const commits = reports.filter(report => report.subject.kind === 'commit');
55
+ const rows = orderSummaries(await withCommitMetadata(commits.map(commitSummary), options.readCommitMetadata));
56
+ const files = await viewerAssets(rows, options);
61
57
  const details = new Map();
62
- if (mode === 'private') {
63
- for (const report of commits) {
64
- const sha = report.subject.id;
65
- const data = JSON.stringify(packJson(inspectionAsset(report, components))) + '\n';
66
- const name = `details/${sha}-${digest(data)}.json`;
67
- details.set(sha, name);
68
- files.set(name, Buffer.from(data));
69
- }
58
+ for (const report of commits) {
59
+ const sha = report.subject.id;
60
+ const data = JSON.stringify(packJson(inspectionAsset(report, options.components))) + '\n';
61
+ const name = `details/${sha}-${digest(data)}.json`;
62
+ details.set(sha, name);
63
+ files.set(name, Buffer.from(data));
70
64
  }
71
- files.set('summary.json', siteSummary(rows, { mode, components, pulls, sources, branch }, details));
65
+ files.set('summary.json', siteSummary(rows, options, row => details.get(row.sha)));
72
66
  return files;
73
67
  }
74
- export function siteSummary(rows, { mode = 'private', components, pulls = [], sources, branch }, details = new Map()) {
68
+ export function siteSummary(rows, { components, pulls = [], sources, branch }, inspectionPath) {
75
69
  const ordered = orderSummaries(rows);
76
- const commits = ordered.map(({ counts, detail, revision, profileDigest, profileBoundary, subject, author, tags, ...row }, index) => {
70
+ const commits = ordered.map((current, index) => {
71
+ const { counts, detail, revision, profileDigest, profileBoundary, subject, author, tags, ...row } = current;
77
72
  const previous = ordered[index + 1];
78
73
  const boundary = !previous ? undefined : !profileDigest || !previous.profileDigest ? 'unavailable'
79
74
  : profileDigest === previous.profileDigest ? undefined : 'changed';
80
75
  return {
81
- ...row, subject, author, tags, detail: mode === 'local' && revision ? `inspection/${row.sha}-${revision}.json` : details.get(row.sha),
76
+ ...row, subject, author, tags, detail: inspectionPath?.(current),
82
77
  counts: counts && { ...counts, componentCount: components?.length ?? 0 },
83
78
  ...(boundary === undefined ? {} : { profileBoundary: boundary }),
84
79
  };
@@ -93,19 +88,10 @@ export async function exportSite(reader, destination, options = {}) {
93
88
  if (!(await lstat(destination)).isDirectory())
94
89
  throw new Error('The viewer destination must be a directory');
95
90
  const entries = await readdir(destination, { withFileTypes: true });
96
- const oldDetails = entries.some(entry => entry.name === 'details.json' && entry.isFile());
97
91
  const detailDirectory = entries.some(entry => entry.name === 'details' && entry.isDirectory());
98
- if (entries.some(entry => !(entry.isFile() && files.has(entry.name))
99
- && !(entry.name === 'details' && entry.isDirectory())
100
- && !(oldDetails && entry.name === 'details.json' && entry.isFile()))) {
92
+ if (entries.some(entry => !(entry.isFile() && files.has(entry.name)) && !(entry.name === 'details' && entry.isDirectory()))) {
101
93
  throw new Error('Use a dedicated viewer destination containing only Repometry export files');
102
94
  }
103
- if (oldDetails) {
104
- const legacy = JSON.parse(await readFile(join(destination, 'details.json'), 'utf8'));
105
- if (!isRecord(legacy) || legacy.schema !== 'urn:repometry:schema:viewer-details:1') {
106
- throw new Error('Existing details.json is not a Repometry export');
107
- }
108
- }
109
95
  if (detailDirectory) {
110
96
  const existing = await readdir(join(destination, 'details'), { withFileTypes: true });
111
97
  if (existing.some(entry => !entry.isFile() || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})-[a-f0-9]{64}\.json$/.test(entry.name))) {
@@ -113,9 +99,9 @@ export async function exportSite(reader, destination, options = {}) {
113
99
  }
114
100
  }
115
101
  if (entries.length > 0) {
116
- const existing = entries.some(entry => entry.name === 'history.json')
117
- ? JSON.parse(await readFile(join(destination, 'history.json'), 'utf8')) : undefined;
118
- if (!isRecord(existing) || existing.schema !== historySchema)
102
+ const existing = entries.some(entry => entry.name === 'summary.json')
103
+ ? JSON.parse(await readFile(join(destination, 'summary.json'), 'utf8')) : undefined;
104
+ if (!validateSummaryIndex(existing))
119
105
  throw new Error('Choose an empty viewer directory or an existing Repometry export');
120
106
  }
121
107
  const staging = join(destination, `.export-${randomUUID()}`);
@@ -128,17 +114,14 @@ export async function exportSite(reader, destination, options = {}) {
128
114
  await writeFile(join(staging, name), bytes, { mode: 0o644 });
129
115
  const afterDependencies = ['viewer.js', 'summary.json', 'index.html'];
130
116
  const install = (name) => rename(join(staging, name), join(destination, name));
131
- await install('history.json');
132
117
  if (hasDetails && !detailDirectory)
133
118
  await mkdir(join(destination, 'details'));
134
119
  for (const name of files.keys()) {
135
- if (name !== 'history.json' && !afterDependencies.includes(name))
120
+ if (!afterDependencies.includes(name))
136
121
  await install(name);
137
122
  }
138
123
  for (const name of afterDependencies)
139
124
  await install(name);
140
- if (oldDetails)
141
- await rm(join(destination, 'details.json'));
142
125
  }
143
126
  finally {
144
127
  await rm(staging, { recursive: true, force: true });
@@ -28,7 +28,8 @@ export async function serveExportedSite(directory, port, access) {
28
28
  const details = new Map(summary.commits.map(row => [row.sha, row.detail]));
29
29
  const local = summary.sources?.provider === 'local' && summary.sources.url === './sources/{revision}/{path}' ? access : undefined;
30
30
  async function file(name) {
31
- if (!/^[A-Za-z0-9_-]+\.(?:html|css|js|json|svg)$/.test(name) && !/^details\/[a-f0-9]+-[a-f0-9]{64}\.json$/.test(name)) {
31
+ if (name !== 'summary.json' && name !== 'pulls.json' && !/^[A-Za-z0-9_-]+\.(?:html|css|js|svg)$/.test(name)
32
+ && !/^details\/[a-f0-9]+-[a-f0-9]{64}\.json$/.test(name)) {
32
33
  return undefined;
33
34
  }
34
35
  const path = join(root, name);
@@ -1,7 +1,7 @@
1
1
  import type { ReportReader } from '../../json/validation/report.js';
2
2
  import type { SiteOptions } from './export-site.js';
3
3
  import type { SourceAccess } from './source-route.js';
4
- export declare function serveSite(reader: ReportReader, port: number, options?: Omit<SiteOptions, 'mode'>, source?: SourceAccess): Promise<{
4
+ export declare function serveSite(reader: ReportReader, port: number, options?: SiteOptions, source?: SourceAccess): Promise<{
5
5
  url: string;
6
6
  close: () => void;
7
7
  }>;
@@ -1,18 +1,19 @@
1
1
  import { reportRevision, validSubjectId } from '../../json/validation/report.js';
2
- import { siteFiles, siteSummary } from './export-site.js';
3
- import { fileMetrics } from '../../json/projections/file-metrics.js';
4
- import { inspectionHistory } from '../../json/projections/inspection-context.js';
5
- import { complexFunctions, inspectionAsset, inspectionDetails } from '../../json/projections/inspection-details.js';
2
+ import { siteSummary, viewerAssets } from './export-site.js';
3
+ import { inspectionAsset } from '../../json/projections/inspection-details.js';
6
4
  import { packJson } from '../../json/wire/compact-json.js';
7
- import { withCommitMetadata } from '../../json/projections/commit-summary.js';
5
+ import { commitSummary, orderSummaries, withCommitMetadata } from '../../json/projections/commit-summary.js';
8
6
  import { serveAssets } from './server.js';
9
7
  import { sourceResponse } from './source-route.js';
10
8
  export async function serveSite(reader, port, options = {}, source) {
11
9
  const indexed = await reader.listSummaries?.();
12
10
  const reports = indexed ? [] : await reader.list();
13
- const siteOptions = { ...options, mode: 'local' };
14
- const files = await siteFiles(reports, siteOptions, indexed);
15
11
  const commits = new Map(reports.filter(report => report.subject.kind === 'commit').map(report => [report.subject.id, report]));
12
+ const rows = orderSummaries(await withCommitMetadata(indexed ?? [...commits.values()].map(commitSummary), options.readCommitMetadata));
13
+ const files = await viewerAssets(rows, options);
14
+ files.set('index.html', Buffer.from(files.get('index.html').toString('utf8')
15
+ .replace('name="repometry-view" content="private"', 'name="repometry-view" content="local"')));
16
+ files.set('summary.json', siteSummary(rows, options, liveInspectionPath));
16
17
  async function read(sha) {
17
18
  if (!validSubjectId('commit', sha))
18
19
  return undefined;
@@ -34,28 +35,21 @@ export async function serveSite(reader, port, options = {}, source) {
34
35
  return report !== undefined && sourceListed(report, path);
35
36
  });
36
37
  if (name === 'summary.json' && reader.listSummaries) {
37
- return siteSummary(await withCommitMetadata(await reader.listSummaries(), options.readCommitMetadata), siteOptions);
38
+ return siteSummary(await withCommitMetadata(await reader.listSummaries(), options.readCommitMetadata), options, liveInspectionPath);
38
39
  }
39
- if (name === 'inspection-context.json')
40
- return Buffer.from(JSON.stringify(inspectionHistory(indexed ? await reader.list() : reports)));
41
40
  const versioned = /^inspection\/([a-f0-9]+)-([a-f0-9]{64})\.json$/.exec(name);
42
41
  if (versioned) {
43
42
  const inspection = await read(versioned[1]);
44
43
  return inspection && reportRevision(inspection) === versioned[2]
45
44
  ? Buffer.from(JSON.stringify(packJson(inspectionAsset(inspection, options.components)))) : undefined;
46
45
  }
47
- const resource = /^(files|details|functions)\/([a-f0-9]+)\.json$/.exec(name);
48
- if (!resource)
49
- return files.get(name);
50
- const inspection = await read(resource[2]);
51
- if (!inspection)
52
- return undefined;
53
- const value = resource[1] === 'files' ? fileMetrics(inspection)
54
- : resource[1] === 'functions' ? complexFunctions(inspection).slice(0, 5) : inspectionDetails(inspection, options.components);
55
- return Buffer.from(JSON.stringify(value));
46
+ return files.get(name);
56
47
  }
57
48
  return serveAssets(port, asset, source?.close);
58
49
  }
50
+ function liveInspectionPath({ sha, revision }) {
51
+ return revision === undefined ? undefined : `inspection/${sha}-${revision}.json`;
52
+ }
59
53
  function sourceListed(report, path) {
60
54
  return (report.pluginData?.inventory ?? []).some(file => file.path === path)
61
55
  || report.measurements.some(row => row.path === path)