# All files graph-builder.ts

91.75% Statements 89/97
81.25% Branches 39/48
100% Functions 9/9
97.67% Lines 84/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259

    17x

    17x
    33x
    33x

    33x
    69x
    69x

    11x

    17x

    11x

    11x
    11x
    11x
    11x

    6x

    18x
    18x

    18x

    18x

    34x
    34x

    34x

    34x
    34x

    34x

    34x

    18x
    18x
    18x

    18x
    18x

    18x
    34x
    52x

    52x
    52x

    18x

    10x

    10x
    10x

    5x
    5x

    5x
    5x

    5x
    5x

    9x

    9x
    9x
    9x

    5x
    5x
    5x
    5x

    5x

    2x
    2x

    2x
    2x

    2x
    2x
    2x

    2x

    3x
    3x
    3x

    8x
    1x
    1x
    1x

    1x

    7x

    6x
    6x
    6x

    6x
    6x
    5x
    4x

    6x

    3x
    5x
    4x

    3x

     import { estimateTokens, parseFileExports } from '@aiready/core';
    import type { DependencyGraph, DependencyNode } from './types';
    import {
      buildCoUsageMatrix,
      buildTypeGraph,
      inferDomainFromSemantics,
    } from './semantic-analysis';
    import { extractExportsWithAST } from './ast-utils';

    interface FileContent {
      file: string;
      content: string;
    }

    /**
     * Auto-detect domain keywords from workspace folder structure
     */
    export function extractDomainKeywordsFromPaths(files: FileContent[]): string[] {
      const folderNames = new Set<string>();

      for (const { file } of files) {
        const segments = file.split('/');
        const skipFolders = new Set([
          'src',
          'lib',
          'dist',
          'build',
          'node_modules',
          'test',
          'tests',
          '__tests__',
          'spec',
          'e2e',
          'scripts',
          'components',
          'utils',
          'helpers',
          'util',
          'helper',
          'api',
          'apis',
        ]);

        for (const segment of segments) {
          const normalized = segment.toLowerCase();
          if (
            normalized &&
            !skipFolders.has(normalized) &&
            !normalized.includes('.')
          ) {
            folderNames.add(singularize(normalized));
          }
        }
      }

      return Array.from(folderNames);
    }

    /**
     * Simple singularization for common English plurals
     */
    function singularize(word: string): string {
      const irregulars: Record<string, string> = {
        people: 'person',
        children: 'child',
        men: 'man',
        women: 'woman',
      };

      Iif (irregulars[word]) return irregulars[word];
      Iif (word.endsWith('ies')) return word.slice(0, -3) + 'y';
      Iif (word.endsWith('ses')) return word.slice(0, -2);
      if (word.endsWith('s') && word.length > 3) return word.slice(0, -1);

      return word;
    }

    /**
     * Build a dependency graph from file contents
     */
    export function buildDependencyGraph(
      files: FileContent[],
      options?: { domainKeywords?: string[] }
    ): DependencyGraph {
      const nodes = new Map<string, DependencyNode>();
      const edges = new Map<string, Set<string>>();

      const autoDetectedKeywords =
        options?.domainKeywords ?? extractDomainKeywordsFromPaths(files);

      for (const { file, content } of files) {
        // 1. Get high-fidelity AST-based imports & exports
        const { imports: astImports } = parseFileExports(content, file);
        const importSources = astImports.map((i) => i.source);

        // 2. Wrap with platform-specific metadata (v0.11+)
        const exports = extractExportsWithAST(
          content,
          file,
          { domainKeywords: autoDetectedKeywords },
          importSources
        );

        const tokenCost = estimateTokens(content);
        const linesOfCode = content.split('\n').length;

        nodes.set(file, {
          file,
          imports: importSources,
          exports,
          tokenCost,
          linesOfCode,
        });
        edges.set(file, new Set(importSources));
      }

      const graph: DependencyGraph = { nodes, edges };
      const coUsageMatrix = buildCoUsageMatrix(graph);
      const typeGraph = buildTypeGraph(graph);

      graph.coUsageMatrix = coUsageMatrix;
      graph.typeGraph = typeGraph;

      for (const [file, node] of nodes) {
        for (const exp of node.exports) {
          const semanticAssignments = inferDomainFromSemantics(
            file,
            exp.name,
            graph,
            coUsageMatrix,
            typeGraph,
            exp.typeReferences
          );
          exp.domains = semanticAssignments;
          Iif (semanticAssignments.length > 0) {
            exp.inferredDomain = semanticAssignments[0].domain;
          }
        }
      }

      return graph;
    }

    /**
     * Calculate the maximum depth of import tree for a file
     */
    export function calculateImportDepth(
      file: string,
      graph: DependencyGraph,
      visited = new Set<string>(),
      depth = 0
    ): number {
      Iif (visited.has(file)) return depth;

      const dependencies = graph.edges.get(file);
      if (!dependencies || dependencies.size === 0) return depth;

      visited.add(file);
      let maxDepth = depth;

      for (const dep of dependencies) {
        maxDepth = Math.max(
          maxDepth,
          calculateImportDepth(dep, graph, visited, depth + 1)
        );
      }

      visited.delete(file);
      return maxDepth;
    }

    /**
     * Get all transitive dependencies for a file
     */
    export function getTransitiveDependencies(
      file: string,
      graph: DependencyGraph,
      visited = new Set<string>()
    ): string[] {
      Iif (visited.has(file)) return [];

      visited.add(file);
      const dependencies = graph.edges.get(file);
      if (!dependencies || dependencies.size === 0) return [];

      const allDeps: string[] = [];
      for (const dep of dependencies) {
        allDeps.push(dep);
        allDeps.push(...getTransitiveDependencies(dep, graph, visited));
      }

      return [...new Set(allDeps)];
    }

    /**
     * Calculate total context budget (tokens needed to understand this file)
     */
    export function calculateContextBudget(
      file: string,
      graph: DependencyGraph
    ): number {
      const node = graph.nodes.get(file);
      Iif (!node) return 0;

      let totalTokens = node.tokenCost;
      const deps = getTransitiveDependencies(file, graph);

      for (const dep of deps) {
        const depNode = graph.nodes.get(dep);
        Iif (depNode) {
          totalTokens += depNode.tokenCost;
        }
      }

      return totalTokens;
    }

    /**
     * Detect circular dependencies
     */
    export function detectCircularDependencies(graph: DependencyGraph): string[][] {
      const cycles: string[][] = [];
      const visited = new Set<string>();
      const recursionStack = new Set<string>();

      function dfs(file: string, path: string[]): void {
        if (recursionStack.has(file)) {
          const cycleStart = path.indexOf(file);
          Eif (cycleStart !== -1) {
            cycles.push([...path.slice(cycleStart), file]);
          }
          return;
        }

        if (visited.has(file)) return;

        visited.add(file);
        recursionStack.add(file);
        path.push(file);

        const dependencies = graph.edges.get(file);
        if (dependencies) {
          for (const dep of dependencies) {
            dfs(dep, [...path]);
          }
        }

        recursionStack.delete(file);
      }

      for (const file of graph.nodes.keys()) {
        if (!visited.has(file)) {
          dfs(file, []);
        }
      }

      return cycles;
    }