code-gauge 1.12.0 → 1.13.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.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { measureArchitecture, type ArchitectureFileMetrics, type ArchitectureMetrics } from './architectureMetrics.js';\nimport {\n type CliOptions,\n configFileName,\n loadConfig,\n type ResolvedOptions,\n resolveOptions,\n resolveThresholds,\n type Thresholds,\n} from './cliConfig.js';\nimport { measureCode } from './metrics.js';\nimport { measureTypeScriptProject, type TypeScriptProjectMetrics } from './typescriptProject.js';\nimport type { CodeMetrics, FunctionMetrics, LanguageName } from './types.js';\n\ninterface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n}\n\ninterface RiskTrigger {\n /** Optional location hint (e.g. duplicated block line ranges) appended to the printed trigger. */\n detail?: string;\n metric: string;\n score: number;\n threshold: number;\n value: number;\n}\n\ninterface RiskFinding {\n cognitiveComplexity: number;\n cyclomaticComplexity: number;\n endLine?: number;\n file: string;\n kind: 'component' | 'file' | 'function';\n language: LanguageName;\n name?: string;\n score: number;\n startLine?: number;\n triggers: RiskTrigger[];\n}\n\ninterface ScanResult {\n architecture?: ArchitectureMetrics;\n componentFunctionKeys?: Set<string>;\n displayRoot: string;\n errors: string[];\n fatalError?: string;\n files: FileMetrics[];\n namedComponentFunctionKeys?: Set<string>;\n typeScriptProject?: TypeScriptProjectMetrics;\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\n/** Caps the `Duplicate symbols` section so large repositories do not flood the report. */\nconst maxDuplicateSymbolGroupLines = 10;\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics and list high-risk findings.')\n .argument('[target]', 'file or directory to measure', '.')\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option('--file-loc-threshold <number>', 'minimum file code LOC to report', parsePositiveInteger)\n .option('--function-loc-threshold <number>', 'minimum function physical LOC span to report', parsePositiveInteger)\n .option(\n '--component-loc-threshold <number>',\n 'minimum React component physical LOC span to report',\n parsePositiveInteger\n )\n .option('--cognitive-threshold <number>', 'minimum cognitive complexity to report', parsePositiveInteger)\n .option('--cyclomatic-threshold <number>', 'minimum cyclomatic complexity to report', parsePositiveInteger)\n .option('--call-threshold <number>', 'minimum function call count to report', parsePositiveInteger)\n .option('--import-threshold <number>', 'minimum unique import sources per file to report', parsePositiveInteger)\n .option('--fan-out-threshold <number>', 'minimum intra-file fan-out per function to report', parsePositiveInteger)\n .option('--parameter-threshold <number>', 'minimum function parameter count to report', parsePositiveInteger)\n .option(\n '--duplicate-block-threshold <number>',\n 'minimum count of duplicated code blocks per file to report',\n parsePositiveInteger\n )\n .option(\n '--duplication-ratio-percent-threshold <number>',\n 'minimum percentage (1-100) of duplicated lines per file to report',\n parsePercentInteger\n )\n .option(\n '--transitive-dependency-threshold <number>',\n 'minimum transitively reachable local files to report',\n parsePositiveInteger\n )\n .option(\n '--structural-breadth-threshold <number>',\n 'minimum structural breadth score to report',\n parsePositiveInteger\n )\n .option(\n '--structural-coordination-threshold <number>',\n 'minimum structural coordination score to report',\n parsePositiveInteger\n )\n .option('--state-mutation-threshold <number>', 'minimum state mutation score to report', parsePositiveInteger)\n .option(\n '--duplicate-symbol-group-threshold <number>',\n 'minimum duplicate symbol group count to report',\n parsePositiveInteger\n )\n .option('--max-findings <number>', 'maximum number of risk findings to print', parsePositiveInteger)\n .option('--largest-files <number>', 'number of largest files by code LOC to list', parsePositiveInteger)\n .option('--include-tests', 'include test files and test directories')\n .option('--tsconfig <path>', 'TypeScript project file to use instead of auto-detected tsconfig.json')\n .option('--json', 'print JSON output')\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .option('--fail-on-risk', 'exit with code 1 when high-risk findings are found');\n\n program.action(async (target: string, cliOptions: CliOptions) => {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, options);\n await addArchitectureMetrics(result);\n await addTypeScriptProjectMetrics(result, options, resolvedTarget);\n const risks = findRiskyFunctions(\n result.files,\n result.architecture,\n result.componentFunctionKeys,\n result.namedComponentFunctionKeys,\n options,\n result.displayRoot\n );\n\n if (options.json) {\n printJson(result, risks, options);\n } else {\n printTextReport(resolvedTarget, result, risks, options);\n }\n\n if (\n result.fatalError ||\n (options.failOnError && result.errors.length > 0) ||\n (options.failOnRisk && risks.length > 0)\n ) {\n process.exitCode = 1;\n }\n });\n\n await program.parseAsync();\n}\n\nfunction resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nasync function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\nasync function scanTarget(target: string, options: ResolvedOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const visitedFiles = new Set<string>();\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], fatalError };\n }\n\n await measureFile(canonicalTarget, language, files, errors, visitedFiles, displayRoot, canonicalTarget);\n return { displayRoot, files, errors };\n }\n\n await scanDirectory(canonicalTarget, options, files, errors, new Set(), visitedFiles, canonicalTarget);\n return { displayRoot: canonicalTarget, files, errors };\n}\n\nasync function addTypeScriptProjectMetrics(\n result: ScanResult,\n options: ResolvedOptions,\n resolvedTarget: string\n): Promise<void> {\n if (result.fatalError) {\n return;\n }\n if (result.files.length === 0) {\n return;\n }\n\n const explicitConfigFile = options.tsconfig;\n const isExplicitConfig = explicitConfigFile !== undefined;\n if (!isExplicitConfig && !result.files.some(({ file }) => isTypeScriptProjectCandidateFile(file))) {\n return;\n }\n\n const configFile = explicitConfigFile ? resolveTarget(explicitConfigFile) : await findNearestTsconfig(resolvedTarget);\n if (!configFile) {\n return;\n }\n\n try {\n result.typeScriptProject = await measureTypeScriptProject(\n configFile,\n result.files.map(({ file }) => file)\n );\n result.componentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.map((component) =>\n functionLocationKey(component.file, component.startLine, component.startColumn)\n )\n );\n result.namedComponentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.flatMap((component) =>\n component.name ? [functionNameLocationKey(component.file, component.name, component.startLine)] : []\n )\n );\n } catch (error) {\n if (isExplicitConfig) {\n result.errors.push(`${formatPath(configFile, result.displayRoot)}: ${formatError(error)}`);\n }\n }\n}\n\nfunction isTypeScriptProjectCandidateFile(file: string): boolean {\n return ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'].includes(path.extname(file));\n}\n\nasync function findNearestTsconfig(target: string): Promise<string | undefined> {\n const targetStat = await stat(target);\n let currentDirectory = targetStat.isDirectory() ? target : path.dirname(target);\n while (true) {\n const configFile = path.join(currentDirectory, 'tsconfig.json');\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nasync function addArchitectureMetrics(result: ScanResult): Promise<void> {\n if (result.fatalError) {\n return;\n }\n\n try {\n result.architecture = measureArchitecture(\n result.files.map(({ file, metrics }) => ({ file, metrics })),\n result.displayRoot\n );\n } catch (error) {\n result.errors.push(`architecture metrics: ${formatError(error)}`);\n }\n}\n\nasync function scanDirectory(\n directory: string,\n options: ResolvedOptions,\n files: FileMetrics[],\n errors: string[],\n visitedDirectories: Set<string>,\n visitedFiles: Set<string>,\n rootDirectory: string\n): Promise<void> {\n let resolvedDirectory;\n try {\n resolvedDirectory = await realpath(directory);\n } catch (error) {\n errors.push(`${formatPath(directory, rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedDirectory, rootDirectory)) {\n return;\n }\n\n if (visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n visitedDirectories.add(resolvedDirectory);\n\n let entries;\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n errors.push(`${formatPath(directory, rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(\n entry.name,\n entryPath,\n options,\n files,\n errors,\n visitedDirectories,\n visitedFiles,\n rootDirectory\n );\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, options)) {\n continue;\n }\n await scanDirectory(entryPath, options, files, errors, visitedDirectories, visitedFiles, rootDirectory);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, options, files, errors, visitedFiles, rootDirectory);\n }\n }\n}\n\nasync function scanSymbolicLink(\n name: string,\n entryPath: string,\n options: ResolvedOptions,\n files: FileMetrics[],\n errors: string[],\n visitedDirectories: Set<string>,\n visitedFiles: Set<string>,\n rootDirectory: string\n): Promise<void> {\n let resolvedPath;\n try {\n resolvedPath = await realpath(entryPath);\n } catch (error) {\n errors.push(`${formatPath(entryPath, rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedPath, rootDirectory)) {\n return;\n }\n\n let entryStat;\n try {\n entryStat = await stat(entryPath);\n } catch (error) {\n errors.push(`${formatPath(entryPath, rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (shouldSkipDirectory(name, options) || shouldSkipDirectory(path.basename(resolvedPath), options)) {\n return;\n }\n await scanDirectory(entryPath, options, files, errors, visitedDirectories, visitedFiles, rootDirectory);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(\n entryPath,\n options,\n files,\n errors,\n visitedFiles,\n rootDirectory,\n resolvedPath,\n resolvedPath\n );\n }\n}\n\nasync function measureScannableFile(\n file: string,\n options: ResolvedOptions,\n files: FileMetrics[],\n errors: string[],\n visitedFiles: Set<string>,\n displayRoot: string,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, options);\n if (language) {\n await measureFile(file, language, files, errors, visitedFiles, displayRoot, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n files: FileMetrics[],\n errors: string[],\n visitedFiles: Set<string>,\n displayRoot: string,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (visitedFiles.has(resolvedFile)) {\n return;\n }\n visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n files.push({\n file,\n metrics: measureCode(code, { language }),\n });\n } catch (error) {\n errors.push(`${formatPath(file, displayRoot)}: ${formatError(error)}`);\n }\n}\n\nfunction findRiskyFunctions(\n files: FileMetrics[],\n architecture: ArchitectureMetrics | undefined,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined,\n options: ResolvedOptions,\n displayRoot: string\n): RiskFinding[] {\n const architectureByFile = new Map(architecture?.files.map((file) => [file.file, file]));\n const findings = files.flatMap(({ file, metrics }) => {\n const isReactFile = metrics.functions.some(\n (fn) => fn.returnsJsx || isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys)\n );\n const thresholds = resolveThresholds(options, metrics.language, isReactFile);\n return [\n ...findRiskyFileMetrics(\n file,\n metrics,\n architectureByFile.get(formatPath(file, displayRoot)),\n thresholds,\n displayRoot\n ),\n ...metrics.functions.flatMap((fn) =>\n findRiskyFunctionMetrics(\n file,\n metrics.language,\n fn,\n thresholds,\n displayRoot,\n componentFunctionKeys,\n namedComponentFunctionKeys\n )\n ),\n ];\n });\n\n findings.sort(compareRiskFindings);\n return findings;\n}\n\nfunction findRiskyFileMetrics(\n file: string,\n metrics: CodeMetrics,\n architecture: ArchitectureFileMetrics | undefined,\n thresholds: Thresholds,\n displayRoot: string\n): RiskFinding[] {\n const triggers: RiskTrigger[] = [];\n const formattedFile = formatPath(file, displayRoot);\n addTrigger(triggers, 'file LOC', metrics.lines.code, thresholds.fileLoc);\n addTrigger(triggers, 'import sources', metrics.coupling.importSourceCount, thresholds.import);\n const duplicateBlockDetail = formatDuplicateBlockGroups(metrics.duplication.duplicateBlockGroups);\n addTrigger(\n triggers,\n 'duplicated blocks',\n metrics.duplication.duplicateBlockCount,\n thresholds.duplicateBlock,\n duplicateBlockDetail\n );\n // Maximal-region selection deliberately compresses adjacent clones into few blocks, so severity\n // must track line coverage, not the block count. Flooring compares like the unrounded ratio\n // against the integer threshold (29.5% must not trigger a >= 30 threshold). The block ranges are\n // repeated as detail because this trigger can fire alone, and a percentage without locations is\n // not actionable.\n addTrigger(\n triggers,\n 'duplicated lines (%)',\n Math.floor(metrics.duplication.duplicationRatio * 100),\n thresholds.duplicationRatioPercent,\n duplicateBlockDetail\n );\n if (architecture) {\n const hasFileScaleRisk = metrics.lines.code >= 100 || architecture.directLocalDependencyCount >= 8;\n if (hasFileScaleRisk) {\n addTrigger(\n triggers,\n 'transitive local dependencies',\n architecture.transitiveLocalDependencyCount,\n thresholds.transitiveDependency\n );\n }\n if (\n triggers.length > 0 ||\n architecture.directLocalDependencyCount >= 8 ||\n architecture.structuralCoordination.score >= thresholds.structuralCoordination\n ) {\n addTrigger(triggers, 'structural breadth', architecture.structuralBreadthScore, thresholds.structuralBreadth);\n }\n addTrigger(\n triggers,\n 'structural coordination',\n architecture.structuralCoordination.score,\n thresholds.structuralCoordination\n );\n addTrigger(\n triggers,\n 'state mutation',\n architecture.structuralCoordination.stateMutationScore,\n thresholds.stateMutation\n );\n addTrigger(\n triggers,\n 'duplicate symbol groups',\n architecture.duplicateSymbolGroupCount,\n thresholds.duplicateSymbolGroup\n );\n }\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formattedFile,\n language: metrics.language,\n kind: 'file',\n cyclomaticComplexity: metrics.cyclomaticComplexity,\n cognitiveComplexity: metrics.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction findRiskyFunctionMetrics(\n file: string,\n language: LanguageName,\n fn: FunctionMetrics,\n thresholds: Thresholds,\n displayRoot: string,\n componentFunctionKeys?: Set<string>,\n namedComponentFunctionKeys?: Set<string>\n): RiskFinding[] {\n const loc = fn.endLine - fn.startLine + 1;\n const isComponent = isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys);\n const kind = isComponent ? 'component' : 'function';\n const triggers: RiskTrigger[] = [];\n addTrigger(triggers, 'cognitive complexity', fn.cognitiveComplexity, thresholds.cognitive);\n addTrigger(triggers, 'cyclomatic complexity', fn.cyclomaticComplexity, thresholds.cyclomatic);\n addTrigger(triggers, isComponent ? 'component LOC' : 'function LOC', loc, getLocThreshold(isComponent, thresholds));\n addTrigger(triggers, 'function calls', fn.callCount, thresholds.call);\n addTrigger(triggers, 'fan-out', fn.fanOut, thresholds.fanOut);\n addTrigger(triggers, 'parameters', fn.parameterCount, thresholds.parameter);\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formatPath(file, displayRoot),\n language,\n kind,\n name: fn.name ?? '<anonymous>',\n startLine: fn.startLine,\n endLine: fn.endLine,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n cognitiveComplexity: fn.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction addTrigger(triggers: RiskTrigger[], metric: string, value: number, threshold: number, detail?: string): void {\n if (value < threshold) {\n return;\n }\n\n triggers.push({ metric, value, threshold, score: value / threshold, detail });\n}\n\n/** Formats duplicated block groups as `12-34 ~ 56-78; 90-99 ~ 100-109` (copies joined by ` ~ `, groups by `; `). */\nfunction formatDuplicateBlockGroups(groups: { endLine: number; startLine: number }[][]): string | undefined {\n if (groups.length === 0) {\n return undefined;\n }\n\n return groups.map((group) => group.map(({ startLine, endLine }) => `${startLine}-${endLine}`).join(' ~ ')).join('; ');\n}\n\nfunction isReactComponent(\n file: string,\n fn: FunctionMetrics,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined\n): boolean {\n return (\n componentFunctionKeys?.has(functionLocationKey(file, fn.startLine, fn.startColumn)) ||\n (fn.name ? namedComponentFunctionKeys?.has(functionNameLocationKey(file, fn.name, fn.startLine)) : false) ||\n false\n );\n}\n\nfunction getLocThreshold(isComponent: boolean, thresholds: Thresholds): number {\n return isComponent ? thresholds.componentLoc : thresholds.functionLoc;\n}\n\nfunction functionLocationKey(file: string, startLine: number, startColumn: number): string {\n return `${path.resolve(file)}:${startLine}:${startColumn}`;\n}\n\nfunction functionNameLocationKey(file: string, name: string, startLine: number): string {\n return `${path.resolve(file)}:${name}:${startLine}`;\n}\n\nfunction maxTriggerScore(triggers: RiskTrigger[]): number {\n return Math.max(...triggers.map((trigger) => trigger.score));\n}\n\nfunction compareRiskFindings(left: RiskFinding, right: RiskFinding): number {\n return (\n right.score - left.score ||\n left.file.localeCompare(right.file) ||\n (left.startLine ?? 0) - (right.startLine ?? 0) ||\n (left.endLine ?? 0) - (right.endLine ?? 0) ||\n left.kind.localeCompare(right.kind)\n );\n}\n\nfunction printJson(result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n const summary = summarize(result.files);\n const reportedRisks = risks.slice(0, options.maxFindings);\n writeStdout(\n JSON.stringify(\n {\n summary,\n thresholds: options.thresholds,\n profileThresholds: options.profileThresholds,\n totalRisks: risks.length,\n truncated: reportedRisks.length < risks.length,\n largestFiles:\n options.largestFiles > 0\n ? findLargestFiles(result.files, options.largestFiles, result.displayRoot)\n : undefined,\n architecture: result.architecture,\n typeScriptProject: result.typeScriptProject,\n risks: reportedRisks,\n errors: result.errors,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(target: string, result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const { thresholds } = options;\n const summary = summarize(result.files);\n writeStdout(`Measured ${summary.fileCount} files under ${target}\\n`);\n writeStdout(\n `LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount}, max cyclomatic ${summary.maxCyclomaticComplexity}, max cognitive ${summary.maxCognitiveComplexity}\\n`\n );\n writeStdout(\n `Calls ${summary.callCount}, internal edges ${summary.internalCallCount}, max call depth ${summary.maxCallDepth}, imports ${summary.importSourceCount}, exports ${summary.exportCount}\\n`\n );\n writeStdout(\n `Type annotations ${summary.typeAnnotationCount}, type aliases ${summary.typeAliasCount}, interfaces ${summary.interfaceCount}, avg cohesion ${summary.averageFunctionIdentifierOverlap.toFixed(2)}\\n`\n );\n if (result.architecture) {\n writeStdout(`${formatArchitectureMetrics(result.architecture)}\\n`);\n }\n if (result.typeScriptProject) {\n writeStdout(`${formatTypeScriptProjectMetrics(result.typeScriptProject)}\\n`);\n }\n writeStdout(\n `Risk thresholds: file LOC >= ${thresholds.fileLoc}, function LOC >= ${thresholds.functionLoc}, component LOC >= ${thresholds.componentLoc}, cognitive >= ${thresholds.cognitive}, cyclomatic >= ${thresholds.cyclomatic}, calls >= ${thresholds.call}, imports >= ${thresholds.import}, fan-out >= ${thresholds.fanOut}, parameters >= ${thresholds.parameter}, duplicated blocks >= ${thresholds.duplicateBlock}, duplicated lines (%) >= ${thresholds.duplicationRatioPercent}\\n`\n );\n const profileOverrides = formatProfileOverrides(options.profileThresholds);\n if (profileOverrides) {\n writeStdout(`Per-language overrides: ${profileOverrides}\\n`);\n }\n\n if (risks.length === 0) {\n writeStdout('No high-risk findings found.\\n');\n } else {\n const reportedRisks = risks.slice(0, options.maxFindings);\n const totalSuffix = risks.length > reportedRisks.length ? ` of ${risks.length}` : '';\n writeStdout(`\\nHigh-risk findings (top ${reportedRisks.length}${totalSuffix}):\\n`);\n for (const risk of reportedRisks) {\n writeStdout(`${formatRiskLocation(risk)} ${formatRiskName(risk)} ${formatRiskMetrics(risk)}\\n`);\n }\n }\n\n const duplicateSymbolGroups = result.architecture?.duplicateSymbolGroups ?? [];\n if (duplicateSymbolGroups.length > 0) {\n const reportedGroups = duplicateSymbolGroups\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name))\n .slice(0, maxDuplicateSymbolGroupLines);\n const totalSuffix =\n duplicateSymbolGroups.length > reportedGroups.length ? ` of ${duplicateSymbolGroups.length}` : '';\n writeStdout(`\\nDuplicate symbols (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.name}: ${group.declarations.map((declaration) => `${declaration.file}:${declaration.line}`).join(', ')}\\n`\n );\n }\n }\n\n if (options.largestFiles > 0) {\n const largestFiles = findLargestFiles(result.files, options.largestFiles, result.displayRoot);\n writeStdout(`\\nLargest files by code LOC (top ${largestFiles.length}):\\n`);\n for (const { file, codeLoc } of largestFiles) {\n writeStdout(`${file} (code LOC ${codeLoc})\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\nfunction findLargestFiles(\n files: FileMetrics[],\n count: number,\n displayRoot: string\n): { file: string; codeLoc: number }[] {\n return files\n .map(({ file, metrics }) => ({ file: formatPath(file, displayRoot), codeLoc: metrics.lines.code }))\n .toSorted((left, right) => right.codeLoc - left.codeLoc || left.file.localeCompare(right.file))\n .slice(0, count);\n}\n\nfunction formatProfileOverrides(profileThresholds: ResolvedOptions['profileThresholds']): string {\n return Object.entries(profileThresholds)\n .map(\n ([profile, overrides]) =>\n `${profile} { ${Object.entries(overrides)\n .map(([metric, value]) => `${metric} ${value}`)\n .join(', ')} }`\n )\n .join('; ');\n}\n\nfunction formatRiskLocation(risk: RiskFinding): string {\n return risk.startLine === undefined || risk.endLine === undefined\n ? risk.file\n : `${risk.file}:${risk.startLine}-${risk.endLine}`;\n}\n\nfunction formatRiskName(risk: RiskFinding): string {\n return risk.name ? `${risk.kind} ${risk.name}` : risk.kind;\n}\n\nfunction formatRiskMetrics(risk: RiskFinding): string {\n const triggerText = risk.triggers\n .map(\n (trigger) =>\n `${trigger.metric} ${formatMetricValue(trigger.value)} >= ${formatMetricValue(trigger.threshold)}${trigger.detail ? ` [${trigger.detail}]` : ''}`\n )\n .join(', ');\n return `(${triggerText}; cyclomatic ${risk.cyclomaticComplexity}, cognitive ${risk.cognitiveComplexity})`;\n}\n\nfunction formatMetricValue(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(2);\n}\n\nfunction formatArchitectureMetrics(metrics: ArchitectureMetrics): string {\n const maxStateMutationScore = Math.max(\n 0,\n ...metrics.files.map((file) => file.structuralCoordination.stateMutationScore)\n );\n return `Architecture max reachable files ${metrics.maxTransitiveLocalDependencyCount}, max structural breadth ${metrics.maxStructuralBreadthScore}, max structural coordination ${metrics.maxStructuralCoordinationScore}, max state mutation ${maxStateMutationScore}, duplicate symbol groups ${metrics.duplicateSymbolGroups.length}`;\n}\n\nfunction formatTypeScriptProjectMetrics(metrics: TypeScriptProjectMetrics): string {\n return `TypeScript project root files ${metrics.rootFileCount}, measured roots ${metrics.measuredRootFileCount}, semantic diagnostics ${metrics.semanticDiagnosticCount}, resolved calls ${metrics.resolvedCallExpressionCount}/${metrics.callExpressionCount} (${(metrics.resolvedCallExpressionRatio * 100).toFixed(1)}%)`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n maxCyclomaticComplexity: number;\n ncssCount: number;\n callCount: number;\n internalCallCount: number;\n maxCallDepth: number;\n importSourceCount: number;\n relativeImportCount: number;\n externalImportCount: number;\n exportCount: number;\n averageFunctionIdentifierOverlap: number;\n typeAnnotationCount: number;\n typeAliasCount: number;\n interfaceCount: number;\n genericParameterCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCyclomaticComplexity = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n let callCount = 0;\n let internalCallCount = 0;\n let maxCallDepth = 0;\n let importSourceCount = 0;\n let relativeImportCount = 0;\n let externalImportCount = 0;\n let exportCount = 0;\n let cohesionTotal = 0;\n let typeAnnotationCount = 0;\n let typeAliasCount = 0;\n let interfaceCount = 0;\n let genericParameterCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functionCount;\n linesOfCode += file.metrics.lines.code;\n maxCyclomaticComplexity = Math.max(maxCyclomaticComplexity, file.metrics.maxCyclomaticComplexity);\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n callCount += file.metrics.callGraph.callCount;\n internalCallCount += file.metrics.callGraph.internalCallCount;\n maxCallDepth = Math.max(maxCallDepth, file.metrics.callGraph.maxCallDepth);\n importSourceCount += file.metrics.coupling.importSourceCount;\n relativeImportCount += file.metrics.coupling.relativeImportCount;\n externalImportCount += file.metrics.coupling.externalImportCount;\n exportCount += file.metrics.coupling.exportCount;\n cohesionTotal += file.metrics.cohesion.averageFunctionIdentifierOverlap;\n typeAnnotationCount += file.metrics.typeComplexity.typeAnnotationCount;\n typeAliasCount += file.metrics.typeComplexity.typeAliasCount;\n interfaceCount += file.metrics.typeComplexity.interfaceCount;\n genericParameterCount += file.metrics.typeComplexity.genericParameterCount;\n }\n\n return {\n fileCount: files.length,\n functionCount,\n linesOfCode,\n maxCyclomaticComplexity,\n maxCognitiveComplexity,\n ncssCount,\n callCount,\n internalCallCount,\n maxCallDepth,\n importSourceCount,\n relativeImportCount,\n externalImportCount,\n exportCount,\n averageFunctionIdentifierOverlap: files.length === 0 ? 0 : cohesionTotal / files.length,\n typeAnnotationCount,\n typeAliasCount,\n interfaceCount,\n genericParameterCount,\n };\n}\n\nfunction shouldSkipDirectory(name: string, options: ResolvedOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\nfunction getLanguage(file: string, options: ResolvedOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number {\n if (!/^[1-9]\\d*$/u.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n\nfunction formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nfunction writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nfunction writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";sdA0DA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eACA,SACA,gBACA,SACA,MACF,CAAC,EAKK,EAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,GAAsB,eAGv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QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,KAM/B,GAAC,GACD,CAAC,EAAQ,eACR,EAAgB,KAAK,EAAK,SAAS,CAAI,CAAC,GAAK,GAAoB,KAAK,EAAK,SAAS,CAAI,CAAC,IAU5F,OAJI,EAAK,QAAQ,CAAI,IAAM,KAClB,MAGF,EAAoB,IAAI,EAAK,QAAQ,CAAS,CAAC,CACxD,CAEA,SAAS,GAAoB,EAAuB,CAClD,IAAM,EAAS,EAAqB,CAAK,EACzC,GAAI,EAAS,IACX,MAAM,IAAI,EAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,EAAqB,EAAuB,CACnD,GAAI,CAAC,cAAc,KAAK,CAAK,EAC3B,MAAM,IAAI,EAAqB,8BAA8B,EAG/D,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAI,EAAqB,8BAA8B,EAE/D,OAAO,CACT,CAEA,SAAS,EAAW,EAAc,EAAsB,CACtD,OAAO,EAAK,SAAS,EAAM,CAAI,GAAK,EAAK,SAAS,CAAI,CACxD,CAEA,SAAS,EAAY,EAAuB,CAC1C,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAS,EAAY,EAAuB,CAC1C,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { measureArchitecture, type ArchitectureFileMetrics, type ArchitectureMetrics } from './architectureMetrics.js';\nimport {\n type CliOptions,\n configFileName,\n loadConfig,\n type ResolvedOptions,\n resolveOptions,\n resolveThresholds,\n type Thresholds,\n} from './cliConfig.js';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicateCandidate } from './duplication.js';\nimport { collectDuplicationCandidates, measureCode } from './metrics.js';\nimport { measureTypeScriptProject, type TypeScriptProjectMetrics } from './typescriptProject.js';\nimport type { CodeMetrics, FunctionMetrics, LanguageName } from './types.js';\n\ninterface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicateCandidate[];\n}\n\ninterface RiskTrigger {\n /** Optional location hint (e.g. duplicated block line ranges) appended to the printed trigger. */\n detail?: string;\n metric: string;\n score: number;\n threshold: number;\n value: number;\n}\n\ninterface RiskFinding {\n cognitiveComplexity: number;\n cyclomaticComplexity: number;\n endLine?: number;\n file: string;\n kind: 'component' | 'file' | 'function';\n language: LanguageName;\n name?: string;\n score: number;\n startLine?: number;\n triggers: RiskTrigger[];\n}\n\ninterface ScanResult {\n architecture?: ArchitectureMetrics;\n componentFunctionKeys?: Set<string>;\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n namedComponentFunctionKeys?: Set<string>;\n typeScriptProject?: TypeScriptProjectMetrics;\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\n/** Caps the `Duplicate symbols` section so large repositories do not flood the report. */\nconst maxDuplicateSymbolGroupLines = 10;\n/** Caps the `Cross-file duplicate blocks` section so large repositories do not flood the report. */\nconst maxCrossFileDuplicateGroupLines = 10;\n/** Caps how many cross-file group locations a single risk finding repeats as detail. */\nconst maxCrossFileDuplicateDetailGroups = 3;\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics and list high-risk findings.')\n .argument('[target]', 'file or directory to measure', '.')\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option('--file-loc-threshold <number>', 'minimum file code LOC to report', parsePositiveInteger)\n .option('--function-loc-threshold <number>', 'minimum function physical LOC span to report', parsePositiveInteger)\n .option(\n '--component-loc-threshold <number>',\n 'minimum React component physical LOC span to report',\n parsePositiveInteger\n )\n .option('--cognitive-threshold <number>', 'minimum cognitive complexity to report', parsePositiveInteger)\n .option('--cyclomatic-threshold <number>', 'minimum cyclomatic complexity to report', parsePositiveInteger)\n .option('--call-threshold <number>', 'minimum function call count to report', parsePositiveInteger)\n .option('--import-threshold <number>', 'minimum unique import sources per file to report', parsePositiveInteger)\n .option('--fan-out-threshold <number>', 'minimum intra-file fan-out per function to report', parsePositiveInteger)\n .option('--parameter-threshold <number>', 'minimum function parameter count to report', parsePositiveInteger)\n .option(\n '--duplicate-block-threshold <number>',\n 'minimum count of duplicated code blocks per file to report',\n parsePositiveInteger\n )\n .option(\n '--duplication-ratio-percent-threshold <number>',\n 'minimum percentage (1-100) of duplicated lines per file to report',\n parsePercentInteger\n )\n .option(\n '--cross-file-duplicate-block-threshold <number>',\n 'minimum count of cross-file duplicate block groups per file to report',\n parsePositiveInteger\n )\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveInteger\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--transitive-dependency-threshold <number>',\n 'minimum transitively reachable local files to report',\n parsePositiveInteger\n )\n .option(\n '--structural-breadth-threshold <number>',\n 'minimum structural breadth score to report',\n parsePositiveInteger\n )\n .option(\n '--structural-coordination-threshold <number>',\n 'minimum structural coordination score to report',\n parsePositiveInteger\n )\n .option('--state-mutation-threshold <number>', 'minimum state mutation score to report', parsePositiveInteger)\n .option(\n '--duplicate-symbol-group-threshold <number>',\n 'minimum duplicate symbol group count to report',\n parsePositiveInteger\n )\n .option('--max-findings <number>', 'maximum number of risk findings to print', parsePositiveInteger)\n .option('--largest-files <number>', 'number of largest files by code LOC to list', parsePositiveInteger)\n .option('--include-tests', 'include test files and test directories')\n .option('--tsconfig <path>', 'TypeScript project file to use instead of auto-detected tsconfig.json')\n .option('--json', 'print JSON output')\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .option('--fail-on-risk', 'exit with code 1 when high-risk findings are found');\n\n program.action(async (target: string, cliOptions: CliOptions) => {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, options);\n addCrossFileDuplication(result);\n await addArchitectureMetrics(result);\n await addTypeScriptProjectMetrics(result, options, resolvedTarget);\n const risks = findRiskyFunctions(\n result.files,\n result.architecture,\n result.crossFileDuplication,\n result.componentFunctionKeys,\n result.namedComponentFunctionKeys,\n options,\n result.displayRoot\n );\n\n if (options.json) {\n printJson(result, risks, options);\n } else {\n printTextReport(resolvedTarget, result, risks, options);\n }\n\n if (\n result.fatalError ||\n (options.failOnError && result.errors.length > 0) ||\n (options.failOnRisk && risks.length > 0)\n ) {\n process.exitCode = 1;\n }\n });\n\n await program.parseAsync();\n}\n\nfunction resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nasync function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ResolvedOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nasync function scanTarget(target: string, options: ResolvedOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return { displayRoot, files, errors, warnings };\n }\n\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\nfunction makeScanContext(\n options: ResolvedOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\nasync function addTypeScriptProjectMetrics(\n result: ScanResult,\n options: ResolvedOptions,\n resolvedTarget: string\n): Promise<void> {\n if (result.fatalError) {\n return;\n }\n if (result.files.length === 0) {\n return;\n }\n\n const explicitConfigFile = options.tsconfig;\n const isExplicitConfig = explicitConfigFile !== undefined;\n if (!isExplicitConfig && !result.files.some(({ file }) => isTypeScriptProjectCandidateFile(file))) {\n return;\n }\n\n const configFile = explicitConfigFile ? resolveTarget(explicitConfigFile) : await findNearestTsconfig(resolvedTarget);\n if (!configFile) {\n return;\n }\n\n try {\n result.typeScriptProject = await measureTypeScriptProject(\n configFile,\n result.files.map(({ file }) => file)\n );\n result.componentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.map((component) =>\n functionLocationKey(component.file, component.startLine, component.startColumn)\n )\n );\n result.namedComponentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.flatMap((component) =>\n component.name ? [functionNameLocationKey(component.file, component.name, component.startLine)] : []\n )\n );\n } catch (error) {\n if (isExplicitConfig) {\n result.errors.push(`${formatPath(configFile, result.displayRoot)}: ${formatError(error)}`);\n }\n }\n}\n\nfunction isTypeScriptProjectCandidateFile(file: string): boolean {\n return ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'].includes(path.extname(file));\n}\n\nasync function findNearestTsconfig(target: string): Promise<string | undefined> {\n const targetStat = await stat(target);\n let currentDirectory = targetStat.isDirectory() ? target : path.dirname(target);\n while (true) {\n const configFile = path.join(currentDirectory, 'tsconfig.json');\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nasync function addArchitectureMetrics(result: ScanResult): Promise<void> {\n if (result.fatalError) {\n return;\n }\n\n try {\n result.architecture = measureArchitecture(\n result.files.map(({ file, metrics }) => ({ file, metrics })),\n result.displayRoot\n );\n } catch (error) {\n result.errors.push(`architecture metrics: ${formatError(error)}`);\n }\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n let resolvedDirectory;\n try {\n resolvedDirectory = await realpath(directory);\n } catch (error) {\n context.errors.push(`${formatPath(directory, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedDirectory, context.rootDirectory)) {\n return;\n }\n\n if (context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n let entries;\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n context.errors.push(`${formatPath(directory, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n let resolvedPath;\n try {\n resolvedPath = await realpath(entryPath);\n } catch (error) {\n context.errors.push(`${formatPath(entryPath, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedPath, context.rootDirectory)) {\n return;\n }\n\n let entryStat;\n try {\n entryStat = await stat(entryPath);\n } catch (error) {\n context.errors.push(`${formatPath(entryPath, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection failing (it always parses with the JavaScript binding, which can give\n // up where the native backend measured fine) must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectDuplicationCandidates(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nfunction addCrossFileDuplication(result: ScanResult): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), candidates: duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles);\n}\n\nfunction findRiskyFunctions(\n files: FileMetrics[],\n architecture: ArchitectureMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined,\n options: ResolvedOptions,\n displayRoot: string\n): RiskFinding[] {\n const architectureByFile = new Map(architecture?.files.map((file) => [file.file, file]));\n const findings = files.flatMap(({ file, metrics }) => {\n const isReactFile = metrics.functions.some(\n (fn) => fn.returnsJsx || isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys)\n );\n const thresholds = resolveThresholds(options, metrics.language, isReactFile);\n return [\n ...findRiskyFileMetrics(\n file,\n metrics,\n architectureByFile.get(formatPath(file, displayRoot)),\n crossFileDuplication,\n thresholds,\n displayRoot\n ),\n ...metrics.functions.flatMap((fn) =>\n findRiskyFunctionMetrics(\n file,\n metrics.language,\n fn,\n thresholds,\n displayRoot,\n componentFunctionKeys,\n namedComponentFunctionKeys\n )\n ),\n ];\n });\n\n findings.sort(compareRiskFindings);\n return findings;\n}\n\nfunction findRiskyFileMetrics(\n file: string,\n metrics: CodeMetrics,\n architecture: ArchitectureFileMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n thresholds: Thresholds,\n displayRoot: string\n): RiskFinding[] {\n const triggers: RiskTrigger[] = [];\n const formattedFile = formatPath(file, displayRoot);\n addTrigger(triggers, 'file LOC', metrics.lines.code, thresholds.fileLoc);\n addTrigger(triggers, 'import sources', metrics.coupling.importSourceCount, thresholds.import);\n const duplicateBlockDetail = formatDuplicateBlockGroups(metrics.duplication.duplicateBlockGroups);\n addTrigger(\n triggers,\n 'duplicated blocks',\n metrics.duplication.duplicateBlockCount,\n thresholds.duplicateBlock,\n duplicateBlockDetail\n );\n // Maximal-region selection deliberately compresses adjacent clones into few blocks, so severity\n // must track line coverage, not the block count. Flooring compares like the unrounded ratio\n // against the integer threshold (29.5% must not trigger a >= 30 threshold). The block ranges are\n // repeated as detail because this trigger can fire alone, and a percentage without locations is\n // not actionable.\n addTrigger(\n triggers,\n 'duplicated lines (%)',\n Math.floor(metrics.duplication.duplicationRatio * 100),\n thresholds.duplicationRatioPercent,\n duplicateBlockDetail\n );\n if (crossFileDuplication) {\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n addTrigger(\n triggers,\n 'cross-file duplicated blocks',\n Object.hasOwn(crossFileDuplication.duplicateBlockGroupCountByFile, formattedFile)\n ? (crossFileDuplication.duplicateBlockGroupCountByFile[formattedFile] ?? 0)\n : 0,\n thresholds.crossFileDuplicateBlock,\n formatCrossFileDuplicateDetail(crossFileDuplication, formattedFile)\n );\n }\n if (architecture) {\n const hasFileScaleRisk = metrics.lines.code >= 100 || architecture.directLocalDependencyCount >= 8;\n if (hasFileScaleRisk) {\n addTrigger(\n triggers,\n 'transitive local dependencies',\n architecture.transitiveLocalDependencyCount,\n thresholds.transitiveDependency\n );\n }\n if (\n triggers.length > 0 ||\n architecture.directLocalDependencyCount >= 8 ||\n architecture.structuralCoordination.score >= thresholds.structuralCoordination\n ) {\n addTrigger(triggers, 'structural breadth', architecture.structuralBreadthScore, thresholds.structuralBreadth);\n }\n addTrigger(\n triggers,\n 'structural coordination',\n architecture.structuralCoordination.score,\n thresholds.structuralCoordination\n );\n addTrigger(\n triggers,\n 'state mutation',\n architecture.structuralCoordination.stateMutationScore,\n thresholds.stateMutation\n );\n addTrigger(\n triggers,\n 'duplicate symbol groups',\n architecture.duplicateSymbolGroupCount,\n thresholds.duplicateSymbolGroup\n );\n }\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formattedFile,\n language: metrics.language,\n kind: 'file',\n cyclomaticComplexity: metrics.cyclomaticComplexity,\n cognitiveComplexity: metrics.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction findRiskyFunctionMetrics(\n file: string,\n language: LanguageName,\n fn: FunctionMetrics,\n thresholds: Thresholds,\n displayRoot: string,\n componentFunctionKeys?: Set<string>,\n namedComponentFunctionKeys?: Set<string>\n): RiskFinding[] {\n const loc = fn.endLine - fn.startLine + 1;\n const isComponent = isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys);\n const kind = isComponent ? 'component' : 'function';\n const triggers: RiskTrigger[] = [];\n addTrigger(triggers, 'cognitive complexity', fn.cognitiveComplexity, thresholds.cognitive);\n addTrigger(triggers, 'cyclomatic complexity', fn.cyclomaticComplexity, thresholds.cyclomatic);\n addTrigger(triggers, isComponent ? 'component LOC' : 'function LOC', loc, getLocThreshold(isComponent, thresholds));\n addTrigger(triggers, 'function calls', fn.callCount, thresholds.call);\n addTrigger(triggers, 'fan-out', fn.fanOut, thresholds.fanOut);\n addTrigger(triggers, 'parameters', fn.parameterCount, thresholds.parameter);\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formatPath(file, displayRoot),\n language,\n kind,\n name: fn.name ?? '<anonymous>',\n startLine: fn.startLine,\n endLine: fn.endLine,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n cognitiveComplexity: fn.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction addTrigger(triggers: RiskTrigger[], metric: string, value: number, threshold: number, detail?: string): void {\n if (value < threshold) {\n return;\n }\n\n triggers.push({ metric, value, threshold, score: value / threshold, detail });\n}\n\n/** Formats the cross-file groups a file participates in as `12-34 ~ b.ts:56-78; ...` (capped). */\nfunction formatCrossFileDuplicateDetail(\n crossFileDuplication: CrossFileDuplicationMetrics,\n formattedFile: string\n): string | undefined {\n const involved = crossFileDuplication.groups.filter((group) => group.files.includes(formattedFile));\n if (involved.length === 0) {\n return undefined;\n }\n const formatted = involved\n .slice(0, maxCrossFileDuplicateDetailGroups)\n .map((group) =>\n group.occurrences\n .map(({ file, startLine, endLine }) =>\n file === formattedFile ? `${startLine}-${endLine}` : `${file}:${startLine}-${endLine}`\n )\n .join(' ~ ')\n )\n .join('; ');\n const truncatedSuffix = involved.length > maxCrossFileDuplicateDetailGroups ? '; ...' : '';\n return `${formatted}${truncatedSuffix}`;\n}\n\n/** Formats duplicated block groups as `12-34 ~ 56-78; 90-99 ~ 100-109` (copies joined by ` ~ `, groups by `; `). */\nfunction formatDuplicateBlockGroups(groups: { endLine: number; startLine: number }[][]): string | undefined {\n if (groups.length === 0) {\n return undefined;\n }\n\n return groups.map((group) => group.map(({ startLine, endLine }) => `${startLine}-${endLine}`).join(' ~ ')).join('; ');\n}\n\nfunction isReactComponent(\n file: string,\n fn: FunctionMetrics,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined\n): boolean {\n return (\n componentFunctionKeys?.has(functionLocationKey(file, fn.startLine, fn.startColumn)) ||\n (fn.name ? namedComponentFunctionKeys?.has(functionNameLocationKey(file, fn.name, fn.startLine)) : false) ||\n false\n );\n}\n\nfunction getLocThreshold(isComponent: boolean, thresholds: Thresholds): number {\n return isComponent ? thresholds.componentLoc : thresholds.functionLoc;\n}\n\nfunction functionLocationKey(file: string, startLine: number, startColumn: number): string {\n return `${path.resolve(file)}:${startLine}:${startColumn}`;\n}\n\nfunction functionNameLocationKey(file: string, name: string, startLine: number): string {\n return `${path.resolve(file)}:${name}:${startLine}`;\n}\n\nfunction maxTriggerScore(triggers: RiskTrigger[]): number {\n return Math.max(...triggers.map((trigger) => trigger.score));\n}\n\nfunction compareRiskFindings(left: RiskFinding, right: RiskFinding): number {\n return (\n right.score - left.score ||\n left.file.localeCompare(right.file) ||\n (left.startLine ?? 0) - (right.startLine ?? 0) ||\n (left.endLine ?? 0) - (right.endLine ?? 0) ||\n left.kind.localeCompare(right.kind)\n );\n}\n\nfunction printJson(result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n const summary = summarize(result.files);\n const reportedRisks = risks.slice(0, options.maxFindings);\n writeStdout(\n JSON.stringify(\n {\n summary,\n thresholds: options.thresholds,\n profileThresholds: options.profileThresholds,\n totalRisks: risks.length,\n truncated: reportedRisks.length < risks.length,\n largestFiles:\n options.largestFiles > 0\n ? findLargestFiles(result.files, options.largestFiles, result.displayRoot)\n : undefined,\n architecture: result.architecture,\n crossFileDuplication: result.crossFileDuplication,\n typeScriptProject: result.typeScriptProject,\n risks: reportedRisks,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(target: string, result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const { thresholds } = options;\n const summary = summarize(result.files);\n writeStdout(`Measured ${summary.fileCount} files under ${target}\\n`);\n writeStdout(\n `LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount}, max cyclomatic ${summary.maxCyclomaticComplexity}, max cognitive ${summary.maxCognitiveComplexity}\\n`\n );\n writeStdout(\n `Calls ${summary.callCount}, internal edges ${summary.internalCallCount}, max call depth ${summary.maxCallDepth}, imports ${summary.importSourceCount}, exports ${summary.exportCount}\\n`\n );\n writeStdout(\n `Type annotations ${summary.typeAnnotationCount}, type aliases ${summary.typeAliasCount}, interfaces ${summary.interfaceCount}, avg cohesion ${summary.averageFunctionIdentifierOverlap.toFixed(2)}\\n`\n );\n if (result.architecture) {\n writeStdout(`${formatArchitectureMetrics(result.architecture)}\\n`);\n }\n if (result.typeScriptProject) {\n writeStdout(`${formatTypeScriptProjectMetrics(result.typeScriptProject)}\\n`);\n }\n writeStdout(\n `Risk thresholds: file LOC >= ${thresholds.fileLoc}, function LOC >= ${thresholds.functionLoc}, component LOC >= ${thresholds.componentLoc}, cognitive >= ${thresholds.cognitive}, cyclomatic >= ${thresholds.cyclomatic}, calls >= ${thresholds.call}, imports >= ${thresholds.import}, fan-out >= ${thresholds.fanOut}, parameters >= ${thresholds.parameter}, duplicated blocks >= ${thresholds.duplicateBlock}, duplicated lines (%) >= ${thresholds.duplicationRatioPercent}, cross-file duplicated blocks >= ${thresholds.crossFileDuplicateBlock}\\n`\n );\n const profileOverrides = formatProfileOverrides(options.profileThresholds);\n if (profileOverrides) {\n writeStdout(`Per-language overrides: ${profileOverrides}\\n`);\n }\n\n if (risks.length === 0) {\n writeStdout('No high-risk findings found.\\n');\n } else {\n const reportedRisks = risks.slice(0, options.maxFindings);\n const totalSuffix = risks.length > reportedRisks.length ? ` of ${risks.length}` : '';\n writeStdout(`\\nHigh-risk findings (top ${reportedRisks.length}${totalSuffix}):\\n`);\n for (const risk of reportedRisks) {\n writeStdout(`${formatRiskLocation(risk)} ${formatRiskName(risk)} ${formatRiskMetrics(risk)}\\n`);\n }\n }\n\n const crossFileGroups = result.crossFileDuplication?.groups ?? [];\n if (crossFileGroups.length > 0) {\n const reportedGroups = crossFileGroups.slice(0, maxCrossFileDuplicateGroupLines);\n const totalSuffix = crossFileGroups.length > reportedGroups.length ? ` of ${crossFileGroups.length}` : '';\n writeStdout(`\\nCross-file duplicate blocks (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.tokenCount} tokens: ${group.occurrences\n .map(({ file, startLine, endLine }) => `${file}:${startLine}-${endLine}`)\n .join(', ')}\\n`\n );\n }\n }\n\n const duplicateSymbolGroups = result.architecture?.duplicateSymbolGroups ?? [];\n if (duplicateSymbolGroups.length > 0) {\n const reportedGroups = duplicateSymbolGroups\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name))\n .slice(0, maxDuplicateSymbolGroupLines);\n const totalSuffix =\n duplicateSymbolGroups.length > reportedGroups.length ? ` of ${duplicateSymbolGroups.length}` : '';\n writeStdout(`\\nDuplicate symbols (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.name}: ${group.declarations.map((declaration) => `${declaration.file}:${declaration.line}`).join(', ')}\\n`\n );\n }\n }\n\n if (options.largestFiles > 0) {\n const largestFiles = findLargestFiles(result.files, options.largestFiles, result.displayRoot);\n writeStdout(`\\nLargest files by code LOC (top ${largestFiles.length}):\\n`);\n for (const { file, codeLoc } of largestFiles) {\n writeStdout(`${file} (code LOC ${codeLoc})\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\nfunction findLargestFiles(\n files: FileMetrics[],\n count: number,\n displayRoot: string\n): { file: string; codeLoc: number }[] {\n return files\n .map(({ file, metrics }) => ({ file: formatPath(file, displayRoot), codeLoc: metrics.lines.code }))\n .toSorted((left, right) => right.codeLoc - left.codeLoc || left.file.localeCompare(right.file))\n .slice(0, count);\n}\n\nfunction formatProfileOverrides(profileThresholds: ResolvedOptions['profileThresholds']): string {\n return Object.entries(profileThresholds)\n .map(\n ([profile, overrides]) =>\n `${profile} { ${Object.entries(overrides)\n .map(([metric, value]) => `${metric} ${value}`)\n .join(', ')} }`\n )\n .join('; ');\n}\n\nfunction formatRiskLocation(risk: RiskFinding): string {\n return risk.startLine === undefined || risk.endLine === undefined\n ? risk.file\n : `${risk.file}:${risk.startLine}-${risk.endLine}`;\n}\n\nfunction formatRiskName(risk: RiskFinding): string {\n return risk.name ? `${risk.kind} ${risk.name}` : risk.kind;\n}\n\nfunction formatRiskMetrics(risk: RiskFinding): string {\n const triggerText = risk.triggers\n .map(\n (trigger) =>\n `${trigger.metric} ${formatMetricValue(trigger.value)} >= ${formatMetricValue(trigger.threshold)}${trigger.detail ? ` [${trigger.detail}]` : ''}`\n )\n .join(', ');\n return `(${triggerText}; cyclomatic ${risk.cyclomaticComplexity}, cognitive ${risk.cognitiveComplexity})`;\n}\n\nfunction formatMetricValue(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(2);\n}\n\nfunction formatArchitectureMetrics(metrics: ArchitectureMetrics): string {\n const maxStateMutationScore = Math.max(\n 0,\n ...metrics.files.map((file) => file.structuralCoordination.stateMutationScore)\n );\n return `Architecture max reachable files ${metrics.maxTransitiveLocalDependencyCount}, max structural breadth ${metrics.maxStructuralBreadthScore}, max structural coordination ${metrics.maxStructuralCoordinationScore}, max state mutation ${maxStateMutationScore}, duplicate symbol groups ${metrics.duplicateSymbolGroups.length}`;\n}\n\nfunction formatTypeScriptProjectMetrics(metrics: TypeScriptProjectMetrics): string {\n return `TypeScript project root files ${metrics.rootFileCount}, measured roots ${metrics.measuredRootFileCount}, semantic diagnostics ${metrics.semanticDiagnosticCount}, resolved calls ${metrics.resolvedCallExpressionCount}/${metrics.callExpressionCount} (${(metrics.resolvedCallExpressionRatio * 100).toFixed(1)}%)`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n maxCyclomaticComplexity: number;\n ncssCount: number;\n callCount: number;\n internalCallCount: number;\n maxCallDepth: number;\n importSourceCount: number;\n relativeImportCount: number;\n externalImportCount: number;\n exportCount: number;\n averageFunctionIdentifierOverlap: number;\n typeAnnotationCount: number;\n typeAliasCount: number;\n interfaceCount: number;\n genericParameterCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCyclomaticComplexity = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n let callCount = 0;\n let internalCallCount = 0;\n let maxCallDepth = 0;\n let importSourceCount = 0;\n let relativeImportCount = 0;\n let externalImportCount = 0;\n let exportCount = 0;\n let cohesionTotal = 0;\n let typeAnnotationCount = 0;\n let typeAliasCount = 0;\n let interfaceCount = 0;\n let genericParameterCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functionCount;\n linesOfCode += file.metrics.lines.code;\n maxCyclomaticComplexity = Math.max(maxCyclomaticComplexity, file.metrics.maxCyclomaticComplexity);\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n callCount += file.metrics.callGraph.callCount;\n internalCallCount += file.metrics.callGraph.internalCallCount;\n maxCallDepth = Math.max(maxCallDepth, file.metrics.callGraph.maxCallDepth);\n importSourceCount += file.metrics.coupling.importSourceCount;\n relativeImportCount += file.metrics.coupling.relativeImportCount;\n externalImportCount += file.metrics.coupling.externalImportCount;\n exportCount += file.metrics.coupling.exportCount;\n cohesionTotal += file.metrics.cohesion.averageFunctionIdentifierOverlap;\n typeAnnotationCount += file.metrics.typeComplexity.typeAnnotationCount;\n typeAliasCount += file.metrics.typeComplexity.typeAliasCount;\n interfaceCount += file.metrics.typeComplexity.interfaceCount;\n genericParameterCount += file.metrics.typeComplexity.genericParameterCount;\n }\n\n return {\n fileCount: files.length,\n functionCount,\n linesOfCode,\n maxCyclomaticComplexity,\n maxCognitiveComplexity,\n ncssCount,\n callCount,\n internalCallCount,\n maxCallDepth,\n importSourceCount,\n relativeImportCount,\n externalImportCount,\n exportCount,\n averageFunctionIdentifierOverlap: files.length === 0 ? 0 : cohesionTotal / files.length,\n typeAnnotationCount,\n typeAliasCount,\n interfaceCount,\n genericParameterCount,\n };\n}\n\nfunction shouldSkipDirectory(name: string, options: ResolvedOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\nfunction getLanguage(file: string, options: ResolvedOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number {\n if (!/^[1-9]\\d*$/u.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n\nfunction formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nfunction writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nfunction writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";gkBAiEA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eACA,SACA,gBACA,SACA,MACF,CAAC,EASK,EAAqB,IAAI,I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AAuB,CAClD,IAAM,EAAS,EAAqB,CAAK,EACzC,GAAI,EAAS,IACX,MAAM,IAAI,EAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,GAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAK,CAAK,EACtB,MAAM,IAAI,EAAqB,kCAAkC,EAGnE,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAI,EAAqB,kCAAkC,EAEnE,OAAO,CACT,CAEA,SAAS,EAAqB,EAAuB,CACnD,GAAI,CAAC,cAAc,KAAK,CAAK,EAC3B,MAAM,IAAI,EAAqB,8BAA8B,EAG/D,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAI,EAAqB,8BAA8B,EAE/D,OAAO,CACT,CAEA,SAAS,EAAW,EAAc,EAAsB,CACtD,OAAO,EAAK,SAAS,EAAM,CAAI,GAAK,EAAK,SAAS,CAAI,CACxD,CAEA,SAAS,EAAY,EAAuB,CAC1C,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAS,EAAY,EAAuB,CAC1C,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./_virtual/_rolldown/runtime.cjs");let t=require("node:fs/promises"),n=require("node:path");n=e.__toESM(n,1);const r={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},i=`code-gauge.config.json`,a=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],o={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function s(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const c={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function l(e,t){let n={...r};for(let r of Object.keys(n))n[r]=e[c[r]]??t.thresholds?.[r]??n[r];return{thresholds:n,profileThresholds:u(o,t.languageThresholds),maxFindings:e.maxFindings??t.maxFindings??20,largestFiles:e.largestFiles??t.largestFiles??0,includeTests:e.includeTests??t.includeTests??!1,failOnRisk:e.failOnRisk??t.failOnRisk??!1,failOnError:e.failOnError??t.failOnError??!1,json:e.json??!1,tsconfig:e.tsconfig??t.tsconfig}}function u(e,t){let n={};for(let r of a){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function d(e,n){let r=e??await f(n);if(!r)return{};let i;try{i=await(0,t.readFile)(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${v(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${v(e)}`)}return m(a,r)}async function f(e){let t=e;for(;;){let e=n.default.join(t,i);if(await p(e))return e;let r=n.default.dirname(t);if(r===t)return;t=r}}async function p(e){try{return(await(0,t.stat)(e)).isFile()}catch{return!1}}function m(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=h(n.thresholds,`thresholds`,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!a.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${a.join(`, `)}).`);e[r]=h(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=g(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=g(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=_(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function h(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let i={};for(let[a,o]of Object.entries(e)){if(!(a in r))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=g(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);i[a]=e}return i}function g(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function _(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function v(e){return e instanceof Error?e.message:String(e)}exports.configFileName=i,exports.defaultProfileThresholds=o,exports.defaultThresholds=r,exports.loadConfig=d,exports.profileKeys=a,exports.resolveOptions=l,exports.resolveThresholds=s;
1
+ "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./duplication.cjs");let n=require("node:fs/promises"),r=require("node:path");r=e.__toESM(r,1);const i={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,crossFileDuplicateBlock:2,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},a=`code-gauge.config.json`,o=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],s={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function c(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const l={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,crossFileDuplicateBlock:`crossFileDuplicateBlockThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function u(e,n){let r={...i};for(let t of Object.keys(r))r[t]=e[l[t]]??n.thresholds?.[t]??r[t];return{thresholds:r,duplication:{minTokens:e.duplicationMinTokens??n.duplication?.minTokens??t.defaultDuplicationOptions.minTokens,maxGapTokens:e.duplicationMaxGapTokens??n.duplication?.maxGapTokens??t.defaultDuplicationOptions.maxGapTokens},profileThresholds:d(s,n.languageThresholds),maxFindings:e.maxFindings??n.maxFindings??20,largestFiles:e.largestFiles??n.largestFiles??0,includeTests:e.includeTests??n.includeTests??!1,failOnRisk:e.failOnRisk??n.failOnRisk??!1,failOnError:e.failOnError??n.failOnError??!1,json:e.json??!1,tsconfig:e.tsconfig??n.tsconfig}}function d(e,t){let n={};for(let r of o){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function f(e,t){let r=e??await p(t);if(!r)return{};let i;try{i=await(0,n.readFile)(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${x(e)}`)}return h(a,r)}async function p(e){let t=e;for(;;){let e=r.default.join(t,a);if(await m(e))return e;let n=r.default.dirname(t);if(n===t)return;t=n}}async function m(e){try{return(await(0,n.stat)(e)).isFile()}catch{return!1}}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=g(n.thresholds,`thresholds`,t)),n.duplication!==void 0&&(r.duplication=_(n.duplication,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!o.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${o.join(`, `)}).`);e[r]=g(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=y(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=y(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=b(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function g(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let r={};for(let[a,o]of Object.entries(e)){if(!(a in i))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=y(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);r[a]=e}return r}function _(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=y(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=v(i,`duplication.maxGapTokens`,t);else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens or maxGapTokens).`);return n}function v(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`Config file "${n}": "${t}" must be a non-negative integer.`);return e}function y(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}exports.configFileName=a,exports.defaultProfileThresholds=s,exports.defaultThresholds=i,exports.loadConfig=f,exports.profileKeys=o,exports.resolveOptions=u,exports.resolveThresholds=c;
2
2
  //# sourceMappingURL=cliConfig.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.cjs","names":["path"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\n/** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */\nexport interface Thresholds {\n fileLoc: number;\n functionLoc: number;\n componentLoc: number;\n cognitive: number;\n cyclomatic: number;\n call: number;\n import: number;\n fanOut: number;\n parameter: number;\n duplicateBlock: number;\n /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */\n duplicationRatioPercent: number;\n transitiveDependency: number;\n structuralBreadth: number;\n structuralCoordination: number;\n stateMutation: number;\n duplicateSymbolGroup: number;\n}\n\n// Defaults tuned against blind human labels across five representative WillBooster/WillBoosterLab\n// repositories to maximize F1 (precision without sacrificing recall); see PR for the evaluation.\nexport const defaultThresholds: Thresholds = {\n fileLoc: 500,\n functionLoc: 120,\n componentLoc: 350,\n cognitive: 25,\n cyclomatic: 20,\n call: 50,\n import: 25,\n fanOut: 10,\n parameter: 8,\n duplicateBlock: 2,\n duplicationRatioPercent: 30,\n transitiveDependency: 25,\n structuralBreadth: 8,\n structuralCoordination: 300,\n stateMutation: 50,\n duplicateSymbolGroup: 5,\n};\n\nexport const defaultMaxFindings = 20;\nexport const configFileName = 'code-gauge.config.json';\n\n/**\n * Profile keys for per-language and React-specific threshold overrides. A file resolves its\n * thresholds as base → its language profile → the `react` profile (when it contains a component).\n */\nexport const profileKeys = [\n 'javascript',\n 'jsx',\n 'typescript',\n 'tsx',\n 'python',\n 'go',\n 'rust',\n 'java',\n 'ruby',\n 'c',\n 'cpp',\n 'react',\n] as const;\nexport type ProfileKey = (typeof profileKeys)[number];\n\n/**\n * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by\n * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)\n * and coordinates more per file, while React files import roughly twice as many sources as pure TS.\n */\nexport const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {\n python: { stateMutation: 90, structuralCoordination: 350 },\n // Ruby scores state mutation via assignments like Python (bindings are assignments).\n ruby: { stateMutation: 90, structuralCoordination: 350 },\n react: { import: 30 },\n};\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n thresholds?: Partial<Thresholds>;\n /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */\n languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n tsconfig?: string;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n thresholds: Thresholds;\n profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings: number;\n /** Number of largest files by code LOC to list; 0 disables the section. */\n largestFiles: number;\n includeTests: boolean;\n failOnRisk: boolean;\n failOnError: boolean;\n json: boolean;\n tsconfig?: string;\n}\n\n/**\n * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile\n * and then, when the file contains a React component, the `react` profile.\n */\nexport function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds {\n let thresholds = options.thresholds;\n const languageOverride = options.profileThresholds[language as ProfileKey];\n if (languageOverride) {\n thresholds = { ...thresholds, ...languageOverride };\n }\n if (isReact && options.profileThresholds.react) {\n thresholds = { ...thresholds, ...options.profileThresholds.react };\n }\n return thresholds;\n}\n\n/** Raw command-line options; every threshold is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n fileLocThreshold?: number;\n functionLocThreshold?: number;\n componentLocThreshold?: number;\n cognitiveThreshold?: number;\n cyclomaticThreshold?: number;\n callThreshold?: number;\n importThreshold?: number;\n fanOutThreshold?: number;\n parameterThreshold?: number;\n duplicateBlockThreshold?: number;\n duplicationRatioPercentThreshold?: number;\n transitiveDependencyThreshold?: number;\n structuralBreadthThreshold?: number;\n structuralCoordinationThreshold?: number;\n stateMutationThreshold?: number;\n duplicateSymbolGroupThreshold?: number;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n json?: boolean;\n tsconfig?: string;\n}\n\n/** Maps each threshold to the matching command-line flag; the config key equals the flag without the `-threshold` suffix. */\nconst thresholdCliKeys: Record<keyof Thresholds, keyof CliOptions> = {\n fileLoc: 'fileLocThreshold',\n functionLoc: 'functionLocThreshold',\n componentLoc: 'componentLocThreshold',\n cognitive: 'cognitiveThreshold',\n cyclomatic: 'cyclomaticThreshold',\n call: 'callThreshold',\n import: 'importThreshold',\n fanOut: 'fanOutThreshold',\n parameter: 'parameterThreshold',\n duplicateBlock: 'duplicateBlockThreshold',\n duplicationRatioPercent: 'duplicationRatioPercentThreshold',\n transitiveDependency: 'transitiveDependencyThreshold',\n structuralBreadth: 'structuralBreadthThreshold',\n structuralCoordination: 'structuralCoordinationThreshold',\n stateMutation: 'stateMutationThreshold',\n duplicateSymbolGroup: 'duplicateSymbolGroupThreshold',\n};\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n const thresholds = { ...defaultThresholds };\n for (const key of Object.keys(thresholds) as (keyof Thresholds)[]) {\n thresholds[key] = (cli[thresholdCliKeys[key]] as number | undefined) ?? config.thresholds?.[key] ?? thresholds[key];\n }\n\n return {\n thresholds,\n profileThresholds: mergeProfileThresholds(defaultProfileThresholds, config.languageThresholds),\n maxFindings: cli.maxFindings ?? config.maxFindings ?? defaultMaxFindings,\n largestFiles: cli.largestFiles ?? config.largestFiles ?? 0,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnRisk: cli.failOnRisk ?? config.failOnRisk ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n tsconfig: cli.tsconfig ?? config.tsconfig,\n };\n}\n\n/** Merges user-supplied per-profile overrides on top of the built-in ones, per profile. */\nfunction mergeProfileThresholds(\n defaults: Partial<Record<ProfileKey, Partial<Thresholds>>>,\n overrides: Partial<Record<ProfileKey, Partial<Thresholds>>> | undefined\n): Partial<Record<ProfileKey, Partial<Thresholds>>> {\n const merged: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const key of profileKeys) {\n const combined = { ...defaults[key], ...overrides?.[key] };\n if (Object.keys(combined).length > 0) {\n merged[key] = combined;\n }\n }\n return merged;\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const config: CodeGaugeConfig = {};\n\n if (raw.thresholds !== undefined) {\n config.thresholds = validateThresholdObject(raw.thresholds, 'thresholds', configFile);\n }\n\n if (raw.languageThresholds !== undefined) {\n if (\n typeof raw.languageThresholds !== 'object' ||\n raw.languageThresholds === null ||\n Array.isArray(raw.languageThresholds)\n ) {\n throw new Error(`Config file \"${configFile}\": \"languageThresholds\" must be an object.`);\n }\n const languageThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const [profile, thresholds] of Object.entries(raw.languageThresholds as Record<string, unknown>)) {\n if (!(profileKeys as readonly string[]).includes(profile)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language profile \"${profile}\" (expected one of ${profileKeys.join(', ')}).`\n );\n }\n languageThresholds[profile as ProfileKey] = validateThresholdObject(\n thresholds,\n `languageThresholds.${profile}`,\n configFile\n );\n }\n config.languageThresholds = languageThresholds;\n }\n\n if (raw.maxFindings !== undefined) {\n config.maxFindings = requirePositiveInteger(raw.maxFindings, 'maxFindings', configFile);\n }\n if (raw.largestFiles !== undefined) {\n config.largestFiles = requirePositiveInteger(raw.largestFiles, 'largestFiles', configFile);\n }\n for (const key of ['includeTests', 'failOnRisk', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n if (raw.tsconfig !== undefined) {\n if (typeof raw.tsconfig !== 'string') {\n throw new TypeError(`Config file \"${configFile}\": \"tsconfig\" must be a string.`);\n }\n config.tsconfig = raw.tsconfig;\n }\n\n return config;\n}\n\nfunction validateThresholdObject(value: unknown, label: string, configFile: string): Partial<Thresholds> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${label}\" must be an object.`);\n }\n const thresholds: Partial<Thresholds> = {};\n for (const [key, threshold] of Object.entries(value as Record<string, unknown>)) {\n if (!(key in defaultThresholds)) {\n throw new Error(`Config file \"${configFile}\": unknown threshold \"${key}\" in \"${label}\".`);\n }\n const parsed = requirePositiveInteger(threshold, `${label}.${key}`, configFile);\n if (key === 'duplicationRatioPercent' && parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"${label}.${key}\" must be between 1 and 100.`);\n }\n thresholds[key as keyof Thresholds] = parsed;\n }\n return thresholds;\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n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B,CAEA,OAAO,CACT,CAEA,SAAS,EAAwB,EAAgB,EAAe,EAAyC,CACvG,GAAI,OAAO,GAAU,WAAY,GAAkB,MAAM,QAAQ,CAAK,EACpE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAM,qBAAqB,EAE9E,IAAM,EAAkC,CAAC,EACzC,IAAK,GAAM,CAAC,EAAK,KAAc,OAAO,QAAQ,CAAgC,EAAG,CAC/E,GAAI,EAAE,KAAO,GACX,MAAU,MAAM,gBAAgB,EAAW,wBAAwB,EAAI,QAAQ,EAAM,GAAG,EAE1F,IAAM,EAAS,EAAuB,EAAW,GAAG,EAAM,GAAG,IAAO,CAAU,EAC9E,GAAI,IAAQ,2BAA6B,EAAS,IAChD,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAM,GAAG,EAAI,6BAA6B,EAE7F,EAAW,GAA2B,CACxC,CACA,OAAO,CACT,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","path","stat"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\n/** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */\nexport interface Thresholds {\n fileLoc: number;\n functionLoc: number;\n componentLoc: number;\n cognitive: number;\n cyclomatic: number;\n call: number;\n import: number;\n fanOut: number;\n parameter: number;\n duplicateBlock: number;\n /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */\n duplicationRatioPercent: number;\n /** Number of cross-file duplicate block groups a file participates in. */\n crossFileDuplicateBlock: number;\n transitiveDependency: number;\n structuralBreadth: number;\n structuralCoordination: number;\n stateMutation: number;\n duplicateSymbolGroup: number;\n}\n\n// Defaults tuned against blind human labels across five representative WillBooster/WillBoosterLab\n// repositories to maximize F1 (precision without sacrificing recall); see PR for the evaluation.\nexport const defaultThresholds: Thresholds = {\n fileLoc: 500,\n functionLoc: 120,\n componentLoc: 350,\n cognitive: 25,\n cyclomatic: 20,\n call: 50,\n import: 25,\n fanOut: 10,\n parameter: 8,\n duplicateBlock: 2,\n duplicationRatioPercent: 30,\n crossFileDuplicateBlock: 2,\n transitiveDependency: 25,\n structuralBreadth: 8,\n structuralCoordination: 300,\n stateMutation: 50,\n duplicateSymbolGroup: 5,\n};\n\nexport const defaultMaxFindings = 20;\nexport const configFileName = 'code-gauge.config.json';\n\n/**\n * Profile keys for per-language and React-specific threshold overrides. A file resolves its\n * thresholds as base → its language profile → the `react` profile (when it contains a component).\n */\nexport const profileKeys = [\n 'javascript',\n 'jsx',\n 'typescript',\n 'tsx',\n 'python',\n 'go',\n 'rust',\n 'java',\n 'ruby',\n 'c',\n 'cpp',\n 'react',\n] as const;\nexport type ProfileKey = (typeof profileKeys)[number];\n\n/**\n * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by\n * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)\n * and coordinates more per file, while React files import roughly twice as many sources as pure TS.\n */\nexport const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {\n python: { stateMutation: 90, structuralCoordination: 350 },\n // Ruby scores state mutation via assignments like Python (bindings are assignments).\n ruby: { stateMutation: 90, structuralCoordination: 350 },\n react: { import: 30 },\n};\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n thresholds?: Partial<Thresholds>;\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */\n languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n tsconfig?: string;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n thresholds: Thresholds;\n duplication: Required<DuplicationOptions>;\n profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings: number;\n /** Number of largest files by code LOC to list; 0 disables the section. */\n largestFiles: number;\n includeTests: boolean;\n failOnRisk: boolean;\n failOnError: boolean;\n json: boolean;\n tsconfig?: string;\n}\n\n/**\n * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile\n * and then, when the file contains a React component, the `react` profile.\n */\nexport function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds {\n let thresholds = options.thresholds;\n const languageOverride = options.profileThresholds[language as ProfileKey];\n if (languageOverride) {\n thresholds = { ...thresholds, ...languageOverride };\n }\n if (isReact && options.profileThresholds.react) {\n thresholds = { ...thresholds, ...options.profileThresholds.react };\n }\n return thresholds;\n}\n\n/** Raw command-line options; every threshold is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n fileLocThreshold?: number;\n functionLocThreshold?: number;\n componentLocThreshold?: number;\n cognitiveThreshold?: number;\n cyclomaticThreshold?: number;\n callThreshold?: number;\n importThreshold?: number;\n fanOutThreshold?: number;\n parameterThreshold?: number;\n duplicateBlockThreshold?: number;\n duplicationRatioPercentThreshold?: number;\n crossFileDuplicateBlockThreshold?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n transitiveDependencyThreshold?: number;\n structuralBreadthThreshold?: number;\n structuralCoordinationThreshold?: number;\n stateMutationThreshold?: number;\n duplicateSymbolGroupThreshold?: number;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n json?: boolean;\n tsconfig?: string;\n}\n\n/** Maps each threshold to the matching command-line flag; the config key equals the flag without the `-threshold` suffix. */\nconst thresholdCliKeys: Record<keyof Thresholds, keyof CliOptions> = {\n fileLoc: 'fileLocThreshold',\n functionLoc: 'functionLocThreshold',\n componentLoc: 'componentLocThreshold',\n cognitive: 'cognitiveThreshold',\n cyclomatic: 'cyclomaticThreshold',\n call: 'callThreshold',\n import: 'importThreshold',\n fanOut: 'fanOutThreshold',\n parameter: 'parameterThreshold',\n duplicateBlock: 'duplicateBlockThreshold',\n duplicationRatioPercent: 'duplicationRatioPercentThreshold',\n crossFileDuplicateBlock: 'crossFileDuplicateBlockThreshold',\n transitiveDependency: 'transitiveDependencyThreshold',\n structuralBreadth: 'structuralBreadthThreshold',\n structuralCoordination: 'structuralCoordinationThreshold',\n stateMutation: 'stateMutationThreshold',\n duplicateSymbolGroup: 'duplicateSymbolGroupThreshold',\n};\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n const thresholds = { ...defaultThresholds };\n for (const key of Object.keys(thresholds) as (keyof Thresholds)[]) {\n thresholds[key] = (cli[thresholdCliKeys[key]] as number | undefined) ?? config.thresholds?.[key] ?? thresholds[key];\n }\n\n return {\n thresholds,\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n },\n profileThresholds: mergeProfileThresholds(defaultProfileThresholds, config.languageThresholds),\n maxFindings: cli.maxFindings ?? config.maxFindings ?? defaultMaxFindings,\n largestFiles: cli.largestFiles ?? config.largestFiles ?? 0,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnRisk: cli.failOnRisk ?? config.failOnRisk ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n tsconfig: cli.tsconfig ?? config.tsconfig,\n };\n}\n\n/** Merges user-supplied per-profile overrides on top of the built-in ones, per profile. */\nfunction mergeProfileThresholds(\n defaults: Partial<Record<ProfileKey, Partial<Thresholds>>>,\n overrides: Partial<Record<ProfileKey, Partial<Thresholds>>> | undefined\n): Partial<Record<ProfileKey, Partial<Thresholds>>> {\n const merged: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const key of profileKeys) {\n const combined = { ...defaults[key], ...overrides?.[key] };\n if (Object.keys(combined).length > 0) {\n merged[key] = combined;\n }\n }\n return merged;\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const config: CodeGaugeConfig = {};\n\n if (raw.thresholds !== undefined) {\n config.thresholds = validateThresholdObject(raw.thresholds, 'thresholds', configFile);\n }\n\n if (raw.duplication !== undefined) {\n config.duplication = validateDuplicationObject(raw.duplication, configFile);\n }\n\n if (raw.languageThresholds !== undefined) {\n if (\n typeof raw.languageThresholds !== 'object' ||\n raw.languageThresholds === null ||\n Array.isArray(raw.languageThresholds)\n ) {\n throw new Error(`Config file \"${configFile}\": \"languageThresholds\" must be an object.`);\n }\n const languageThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const [profile, thresholds] of Object.entries(raw.languageThresholds as Record<string, unknown>)) {\n if (!(profileKeys as readonly string[]).includes(profile)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language profile \"${profile}\" (expected one of ${profileKeys.join(', ')}).`\n );\n }\n languageThresholds[profile as ProfileKey] = validateThresholdObject(\n thresholds,\n `languageThresholds.${profile}`,\n configFile\n );\n }\n config.languageThresholds = languageThresholds;\n }\n\n if (raw.maxFindings !== undefined) {\n config.maxFindings = requirePositiveInteger(raw.maxFindings, 'maxFindings', configFile);\n }\n if (raw.largestFiles !== undefined) {\n config.largestFiles = requirePositiveInteger(raw.largestFiles, 'largestFiles', configFile);\n }\n for (const key of ['includeTests', 'failOnRisk', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n if (raw.tsconfig !== undefined) {\n if (typeof raw.tsconfig !== 'string') {\n throw new TypeError(`Config file \"${configFile}\": \"tsconfig\" must be a string.`);\n }\n config.tsconfig = raw.tsconfig;\n }\n\n return config;\n}\n\nfunction validateThresholdObject(value: unknown, label: string, configFile: string): Partial<Thresholds> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${label}\" must be an object.`);\n }\n const thresholds: Partial<Thresholds> = {};\n for (const [key, threshold] of Object.entries(value as Record<string, unknown>)) {\n if (!(key in defaultThresholds)) {\n throw new Error(`Config file \"${configFile}\": unknown threshold \"${key}\" in \"${label}\".`);\n }\n const parsed = requirePositiveInteger(threshold, `${label}.${key}`, configFile);\n if (key === 'duplicationRatioPercent' && parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"${label}.${key}\" must be between 1 and 100.`);\n }\n thresholds[key as keyof Thresholds] = parsed;\n }\n return thresholds;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens or maxGapTokens).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a non-negative integer.`);\n }\n return value;\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"0KA8BA,MAAa,EAAgC,CAC3C,QAAS,IACT,YAAa,IACb,aAAc,IACd,UAAW,GACX,WAAY,GACZ,KAAM,GACN,OAAQ,GACR,OAAQ,GACR,UAAW,EACX,eAAgB,EAChB,wBAAyB,GACzB,wBAAyB,EACzB,qBAAsB,GACtB,kBAAmB,EACnB,uBAAwB,IACxB,cAAe,GACf,qBAAsB,CACxB,EAGa,EAAiB,yBAMjB,EAAc,CACzB,aACA,MACA,aACA,MACA,SACA,KACA,OACA,OACA,OACA,IACA,MACA,OACF,EAQa,EAA6E,CACxF,OAAQ,CAAE,cAAe,GAAI,uBAAwB,GAAI,EAEzD,KAAM,CAAE,cAAe,GAAI,uBAAwB,GAAI,EACvD,MAAO,CAAE,OAAQ,EAAG,CACtB,EAoCA,SAAgB,EAAkB,EAA0B,EAAkB,EAA8B,CAC1G,IAAI,EAAa,EAAQ,WACnB,EAAmB,EAAQ,kBAAkB,GAOnD,OANI,IACF,EAAa,CAAE,GAAG,EAAY,GAAG,CAAiB,GAEhD,GAAW,EAAQ,kBAAkB,QACvC,EAAa,CAAE,GAAG,EAAY,GAAG,EAAQ,kBAAkB,KAAM,GAE5D,CACT,CAkCA,MAAM,EAA+D,CACnE,QAAS,mBACT,YAAa,uBACb,aAAc,wBACd,UAAW,qBACX,WAAY,sBACZ,KAAM,gBACN,OAAQ,kBACR,OAAQ,kBACR,UAAW,qBACX,eAAgB,0BAChB,wBAAyB,mCACzB,wBAAyB,mCACzB,qBAAsB,gCACtB,kBAAmB,6BACnB,uBAAwB,kCACxB,cAAe,yBACf,qBAAsB,+BACxB,EAGA,SAAgB,EAAe,EAAiB,EAA0C,CACxF,IAAM,EAAa,CAAE,GAAG,CAAkB,EAC1C,IAAK,IAAM,KAAO,OAAO,KAAK,CAAU,EACtC,EAAW,GAAQ,EAAI,EAAiB,KAAgC,EAAO,a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EAAI,yDACvD,EAGJ,OAAO,CACT,CAEA,SAAS,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,kCAAkC,EAEzF,OAAO,CACT,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
@@ -1,3 +1,4 @@
1
+ import type { DuplicationOptions } from './types.js';
1
2
  /** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */
2
3
  export interface Thresholds {
3
4
  fileLoc: number;
@@ -12,6 +13,8 @@ export interface Thresholds {
12
13
  duplicateBlock: number;
13
14
  /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */
14
15
  duplicationRatioPercent: number;
16
+ /** Number of cross-file duplicate block groups a file participates in. */
17
+ crossFileDuplicateBlock: number;
15
18
  transitiveDependency: number;
16
19
  structuralBreadth: number;
17
20
  structuralCoordination: number;
@@ -36,6 +39,8 @@ export declare const defaultProfileThresholds: Partial<Record<ProfileKey, Partia
36
39
  /** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */
37
40
  export interface CodeGaugeConfig {
38
41
  thresholds?: Partial<Thresholds>;
42
+ /** Duplication detection settings applied to every measured file. */
43
+ duplication?: DuplicationOptions;
39
44
  /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */
40
45
  languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;
41
46
  maxFindings?: number;
@@ -48,6 +53,7 @@ export interface CodeGaugeConfig {
48
53
  /** Options after merging command-line flags, the configuration file, and the built-in defaults. */
49
54
  export interface ResolvedOptions {
50
55
  thresholds: Thresholds;
56
+ duplication: Required<DuplicationOptions>;
51
57
  profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;
52
58
  maxFindings: number;
53
59
  /** Number of largest files by code LOC to list; 0 disables the section. */
@@ -77,6 +83,9 @@ export interface CliOptions {
77
83
  parameterThreshold?: number;
78
84
  duplicateBlockThreshold?: number;
79
85
  duplicationRatioPercentThreshold?: number;
86
+ crossFileDuplicateBlockThreshold?: number;
87
+ duplicationMinTokens?: number;
88
+ duplicationMaxGapTokens?: number;
80
89
  transitiveDependencyThreshold?: number;
81
90
  structuralBreadthThreshold?: number;
82
91
  structuralCoordinationThreshold?: number;
package/dist/cliConfig.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readFile as e,stat as t}from"node:fs/promises";import n from"node:path";const r={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},i=`code-gauge.config.json`,a=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],o={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function s(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const c={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function l(e,t){let n={...r};for(let r of Object.keys(n))n[r]=e[c[r]]??t.thresholds?.[r]??n[r];return{thresholds:n,profileThresholds:u(o,t.languageThresholds),maxFindings:e.maxFindings??t.maxFindings??20,largestFiles:e.largestFiles??t.largestFiles??0,includeTests:e.includeTests??t.includeTests??!1,failOnRisk:e.failOnRisk??t.failOnRisk??!1,failOnError:e.failOnError??t.failOnError??!1,json:e.json??!1,tsconfig:e.tsconfig??t.tsconfig}}function u(e,t){let n={};for(let r of a){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function d(t,n){let r=t??await f(n);if(!r)return{};let i;try{i=await e(r,`utf8`)}catch(e){if(t)throw Error(`Cannot read config file "${r}": ${v(e)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${v(e)}`)}return m(a,r)}async function f(e){let t=e;for(;;){let e=n.join(t,i);if(await p(e))return e;let r=n.dirname(t);if(r===t)return;t=r}}async function p(e){try{return(await t(e)).isFile()}catch{return!1}}function m(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=h(n.thresholds,`thresholds`,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!a.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${a.join(`, `)}).`);e[r]=h(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=g(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=g(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=_(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function h(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let i={};for(let[a,o]of Object.entries(e)){if(!(a in r))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=g(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);i[a]=e}return i}function g(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function _(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function v(e){return e instanceof Error?e.message:String(e)}export{i as configFileName,o as defaultProfileThresholds,r as defaultThresholds,d as loadConfig,a as profileKeys,l as resolveOptions,s as resolveThresholds};
1
+ import{defaultDuplicationOptions as e}from"./duplication.js";import{readFile as t,stat as n}from"node:fs/promises";import r from"node:path";const i={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,crossFileDuplicateBlock:2,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},a=`code-gauge.config.json`,o=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],s={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function c(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const l={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,crossFileDuplicateBlock:`crossFileDuplicateBlockThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function u(t,n){let r={...i};for(let e of Object.keys(r))r[e]=t[l[e]]??n.thresholds?.[e]??r[e];return{thresholds:r,duplication:{minTokens:t.duplicationMinTokens??n.duplication?.minTokens??e.minTokens,maxGapTokens:t.duplicationMaxGapTokens??n.duplication?.maxGapTokens??e.maxGapTokens},profileThresholds:d(s,n.languageThresholds),maxFindings:t.maxFindings??n.maxFindings??20,largestFiles:t.largestFiles??n.largestFiles??0,includeTests:t.includeTests??n.includeTests??!1,failOnRisk:t.failOnRisk??n.failOnRisk??!1,failOnError:t.failOnError??n.failOnError??!1,json:t.json??!1,tsconfig:t.tsconfig??n.tsconfig}}function d(e,t){let n={};for(let r of o){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function f(e,n){let r=e??await p(n);if(!r)return{};let i;try{i=await t(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${x(e)}`)}return h(a,r)}async function p(e){let t=e;for(;;){let e=r.join(t,a);if(await m(e))return e;let n=r.dirname(t);if(n===t)return;t=n}}async function m(e){try{return(await n(e)).isFile()}catch{return!1}}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=g(n.thresholds,`thresholds`,t)),n.duplication!==void 0&&(r.duplication=_(n.duplication,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!o.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${o.join(`, `)}).`);e[r]=g(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=y(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=y(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=b(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function g(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let r={};for(let[a,o]of Object.entries(e)){if(!(a in i))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=y(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);r[a]=e}return r}function _(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=y(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=v(i,`duplication.maxGapTokens`,t);else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens or maxGapTokens).`);return n}function v(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`Config file "${n}": "${t}" must be a non-negative integer.`);return e}function y(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}export{a as configFileName,s as defaultProfileThresholds,i as defaultThresholds,f as loadConfig,o as profileKeys,u as resolveOptions,c as resolveThresholds};
2
2
  //# sourceMappingURL=cliConfig.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\n/** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */\nexport interface Thresholds {\n fileLoc: number;\n functionLoc: number;\n componentLoc: number;\n cognitive: number;\n cyclomatic: number;\n call: number;\n import: number;\n fanOut: number;\n parameter: number;\n duplicateBlock: number;\n /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */\n duplicationRatioPercent: number;\n transitiveDependency: number;\n structuralBreadth: number;\n structuralCoordination: number;\n stateMutation: number;\n duplicateSymbolGroup: number;\n}\n\n// Defaults tuned against blind human labels across five representative WillBooster/WillBoosterLab\n// repositories to maximize F1 (precision without sacrificing recall); see PR for the evaluation.\nexport const defaultThresholds: Thresholds = {\n fileLoc: 500,\n functionLoc: 120,\n componentLoc: 350,\n cognitive: 25,\n cyclomatic: 20,\n call: 50,\n import: 25,\n fanOut: 10,\n parameter: 8,\n duplicateBlock: 2,\n duplicationRatioPercent: 30,\n transitiveDependency: 25,\n structuralBreadth: 8,\n structuralCoordination: 300,\n stateMutation: 50,\n duplicateSymbolGroup: 5,\n};\n\nexport const defaultMaxFindings = 20;\nexport const configFileName = 'code-gauge.config.json';\n\n/**\n * Profile keys for per-language and React-specific threshold overrides. A file resolves its\n * thresholds as base → its language profile → the `react` profile (when it contains a component).\n */\nexport const profileKeys = [\n 'javascript',\n 'jsx',\n 'typescript',\n 'tsx',\n 'python',\n 'go',\n 'rust',\n 'java',\n 'ruby',\n 'c',\n 'cpp',\n 'react',\n] as const;\nexport type ProfileKey = (typeof profileKeys)[number];\n\n/**\n * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by\n * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)\n * and coordinates more per file, while React files import roughly twice as many sources as pure TS.\n */\nexport const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {\n python: { stateMutation: 90, structuralCoordination: 350 },\n // Ruby scores state mutation via assignments like Python (bindings are assignments).\n ruby: { stateMutation: 90, structuralCoordination: 350 },\n react: { import: 30 },\n};\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n thresholds?: Partial<Thresholds>;\n /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */\n languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n tsconfig?: string;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n thresholds: Thresholds;\n profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings: number;\n /** Number of largest files by code LOC to list; 0 disables the section. */\n largestFiles: number;\n includeTests: boolean;\n failOnRisk: boolean;\n failOnError: boolean;\n json: boolean;\n tsconfig?: string;\n}\n\n/**\n * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile\n * and then, when the file contains a React component, the `react` profile.\n */\nexport function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds {\n let thresholds = options.thresholds;\n const languageOverride = options.profileThresholds[language as ProfileKey];\n if (languageOverride) {\n thresholds = { ...thresholds, ...languageOverride };\n }\n if (isReact && options.profileThresholds.react) {\n thresholds = { ...thresholds, ...options.profileThresholds.react };\n }\n return thresholds;\n}\n\n/** Raw command-line options; every threshold is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n fileLocThreshold?: number;\n functionLocThreshold?: number;\n componentLocThreshold?: number;\n cognitiveThreshold?: number;\n cyclomaticThreshold?: number;\n callThreshold?: number;\n importThreshold?: number;\n fanOutThreshold?: number;\n parameterThreshold?: number;\n duplicateBlockThreshold?: number;\n duplicationRatioPercentThreshold?: number;\n transitiveDependencyThreshold?: number;\n structuralBreadthThreshold?: number;\n structuralCoordinationThreshold?: number;\n stateMutationThreshold?: number;\n duplicateSymbolGroupThreshold?: number;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n json?: boolean;\n tsconfig?: string;\n}\n\n/** Maps each threshold to the matching command-line flag; the config key equals the flag without the `-threshold` suffix. */\nconst thresholdCliKeys: Record<keyof Thresholds, keyof CliOptions> = {\n fileLoc: 'fileLocThreshold',\n functionLoc: 'functionLocThreshold',\n componentLoc: 'componentLocThreshold',\n cognitive: 'cognitiveThreshold',\n cyclomatic: 'cyclomaticThreshold',\n call: 'callThreshold',\n import: 'importThreshold',\n fanOut: 'fanOutThreshold',\n parameter: 'parameterThreshold',\n duplicateBlock: 'duplicateBlockThreshold',\n duplicationRatioPercent: 'duplicationRatioPercentThreshold',\n transitiveDependency: 'transitiveDependencyThreshold',\n structuralBreadth: 'structuralBreadthThreshold',\n structuralCoordination: 'structuralCoordinationThreshold',\n stateMutation: 'stateMutationThreshold',\n duplicateSymbolGroup: 'duplicateSymbolGroupThreshold',\n};\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n const thresholds = { ...defaultThresholds };\n for (const key of Object.keys(thresholds) as (keyof Thresholds)[]) {\n thresholds[key] = (cli[thresholdCliKeys[key]] as number | undefined) ?? config.thresholds?.[key] ?? thresholds[key];\n }\n\n return {\n thresholds,\n profileThresholds: mergeProfileThresholds(defaultProfileThresholds, config.languageThresholds),\n maxFindings: cli.maxFindings ?? config.maxFindings ?? defaultMaxFindings,\n largestFiles: cli.largestFiles ?? config.largestFiles ?? 0,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnRisk: cli.failOnRisk ?? config.failOnRisk ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n tsconfig: cli.tsconfig ?? config.tsconfig,\n };\n}\n\n/** Merges user-supplied per-profile overrides on top of the built-in ones, per profile. */\nfunction mergeProfileThresholds(\n defaults: Partial<Record<ProfileKey, Partial<Thresholds>>>,\n overrides: Partial<Record<ProfileKey, Partial<Thresholds>>> | undefined\n): Partial<Record<ProfileKey, Partial<Thresholds>>> {\n const merged: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const key of profileKeys) {\n const combined = { ...defaults[key], ...overrides?.[key] };\n if (Object.keys(combined).length > 0) {\n merged[key] = combined;\n }\n }\n return merged;\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const config: CodeGaugeConfig = {};\n\n if (raw.thresholds !== undefined) {\n config.thresholds = validateThresholdObject(raw.thresholds, 'thresholds', configFile);\n }\n\n if (raw.languageThresholds !== undefined) {\n if (\n typeof raw.languageThresholds !== 'object' ||\n raw.languageThresholds === null ||\n Array.isArray(raw.languageThresholds)\n ) {\n throw new Error(`Config file \"${configFile}\": \"languageThresholds\" must be an object.`);\n }\n const languageThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const [profile, thresholds] of Object.entries(raw.languageThresholds as Record<string, unknown>)) {\n if (!(profileKeys as readonly string[]).includes(profile)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language profile \"${profile}\" (expected one of ${profileKeys.join(', ')}).`\n );\n }\n languageThresholds[profile as ProfileKey] = validateThresholdObject(\n thresholds,\n `languageThresholds.${profile}`,\n configFile\n );\n }\n config.languageThresholds = languageThresholds;\n }\n\n if (raw.maxFindings !== undefined) {\n config.maxFindings = requirePositiveInteger(raw.maxFindings, 'maxFindings', configFile);\n }\n if (raw.largestFiles !== undefined) {\n config.largestFiles = requirePositiveInteger(raw.largestFiles, 'largestFiles', configFile);\n }\n for (const key of ['includeTests', 'failOnRisk', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n if (raw.tsconfig !== undefined) {\n if (typeof raw.tsconfig !== 'string') {\n throw new TypeError(`Config file \"${configFile}\": \"tsconfig\" must be a string.`);\n }\n config.tsconfig = raw.tsconfig;\n }\n\n return config;\n}\n\nfunction validateThresholdObject(value: unknown, label: string, configFile: string): Partial<Thresholds> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${label}\" must be an object.`);\n }\n const thresholds: Partial<Thresholds> = {};\n for (const [key, threshold] of Object.entries(value as Record<string, unknown>)) {\n if (!(key in defaultThresholds)) {\n throw new Error(`Config file \"${configFile}\": unknown threshold \"${key}\" in \"${label}\".`);\n }\n const parsed = requirePositiveInteger(threshold, `${label}.${key}`, configFile);\n if (key === 'duplicationRatioPercent' && parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"${label}.${key}\" must be between 1 and 100.`);\n }\n thresholds[key as keyof Thresholds] = parsed;\n }\n return thresholds;\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"+EA0BA,MAAa,EAAgC,CAC3C,QAAS,IACT,YAAa,IACb,aAAc,IACd,UAAW,GACX,WAAY,GACZ,KAAM,GACN,OAAQ,GACR,OAAQ,GACR,UAAW,EACX,eAAgB,EAChB,wBAAyB,GACzB,qBAAsB,GACtB,kBAAmB,EACnB,uBAAwB,IACxB,cAAe,GACf,qBAAsB,CACxB,EAGa,EAAiB,yBAMjB,EAAc,CACzB,aACA,MACA,aACA,MACA,SACA,KACA,OACA,OACA,OACA,IACA,MACA,OACF,EAQa,EAA6E,CACxF,OAAQ,CAAE,cAAe,GAAI,uBAAwB,GAAI,EAEzD,KAAM,CAAE,cAAe,GAAI,uBAAwB,GAAI,EACvD,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AAW,GAA2B,CACxC,CACA,OAAO,CACT,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\n/** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */\nexport interface Thresholds {\n fileLoc: number;\n functionLoc: number;\n componentLoc: number;\n cognitive: number;\n cyclomatic: number;\n call: number;\n import: number;\n fanOut: number;\n parameter: number;\n duplicateBlock: number;\n /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */\n duplicationRatioPercent: number;\n /** Number of cross-file duplicate block groups a file participates in. */\n crossFileDuplicateBlock: number;\n transitiveDependency: number;\n structuralBreadth: number;\n structuralCoordination: number;\n stateMutation: number;\n duplicateSymbolGroup: number;\n}\n\n// Defaults tuned against blind human labels across five representative WillBooster/WillBoosterLab\n// repositories to maximize F1 (precision without sacrificing recall); see PR for the evaluation.\nexport const defaultThresholds: Thresholds = {\n fileLoc: 500,\n functionLoc: 120,\n componentLoc: 350,\n cognitive: 25,\n cyclomatic: 20,\n call: 50,\n import: 25,\n fanOut: 10,\n parameter: 8,\n duplicateBlock: 2,\n duplicationRatioPercent: 30,\n crossFileDuplicateBlock: 2,\n transitiveDependency: 25,\n structuralBreadth: 8,\n structuralCoordination: 300,\n stateMutation: 50,\n duplicateSymbolGroup: 5,\n};\n\nexport const defaultMaxFindings = 20;\nexport const configFileName = 'code-gauge.config.json';\n\n/**\n * Profile keys for per-language and React-specific threshold overrides. A file resolves its\n * thresholds as base → its language profile → the `react` profile (when it contains a component).\n */\nexport const profileKeys = [\n 'javascript',\n 'jsx',\n 'typescript',\n 'tsx',\n 'python',\n 'go',\n 'rust',\n 'java',\n 'ruby',\n 'c',\n 'cpp',\n 'react',\n] as const;\nexport type ProfileKey = (typeof profileKeys)[number];\n\n/**\n * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by\n * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)\n * and coordinates more per file, while React files import roughly twice as many sources as pure TS.\n */\nexport const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {\n python: { stateMutation: 90, structuralCoordination: 350 },\n // Ruby scores state mutation via assignments like Python (bindings are assignments).\n ruby: { stateMutation: 90, structuralCoordination: 350 },\n react: { import: 30 },\n};\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n thresholds?: Partial<Thresholds>;\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */\n languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n tsconfig?: string;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n thresholds: Thresholds;\n duplication: Required<DuplicationOptions>;\n profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings: number;\n /** Number of largest files by code LOC to list; 0 disables the section. */\n largestFiles: number;\n includeTests: boolean;\n failOnRisk: boolean;\n failOnError: boolean;\n json: boolean;\n tsconfig?: string;\n}\n\n/**\n * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile\n * and then, when the file contains a React component, the `react` profile.\n */\nexport function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds {\n let thresholds = options.thresholds;\n const languageOverride = options.profileThresholds[language as ProfileKey];\n if (languageOverride) {\n thresholds = { ...thresholds, ...languageOverride };\n }\n if (isReact && options.profileThresholds.react) {\n thresholds = { ...thresholds, ...options.profileThresholds.react };\n }\n return thresholds;\n}\n\n/** Raw command-line options; every threshold is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n fileLocThreshold?: number;\n functionLocThreshold?: number;\n componentLocThreshold?: number;\n cognitiveThreshold?: number;\n cyclomaticThreshold?: number;\n callThreshold?: number;\n importThreshold?: number;\n fanOutThreshold?: number;\n parameterThreshold?: number;\n duplicateBlockThreshold?: number;\n duplicationRatioPercentThreshold?: number;\n crossFileDuplicateBlockThreshold?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n transitiveDependencyThreshold?: number;\n structuralBreadthThreshold?: number;\n structuralCoordinationThreshold?: number;\n stateMutationThreshold?: number;\n duplicateSymbolGroupThreshold?: number;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n json?: boolean;\n tsconfig?: string;\n}\n\n/** Maps each threshold to the matching command-line flag; the config key equals the flag without the `-threshold` suffix. */\nconst thresholdCliKeys: Record<keyof Thresholds, keyof CliOptions> = {\n fileLoc: 'fileLocThreshold',\n functionLoc: 'functionLocThreshold',\n componentLoc: 'componentLocThreshold',\n cognitive: 'cognitiveThreshold',\n cyclomatic: 'cyclomaticThreshold',\n call: 'callThreshold',\n import: 'importThreshold',\n fanOut: 'fanOutThreshold',\n parameter: 'parameterThreshold',\n duplicateBlock: 'duplicateBlockThreshold',\n duplicationRatioPercent: 'duplicationRatioPercentThreshold',\n crossFileDuplicateBlock: 'crossFileDuplicateBlockThreshold',\n transitiveDependency: 'transitiveDependencyThreshold',\n structuralBreadth: 'structuralBreadthThreshold',\n structuralCoordination: 'structuralCoordinationThreshold',\n stateMutation: 'stateMutationThreshold',\n duplicateSymbolGroup: 'duplicateSymbolGroupThreshold',\n};\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n const thresholds = { ...defaultThresholds };\n for (const key of Object.keys(thresholds) as (keyof Thresholds)[]) {\n thresholds[key] = (cli[thresholdCliKeys[key]] as number | undefined) ?? config.thresholds?.[key] ?? thresholds[key];\n }\n\n return {\n thresholds,\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n },\n profileThresholds: mergeProfileThresholds(defaultProfileThresholds, config.languageThresholds),\n maxFindings: cli.maxFindings ?? config.maxFindings ?? defaultMaxFindings,\n largestFiles: cli.largestFiles ?? config.largestFiles ?? 0,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnRisk: cli.failOnRisk ?? config.failOnRisk ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n tsconfig: cli.tsconfig ?? config.tsconfig,\n };\n}\n\n/** Merges user-supplied per-profile overrides on top of the built-in ones, per profile. */\nfunction mergeProfileThresholds(\n defaults: Partial<Record<ProfileKey, Partial<Thresholds>>>,\n overrides: Partial<Record<ProfileKey, Partial<Thresholds>>> | undefined\n): Partial<Record<ProfileKey, Partial<Thresholds>>> {\n const merged: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const key of profileKeys) {\n const combined = { ...defaults[key], ...overrides?.[key] };\n if (Object.keys(combined).length > 0) {\n merged[key] = combined;\n }\n }\n return merged;\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const config: CodeGaugeConfig = {};\n\n if (raw.thresholds !== undefined) {\n config.thresholds = validateThresholdObject(raw.thresholds, 'thresholds', configFile);\n }\n\n if (raw.duplication !== undefined) {\n config.duplication = validateDuplicationObject(raw.duplication, configFile);\n }\n\n if (raw.languageThresholds !== undefined) {\n if (\n typeof raw.languageThresholds !== 'object' ||\n raw.languageThresholds === null ||\n Array.isArray(raw.languageThresholds)\n ) {\n throw new Error(`Config file \"${configFile}\": \"languageThresholds\" must be an object.`);\n }\n const languageThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const [profile, thresholds] of Object.entries(raw.languageThresholds as Record<string, unknown>)) {\n if (!(profileKeys as readonly string[]).includes(profile)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language profile \"${profile}\" (expected one of ${profileKeys.join(', ')}).`\n );\n }\n languageThresholds[profile as ProfileKey] = validateThresholdObject(\n thresholds,\n `languageThresholds.${profile}`,\n configFile\n );\n }\n config.languageThresholds = languageThresholds;\n }\n\n if (raw.maxFindings !== undefined) {\n config.maxFindings = requirePositiveInteger(raw.maxFindings, 'maxFindings', configFile);\n }\n if (raw.largestFiles !== undefined) {\n config.largestFiles = requirePositiveInteger(raw.largestFiles, 'largestFiles', configFile);\n }\n for (const key of ['includeTests', 'failOnRisk', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n if (raw.tsconfig !== undefined) {\n if (typeof raw.tsconfig !== 'string') {\n throw new TypeError(`Config file \"${configFile}\": \"tsconfig\" must be a string.`);\n }\n config.tsconfig = raw.tsconfig;\n }\n\n return config;\n}\n\nfunction validateThresholdObject(value: unknown, label: string, configFile: string): Partial<Thresholds> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${label}\" must be an object.`);\n }\n const thresholds: Partial<Thresholds> = {};\n for (const [key, threshold] of Object.entries(value as Record<string, unknown>)) {\n if (!(key in defaultThresholds)) {\n throw new Error(`Config file \"${configFile}\": unknown threshold \"${key}\" in \"${label}\".`);\n }\n const parsed = requirePositiveInteger(threshold, `${label}.${key}`, configFile);\n if (key === 'duplicationRatioPercent' && parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"${label}.${key}\" must be between 1 and 100.`);\n }\n thresholds[key as keyof Thresholds] = parsed;\n }\n return thresholds;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens or maxGapTokens).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a non-negative integer.`);\n }\n return value;\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"4IA8BA,MAAa,EAAgC,CAC3C,QAAS,IACT,YAAa,IACb,aAAc,IACd,UAAW,GACX,WAAY,GACZ,KAAM,GACN,OAAQ,GACR,OAAQ,GACR,UAAW,EACX,eAAgB,EAChB,wBAAyB,GACzB,wBAAyB,EACzB,qBAAsB,GACtB,kBAAmB,EACnB,uBAAwB,IACxB,cAAe,GACf,qBAAsB,CACxB,EAGa,EAAiB,yBAMjB,EAAc,CACzB,aACA,MACA,aACA,MACA,SACA,KACA,OACA,OACA,OACA,IACA,MACA,OACF,EAQa,EAA6E,CACxF,OAAQ,CAAE,cAAe,GAAI,uBAAwB,GAAI,EAEzD,KAAM,CAAE,cAAe,GAAI,uBAAwB,GAAI,EACvD,MAAO,CAAE,OAAQ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
1
+ "use strict";const e=require("./duplicateSelection.cjs");function t(t){let i=t.flatMap(({file:e,candidates:t},n)=>t.map(t=>({...t,regionBucket:n,file:e})));return r(e.selectMaximalGroups(i,n,(e,t)=>e.regionBucket-t.regionBucket||e.startIndex-t.startIndex))}function n(e){return e.length>=2&&new Set(e.map(e=>e.regionBucket)).size>=2}function r(e){let t=[],n=new Map,r=0;for(let i of e.values()){r+=i.length-1;let e=i.map(({file:e,startLine:t,endLine:n})=>({file:e,startLine:t,endLine:n})).toSorted((e,t)=>e.file.localeCompare(t.file)||e.startLine-t.startLine),a=[...new Set(e.map(({file:e})=>e))];for(let e of a)n.set(e,(n.get(e)??0)+1);t.push({files:a,occurrences:e,tokenCount:i[0]?.tokenCount??0})}return t.sort((e,t)=>t.tokenCount-e.tokenCount||(e.occurrences[0]?.file??``).localeCompare(t.occurrences[0]?.file??``)||(e.occurrences[0]?.startLine??0)-(t.occurrences[0]?.startLine??0)),{duplicateBlockCount:r,duplicateBlockGroupCountByFile:Object.fromEntries(n),groups:t}}exports.measureCrossFileDuplication=t;
2
+ //# sourceMappingURL=crossFileDuplication.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crossFileDuplication.cjs","names":["selectMaximalGroups"],"sources":["../src/crossFileDuplication.ts"],"sourcesContent":["import { selectMaximalGroups } from './duplicateSelection.js';\nimport type { CrossFileDuplicateCandidate } from './duplication.js';\n\nexport interface CrossFileDuplicationSourceFile {\n file: string;\n candidates: CrossFileDuplicateCandidate[];\n}\n\nexport interface CrossFileDuplicateOccurrence {\n endLine: number;\n file: string;\n startLine: number;\n}\n\nexport interface CrossFileDuplicateBlockGroup {\n files: string[];\n occurrences: CrossFileDuplicateOccurrence[];\n /** Normalized token count of one occurrence (all occurrences share it). */\n tokenCount: number;\n}\n\nexport interface CrossFileDuplicationMetrics {\n /** Number of redundant copies across all groups, i.e. sum of (occurrenceCount - 1). */\n duplicateBlockCount: number;\n /** Groups the file participates in, keyed by the file name passed in. */\n duplicateBlockGroupCountByFile: Record<string, number>;\n groups: CrossFileDuplicateBlockGroup[];\n}\n\ninterface SelectableCandidate extends CrossFileDuplicateCandidate {\n regionBucket: number;\n file: string;\n}\n\n/**\n * Detects code regions duplicated across files: per-file candidates (whole block subtrees and\n * full container runs, fingerprinted with the same normalization as within-file duplication) are\n * grouped by fingerprint, and only maximal, non-overlapping regions whose group spans at least two\n * files are counted. Groups that shrink to a single file during selection are shed — a\n * within-file repeat is already reported by that file's own duplication metrics.\n */\nexport function measureCrossFileDuplication(files: CrossFileDuplicationSourceFile[]): CrossFileDuplicationMetrics {\n const candidates: SelectableCandidate[] = files.flatMap(({ file, candidates }, fileIndex) =>\n candidates.map((candidate) => ({ ...candidate, regionBucket: fileIndex, file }))\n );\n const counted = selectMaximalGroups(\n candidates,\n spansMultipleFiles,\n // File index and position break coverage ties deterministically.\n (left, right) => left.regionBucket - right.regionBucket || left.startIndex - right.startIndex\n );\n return summarize(counted);\n}\n\nfunction spansMultipleFiles(group: SelectableCandidate[]): boolean {\n return group.length >= 2 && new Set(group.map((candidate) => candidate.regionBucket)).size >= 2;\n}\n\nfunction summarize(counted: Map<string, SelectableCandidate[]>): CrossFileDuplicationMetrics {\n const groups: CrossFileDuplicateBlockGroup[] = [];\n // Accumulated in a Map: file names are arbitrary strings, and a plain object would read\n // inherited properties for names like \"constructor\".\n const groupCountByFile = new Map<string, number>();\n let duplicateBlockCount = 0;\n for (const group of counted.values()) {\n duplicateBlockCount += group.length - 1;\n const occurrences = group\n .map(({ file, startLine, endLine }) => ({ file, startLine, endLine }))\n .toSorted((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n const files = [...new Set(occurrences.map(({ file }) => file))];\n for (const file of files) {\n groupCountByFile.set(file, (groupCountByFile.get(file) ?? 0) + 1);\n }\n groups.push({ files, occurrences, tokenCount: group[0]?.tokenCount ?? 0 });\n }\n groups.sort(\n (left, right) =>\n right.tokenCount - left.tokenCount ||\n (left.occurrences[0]?.file ?? '').localeCompare(right.occurrences[0]?.file ?? '') ||\n (left.occurrences[0]?.startLine ?? 0) - (right.occurrences[0]?.startLine ?? 0)\n );\n return { duplicateBlockCount, duplicateBlockGroupCountByFile: Object.fromEntries(groupCountByFile), groups };\n}\n"],"mappings":"yDAyCA,SAAgB,EAA4B,EAAsE,CAChH,IAAM,EAAoC,EAAM,SAAS,CAAE,OAAM,cAAc,IAC7E,EAAW,IAAK,IAAe,CAAE,GAAG,EAAW,aAAc,EAAW,MAAK,EAAE,CACjF,EAOA,OAAO,EANSA,EAAAA,oBACd,EACA,GAEC,EAAM,IAAU,EAAK,aAAe,EAAM,cAAgB,EAAK,WAAa,EAAM,UAE9D,CAAC,CAC1B,CAEA,SAAS,EAAmB,EAAuC,CACjE,OAAO,EAAM,QAAU,GAAK,IAAI,IAAI,EAAM,IAAK,GAAc,EAAU,YAAY,CAAC,CAAC,CAAC,MAAQ,CAChG,CAEA,SAAS,EAAU,EAA0E,CAC3F,IAAM,EAAyC,CAAC,EAG1C,EAAmB,IAAI,IACzB,EAAsB,EAC1B,IAAK,IAAM,KAAS,EAAQ,OAAO,EAAG,CACpC,GAAuB,EAAM,OAAS,EACtC,IAAM,EAAc,EACjB,KAAK,CAAE,OAAM,YAAW,cAAe,CAAE,OAAM,YAAW,SAAQ,EAAE,CAAC,CACrE,UAAU,EAAM,IAAU,EAAK,KAAK,cAAc,EAAM,IAAI,GAAK,EAAK,UAAY,EAAM,SAAS,EAC9F,EAAQ,CAAC,GAAG,IAAI,IAAI,EAAY,KAAK,CAAE,UAAW,CAAI,CAAC,CAAC,EAC9D,IAAK,IAAM,KAAQ,EACjB,EAAiB,IAAI,GAAO,EAAiB,IAAI,CAAI,GAAK,GAAK,CAAC,EAElE,EAAO,KAAK,CAAE,QAAO,cAAa,WAAY,EAAM,EAAE,EAAE,YAAc,CAAE,CAAC,CAC3E,CAOA,OANA,EAAO,MACJ,EAAM,IACL,EAAM,WAAa,EAAK,aACvB,EAAK,YAAY,EAAE,EAAE,MAAQ,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