reportJson function

Map<String, Object?> reportJson(
  1. ImportGraph graph, {
  2. required String packageName,
  3. required Iterable<String> files,
  4. required List<List<String>> cycles,
  5. required Iterable<String> unreachable,
  6. int featureDepth = 1,
  7. int top = 10,
  8. Map<String, Object?>? dependencies,
})

Everything --report knows, as a JSON-ready map.

files is what the report is about — the in-scope files, library or not. files, unreachable and the two ranked lists hold only those; each of cycles is a whole group, since a cycle cut to the files in scope is not a cycle any more; features and coupling describe the package, because a feature's coupling is to everything outside it. The graph itself is always read whole: fan-in counts an importer that is out of scope, since the import is real either way. top caps the two ranked lists.

Implementation

Map<String, Object?> reportJson(
  ImportGraph graph, {
  required String packageName,
  required Iterable<String> files,
  required List<List<String>> cycles,
  required Iterable<String> unreachable,
  int featureDepth = 1,
  int top = 10,
  Map<String, Object?>? dependencies,
}) {
  final scope = files.toSet();
  final fanIn = graph.fanIn();
  final fanOut = graph.fanOut();
  final dead = unreachable.toSet();
  final cycleOf = <String, int>{};
  for (final (index, group) in cycles.indexed) {
    for (final file in group) {
      cycleOf[file] = index;
    }
  }

  List<Map<String, Object>> top10(Map<String, int> counts) => [
        for (final entry in ranked(counts, scope: scope, top: top))
          {'path': entry.key, 'count': entry.value},
      ];

  return {
    'schemaVersion': reportSchemaVersion,
    'package': packageName,
    'featureDepth': featureDepth,
    'files': [
      for (final file in scope.toList()..sort())
        {
          'path': file,
          'library': graph.isLibraryFile(file),
          'feature': graph.featureOf(file, featureDepth),
          'imports': (graph.edges[file] ?? const <String>{}).toList()..sort(),
          'importedBy': fanIn[file] ?? 0,
          'reachable': !dead.contains(file),
          'cycle': cycleOf[file],
        },
    ],
    'cycles': cycles,
    'unreachable': [
      for (final file in dead.toList()..sort())
        if (scope.contains(file)) file,
    ],
    'metrics': {
      'mostImported': top10(fanIn),
      'mostImporting': top10(fanOut),
      'features': [
        for (final feature in graph.features(featureDepth))
          {
            'name': feature.name,
            'files': feature.files,
            'afferent': feature.afferent,
            'efferent': feature.efferent,
            'instability': feature.instability,
          },
      ],
      'coupling': [
        for (final pair in graph.coupling(featureDepth))
          {'from': pair.from, 'to': pair.to, 'edges': pair.edges},
      ],
    },
    if (dependencies != null) 'dependencies': dependencies,
  };
}