All files / src/semantic domain-inference.ts

98.86% Statements 87/88
84.21% Branches 48/57
100% Functions 8/8
100% Lines 77/77

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                              8x             8x 8x 8x 8x 8x 8x 8x                                           62x   62x 62x 4x 3x   62x 3x 3x 3x 3x 3x 3x 3x               3x           62x 58x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x                 62x 62x 4x 4x     62x 62x                                   8x 8x                 8x                 8x   48x 9x 9x 9x           9x       8x                                   75x 75x                   75x                                       75x       75x 1286x     74x 1011x     55x 46x 116x 116x 225x 225x 225x 3775x         4x           51x 43x 43x 54x 54x 54x 891x         48x    
import type {
  DependencyGraph,
  DomainAssignment,
  DomainSignals,
  ExportInfo,
} from '../types';
import { singularize } from '../utils/string-utils';
 
/**
 * Calculate confidence score for a domain assignment based on signals.
 *
 * @param signals - The set of semantic signals detected for a domain.
 * @returns Numerical confidence score (0-1).
 */
export function calculateDomainConfidence(signals: DomainSignals): number {
  const weights = {
    coUsage: 0.35,
    typeReference: 0.3,
    exportName: 0.15,
    importPath: 0.1,
    folderStructure: 0.1,
  };
  let confidence = 0;
  if (signals.coUsage) confidence += weights.coUsage;
  if (signals.typeReference) confidence += weights.typeReference;
  if (signals.exportName) confidence += weights.exportName;
  if (signals.importPath) confidence += weights.importPath;
  if (signals.folderStructure) confidence += weights.folderStructure;
  return confidence;
}
 
/**
 * Infer domain from semantic analysis (co-usage + types) to identify logical modules.
 *
 * @param file - The file path to infer domain for.
 * @param exportName - The specific export identifier.
 * @param graph - The full dependency graph.
 * @param coUsageMatrix - Matrix of files frequently imported together.
 * @param typeGraph - Map of type references to files.
 * @param exportTypeRefs - Optional list of types referenced by the export.
 * @returns Array of potential domain assignments with confidence scores.
 */
export function inferDomainFromSemantics(
  file: string,
  exportName: string,
  graph: DependencyGraph,
  coUsageMatrix: Map<string, Map<string, number>>,
  typeGraph: Map<string, Set<string>>,
  exportTypeRefs?: string[]
): DomainAssignment[] {
  const domainSignals = new Map<string, DomainSignals>();
 
  const coUsages = coUsageMatrix.get(file) || new Map();
  const strongCoUsages = Array.from(coUsages.entries())
    .filter(([, count]) => count >= 3)
    .map(([coFile]) => coFile);
 
  for (const coFile of strongCoUsages) {
    const coNode = graph.nodes.get(coFile);
    Eif (coNode) {
      for (const exp of coNode.exports) {
        Eif (exp.inferredDomain && exp.inferredDomain !== 'unknown') {
          const domain = exp.inferredDomain;
          Eif (!domainSignals.has(domain)) {
            domainSignals.set(domain, {
              coUsage: false,
              typeReference: false,
              exportName: false,
              importPath: false,
              folderStructure: false,
            });
          }
          domainSignals.get(domain)!.coUsage = true;
        }
      }
    }
  }
 
  if (exportTypeRefs) {
    for (const typeRef of exportTypeRefs) {
      const filesWithType = typeGraph.get(typeRef);
      Eif (filesWithType) {
        for (const typeFile of filesWithType) {
          Iif (typeFile === file) continue;
          const typeNode = graph.nodes.get(typeFile);
          Eif (typeNode) {
            for (const exp of typeNode.exports) {
              Eif (exp.inferredDomain && exp.inferredDomain !== 'unknown') {
                const domain = exp.inferredDomain;
                Eif (!domainSignals.has(domain)) {
                  domainSignals.set(domain, {
                    coUsage: false,
                    typeReference: false,
                    exportName: false,
                    importPath: false,
                    folderStructure: false,
                  });
                }
                domainSignals.get(domain)!.typeReference = true;
              }
            }
          }
        }
      }
    }
  }
 
  const assignments: DomainAssignment[] = [];
  for (const [domain, signals] of domainSignals) {
    const confidence = calculateDomainConfidence(signals);
    Eif (confidence >= 0.3) assignments.push({ domain, confidence, signals });
  }
 
  assignments.sort((a, b) => b.confidence - a.confidence);
  return assignments;
}
 
/**
 * Regex-based export extraction (legacy/fallback)
 *
 * @param content - Source code content.
 * @param filePath - Optional file path for domain context.
 * @param domainOptions - Optional overrides for domain keywords.
 * @param fileImports - Optional list of actual imports for semantic context.
 * @returns Array of extracted export information.
 */
export function extractExports(
  content: string,
  filePath?: string,
  domainOptions?: { domainKeywords?: string[] },
  fileImports?: string[]
): ExportInfo[] {
  const exports: ExportInfo[] = [];
  const patterns = [
    /export\s+function\s+(\w+)/g,
    /export\s+class\s+(\w+)/g,
    /export\s+const\s+(\w+)/g,
    /export\s+type\s+(\w+)/g,
    /export\s+interface\s+(\w+)/g,
    /export\s+default/g,
  ];
 
  const types: ExportInfo['type'][] = [
    'function',
    'class',
    'const',
    'type',
    'interface',
    'default',
  ];
 
  patterns.forEach((pattern, index) => {
    let match;
    while ((match = pattern.exec(content)) !== null) {
      const name = match[1] || 'default';
      const type = types[index];
      const inferredDomain = inferDomain(
        name,
        filePath,
        domainOptions,
        fileImports
      );
      exports.push({ name, type, inferredDomain });
    }
  });
 
  return exports;
}
 
/**
 * Infer domain from name, path, or imports
 *
 * @param name - The identifier name to analyze.
 * @param filePath - Optional file path for structure context.
 * @param domainOptions - Optional overrides for domain keywords.
 * @param fileImports - Optional list of imports for domain context.
 * @returns The inferred domain name (string).
 */
export function inferDomain(
  name: string,
  filePath?: string,
  domainOptions?: { domainKeywords?: string[] },
  fileImports?: string[]
): string {
  const lower = name.toLowerCase();
  const tokens = Array.from(
    new Set(
      lower
        .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
        .replace(/[^a-z0-9]+/gi, ' ')
        .split(' ')
        .filter(Boolean)
    )
  );
 
  const defaultKeywords = [
    'authentication',
    'authorization',
    'payment',
    'invoice',
    'customer',
    'product',
    'order',
    'cart',
    'user',
    'admin',
    'repository',
    'controller',
    'service',
    'config',
    'model',
    'view',
    'auth',
  ];
 
  const domainKeywords = domainOptions?.domainKeywords?.length
    ? [...domainOptions.domainKeywords, ...defaultKeywords]
    : defaultKeywords;
 
  for (const keyword of domainKeywords) {
    if (tokens.includes(keyword)) return keyword;
  }
 
  for (const keyword of domainKeywords) {
    if (lower.includes(keyword)) return keyword;
  }
 
  if (fileImports) {
    for (const importPath of fileImports) {
      const segments = importPath.split('/');
      for (const segment of segments) {
        const segLower = segment.toLowerCase();
        const singularSegment = singularize(segLower);
        for (const keyword of domainKeywords) {
          if (
            singularSegment === keyword ||
            segLower === keyword ||
            segLower.includes(keyword)
          )
            return keyword;
        }
      }
    }
  }
 
  if (filePath) {
    const segments = filePath.split('/');
    for (const segment of segments) {
      const segLower = segment.toLowerCase();
      const singularSegment = singularize(segLower);
      for (const keyword of domainKeywords) {
        if (singularSegment === keyword || segLower === keyword) return keyword;
      }
    }
  }
 
  return 'unknown';
}