All files ts-analyzer.ts

94.07% Statements 127/135
83.09% Branches 59/71
100% Functions 2/2
96% Lines 120/125

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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377                                                          1x                   2x 2x   2x 2x   1x       2x 3x         3x                         5x 5x     2x     3x       3x 3x           140x 140x                                   118x 118x 118x 118x 118x   118x                       28x 28x   28x               118x 118x 118x 118x 118x 118x 118x 118x 118x     1938x 1938x 1938x 1938x 1938x     3x   1x 1x         4x   1x 1x         24x     1x         1x 1x     1x 1x       1x 1x       78x   21x 21x     21x   14x 14x           127x 127x 127x 127x 127x 127x                   127x                                           127x 127x               55x       1x 1x               127x     127x 127x 127x       13x 13x 13x                 13x 13x                     1938x     118x   118x 118x 118x 118x 118x   118x 118x   127x 6x     12x   6x 6x       6x 6x 6x 127x   6x 6x 6x   90x 90x           1x   90x 90x   6x         4x     118x 118x   118x   81x   118x   37x       81x   9x   81x   5x       118x      
import path from 'node:path';
 
import * as ts from 'typescript';
 
import { computeCognitiveComplexity } from './architecture.js';
import { getFunctionName, isFunctionLike } from './ast-helpers.js';
import { collectTopLevelEffects } from './collect-effects.js';
import { collectInputSourceProfile } from './collect-input-sources.js';
import { collectPerformanceData } from './collect-performance.js';
import { collectPrototypePollutionSites } from './collect-prototype-pollution.js';
import { collectSecurityData } from './collect-security.js';
import { collectTestProfile } from './collect-test-profile.js';
import { collectMetrics, computeHalstead, computeMaintainabilityIndex, countLinesInNode } from './metrics.js';
import { TS_CONTROL_KINDS } from './types.js';
import { buildNodeTree, getLineAndCharacter, hashString, increment, isTestFile, makeFingerprint } from './utils.js';
 
import type {
  AnalysisOptions, CodeLocation, DependencyProfile, FileCriticality, FileEntry,
  FlowEntry, FlowMaps, FunctionEntry,
  Location, MagicNumberEntry, Metrics, NodeBudget,
  PackageFileSummary,
  TreeEntry,
} from './types.js';
 
export { isFunctionLike, getFunctionName } from './ast-helpers.js';
export { collectMetrics, computeHalstead, computeMaintainabilityIndex, countLinesInNode } from './metrics.js';
 
export function buildDependencyCriticality(fileSummary: FileEntry | null, options: AnalysisOptions): FileCriticality {
  if (!fileSummary || !Array.isArray(fileSummary.functions)) {
    return {
      file: fileSummary?.file || '<unknown>',
      complexityRisk: 1,
      highComplexityFunctions: 0,
      functionCount: 0,
      flows: 0,
      score: 1,
    };
  }
 
  let totalComplexity = 0;
  let highComplexity = 0;
  for (const fn of fileSummary.functions) {
    const complexity = Number(fn.complexity) || 0;
    totalComplexity += complexity;
    if (complexity >= options.criticalComplexityThreshold) {
      highComplexity += 1;
    }
  }
 
  const flows = fileSummary.flows ? fileSummary.flows.length : 0;
  const score = Math.max(
    1,
    Math.round(totalComplexity * 0.7 + fileSummary.functions.length * 2 + flows * 0.2),
  );
 
  return {
    file: fileSummary.file,
    functionCount: fileSummary.functions.length,
    highComplexityFunctions: highComplexity,
    flows,
    complexitySum: totalComplexity,
    complexityRisk: highComplexity,
    score,
  };
}
 
function countControlFlowStatements(node: ts.Node): number {
  if (ts.isIfStatement(node)) {
    const then = node.thenStatement;
    return ts.isBlock(then) ? then.statements.length : 1;
  }
  if (ts.isSwitchStatement(node)) {
    return node.caseBlock.clauses.length;
  }
  if (ts.isTryStatement(node)) {
    return node.tryBlock.statements.length;
  }
  if (ts.isForStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node)
      || ts.isForOfStatement(node) || ts.isForInStatement(node)) {
    const stmt = node.statement;
    return ts.isBlock(stmt) ? stmt.statements.length : 1;
  }
  return 1;
}
 
function makeLocationFromTs(node: ts.Node, sourceFile: ts.SourceFile, repoRoot: string): Location {
  const loc = getLineAndCharacter(sourceFile, node);
  return {
    file: path.relative(repoRoot, node.getSourceFile().fileName),
    lineStart: loc.lineStart,
    lineEnd: loc.lineEnd,
    columnStart: loc.columnStart,
    columnEnd: loc.columnEnd,
  };
}
 
export function analyzeSourceFile(
  sourceFile: ts.SourceFile,
  packageName: string,
  packageFileSummary: PackageFileSummary,
  options: AnalysisOptions,
  maps: FlowMaps,
  trees: TreeEntry[],
  dependencyProfile: DependencyProfile,
): FileEntry {
  const filePath = sourceFile.fileName;
  const fileRelative = path.relative(options.root, filePath);
  packageFileSummary.fileCount += 1;
  packageFileSummary.nodeCount += 1;
  packageFileSummary.kindCounts.SourceFile = (packageFileSummary.kindCounts.SourceFile || 0) + 1;
 
  const fileEntry: FileEntry = {
    package: packageName,
    file: fileRelative,
    parseEngine: 'typescript',
    nodeCount: 0,
    kindCounts: {},
    functions: [],
    flows: [],
    dependencyProfile,
  };
 
  if (options.emitTree) {
    const nodeBudget: NodeBudget = { size: 8000 };
    const tree = buildNodeTree(sourceFile, sourceFile, options.treeDepth, nodeBudget);
    if (tree) {
      trees.push({
        package: packageName,
        file: fileRelative,
        tree,
      });
    }
  }
 
  const controlKinds = TS_CONTROL_KINDS;
  const emptyCatches: CodeLocation[] = [];
  const switchesWithoutDefault: CodeLocation[] = [];
  const magicNumbers: MagicNumberEntry[] = [];
  let anyCount = 0;
  const asAnyLocs: CodeLocation[] = [];
  const doubleAssertionLocs: CodeLocation[] = [];
  const nonNullLocs: CodeLocation[] = [];
  const MAGIC_EXCLUDED = new Set([0, 1, -1, 2, 100]);
 
  const visit = (node: ts.Node): void => {
    fileEntry.nodeCount += 1;
    packageFileSummary.nodeCount += 1;
    const kind = ts.SyntaxKind[node.kind] || 'UNKNOWN';
    fileEntry.kindCounts[kind] = (fileEntry.kindCounts[kind] || 0) + 1;
    packageFileSummary.kindCounts[kind] = (packageFileSummary.kindCounts[kind] || 0) + 1;
 
    if (ts.isCatchClause(node)) {
      const block = node.block;
      if (block.statements.length === 0) {
        const loc = getLineAndCharacter(sourceFile, node);
        emptyCatches.push({ file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
      }
    }
 
    if (ts.isSwitchStatement(node)) {
      const hasDefault = node.caseBlock.clauses.some(c => c.kind === ts.SyntaxKind.DefaultClause);
      if (!hasDefault) {
        const loc = getLineAndCharacter(sourceFile, node);
        switchesWithoutDefault.push({ file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
      }
    }
 
    if (node.kind === ts.SyntaxKind.AnyKeyword) {
      anyCount += 1;
    }
    if (ts.isAsExpression(node) && node.type.kind === ts.SyntaxKind.AnyKeyword) {
      anyCount += 1;
    }
 
    if (ts.isAsExpression(node)) {
      if (node.type.kind === ts.SyntaxKind.AnyKeyword) {
        const loc = getLineAndCharacter(sourceFile, node);
        asAnyLocs.push({ file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
      }
      if (ts.isAsExpression(node.expression) && node.expression.type.kind === ts.SyntaxKind.UnknownKeyword) {
        const loc = getLineAndCharacter(sourceFile, node);
        doubleAssertionLocs.push({ file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
      }
    }
    if (ts.isNonNullExpression(node)) {
      const loc = getLineAndCharacter(sourceFile, node);
      nonNullLocs.push({ file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
    }
 
    if (ts.isNumericLiteral(node)) {
      const value = Number(node.text);
      if (!MAGIC_EXCLUDED.has(value)) {
        const parent = node.parent;
        const inConst = parent && ts.isVariableDeclaration(parent) &&
          parent.parent && ts.isVariableDeclarationList(parent.parent) &&
          (parent.parent.flags & ts.NodeFlags.Const) !== 0;
        const inEnum = parent && ts.isEnumMember(parent);
        if (!inConst && !inEnum) {
          const loc = getLineAndCharacter(sourceFile, node);
          magicNumbers.push({ value, file: fileRelative, lineStart: loc.lineStart, lineEnd: loc.lineEnd });
        }
      }
    }
 
    if (isFunctionLike(node)) {
      const funcNode = node as ts.FunctionLikeDeclaration;
      const body = funcNode.body;
      const statementCount = body && ts.isBlock(body) ? body.statements.length : 1;
      const loc = makeLocationFromTs(node, sourceFile, options.root);
      const signature = getFunctionName(node, sourceFile);
      const metrics: Metrics = body ? collectMetrics(body) : {
        complexity: 1,
        maxBranchDepth: 0,
        maxLoopDepth: 0,
        returns: 0,
        awaits: 0,
        calls: 0,
        loops: 0,
      };
 
      const entry: FunctionEntry = {
        kind,
        name: signature,
        nameHint: signature,
        file: fileRelative,
        lineStart: loc.lineStart,
        lineEnd: loc.lineEnd,
        columnStart: loc.columnStart,
        columnEnd: loc.columnEnd,
        statementCount,
        complexity: metrics.complexity,
        maxBranchDepth: metrics.maxBranchDepth,
        maxLoopDepth: metrics.maxLoopDepth,
        returns: metrics.returns,
        awaits: metrics.awaits,
        calls: metrics.calls,
        loops: metrics.loops,
        lengthLines: countLinesInNode(sourceFile, node),
        cognitiveComplexity: body ? computeCognitiveComplexity(body) : 0,
      };
 
      if (body) {
        entry.halstead = computeHalstead(body);
        entry.maintainabilityIndex = computeMaintainabilityIndex(
          entry.halstead.volume,
          metrics.complexity,
          entry.lengthLines,
        );
      }
 
      if (ts.isFunctionDeclaration(node)) {
        entry.declared = true;
      }
 
      if (statementCount >= options.minFunctionStatements) {
        const bodyHash = body ? makeFingerprint(body) : hashString(fileRelative);
        increment(maps.flowMap, `${bodyHash}|${node.kind}`, {
          ...entry,
          hash: bodyHash,
          metrics,
        });
      }
 
      if (funcNode.parameters) {
        entry.params = funcNode.parameters.length;
      }
 
      fileEntry.functions.push(entry);
      packageFileSummary.functions.push(entry);
      packageFileSummary.functionCount += 1;
    }
 
    if (controlKinds.has(node.kind)) {
      const statementCount = countControlFlowStatements(node);
      const loc = makeLocationFromTs(node, sourceFile, options.root);
      const flowEntry: FlowEntry = {
        kind,
        file: fileRelative,
        lineStart: loc.lineStart,
        lineEnd: loc.lineEnd,
        columnStart: loc.columnStart,
        columnEnd: loc.columnEnd,
        statementCount,
      };
      fileEntry.flows.push(flowEntry);
      packageFileSummary.flowCount += 1;
 
      if (statementCount >= options.minFlowStatements) {
        const flowHash = makeFingerprint(node);
        increment(maps.controlMap, `${flowHash}|${node.kind}`, {
          ...flowEntry,
          hash: flowHash,
        });
      }
    }
 
    ts.forEachChild(node, visit);
  };
 
  ts.forEachChild(sourceFile, visit);
 
  fileEntry.emptyCatches = emptyCatches;
  fileEntry.switchesWithoutDefault = switchesWithoutDefault;
  fileEntry.anyCount = anyCount;
  fileEntry.magicNumbers = magicNumbers;
  fileEntry.typeAssertionEscapes = { asAny: asAnyLocs, doubleAssertion: doubleAssertionLocs, nonNull: nonNullLocs };
 
  const asyncWithoutAwait: Array<{ name: string; lineStart: number; lineEnd: number }> = [];
  const unprotectedAsync: Array<{ name: string; awaitCount: number; lineStart: number; lineEnd: number }> = [];
  for (const fn of fileEntry.functions) {
    if (fn.awaits === 0) continue;
    const fnStart = sourceFile.getPositionOfLineAndCharacter(Math.max(0, fn.lineStart - 1), 0);
    let fnAstNode: ts.Node | undefined;
    const findFnNode = (node: ts.Node): void => {
      if (fnAstNode) return;
      if (isFunctionLike(node) && node.getStart(sourceFile) >= fnStart) {
        const fnLoc = getLineAndCharacter(sourceFile, node);
        if (fnLoc.lineStart === fn.lineStart) { fnAstNode = node; return; }
      }
      ts.forEachChild(node, findFnNode);
    };
    ts.forEachChild(sourceFile, findFnNode);
    Iif (!fnAstNode) continue;
    const isAsync = (fnAstNode as ts.FunctionLikeDeclaration).modifiers?.some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.AsyncKeyword);
    Iif (!isAsync) continue;
 
    let awaitCount = 0;
    let hasTryCatch = false;
    let hasCatchChain = false;
    const scanBody = (child: ts.Node): void => {
      if (ts.isAwaitExpression(child)) awaitCount++;
      if (ts.isTryStatement(child)) hasTryCatch = true;
      if (
        ts.isCallExpression(child) &&
        ts.isPropertyAccessExpression(child.expression) &&
        child.expression.name.text === 'catch'
      ) {
        hasCatchChain = true;
      }
      Iif (isFunctionLike(child) && child !== fnAstNode) return;
      ts.forEachChild(child, scanBody);
    };
    ts.forEachChild(fnAstNode, scanBody);
 
    if (awaitCount === 0) {
      asyncWithoutAwait.push({ name: fn.name, lineStart: fn.lineStart, lineEnd: fn.lineEnd });
    } else if (!hasTryCatch && !hasCatchChain) {
      unprotectedAsync.push({ name: fn.name, awaitCount, lineStart: fn.lineStart, lineEnd: fn.lineEnd });
    }
  }
  fileEntry.asyncWithoutAwait = asyncWithoutAwait;
  fileEntry.unprotectedAsync = unprotectedAsync;
 
  collectSecurityData(sourceFile, fileRelative, fileEntry);
  if (!isTestFile(fileRelative)) {
    collectInputSourceProfile(sourceFile, fileRelative, fileEntry);
  }
  collectPerformanceData(sourceFile, fileRelative, fileEntry);
  if (isTestFile(fileRelative)) {
    collectTestProfile(sourceFile, fileRelative, fileEntry);
  }
 
  if (!isTestFile(fileRelative)) {
    const topLevelEffects = collectTopLevelEffects(sourceFile, fileRelative);
    if (topLevelEffects.length > 0) {
      fileEntry.topLevelEffects = topLevelEffects;
    }
    const ppSites = collectPrototypePollutionSites(sourceFile);
    if (ppSites.length > 0) {
      fileEntry.prototypePollutionSites = ppSites;
    }
  }
 
  return fileEntry;
}