repometry 0.6.1 → 0.7.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 (104) hide show
  1. package/package.json +1 -1
  2. package/target/main/resources/config/process-plugins-v1.schema.json +75 -0
  3. package/target/main/resources/report/json/report-v2.schema.json +21 -1
  4. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  5. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +11 -3
  6. package/target/main/resources/viewer/files.css +6 -0
  7. package/target/main/resources/viewer/index.html +1 -1
  8. package/target/main/resources/viewer/styles.css +1 -0
  9. package/target/main/ts/cli/config.d.ts +1 -0
  10. package/target/main/ts/cli/config.js +3 -2
  11. package/target/main/ts/cli/main.js +37 -19
  12. package/target/main/ts/cli/reporting.js +3 -3
  13. package/target/main/ts/compose/analysis-files.d.ts +1 -0
  14. package/target/main/ts/compose/analysis-files.js +27 -7
  15. package/target/main/ts/compose/analysis-imports.js +2 -1
  16. package/target/main/ts/compose/analysis-report.js +9 -5
  17. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  18. package/target/main/ts/compose/analysis-results.js +3 -0
  19. package/target/main/ts/compose/analysis-sources.d.ts +2 -32
  20. package/target/main/ts/compose/analysis-sources.js +4 -4
  21. package/target/main/ts/compose/languages.js +4 -1
  22. package/target/main/ts/compose/plugin-list.d.ts +11 -2
  23. package/target/main/ts/compose/plugin-list.js +6 -3
  24. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  25. package/target/main/ts/compose/process-plugins.js +63 -0
  26. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  27. package/target/main/ts/compose/structure-measures.js +57 -0
  28. package/target/main/ts/core/engine/execute.js +40 -39
  29. package/target/main/ts/core/engine/manifest.js +45 -38
  30. package/target/main/ts/core/model/clone-source.js +0 -1
  31. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  32. package/target/main/ts/core/model/code-structure.js +23 -10
  33. package/target/main/ts/core/model/language.d.ts +2 -0
  34. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  35. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  36. package/target/main/ts/core/model/quality-summary.js +53 -29
  37. package/target/main/ts/core/model/report.d.ts +8 -0
  38. package/target/main/ts/core/model/report.js +20 -0
  39. package/target/main/ts/core/usecases/compare.js +3 -4
  40. package/target/main/ts/index.d.ts +3 -2
  41. package/target/main/ts/index.js +2 -1
  42. package/target/main/ts/plugin.d.ts +1 -1
  43. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  44. package/target/main/ts/plugins/coverage/coverage.js +106 -108
  45. package/target/main/ts/plugins/duplication/duplication.js +2 -3
  46. package/target/main/ts/plugins/language-js/babel-provider.js +1 -1
  47. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  48. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  49. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  50. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  51. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  52. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  53. package/target/main/ts/plugins/security/dockerfile.js +45 -37
  54. package/target/main/ts/plugins/structure/structure.js +2 -2
  55. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  56. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  57. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  58. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  59. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  60. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  61. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  62. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  63. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  64. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  65. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  66. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  67. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  68. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  69. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  70. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  71. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  72. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  73. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  74. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  75. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  76. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  77. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  78. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  79. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  80. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  81. package/target/main/ts/report/html/app/viewer-profile.js +15 -1
  82. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  83. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  84. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  85. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  86. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  87. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  88. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  89. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  90. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  91. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  92. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  93. package/target/main/ts/report/html/app/viewer.js +1 -7
  94. package/target/main/ts/report/json/projections/commit-summary.js +5 -0
  95. package/target/main/ts/report/json/projections/components.d.ts +1 -1
  96. package/target/main/ts/report/json/projections/file-metrics.d.ts +0 -2
  97. package/target/main/ts/report/json/projections/file-metrics.js +69 -66
  98. package/target/main/ts/report/json/projections/inspection-context.d.ts +0 -1
  99. package/target/main/ts/report/json/projections/inspection-context.js +5 -3
  100. package/target/main/ts/report/json/projections/inspection-details.d.ts +0 -1
  101. package/target/main/ts/report/json/projections/inspection-details.js +32 -14
  102. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  103. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  104. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +8 -1
@@ -1,12 +1,11 @@
1
1
  import { plan } from '../core/engine/plan.js';
2
2
  import { coverage } from '../plugins/coverage/coverage.js';
3
3
  import { duplication } from '../plugins/duplication/duplication.js';
4
- import { babelProvider, babelTypes } from '../plugins/language-js/babel-provider.js';
5
4
  import { maintainability } from '../plugins/maintainability/maintainability.js';
6
5
  import { structure } from '../plugins/structure/structure.js';
7
6
  import { claimMatcher, defaultLanguages, languageRegistry } from './languages.js';
8
7
  import { securityPlugins } from './security-plugins.js';
9
- export const structuralInspections = [{ ...structure, tools: babelTypes }, { ...maintainability, tools: babelTypes }];
8
+ export const structuralInspections = [structure, maintainability];
10
9
  export const defaultProvider = defaultLanguages.providers[0];
11
10
  export function inspectionFileMatcher(additional, languages = defaultLanguages) {
12
11
  const matches = [...securityPlugins, ...additional].filter(plugin => !plugin.kinds.includes('language'))
@@ -18,8 +17,9 @@ export function selectAnalysisSources(snapshot, additional, withCoverage) {
18
17
  const sources = snapshot.files.map(file => ({ file, provider: languages.select(file.path) }));
19
18
  const providersByPath = new Map(sources.flatMap(({ file, provider }) => provider ? [[file.path, provider]] : []));
20
19
  const sourceFiles = sources.flatMap(({ file, provider }) => provider ? [file] : []);
21
- const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional];
22
- const plugins = [babelProvider, ...structuralInspections, duplication, ...(withCoverage ? [coverage] : []), ...claimedPlugins];
20
+ const bound = new Map(languages.providers.map(({ plugin }) => [plugin.id, plugin]));
21
+ const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional.map(plugin => bound.get(plugin.id) ?? plugin)];
22
+ const plugins = [defaultProvider.plugin, ...structuralInspections, duplication, ...(withCoverage ? [coverage] : []), ...claimedPlugins];
23
23
  validateRegistration(plugins, additional, withCoverage);
24
24
  const claims = claimedPlugins.map(plugin => ({ plugin, matches: plugin.kinds.includes('language')
25
25
  ? path => providersByPath.get(path)?.plugin.id === plugin.id : claimMatcher(plugin.claims, languages.id) }));
@@ -3,6 +3,7 @@ import { fileTypeId } from '../core/model/file-types.js';
3
3
  import { codeStructure, codeStructures } from '../core/model/code-structure.js';
4
4
  import { isExcludedDirectory } from '../core/model/snapshot.js';
5
5
  import { exclusionMatcher } from '../core/profile/exclusions.js';
6
+ import { restrictStructureMeasures } from './structure-measures.js';
6
7
  import { babelProvider } from '../plugins/language-js/babel-provider.js';
7
8
  export const defaultLanguages = languageRegistry([]);
8
9
  export function languageRegistry(plugins) {
@@ -26,7 +27,9 @@ export function languageRegistry(plugins) {
26
27
  }
27
28
  return found;
28
29
  }
29
- const provider = { plugin, operation, key: `${plugin.id}/${operation.id}`, batch: operation.scope === 'repository', language };
30
+ const bound = restrictStructureMeasures(operation, declared, language);
31
+ const executable = bound === operation ? plugin : { ...plugin, operations: plugin.operations.map(item => item === operation ? bound : item) };
32
+ const provider = { plugin: executable, operation: bound, key: `${plugin.id}/${operation.id}`, batch: operation.scope === 'repository', language };
30
33
  const claims = declared.length ? declared : [plugin.claims];
31
34
  return { provider, claims, matches: declared.length ? (path) => language(path) !== undefined : claimMatcher(plugin.claims) };
32
35
  });
@@ -1,6 +1,15 @@
1
+ import type { Plugin } from '../core/engine/plugin.js';
1
2
  export declare const builtInPlugins: {
2
3
  id: string;
3
4
  version: string;
4
- kinds: readonly import("../plugin.js").PluginKind[];
5
- claims?: import("../plugin.js").FileClaims | undefined;
5
+ kinds: readonly import("../core/engine/plugin.js").PluginKind[];
6
+ claims?: import("../core/engine/plugin.js").FileClaims | undefined;
7
+ providesLanguages?: readonly import("../plugin.js").ProvidedLanguage[] | undefined;
6
8
  }[];
9
+ export declare function describePlugin({ id, version, kinds, claims, providesLanguages }: Pick<Plugin, 'id' | 'version' | 'kinds' | 'claims' | 'providesLanguages'>): {
10
+ id: string;
11
+ version: string;
12
+ kinds: readonly import("../core/engine/plugin.js").PluginKind[];
13
+ claims?: import("../core/engine/plugin.js").FileClaims | undefined;
14
+ providesLanguages?: readonly import("../plugin.js").ProvidedLanguage[] | undefined;
15
+ };
@@ -1,11 +1,14 @@
1
1
  import { coverage } from '../plugins/coverage/coverage.js';
2
2
  import { diffCoverage } from '../plugins/coverage/diff-coverage.js';
3
3
  import { duplication } from '../plugins/duplication/duplication.js';
4
- import { babelProvider } from '../plugins/language-js/babel-provider.js';
5
4
  import { maintainability } from '../plugins/maintainability/maintainability.js';
6
5
  import { structure } from '../plugins/structure/structure.js';
6
+ import { defaultLanguages } from './languages.js';
7
7
  import { sourceProviders } from './sources.js';
8
8
  import { securityPlugins } from './security-plugins.js';
9
- export const builtInPlugins = [babelProvider, structure, maintainability, duplication, coverage, diffCoverage, ...securityPlugins, ...sourceProviders]
10
- .map(({ id, version, kinds, claims }) => ({ id, version, kinds, ...(claims ? { claims } : {}) }));
9
+ export const builtInPlugins = [...defaultLanguages.providers.map(({ plugin }) => plugin), structure, maintainability, duplication, coverage, diffCoverage, ...securityPlugins, ...sourceProviders]
10
+ .map(describePlugin);
11
+ export function describePlugin({ id, version, kinds, claims, providesLanguages }) {
12
+ return { id, version, kinds, ...(claims ? { claims } : {}), ...(providesLanguages ? { providesLanguages } : {}) };
13
+ }
11
14
  //# sourceMappingURL=plugin-list.js.map
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from '../core/engine/plugin.js';
2
+ export declare function readProcessPlugins(value: unknown): readonly Plugin[];
@@ -0,0 +1,63 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import schema from '../../resources/config/process-plugins-v1.schema.json' with { type: 'json' };
3
+ import { DockerToolRunner } from '../api/process/docker-tool-runner.js';
4
+ import { processPlugin } from '../api/process/plugin.js';
5
+ import { pluginApi } from '../core/engine/plugin.js';
6
+ import { codeStructure, codeStructures } from '../core/model/code-structure.js';
7
+ import { sourceFile, sourceFiles } from '../core/model/snapshot.js';
8
+ import { languageRegistry } from './languages.js';
9
+ import { builtInPlugins } from './plugin-list.js';
10
+ let check;
11
+ export function readProcessPlugins(value) {
12
+ if (value === undefined)
13
+ return [];
14
+ const validate = check ??= new Ajv2020().compile(schema);
15
+ if (!validate(value)) {
16
+ const error = validate.errors?.[0];
17
+ throw new Error(`Config plugins${error?.instancePath ?? ''} ${error?.message ?? 'is invalid'}`);
18
+ }
19
+ const ids = new Set(builtInPlugins.map(({ id }) => id));
20
+ const plugins = value.map((definition, index) => {
21
+ if (ids.has(definition.id))
22
+ throw new Error(`Config plugins/${index}/id duplicates plugin ${definition.id}`);
23
+ ids.add(definition.id);
24
+ return configuredPlugin(definition, index);
25
+ });
26
+ languageRegistry(plugins);
27
+ return plugins;
28
+ }
29
+ function configuredPlugin({ id, version, image, command, scope, claims, limits = {}, tools, settings, providesLanguages }, index) {
30
+ const base = `Config plugins/${index}`;
31
+ if (!command[0]?.trim())
32
+ throw new Error(`${base}/command/0 must name an executable`);
33
+ const languages = providesLanguages.map((language, languageIndex) => {
34
+ const selectors = providesLanguages.length === 1 ? { ...claims, ...language } : language;
35
+ if (!selectors.extensions?.length && !selectors.globs?.length) {
36
+ throw new Error(`${base}/providesLanguages/${languageIndex} must claim an extension or glob`);
37
+ }
38
+ return selectors;
39
+ });
40
+ const effective = effectiveClaims(languages, claims, base);
41
+ const repository = scope === 'repository';
42
+ const output = repository ? codeStructures : codeStructure;
43
+ return processPlugin({ id, version, api: pluginApi, kinds: ['language'], tools, claims: effective, providesLanguages: languages,
44
+ ...(settings === undefined ? {} : { settings }),
45
+ produces: [{ contract: output.id, persistence: 'transient' }],
46
+ operations: [{ id: 'parse', role: 'provider', scope, inputs: repository ? { files: sourceFiles } : { source: sourceFile },
47
+ output, argv: command, timeoutMs: limits.timeoutMs ?? 30_000, maxOutputBytes: limits.maxOutputBytes ?? 8 * 1024 * 1024 }],
48
+ }, new DockerToolRunner(image, { memoryBytes: limits.memoryBytes ?? 512 * 1024 * 1024, pidsLimit: limits.pidsLimit ?? 128 }));
49
+ }
50
+ function effectiveClaims(languages, declared, base) {
51
+ const selectors = {};
52
+ for (const key of ['extensions', 'globs']) {
53
+ const union = new Set(languages.flatMap(language => language[key] ?? []));
54
+ const expected = declared?.[key];
55
+ if (expected !== undefined && (expected.length !== union.size || expected.some(value => !union.has(value)))) {
56
+ throw new Error(`${base}/claims/${key} must match the claims of its languages`);
57
+ }
58
+ if (union.size)
59
+ selectors[key] = [...union];
60
+ }
61
+ return selectors;
62
+ }
63
+ //# sourceMappingURL=process-plugins.js.map
@@ -0,0 +1,5 @@
1
+ import type { Operation } from '../core/engine/plugin.js';
2
+ import type { CodeStructure, StructureMeasure } from '../core/model/code-structure.js';
3
+ import type { ProvidedLanguage } from '../core/model/language.js';
4
+ export declare function restrictStructureMeasures(operation: Operation, declared: readonly ProvidedLanguage[], language: (path: string) => string | undefined): Operation;
5
+ export declare function unmeasuredStructure(facts: CodeStructure): readonly StructureMeasure[];
@@ -0,0 +1,57 @@
1
+ import { codeStructure, codeStructures, structureCodeLines } from '../core/model/code-structure.js';
2
+ import { digest } from '../core/model/snapshot.js';
3
+ export function restrictStructureMeasures(operation, declared, language) {
4
+ const measured = new Map(declared.flatMap(entry => entry.measures === undefined ? [] : [[entry.id, entry.measures]]));
5
+ if (!measured.size)
6
+ return operation;
7
+ const implementation = digest(JSON.stringify([operation.implementation ?? operation.execute.toString(), [...measured]]));
8
+ return { ...operation, implementation, async execute(inputs) {
9
+ const value = await operation.execute(inputs);
10
+ if (operation.scope === 'repository')
11
+ return codeStructures.accepts(value) ? value.map(project) : value;
12
+ return codeStructure.accepts(value) ? project(value) : value;
13
+ } };
14
+ function project(facts) {
15
+ const id = language(facts.path);
16
+ const measures = id === undefined ? undefined : measured.get(id);
17
+ return measures === undefined ? facts : selectMeasures(facts, measures);
18
+ }
19
+ }
20
+ function selectMeasures(facts, measures) {
21
+ const selected = { ...facts };
22
+ if (!measures.includes('functions'))
23
+ delete selected.functions;
24
+ if (!measures.includes('cyclomaticComplexity'))
25
+ delete selected.cyclomaticFunctions;
26
+ if (!measures.includes('cognitiveComplexity')) {
27
+ delete selected.cognitiveComplexity;
28
+ delete selected.cognitiveFunctions;
29
+ }
30
+ if (!measures.includes('classes'))
31
+ delete selected.classes;
32
+ if (!measures.includes('commentLines'))
33
+ delete selected.commentLines;
34
+ if (measures.includes('codeLines'))
35
+ selected.codeLines = structureCodeLines(facts);
36
+ else
37
+ delete selected.codeLines;
38
+ if (!measures.includes('duplication'))
39
+ delete selected.clones;
40
+ if (!measures.includes('structuralRules'))
41
+ delete selected.observations;
42
+ return selected;
43
+ }
44
+ export function unmeasuredStructure(facts) {
45
+ const values = {
46
+ functions: facts.functions,
47
+ cyclomaticComplexity: facts.cyclomaticFunctions,
48
+ cognitiveComplexity: facts.cognitiveComplexity,
49
+ classes: facts.classes,
50
+ commentLines: facts.commentLines,
51
+ codeLines: structureCodeLines(facts),
52
+ duplication: facts.clones,
53
+ structuralRules: facts.observations,
54
+ };
55
+ return Object.keys(values).filter(key => values[key] === undefined);
56
+ }
57
+ //# sourceMappingURL=structure-measures.js.map
@@ -3,55 +3,56 @@ export async function execute(plan, external, cache) {
3
3
  const results = new Map();
4
4
  for (const task of plan) {
5
5
  const inputs = new Map();
6
+ const missing = [];
6
7
  for (const [name, binding] of task.inputs) {
7
8
  const producer = 'operation' in binding ? results.get(binding.operation) : undefined;
8
9
  const product = 'external' in binding ? external.get(binding.external)
9
10
  : producer?.state === 'completed' ? producer.product : undefined;
10
11
  if (product)
11
12
  inputs.set(name, product);
13
+ else
14
+ missing.push(name);
12
15
  }
13
- const missing = [...task.inputs.keys()].filter(name => !inputs.has(name));
14
- if (missing.length > 0) {
15
- results.set(task.key, { state: 'blocked', reason: `Unavailable inputs: ${missing.join(', ')}` });
16
- continue;
17
- }
18
- try {
19
- for (const [name, contract] of Object.entries(task.operation.inputs)) {
20
- readInput(inputs, name, contract);
21
- }
22
- const key = cache && operationCacheKey(task, inputs, cache.configurationDigest);
23
- const hit = key && cache ? await readCachedOperation(cache.store, key, task) : undefined;
24
- if (hit) {
25
- results.set(task.key, { state: 'completed', product: hit });
26
- continue;
27
- }
28
- const diagnostics = [];
29
- const context = {
30
- read: (port, contract) => {
31
- if (!Object.hasOwn(task.operation.inputs, port) || task.operation.inputs[port]?.id !== contract.id) {
32
- throw new Error(`Undeclared input contract: ${port} (${contract.id})`);
33
- }
34
- return readInput(inputs, port, contract);
35
- },
36
- emitDiagnostic: message => diagnostics.push(message),
37
- };
38
- const value = await task.operation.execute(context);
39
- const { output } = task.operation;
40
- if (!output.accepts(value))
41
- throw new Error(`Invalid output for ${output.id}`);
42
- if (task.validateOutput && !task.validateOutput(value))
43
- throw new Error(`Output violates the schema for ${output.id}`);
44
- const product = { contract: output.id, value };
45
- if (key && cache && diagnostics.length === 0)
46
- await writeCachedOperation(cache.store, key, product);
47
- results.set(task.key, { state: 'completed', product, ...(diagnostics.length ? { diagnostics } : {}) });
48
- }
49
- catch (error) {
50
- results.set(task.key, { state: 'failed', reason: error instanceof Error ? error.message : String(error) });
51
- }
16
+ results.set(task.key, missing.length
17
+ ? { state: 'blocked', reason: `Unavailable inputs: ${missing.join(', ')}` }
18
+ : await runTask(task, inputs, cache));
52
19
  }
53
20
  return results;
54
21
  }
22
+ async function runTask(task, inputs, cache) {
23
+ try {
24
+ const { operation, validateOutput } = task;
25
+ for (const [name, contract] of Object.entries(operation.inputs))
26
+ readInput(inputs, name, contract);
27
+ const key = cache && operationCacheKey(task, inputs, cache.configurationDigest);
28
+ const hit = key && cache ? await readCachedOperation(cache.store, key, task) : undefined;
29
+ if (hit)
30
+ return { state: 'completed', product: hit };
31
+ const diagnostics = [];
32
+ const context = {
33
+ read: (port, contract) => {
34
+ if (!Object.hasOwn(operation.inputs, port) || operation.inputs[port]?.id !== contract.id) {
35
+ throw new Error(`Undeclared input contract: ${port} (${contract.id})`);
36
+ }
37
+ return readInput(inputs, port, contract);
38
+ },
39
+ emitDiagnostic: message => diagnostics.push(message),
40
+ };
41
+ const value = await operation.execute(context);
42
+ const { output } = operation;
43
+ if (!output.accepts(value))
44
+ throw new Error(`Invalid output for ${output.id}`);
45
+ if (validateOutput && !validateOutput(value))
46
+ throw new Error(`Output violates the schema for ${output.id}`);
47
+ const product = { contract: output.id, value };
48
+ if (key && cache && diagnostics.length === 0)
49
+ await writeCachedOperation(cache.store, key, product);
50
+ return { state: 'completed', product, ...(diagnostics.length ? { diagnostics } : {}) };
51
+ }
52
+ catch (error) {
53
+ return { state: 'failed', reason: error instanceof Error ? error.message : String(error) };
54
+ }
55
+ }
55
56
  function readInput(inputs, port, contract) {
56
57
  const product = inputs.get(port);
57
58
  if (!product || product.contract !== contract.id || !contract.accepts(product.value)) {
@@ -1,5 +1,6 @@
1
1
  import { isRecord } from './plugin.js';
2
2
  import { definitions } from '../model/measurement.js';
3
+ import { structureMeasures } from '../model/code-structure.js';
3
4
  import { isLanguageDisplay } from '../model/language.js';
4
5
  const kinds = new Set(['language', 'analysis', 'coverage', 'security', 'import', 'source']);
5
6
  const persistence = new Set(['report', 'cache', 'transient']);
@@ -17,30 +18,7 @@ export function isCoreReportProduct(contract) {
17
18
  return coreProducts.has(contract);
18
19
  }
19
20
  export function manifestProducts(plugin) {
20
- const { id, kinds: declaredKinds, claims, providesLanguages, produces, rules, config } = plugin;
21
- if (declaredKinds === undefined && claims === undefined && providesLanguages === undefined && produces === undefined) {
22
- throw new Error(`Missing plugin manifest for ${id}. Declare kinds and produces.`);
23
- }
24
- if (Object.hasOwn(plugin, 'languages'))
25
- throw new Error(`Plugin ${id} must declare languages in claims.languages`);
26
- if (!strings(declaredKinds) || declaredKinds.length === 0 || declaredKinds.some(kind => !kinds.has(kind))) {
27
- throw new Error(`Invalid kinds for plugin ${id}`);
28
- }
29
- if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => key === 'scanOnly' ? typeof values !== 'boolean'
30
- : !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
31
- || (key === 'extensions' && values.some(extension => !/^\.[\w-]+$/.test(extension)))))) {
32
- throw new Error(`Invalid file claims for plugin ${id}`);
33
- }
34
- if (providesLanguages !== undefined && (!declaredKinds.includes('language') || !validLanguages(providesLanguages))) {
35
- throw new Error(`Invalid provided languages for plugin ${id}`);
36
- }
37
- if (!Array.isArray(produces))
38
- throw new Error(`Plugin ${id} must declare its products`);
39
- if (rules !== undefined && (!Array.isArray(rules) || !rules.every(isRuleDescriptor)
40
- || new Set(rules.map(rule => rule.id)).size !== rules.length))
41
- throw new Error(`Invalid or duplicate rules for plugin ${id}`);
42
- if (config !== undefined && typeof config !== 'boolean' && !isRecord(config))
43
- throw new Error(`Invalid configuration schema for plugin ${id}`);
21
+ const { id, produces, rules } = manifestDeclarations(plugin);
44
22
  const products = new Map();
45
23
  const catalog = new Map();
46
24
  for (const product of produces) {
@@ -48,8 +26,8 @@ export function manifestProducts(plugin) {
48
26
  || products.has(product.contract))
49
27
  throw new Error(`Invalid or duplicate product for plugin ${id}`);
50
28
  const { contract, schema, metrics } = product;
51
- if ((schema === undefined && product.persistence !== 'transient' && !isCoreReportProduct(contract))
52
- || (schema !== undefined && typeof schema !== 'boolean' && !isRecord(schema))) {
29
+ if (schema === undefined ? product.persistence !== 'transient' && !isCoreReportProduct(contract)
30
+ : typeof schema !== 'boolean' && !isRecord(schema)) {
53
31
  throw new Error(`Missing or invalid product schema for ${contract} in plugin ${id}`);
54
32
  }
55
33
  if (metrics !== undefined && (!Array.isArray(metrics) || !metrics.every(isMetricDescriptor))) {
@@ -63,22 +41,45 @@ export function manifestProducts(plugin) {
63
41
  }
64
42
  products.set(contract, declaration);
65
43
  }
66
- for (const rule of rules ?? []) {
67
- if (rule.measure !== undefined && !catalog.has(rule.measure)) {
68
- throw new Error(`Rule ${rule.id} in plugin ${id} references undeclared metric ${rule.measure}`);
69
- }
70
- }
44
+ const undeclared = rules?.find(rule => rule.measure !== undefined && !catalog.has(rule.measure));
45
+ if (undeclared)
46
+ throw new Error(`Rule ${undeclared.id} in plugin ${id} references undeclared metric ${undeclared.measure}`);
71
47
  for (const metric of catalog.values()) {
72
48
  if (!metric.ratio)
73
49
  continue;
74
- for (const component of [metric.ratio.of, metric.ratio.over]) {
75
- if (component === metric.id || (!catalog.has(component) && !coreMetrics.has(component))) {
76
- throw new Error(`Ratio ${metric.id} in plugin ${id} references invalid component ${component}`);
77
- }
78
- }
50
+ const invalid = [metric.ratio.of, metric.ratio.over].find(component => component === metric.id || (!catalog.has(component) && !coreMetrics.has(component)));
51
+ if (invalid !== undefined)
52
+ throw new Error(`Ratio ${metric.id} in plugin ${id} references invalid component ${invalid}`);
79
53
  }
80
54
  return products;
81
55
  }
56
+ function manifestDeclarations(plugin) {
57
+ const { id, kinds: declaredKinds, claims, providesLanguages, produces, rules, config } = plugin;
58
+ if (declaredKinds === undefined && claims === undefined && providesLanguages === undefined && produces === undefined) {
59
+ throw new Error(`Missing plugin manifest for ${id}. Declare kinds and produces.`);
60
+ }
61
+ if (Object.hasOwn(plugin, 'languages'))
62
+ throw new Error(`Plugin ${id} must declare languages in claims.languages`);
63
+ if (!strings(declaredKinds) || declaredKinds.length === 0 || declaredKinds.some(kind => !kinds.has(kind))) {
64
+ throw new Error(`Invalid kinds for plugin ${id}`);
65
+ }
66
+ if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => key === 'scanOnly' ? typeof values !== 'boolean'
67
+ : !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
68
+ || (key === 'extensions' && !values.every(isExtension))))) {
69
+ throw new Error(`Invalid file claims for plugin ${id}`);
70
+ }
71
+ if (providesLanguages !== undefined && (!declaredKinds.includes('language') || !validLanguages(providesLanguages))) {
72
+ throw new Error(`Invalid provided languages for plugin ${id}`);
73
+ }
74
+ if (!Array.isArray(produces))
75
+ throw new Error(`Plugin ${id} must declare its products`);
76
+ if (rules !== undefined && (!Array.isArray(rules) || !rules.every(isRuleDescriptor)
77
+ || new Set(rules.map(rule => rule.id)).size !== rules.length))
78
+ throw new Error(`Invalid or duplicate rules for plugin ${id}`);
79
+ if (config !== undefined && typeof config !== 'boolean' && !isRecord(config))
80
+ throw new Error(`Invalid configuration schema for plugin ${id}`);
81
+ return { id, produces, rules };
82
+ }
82
83
  function validLanguages(values) {
83
84
  if (!Array.isArray(values) || values.length === 0)
84
85
  return false;
@@ -86,11 +87,14 @@ function validLanguages(values) {
86
87
  for (const value of values) {
87
88
  if (!isRecord(value) || !isLanguageDisplay(value) || ids.has(value.id))
88
89
  return false;
89
- const { extensions, globs } = value;
90
- if (extensions !== undefined && (!strings(extensions) || extensions.some(extension => !/^\.[\w-]+$/.test(extension))))
90
+ const { extensions, globs, measures } = value;
91
+ if (extensions !== undefined && (!strings(extensions) || !extensions.every(isExtension)))
91
92
  return false;
92
93
  if (globs !== undefined && !strings(globs))
93
94
  return false;
95
+ if (measures !== undefined && (!strings(measures) || measures.some(measure => !structureMeasures.includes(measure))
96
+ || measures.includes('duplication') && !measures.includes('codeLines')))
97
+ return false;
94
98
  if (!(Array.isArray(extensions) && extensions.length || Array.isArray(globs) && globs.length))
95
99
  return false;
96
100
  ids.add(value.id);
@@ -114,6 +118,9 @@ export function isMetricDescriptor(value) {
114
118
  && value.bands.every((limit, index, array) => typeof limit === 'number' && Number.isFinite(limit)
115
119
  && (index === 0 || limit > array[index - 1]))));
116
120
  }
121
+ function isExtension(value) {
122
+ return /^\.[\w-]+$/.test(value);
123
+ }
117
124
  function strings(value) {
118
125
  return Array.isArray(value) && value.every(text) && new Set(value).size === value.length;
119
126
  }
@@ -13,4 +13,3 @@ export function isCloneSource(value) {
13
13
  && value.codeLines.every((line, index, lines) => isCount(line) && line > (lines[index - 1] ?? 0))
14
14
  && Array.isArray(value.candidates) && value.candidates.every(isCandidate);
15
15
  }
16
- //# sourceMappingURL=clone-source.js.map
@@ -3,8 +3,11 @@ import type { CloneSource } from './clone-source.js';
3
3
  import type { SourceLineRange } from './source.js';
4
4
  export declare const structuralCheckIds: readonly ['function-parameters', 'return-statements', 'boolean-logic', 'nested-control-flow', 'function-complexity', 'file-complexity'];
5
5
  export type StructuralCheck = typeof structuralCheckIds[number];
6
+ export declare const structureMeasures: readonly ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'classes', 'commentLines', 'codeLines', 'duplication', 'structuralRules'];
7
+ export type StructureMeasure = typeof structureMeasures[number];
6
8
  export interface FunctionComplexity {
7
- readonly name: string;
9
+ /** Functions without a name omit this field. Reports display them as (anonymous). */
10
+ readonly name?: string;
8
11
  readonly line?: number;
9
12
  readonly column?: number;
10
13
  readonly value: number;
@@ -19,17 +22,19 @@ export interface StructuralObservation {
19
22
  export interface CodeStructure {
20
23
  readonly path: string;
21
24
  readonly lines: number;
22
- readonly functions: number;
23
- readonly classes: number;
24
- readonly cognitiveComplexity: number;
25
- readonly commentLines: number;
26
- readonly cyclomaticFunctions: readonly FunctionComplexity[];
27
- readonly cognitiveFunctions: readonly FunctionComplexity[];
25
+ readonly functions?: number;
26
+ readonly classes?: number;
27
+ readonly cognitiveComplexity?: number;
28
+ readonly commentLines?: number;
29
+ readonly cyclomaticFunctions?: readonly FunctionComplexity[];
30
+ readonly cognitiveFunctions?: readonly FunctionComplexity[];
28
31
  /** Sorted, merged lines containing code inside a function body. An empty list means the provider found none. */
29
32
  readonly functionBodies?: readonly SourceLineRange[];
30
- readonly observations: readonly StructuralObservation[];
31
- readonly clones: CloneSource;
33
+ readonly observations?: readonly StructuralObservation[];
34
+ readonly codeLines?: readonly number[];
35
+ readonly clones?: CloneSource;
32
36
  }
33
37
  export declare const codeStructure: DataContract<CodeStructure>;
38
+ export declare function structureCodeLines(value: CodeStructure): readonly number[] | undefined;
34
39
  /** A repository provider returns at most one structure per input path. */
35
40
  export declare const codeStructures: DataContract<readonly CodeStructure[]>;
@@ -5,6 +5,8 @@ export const structuralCheckIds = [
5
5
  'function-parameters', 'return-statements', 'boolean-logic', 'nested-control-flow',
6
6
  'function-complexity', 'file-complexity',
7
7
  ];
8
+ export const structureMeasures = ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'classes',
9
+ 'commentLines', 'codeLines', 'duplication', 'structuralRules'];
8
10
  const checkIds = new Set(structuralCheckIds);
9
11
  function isCount(value) {
10
12
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
@@ -13,7 +15,7 @@ function isPosition(value) {
13
15
  return value === undefined || (isCount(value) && value > 0);
14
16
  }
15
17
  function isFunctionComplexity(value) {
16
- return isRecord(value) && typeof value.name === 'string' && isCount(value.value)
18
+ return isRecord(value) && (value.name === undefined || typeof value.name === 'string') && isCount(value.value)
17
19
  && isPosition(value.line) && isPosition(value.column);
18
20
  }
19
21
  function isObservation(value) {
@@ -23,19 +25,30 @@ function isObservation(value) {
23
25
  export const codeStructure = {
24
26
  id: 'repometry.code-structure/v1',
25
27
  accepts: (value) => isRecord(value)
26
- && typeof value.path === 'string' && isCount(value.lines) && isCount(value.functions) && isCount(value.classes)
27
- && isCount(value.cognitiveComplexity) && isCount(value.commentLines)
28
- && Array.isArray(value.cyclomaticFunctions) && value.cyclomaticFunctions.every(isFunctionComplexity)
29
- && Array.isArray(value.cognitiveFunctions) && value.cognitiveFunctions.every(isFunctionComplexity)
30
- && (value.functionBodies === undefined
31
- || isMergedLineRanges(value.functionBodies) && (value.functionBodies.at(-1)?.[1] ?? 0) <= value.lines)
32
- && Array.isArray(value.observations) && value.observations.every(isObservation)
33
- && isCloneSource(value.clones) && value.clones.path === value.path,
28
+ && typeof value.path === 'string' && isCount(value.lines)
29
+ && [value.functions, value.classes, value.cognitiveComplexity, value.commentLines].every(count => count === undefined || isCount(count))
30
+ && (value.cyclomaticFunctions === undefined || Array.isArray(value.cyclomaticFunctions) && value.cyclomaticFunctions.every(isFunctionComplexity))
31
+ && (value.cognitiveFunctions === undefined || Array.isArray(value.cognitiveFunctions) && value.cognitiveFunctions.every(isFunctionComplexity))
32
+ && (value.functionBodies === undefined || isMergedLineRanges(value.functionBodies) && (value.functionBodies.at(-1)?.[1] ?? 0) <= value.lines)
33
+ && (value.observations === undefined || Array.isArray(value.observations) && value.observations.every(isObservation))
34
+ && (value.codeLines === undefined || Array.isArray(value.codeLines) && isCodeLines(value.codeLines, value.lines))
35
+ && (value.clones === undefined || isCloneSource(value.clones) && value.clones.path === value.path),
34
36
  };
37
+ function isCodeLines(lines, lastLine) {
38
+ let previous = 0;
39
+ for (const line of lines) {
40
+ if (!isCount(line) || line <= previous || line > lastLine)
41
+ return false;
42
+ previous = line;
43
+ }
44
+ return true;
45
+ }
46
+ export function structureCodeLines(value) {
47
+ return value.codeLines ?? value.clones?.codeLines;
48
+ }
35
49
  /** A repository provider returns at most one structure per input path. */
36
50
  export const codeStructures = {
37
51
  id: 'repometry.code-structures/v1',
38
52
  accepts: (value) => Array.isArray(value) && value.every(codeStructure.accepts)
39
53
  && new Set(value.map(({ path }) => path)).size === value.length,
40
54
  };
41
- //# sourceMappingURL=code-structure.js.map
@@ -1,3 +1,4 @@
1
+ import type { StructureMeasure } from './code-structure.js';
1
2
  export interface LanguageDisplay {
2
3
  readonly id: string;
3
4
  readonly label: string;
@@ -10,5 +11,6 @@ export interface LanguageLookup {
10
11
  export interface ProvidedLanguage extends LanguageDisplay {
11
12
  readonly extensions?: readonly string[];
12
13
  readonly globs?: readonly string[];
14
+ readonly measures?: readonly StructureMeasure[];
13
15
  }
14
16
  export declare function isLanguageDisplay(value: unknown): value is LanguageDisplay;
@@ -1,3 +1,4 @@
1
+ import type { StructureMeasure } from './code-structure.js';
1
2
  import type { MetricDescriptor, PluginConfigSchema, RuleDescriptor } from '../engine/plugin.js';
2
3
  import type { InventoryFile } from './source.js';
3
4
  import type { LanguageDisplay } from './language.js';
@@ -26,5 +27,6 @@ export interface PluginData {
26
27
  readonly language: string;
27
28
  readonly analysed: boolean;
28
29
  readonly provider?: string;
30
+ readonly unmeasured?: readonly StructureMeasure[];
29
31
  })[];
30
32
  }
@@ -15,6 +15,10 @@ export interface QualitySummary {
15
15
  readonly effortMinutes: number;
16
16
  readonly debtRatio: number | null;
17
17
  readonly grade: Grade | null;
18
+ readonly gradeCoverage?: {
19
+ readonly measuredFiles: number;
20
+ readonly totalFiles: number;
21
+ };
18
22
  } | null;
19
23
  }
20
24
  interface DebtModel {