code-gauge 1.11.0 → 1.11.1
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/README.md +2 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/cliConfig.cjs +1 -1
- package/dist/cliConfig.js +1 -1
- package/dist/metrics.cjs +1 -1
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.js +1 -1
- package/dist/metrics.js.map +1 -1
- package/package.json +20 -19
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}, 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 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 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 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 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,kB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EAAiB,GAAiC,CAC7G,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,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 { 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}, 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 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 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 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 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,EAAs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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"}
|
package/dist/cliConfig.cjs
CHANGED
|
@@ -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.loadConfig=d,exports.resolveOptions=l,exports.resolveThresholds=s;
|
|
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;
|
|
2
2
|
//# sourceMappingURL=cliConfig.cjs.map
|
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,d as loadConfig,l as resolveOptions,s as resolveThresholds};
|
|
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};
|
|
2
2
|
//# sourceMappingURL=cliConfig.js.map
|
package/dist/metrics.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./languages.cjs"),n=require("./duplication.cjs"),r=require("./nativeMetrics.cjs");let i=require("tree-sitter");i=e.__toESM(i,1);const a=new Set([`&&`,`||`,`and`,`or`]),o=new Set(`+,-,*,/,%,**,=,+=,-=,*=,/=,%=,==,!=,===,!==,<,<=,>,>=,!,~,&,|,^,++,--,<<,>>,>>>,=>,**=,<<=,>>=,>>>=,&=,|=,^=,&&=,||=,??=,??,?.,?,//,//=,@,@=,:=,<-,<=>,=~,..,...,..=,&&,||,!~,&^,&^=,&.,.,->,::,->*,.*,sizeof,alignof,defined?,as,bitand,bitor,xor,compl,and_eq,or_eq,xor_eq,not_eq,and,or,not,in,is,instanceof,typeof,new,delete,return,throw,raise,yield,await,co_await,co_yield,co_return,break,continue`.split(`,`)),s=new Set(`identifier.property_identifier.field_identifier.type_identifier.constant.instance_variable.class_variable.global_variable.simple_symbol.self.this.super.primitive_type.boolean_type.void_type.auto.number.integer.float.integer_literal.float_literal.int_literal.rune_literal.imaginary_literal.number_literal.decimal_integer_literal.hex_integer_literal.octal_integer_literal.binary_integer_literal.decimal_floating_point_literal.hex_floating_point_literal.string.string_literal.raw_string_literal.string_fragment.multiline_string_fragment.string_content.raw_string_content.template_string.character_literal.char_literal.character.true.false.null.null_literal.undefined.nil.none`.split(`.`)),c=new Set([`interpreted_string_literal`,`regex`,`user_defined_literal`,`integral_type`,`floating_point_type`,`sized_type_specifier`,`placeholder_type_specifier`]);var l=class{registry=t.createLanguageRegistry();registerLanguage(e){this.registry.set(e.name,e);for(let t of e.aliases??[])this.registry.set(t,e)}getSupportedLanguages(){return[...new Set([...this.registry.values()].map(e=>e.name))]}measure(e,t){let a=this.registry.get(t.language);if(!a)throw Error(`Unsupported language: ${t.language}`);let o=r.measureWithNativeBackend(e,a,t.includeSyntaxTree??!1);if(o)return f(o,t.includeSyntaxTree??!1);let s=new i.default;s.setLanguage(a.parserLanguage);let c=s.parse(e,void 0,{bufferSize:e.length+1}).rootNode,l=p(c,y(c,new Set(a.functionNodeTypes)).filter(e=>!ae(e)&&ie(e)),a),u=l.functions,d=se(c,a,0,!1),{lines:m,codeLineNumbers:h}=dt(e,c),g=mt(c,e);return{language:a.name,bytes:Buffer.byteLength(e),lines:m,functions:u,classCount:be(c,a),functionCount:u.length,cyclomaticComplexity:d.cyclomaticComplexity,maxCyclomaticComplexity:$t(u,`cyclomaticComplexity`),cognitiveComplexity:d.cognitiveComplexity,maxCognitiveComplexity:$t(u,`cognitiveComplexity`),nestingDepth:d.nestingDepth,callGraph:l.callGraph,coupling:l.coupling,module:l.module,cohesion:l.cohesion,syntaxFeatures:l.syntaxFeatures,typeComplexity:l.typeComplexity,duplication:n.measureDuplication(c,h),halstead:g,maintainabilityIndex:Qt(g.volume,d.cyclomaticComplexity,m.code),syntaxTree:t.includeSyntaxTree?c.toString():void 0}}};const u=new l;function d(e,t){return u.measure(e,t)}function f(e,t){let n=ht(e.halsteadCounts);return{language:e.language,bytes:e.bytes,lines:e.lines,functions:e.functions.map(e=>({name:e.name,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,returnsJsx:e.returnsJsx,cyclomaticComplexity:e.cyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,callCount:e.callCount,uniqueCalleeCount:e.uniqueCalleeCount,fanIn:e.fanIn,fanOut:e.fanOut,parameterCount:e.parameterCount,recursive:e.recursive})),classCount:e.classCount,functionCount:e.functionCount,cyclomaticComplexity:e.cyclomaticComplexity,maxCyclomaticComplexity:e.maxCyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,maxCognitiveComplexity:e.maxCognitiveComplexity,nestingDepth:e.nestingDepth,callGraph:e.callGraph,coupling:e.coupling,module:e.module,cohesion:e.cohesion,syntaxFeatures:e.syntaxFeatures,typeComplexity:e.typeComplexity,duplication:e.duplication,halstead:n,maintainabilityIndex:Qt(n.volume,e.cyclomaticComplexity,e.lines.code),syntaxTree:t?e.syntaxTree:void 0}}function p(e,t,n){let r=_e(e,n),i=t.map((e,t)=>m(e,n,t,r)),a=te(i);return{functions:i.map(e=>({name:e.name,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,returnsJsx:e.returnsJsx,cyclomaticComplexity:e.cyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,callCount:e.callCount,uniqueCalleeCount:e.callees.size,fanIn:a.fanInByIndex.get(e.index)??0,fanOut:a.fanOutByIndex.get(e.index)??0,parameterCount:e.parameterCount,recursive:a.recursiveIndexes.has(e.index)})),callGraph:a.metrics,coupling:Ge(e,n),module:ke(e,n),cohesion:lt(i),syntaxFeatures:Ke(e,n.name),typeComplexity:ut(e)}}function m(e,t,n,r){let i=se(e,t,0,!0),a=fe(e,t,r);return{index:n,name:gt(e),startLine:e.startPosition.row+1,startColumn:e.startPosition.column,endLine:e.endPosition.row+1,returnsJsx:Se(e,t),cyclomaticComplexity:i.cyclomaticComplexity,cognitiveComplexity:i.cognitiveComplexity,nestingDepth:i.nestingDepth,callCount:a.callCount,parameterCount:h(e),callees:a.callees,identifiers:ye(e)}}function h(e){if(e.childForFieldName(`parameter`))return 1;let t=ee(e);if(!t)return 0;if(t.type===`identifier`)return 1;let n=new Set(Y(t,`locals`).map(e=>e.id));return $(t.namedChildren.filter(e=>e.type!==`comment`&&e.type!==`self_parameter`&&e.type!==`receiver_parameter`&&e.type!==`positional_separator`&&e.type!==`keyword_separator`&&!n.has(e.id)&&!g(e)).map(e=>e.type===`parameter_declaration`?Math.max(1,Y(e,`name`).length):1))+t.children.filter(e=>!e.isNamed&&e.text===`...`).length}function g(e){return e.type===`parameter_declaration`&&e.childForFieldName(`declarator`)===null&&e.childForFieldName(`type`)?.text===`void`}function ee(e){let t=e.childForFieldName(`parameters`);if(t)return t;if(e.type===`compact_constructor_declaration`)return e.parent?.parent?.childForFieldName(`parameters`)??void 0;let n=e.childForFieldName(`declarator`);for(;n;){let e=n.childForFieldName(`parameters`);if(e)return e;n=L(n)}return e.namedChildren.find(e=>e.type===`formal_parameters`||e.type===`parameter_list`)}function te(e){let t=ne(e),n=new Set(t.keys()),r=new Map,i=new Map,a=new Map,o=0,s=0,c=new Set;for(let l of e){o+=l.callCount;for(let e of l.callees)c.add(e);let e=new Set([...l.callees].filter(e=>n.has(e))),u=new Set;for(let n of e){let e=t.get(n);e!==void 0&&u.add(e)}a.set(l.index,u),i.set(l.index,e.size),s+=e.size;for(let e of u)r.set(e,(r.get(e)??0)+1)}let l=qt(a);return{fanInByIndex:r,fanOutByIndex:i,recursiveIndexes:l,metrics:{callCount:o,uniqueCalleeCount:c.size,internalCallCount:s,internalEdgeCount:$([...a.values()].map(e=>e.size)),recursiveFunctionCount:l.size,maxFanIn:en(r),maxFanOut:en(i),maxCallDepth:Yt(a)}}}function ne(e){let t=new Map;for(let n of e)n.name&&t.set(n.name,t.has(n.name)?void 0:n.index);return new Map([...t.entries()].filter(e=>e[1]!==void 0))}const re=new Set([`function_definition`,`method_declaration`,`constructor_declaration`,`compact_constructor_declaration`,`function_signature_item`]);function ie(e){return!re.has(e.type)||e.childForFieldName(`body`)!==null?!0:e.namedChildren.some(e=>e.type===`try_statement`)}function ae(e){return(e.type===`block`||e.type===`do_block`)&&e.parent?.type===`lambda`}function oe(e,t){return t.has(e.type)&&!ae(e)}function se(e,t,n,r){let i=1,a=0,o=n,s=new Set(t.functionNodeTypes),c=new Set(t.decisionNodeTypes),l=new Set(t.nestingNodeTypes);function u(e,t,n){if(r&&!n&&oe(e,s))return;let d=e.isNamed&&c.has(e.type)&&!_(e),f=e.isNamed&&l.has(e.type)&&!_(e),p=d&&le(e);d&&(i+=1,a+=p?1:1+t),de(e)&&(i+=1,a+=1),ce(e)&&(i+=1,a+=1);let m=f&&!p?t+1:t;o=Math.max(o,m);for(let t of e.children)u(t,m,!1)}for(let t of e.children)u(t,n,!1);return{cyclomaticComplexity:i,cognitiveComplexity:a,nestingDepth:o}}function ce(e){return e.isNamed?e.type===`guard`||e.type===`if_guard`||e.type===`unless_guard`||e.type===`if_clause`?!0:e.type===`match_pattern`&&e.children.some(e=>!e.isNamed&&e.type===`if`):!1}function le(e){if(e.type===`elsif`||e.type===`elif_clause`)return!0;if(e.type!==`if_statement`&&e.type!==`if_expression`&&e.type!==`if`)return!1;let t=e.parent;return t?t.type===`else_clause`||t.childForFieldName(`alternative`)?.id===e.id:!1}function _(e){if(e.type===`case_statement`)return e.childForFieldName(`value`)===null;if(e.type===`switch_block_statement_group`||e.type===`switch_rule`){let t=e.namedChildren.find(e=>e.type===`switch_label`);return t!==void 0&&t.namedChildCount===0}if(e.type===`case_clause`||e.type===`match_arm`){let t=e.namedChildren.find(e=>e.type===`case_pattern`||e.type===`match_pattern`);if(!t)return!1;if(t.child(0)?.type===`_`&&(t.childCount===1||t.child(1)?.type===`if`))return!0;let n=t.namedChildCount===1?t.namedChild(0):void 0;return e.type===`case_clause`&&n?.type===`dotted_name`&&n.namedChildCount===1&&n.namedChild(0)?.type===`identifier`}return e.type===`in_clause`?e.namedChild(0)?.type===`identifier`:!1}const ue=new Set([`binary_expression`,`binary`,`boolean_operator`]);function de(e){if(e.isNamed||!a.has(e.text))return!1;let t=e.parent;return t!==null&&ue.has(t.type)}function fe(e,t,n=new Set){let r=new Set,i=new Set(t.functionNodeTypes),a=0;function o(e,s){if(!(!s&&oe(e,i))){if(!(t.name===`cpp`&&me(e)))if(R(e)){a+=1;let i=t.name===`cpp`&&(e.type===`new_expression`||e.type===`call_expression`&&n.has(v(e.childForFieldName(`function`))??``))?void 0:Et(e);if(i&&r.add(i),t.name===`ruby`&&e.type===`call`&&e.parent?.type===`operator_assignment`&&e.parent.childForFieldName(`left`)?.id===e.id){a+=1;let t=e.childForFieldName(`method`);t&&r.add(`${t.text}=`)}}else(ve(e,t)||he(e,n))&&(a+=1);for(let t of e.namedChildren)o(t,!1)}}return o(e,!0),{callCount:a,callees:r}}const pe=new Set([`static_cast`,`dynamic_cast`,`const_cast`,`reinterpret_cast`]);function me(e){if(e.type!==`call_expression`)return!1;let t=e.childForFieldName(`function`);if(t?.type===`primitive_type`)return!0;let n=t?.type===`template_function`?t.childForFieldName(`name`)?.text:t?.text;return n!==void 0&&pe.has(n)}function he(e,t){if(t.size===0)return!1;if(e.type===`compound_literal_expression`)return t.has(v(e.childForFieldName(`type`))??``);if(e.type===`init_declarator`){let n=e.childForFieldName(`value`);return n?.type!==`argument_list`&&n?.type!==`initializer_list`?!1:t.has(v(e.parent?.childForFieldName(`type`))??``)}if((e.type===`identifier`||e.type===`array_declarator`)&&e.parent?.type===`declaration`&&Y(e.parent,`declarator`).some(t=>t.id===e.id)&&!k(e.parent,`extern`)){let n=e;for(;n?.type===`array_declarator`;)n=n.childForFieldName(`declarator`);return n?.type===`identifier`&&t.has(v(e.parent.childForFieldName(`type`))??``)}if(e.type===`field_initializer`){let n=e.namedChild(0),r=n?.type===`field_identifier`?n.text:v(n);return t.has(r??``)}return!1}function v(e){let t=e;for(;t;){if(t.type===`type_identifier`||t.type===`identifier`)return t.text;if(t.type===`qualified_identifier`||t.type===`scoped_identifier`||t.type===`template_type`||t.type===`template_function`){t=t.childForFieldName(`name`);continue}return}}const ge=new Set([`class_specifier`,`struct_specifier`,`union_specifier`]);function _e(e,t){let n=new Set;if(t.name!==`cpp`)return n;for(let t of y(e,ge)){let e=t.childForFieldName(`name`)?.text;e&&t.childForFieldName(`body`)&&n.add(e)}return n}function ve(e,t){return t.name===`ruby`?e.type===`yield`||e.type===`super`&&e.parent?.type!==`call`:!1}function ye(e){let t=new Set;function n(e){(e.type===`identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`constant`||e.type===`instance_variable`||e.type===`class_variable`||e.type===`global_variable`)&&t.add(e.text);for(let t of e.namedChildren)n(t)}return n(e),t}function be(e,t){return y(e,new Set(t.classNodeTypes)).filter(xe).length}function xe(e){return e.type===`object_creation_expression`||e.type===`enum_constant`?e.namedChildren.some(e=>e.type===`class_body`):!e.type.endsWith(`_specifier`)||e.childForFieldName(`body`)!==null}function y(e,t){let n=[];function r(e){t.has(e.type)&&n.push(e);for(let t of e.namedChildren)r(t)}return r(e),n}function Se(e,t){let n=new Set(t.functionNodeTypes);function r(t,i){if(!i&&n.has(t.type))return!1;if(t.type===`return_statement`||e.type===`arrow_function`&&t.id===Ce(e)?.id&&t.type!==`statement_block`&&!n.has(t.type))return b(t,n)||x(t,n);for(let e of t.namedChildren)if(r(e,!1))return!0;return!1}return r(e,!0)}function Ce(e){return e.childForFieldName(`body`)??e.namedChild(e.namedChildCount-1)??void 0}function b(e,t){return we(e,t,e=>e.type.startsWith(`jsx_`)||Te(e,t))}function x(e,t){return we(e,t,At)}function we(e,t,n){function r(e,i){if(!i&&t.has(e.type))return!1;if(n(e))return!0;for(let t of e.namedChildren)if(r(t,!1))return!0;return!1}return r(e,!0)}function Te(e,t){return!R(e)||!Ee(e.childForFieldName(`function`)??e.namedChild(0))?!1:e.namedChildren.some(e=>S(e,t))}function Ee(e){if(!e)return!1;let t=z(e);return t===`map`||t===`flatMap`}function S(e,t){return t.has(e.type)?De(e,t):e.namedChildren.some(e=>S(e,t))}function De(e,t){let n=e.type===`arrow_function`?Ce(e):void 0;return n&&n.type!==`statement_block`&&!t.has(n.type)?b(n,t)||x(n,t):Oe(e,t,e=>b(e,t)||x(e,t))}function Oe(e,t,n){function r(e,i){if(!i&&t.has(e.type))return!1;if(e.type===`return_statement`&&n(e))return!0;for(let t of e.namedChildren)if(r(t,!1))return!0;return!1}return r(e,!0)}function ke(e,t){let n=new Set;function r(e){if(Mt(e,t))for(let r of Pt(e,t,{expandPythonSubmodules:!0}))n.add(r);for(let t of e.namedChildren)r(t)}return r(e),{declarations:Ae(e,t),importSources:[...n]}}function Ae(e,t){let n=Be(e),r=t.name===`java`?je(e):``;return e.namedChildren.flatMap(e=>w(e,!1,r,t.name===`cpp`)).map(e=>n.has(e.name)?{...e,exported:!0}:e)}function je(e){let t=e.namedChildren.find(e=>e.type===`package_declaration`)?.namedChildren.find(e=>e.type===`scoped_identifier`||e.type===`identifier`);return t?`${t.text}::`:``}const C=new Set([`module`,`class`,`singleton_class`]);function w(e,t,n=``,r=!1){if(N(e))return e.namedChildren.flatMap(e=>w(e,!0,n,r));if(e.type===`namespace_definition`){let i=e.childForFieldName(`name`)?.text;return i?(e.childForFieldName(`body`)?.namedChildren??[]).flatMap(e=>w(e,t,`${n}${i}::`,r)):[]}return Re(e)?e.namedChildren.flatMap(e=>w(e,t,n,r)):e.type===`declaration`?T(Pe(e,t,r),n):e.type===`type_definition`?T(Me(e,t),n):C.has(e.type)?E(e,t,n):e.type===`assignment`||e.type===`operator_assignment`?T(D(e,t),n,!0):T(M(e,t),n)}function T(e,t,n=!1){return t?e.map(e=>n&&e.name.includes(`::`)?e:{...e,name:`${t}${e.name}`}):e}function E(e,t,n=``){let r=T(M(e,t),n,!0),i=r[0]?`${r[0].name}::`:n,a=e.childForFieldName(`body`);for(let e of a?.namedChildren??[])C.has(e.type)?r.push(...E(e,t,i)):(e.type===`assignment`||e.type===`operator_assignment`)&&r.push(...T(D(e,t),i,!0));return r}function D(e,t){if(e.type===`operator_assignment`&&!e.children.some(e=>!e.isNamed&&e.text===`||=`))return[];let n=e.childForFieldName(`left`);return n?(n.type===`left_assignment_list`?n.namedChildren:[n]).filter(e=>e.type===`constant`||e.type===`scope_resolution`&&e.childForFieldName(`name`)?.type===`constant`).map(e=>({exported:t,name:e.text,startLine:e.startPosition.row+1})):[]}function Me(e,t){let n=e.childForFieldName(`type`),r=n?M(n,t):[],i=n?.type.endsWith(`_specifier`)&&!n.childForFieldName(`body`)?n.childForFieldName(`name`)?.text:void 0,a=new Set(r.map(e=>e.name));for(let n of Y(e,`declarator`)){let e=n.type===`type_identifier`?n.text:I(n);e&&e!==i&&!a.has(e)&&(a.add(e),r.push({exported:t,name:e,startLine:n.startPosition.row+1}))}return r}const Ne=new Set([`init_declarator`,`pointer_declarator`,`array_declarator`,`reference_declarator`,`identifier`,`field_identifier`]);function O(e){if(e.type===`pointer_declarator`||e.type===`reference_declarator`){let t=e;for(;t&&(t.type===`pointer_declarator`||t.type===`reference_declarator`||t.type===`array_declarator`);)t=L(t);return t?.type===`function_declarator`?t.childForFieldName(`declarator`)?.type===`parenthesized_declarator`:!0}return Ne.has(e.type)?!0:e.type===`function_declarator`&&e.childForFieldName(`declarator`)?.type===`parenthesized_declarator`}function k(e,t){return e.children.some(e=>e.type===`storage_class_specifier`&&e.text===t)}function A(e){let t=e.childForFieldName(`type`);return t?.type!==`type_identifier`||t.text!==`import`&&t.text!==`export`&&t.text!==`module`?!1:!j(e,t.text)}function j(e,t){let n=e;for(;n.parent;)n=n.parent;return y(n,new Set([`type_definition`,`alias_declaration`])).some(e=>(e.childForFieldName(`declarator`)??e.childForFieldName(`name`))?.text===t)}function Pe(e,t,n=!1){if(n&&A(e)||k(e,`static`))return[];let r=e.childForFieldName(`type`),i=r?M(r,t):[],a=new Set(i.map(e=>e.name)),o=k(e,`extern`);for(let r of e.namedChildren.filter(O)){if(o&&r.type!==`init_declarator`||n&&!o&&!k(e,`inline`)&&!Fe(r)&&!F(e,r))continue;let s=I(r);s&&!a.has(s)&&(a.add(s),i.push({exported:t,name:s,startLine:r.startPosition.row+1}))}return i}function Fe(e){let t=e.type===`init_declarator`?e.childForFieldName(`declarator`)??e:e;for(;t;){if(t.type===`reference_declarator`)return!0;t=L(t)}return!1}function M(e,t){if(!ze(e)||e.type.endsWith(`_specifier`)&&!e.childForFieldName(`body`)||k(e,`static`))return[];if(e.type===`enum_specifier`)return Ie(e,t);let n=Le(e);return n?[{exported:t,name:n,startLine:e.startPosition.row+1}]:[]}function Ie(e,t){let n=[],r=e.childForFieldName(`name`)?.text;r&&n.push({exported:t,name:r,startLine:e.startPosition.row+1});let i=e.children.some(e=>!e.isNamed&&(e.text===`class`||e.text===`struct`));for(let a of e.childForFieldName(`body`)?.namedChildren??[]){if(a.type!==`enumerator`)continue;let e=a.childForFieldName(`name`)?.text;e&&n.push({exported:t,name:i&&r?`${r}::${e}`:e,startLine:a.startPosition.row+1})}return n}function Le(e){if(e.type===`method_declaration`&&e.childForFieldName(`receiver`))return Ue(e);let t=e.childForFieldName(`name`);return t?.type===`template_type`&&(t=t.childForFieldName(`name`)),t?.type===`scope_resolution`?t.text:t?P(t)?t.text:void 0:I(e.childForFieldName(`declarator`),!0)||e.namedChildren.find(P)?.text}function N(e){return e.type===`export_statement`||e.type===`export_declaration`}function Re(e){return e.type===`lexical_declaration`||e.type===`variable_declaration`||e.type===`decorated_definition`||e.type===`type_declaration`||e.type===`const_declaration`||e.type===`var_declaration`||e.type===`var_spec_list`||e.type===`linkage_specification`||e.type===`template_declaration`||e.type===`declaration_list`||e.type===`preproc_ifdef`||e.type===`preproc_if`||e.type===`preproc_else`||e.type===`preproc_elif`}function ze(e){return e.type===`function_declaration`||e.type===`function_definition`||e.type===`function_item`||e.type===`method_declaration`||e.type===`class_declaration`||e.type===`class_definition`||e.type===`interface_declaration`||e.type===`type_alias_declaration`||e.type===`type_declaration`||e.type===`type_spec`||e.type===`const_spec`||e.type===`var_spec`||e.type===`variable_declarator`||e.type===`struct_item`||e.type===`enum_item`||e.type===`union_item`||e.type===`trait_item`||e.type===`type_item`||e.type===`const_item`||e.type===`static_item`||e.type===`mod_item`||e.type===`enum_declaration`||e.type===`record_declaration`||e.type===`annotation_type_declaration`||e.type===`method`||e.type===`singleton_method`||e.type===`class`||e.type===`module`||e.type===`alias_declaration`||e.type===`struct_specifier`||e.type===`class_specifier`||e.type===`enum_specifier`||e.type===`union_specifier`}function P(e){return e.type===`identifier`||e.type===`type_identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`constant`}function Be(e){let t=new Set;function n(e,r){if(!r&&Ve(e)){let n=He(e);n&&t.add(n)}let i=r||N(e)&&e.childForFieldName(`source`)!==null;for(let t of e.namedChildren)n(t,i)}return n(e,!1),t}function Ve(e){return e.type===`export_specifier`||e.type===`namespace_export`}function He(e){let t=e.childForFieldName(`name`)??e.childForFieldName(`alias`)??e.namedChildren.find(P);return t&&P(t)?t.text:void 0}function Ue(e){let t=e.childForFieldName(`name`),n=e.childForFieldName(`receiver`)?.namedChildren[0]?.childForFieldName(`type`);return!t||!P(t)||!n?t&&P(t)?t.text:void 0:`${We(n.text)}.${t.text}`}function We(e){return e.replaceAll(/\s+/gu,``).replace(/^\*+/u,``)}function Ge(e,t){let n=new Set,r=0,i=0;function a(e){if(!(t.name===`go`&&(e.type===`import_declaration`||e.type===`import_spec_list`))&&(jt(e)||Nt(e,t)||B(e,t)||V(e)||H(e,t))&&(r+=1),Mt(e,t))for(let r of Pt(e,t,{expandPythonSubmodules:!1}))n.add(r);Kt(e)&&(i+=1);for(let t of e.namedChildren)a(t)}a(e);let o=[...n].filter(e=>Bt(e,t.name)).length;return{importCount:r,importSourceCount:n.size,relativeImportCount:o,externalImportCount:n.size-o,exportCount:i}}function Ke(e,t){let n={assignmentCount:0,awaitExpressionCount:0,loopStatementCount:0,mutableBindingCount:0,returnStatementCount:0,throwStatementCount:0,tryStatementCount:0};function r(e){qe(e)&&(n.assignmentCount+=1),Je(e)&&(n.awaitExpressionCount+=1),Ye(e)&&(n.loopStatementCount+=1),n.mutableBindingCount+=Xe(e,t),it(e)&&(n.returnStatementCount+=1),at(e)&&(n.throwStatementCount+=1),st(e)&&(n.tryStatementCount+=1);for(let t of e.namedChildren)r(t)}return r(e),n}function qe(e){return e.type===`assignment_expression`||e.type===`augmented_assignment_expression`||e.type===`assignment_statement`||e.type===`assignment`||e.type===`augmented_assignment`||e.type===`operator_assignment`||e.type===`short_var_declaration`||e.type===`compound_assignment_expr`||e.type===`named_expression`||e.type===`update_expression`||e.type===`inc_statement`||e.type===`dec_statement`}function Je(e){return e.type===`await_expression`||e.type===`await`||e.type===`co_await_expression`}function Ye(e){return e.type===`for_statement`||e.type===`for_in_statement`||e.type===`enhanced_for_statement`||e.type===`for_range_loop`||e.type===`while_statement`||e.type===`do_statement`||e.type===`for_expression`||e.type===`while_expression`||e.type===`loop_expression`||e.type===`while`||e.type===`until`||e.type===`for`||e.type===`while_modifier`||e.type===`until_modifier`}function Xe(e,t){let n=t===`c`||t===`cpp`;if(e.type===`local_variable_declaration`||e.type===`field_declaration`&&t===`java`){let t=e.namedChildren.filter(e=>e.type===`variable_declarator`);return et(e)?t.length:0}if(n&&(e.type===`declaration`||e.type===`field_declaration`))return Ze(e,t===`cpp`);if(n&&e.type===`function_definition`){let n=e.childForFieldName(`declarator`);return n?.type===`field_identifier`||n?.type===`identifier`?Ze(e,t===`cpp`):0}if(e.type===`enhanced_for_statement`)return+!!et(e);if(t===`java`&&(e.type===`instanceof_expression`||e.type===`type_pattern`||e.type===`record_pattern_component`)){let t=e.type===`instanceof_expression`?e.childForFieldName(`name`)!==null:e.namedChildren.some(e=>e.type===`identifier`),n=e.children.some(e=>!e.isNamed&&e.text===`final`);return t&&!n?1:0}if(n&&e.type===`for_range_loop`){let t=e.childForFieldName(`declarator`);return t&&F(e,t)?Qe(t):0}return+!!$e(e)}function Ze(e,t){return t&&A(e)?0:$(e.namedChildren.filter(t=>O(t)&&F(e,t)).map(Qe))}function Qe(e){let t=e.type===`init_declarator`?e.childForFieldName(`declarator`)??e:e;return t.type===`structured_binding_declarator`?Math.max(1,t.namedChildren.filter(e=>e.type===`identifier`).length):1}function $e(e){return e.type===`lexical_declaration`&&e.firstChild?.text===`let`||e.type===`variable_declaration`&&e.firstChild?.text===`var`||e.type===`var_declaration`||e.type===`let_declaration`&&rt(e)}function et(e){return!e.namedChildren.find(e=>e.type===`modifiers`)?.children.some(e=>e.text===`final`)}function F(e,t){let n=t.type===`init_declarator`?t.childForFieldName(`declarator`)??t:t,r=!1;for(;n.type===`reference_declarator`||n.type===`pointer_declarator`||n.type===`array_declarator`||n.type===`parenthesized_declarator`||n.type===`function_declarator`;){if(n.type===`reference_declarator`)return!1;let e=L(n);if(!e)break;if(n.type===`pointer_declarator`&&(r=!0,nt(n)&&!tt(e)))return!1;n=e}return r||!nt(e)}function tt(e){let t=e;for(;t;){if(t.type===`pointer_declarator`)return!0;t=L(t)}return!1}function nt(e){return e.namedChildren.some(e=>e.type===`type_qualifier`&&(e.text===`const`||e.text===`constexpr`))}function rt(e){if(e.children.some(e=>e.type===`mutable_specifier`))return!0;let t=e.childForFieldName(`pattern`);return t?t.descendantsOfType(`mutable_specifier`).some(e=>e.parent?.type!==`reference_pattern`):!1}function it(e){return e.type===`return_statement`||e.type===`return_expression`||e.type===`return`||e.type===`co_return_statement`}function at(e){return e.type===`throw_statement`||e.type===`raise_statement`||ot(e)}function ot(e){if(e.type!==`call`||e.childForFieldName(`receiver`))return!1;let t=e.childForFieldName(`method`);return t?.type===`identifier`&&(t.text===`raise`||t.text===`fail`)}function st(e){return e.type===`try_statement`||e.type===`try_with_resources_statement`||e.type===`rescue_modifier`||ct(e)}function ct(e){return(e.type===`begin`||e.type===`body_statement`)&&e.namedChildren.some(e=>e.type===`rescue`||e.type===`ensure`)}function lt(e){let t=new Map;for(let n of e)for(let e of n.identifiers)t.set(e,(t.get(e)??0)+1);let n=0;for(let e of t.values())e>=2&&(n+=1);let r=e.length,i=r*(r-1)/2,a=Math.max(1,Math.ceil(i/25e4)),o=0,s=0,c=0,l=0,u=r-1;for(let t=0;t<i;t+=a){for(;t>=l+u;)l+=u,c+=1,u=r-1-c;let n=c+1+(t-l),i=e[c],a=e[n];if(!i||!a)continue;let d=Zt(i.identifiers,a.identifiers),f=i.identifiers.size+a.identifiers.size-d;o+=f===0?0:d/f,s+=1}return{averageFunctionIdentifierOverlap:s===0?1:o/s,sharedIdentifierCount:n,uniqueIdentifierCount:t.size}}function ut(e){let t={typeAnnotationCount:0,typeAliasCount:0,interfaceCount:0,genericParameterCount:0,unionTypeCount:0,intersectionTypeCount:0,conditionalTypeCount:0,typeAssertionCount:0,nonNullAssertionCount:0,satisfiesExpressionCount:0};function n(e){switch(e.type){case`type_annotation`:t.typeAnnotationCount+=1;break;case`type_alias_declaration`:t.typeAliasCount+=1;break;case`interface_declaration`:t.interfaceCount+=1;break;case`type_parameters`:case`type_parameter`:t.genericParameterCount+=+(e.type===`type_parameter`);break;case`union_type`:t.unionTypeCount+=1;break;case`intersection_type`:t.intersectionTypeCount+=1;break;case`conditional_type`:t.conditionalTypeCount+=1;break;case`as_expression`:case`type_assertion`:t.typeAssertionCount+=1;break;case`non_null_expression`:t.nonNullAssertionCount+=1;break;case`satisfies_expression`:t.satisfiesExpressionCount+=1;break}for(let t of e.namedChildren)n(t)}return n(e),t}function dt(e,t){let n=e.length===0?[]:e.split(/\r\n|\n|\r/),r=new Map;for(let e of ft(t)){let t=r.get(e.line)??[];t.push(e),r.set(e.line,t)}let i=0,a=0,o=new Set;for(let[e,t]of n.entries()){if(t.trim()===``){i+=1;continue}pt(t,r.get(e)??[])?a+=1:o.add(e+1)}return{lines:{total:n.length,code:o.size,comment:a,blank:i},codeLineNumbers:o}}function ft(e){let t=[];function n(e){if(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)for(let n=e.startPosition.row;n<=e.endPosition.row;n+=1)t.push({line:n,startColumn:n===e.startPosition.row?e.startPosition.column:0,endColumn:n===e.endPosition.row?e.endPosition.column:1/0});for(let t of e.namedChildren)n(t)}return n(e),t}function pt(e,t){if(t.length===0)return!1;for(let n=0;n<e.length;n+=1)if(!/\s/u.test(e[n]??` `)&&!t.some(e=>e.startColumn<=n&&n<e.endColumn))return!1;return!0}function mt(e,t){let n=new Map,r=new Map;function i(e){if(!(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)){if(c.has(e.type)){Q(r,t.slice(e.startIndex,e.endIndex));return}if(e.childCount===0){let i=t.slice(e.startIndex,e.endIndex);s.has(e.type)?Q(r,i):(o.has(i)||o.has(e.type))&&kt(e,i)&&Q(n,i||e.type);return}for(let t of e.children)i(t)}}return i(e),ht({distinctOperators:n.size,distinctOperands:r.size,totalOperators:$(n.values()),totalOperands:$(r.values())})}function ht(e){let{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i}=e,a=t+n,o=r+i,s=a===0?0:o*Math.log2(a),c=n===0?0:t/2*(i/n),l=c*s;return{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i,vocabulary:a,length:o,volume:s,difficulty:c,effort:l,time:l/18,bugs:s/3e3}}function gt(e){let t=St(e);if(t)return t;let n=e.childForFieldName(`name`);if(n)return n.text;let r=_t(e);if(r)return r;let i=e.parent;if(i){if(e.type===`closure_expression`&&i.type===`let_declaration`){let e=i.childForFieldName(`pattern`);return e?.type===`identifier`?e.text:void 0}return e.type===`lambda_expression`&&i.type===`init_declarator`?I(i.childForFieldName(`declarator`)):e.type===`func_literal`&&i.type===`expression_list`?bt(e,i):e.type===`lambda`&&i.type===`assignment`?vt(i):(e.type===`block`||e.type===`do_block`)&&yt(i)?i.parent?.type===`assignment`?vt(i.parent):void 0:i.childForFieldName(`name`)?.text}}function _t(e){return I(e.childForFieldName(`declarator`))}function I(e,t=!1){let n=e,r=``;for(;n;)switch(n.type){case`identifier`:case`field_identifier`:case`type_identifier`:case`destructor_name`:case`operator_name`:return r?`${r}::${n.text}`:n.text;case`operator_cast`:{let e=`operator ${n.childForFieldName(`type`)?.text??``}`.trimEnd();return r?`${r}::${e}`:e}case`template_function`:n=n.childForFieldName(`name`);break;case`qualified_identifier`:if(t){let e=n.childForFieldName(`scope`)?.text.replaceAll(/\s+/gu,``);e&&(r=r?`${r}::${e}`:e)}n=n.childForFieldName(`name`);break;default:n=L(n)}}function L(e){let t=e.childForFieldName(`declarator`);if(t)return t;if(e.type===`reference_declarator`||e.type===`parenthesized_declarator`)return e.namedChild(0)??void 0}function vt(e){let t=e.childForFieldName(`left`);return t?.type===`identifier`||t?.type===`constant`?t.text:void 0}function yt(e){if(e.type!==`call`||e.childForFieldName(`receiver`))return!1;let t=e.childForFieldName(`method`);return t?.type===`identifier`&&(t.text===`lambda`||t.text===`proc`)}function bt(e,t){let n=t.parent,r=t.namedChildren.filter(e=>e.type!==`comment`).findIndex(t=>t.id===e.id);if(!(!n||r===-1)){if(n.type===`short_var_declaration`){let e=n.childForFieldName(`left`)?.namedChildren.filter(e=>e.type!==`comment`);return xt(e?.[r])}if(n.type===`var_spec`){let e=Y(n,`name`)[r];return xt(e)}}}function xt(e){return e?.type===`identifier`&&e.text!==`_`?e.text:void 0}function St(e){let t=e;for(;t;){let e=t.parent,n=e?.parent;if(e?.type!==`arguments`||n?.type!==`call_expression`||!Ct(n))return;let r=n.parent;if(r?.type===`variable_declarator`)return r.childForFieldName(`name`)?.text;t=n}}function Ct(e){let t=e.childForFieldName(`function`)??e.namedChild(0);return t?.text===`memo`||t?.text===`React.memo`||t?.text===`forwardRef`||t?.text===`React.forwardRef`}function R(e){return e.type===`call_expression`||e.type===`call`||e.type===`method_invocation`||e.type===`macro_invocation`||e.type===`new_expression`||e.type===`object_creation_expression`||e.type===`explicit_constructor_invocation`}function wt(e){for(let t of e.children)if(t.type===`ERROR`){let e=t.children.find(e=>e.type===`operator_name`);if(e)return e.text}let t=e.childForFieldName(`function`);if(t?.type===`field_expression`){let e=t.children.findIndex(e=>e.type===`ERROR`&&e.text===`operator`),n=e===-1?void 0:t.children[e+1];if(n?.type===`field_identifier`||n?.type===`primitive_type`)return`operator ${n.text}`}}const Tt=new Set([`arrow_function`,`function_expression`,`function`,`lambda`,`lambda_expression`,`closure_expression`,`func_literal`,`anonymous_function`]);function Et(e){if(e.type===`call`){let t=e.childForFieldName(`method`),n=e.childForFieldName(`receiver`);if(t?.text===`call`&&n?.type===`identifier`)return n.text;if(t&&e.parent?.type===`assignment`&&e.parent.childForFieldName(`left`)?.id===e.id)return`${t.text}=`;if(t?.type===`operator`)return t.text}if(e.type===`call_expression`){let t=wt(e);if(t)return t}let t=e.childForFieldName(`function`)??e.childForFieldName(`name`)??e.childForFieldName(`method`)??e.childForFieldName(`constructor`)??e.childForFieldName(`type`)??e.namedChild(0);if(!t)return;let n=Dt(t);if(!Tt.has(n.type))return z(n)}function Dt(e){let t=e;for(;t.type===`parenthesized_expression`&&t.namedChildCount===1;){let e=t.namedChild(0);if(!e)break;t=e}return t}const Ot=new Set([`ternary_expression`,`conditional_expression`,`conditional`,`try_expression`,`conditional_type`]);function kt(e,t){if(t===`@`){let t=e.parent?.type;return t===`binary_operator`||t===`augmented_assignment`}if(t!==`?`)return!0;let n=e.parent?.type;return n!==void 0&&Ot.has(n)}function z(e){if(e.type===`generic_function`||e.type===`template_function`||e.type===`template_method`){let t=e.childForFieldName(`function`)??e.childForFieldName(`name`);if(t)return z(t)}if(e.type===`destructor_name`)return e.text;if(e.type===`generic_type`){let t=e.namedChildren.find(e=>e.type===`type_identifier`||e.type===`scoped_type_identifier`);if(t)return z(t)}if(e.type===`identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`type_identifier`||e.type===`attribute`)return e.text;for(let t=e.namedChildCount-1;t>=0;--t){let n=e.namedChild(t);if(!n)continue;let r=z(n);if(r)return r}}function At(e){if(!R(e))return!1;let t=e.childForFieldName(`function`)??e.namedChild(0);return t?.text===`React.createElement`||t?.text===`createElement`}function jt(e){return e.type===`import_statement`||e.type===`import_declaration`||e.type===`import_from_statement`||e.type===`import_spec`||e.type===`import_spec_list`||e.type===`use_declaration`||e.type===`extern_crate_declaration`||e.type===`requires_module_directive`||e.type===`preproc_include`}function Mt(e,t){return jt(e)||Nt(e,t)||B(e,t)||V(e)||H(e,t)||Kt(e)&&e.childForFieldName(`source`)!==null}function B(e,t){if(t.name!==`cpp`)return!1;if(e.type===`declaration`){let t=e.childForFieldName(`type`);return t?.type===`type_identifier`?t.text===`import`?!j(e,`import`):t.text===`export`&&/^export\s+import\b/u.test(e.text):!1}return e.type===`labeled_statement`||e.type===`expression_statement`?e.parent?.type===`translation_unit`&&/^import\s+[:"<]/u.test(e.text):!1}function Nt(e,t){return t.name===`rust`&&e.type===`mod_item`&&!e.childForFieldName(`body`)}function V(e){return R(e)?(e.childForFieldName(`function`)??e.namedChild(0))?.text===`import`:!1}function Pt(e,t,n){if(t.name===`python`){let t=Ht(e,n);if(t.length>0)return t}if(t.name===`rust`)return Vt(e);if(t.name===`java`&&e.type===`requires_module_directive`){let t=e.childForFieldName(`module`);return t?[X(t.text)]:[]}if(t.name===`java`&&e.type===`import_declaration`){let t=e.namedChild(0);if(!t)return[];let n=e.children.some(e=>e.type===`static`),r=e.namedChildren.some(e=>e.type===`asterisk`),i=X(t.text);return[r&&!n?`${i}.*`:i]}if(B(e,t)){let t=/^(?:export\s+)?import\s+([\w.:]+|"[^"]+"|<[^>]+>)/u.exec(e.text)?.[1];return t?t.startsWith(`"`)?[`./${Z(t)}`]:[t]:[]}if(H(e,t))return It(e);if(e.type===`preproc_include`){let t=e.childForFieldName(`path`);if(!t)return[];let n=Z(t.text);return[t.type===`string_literal`&&!n.startsWith(`.`)&&!n.startsWith(`/`)?`./${n}`:n]}if(V(e))return zt(e);let r=e.childForFieldName(`source`)??Wt(e);return r?[Z(r.text)]:[]}const Ft=new Set([`require`,`require_relative`,`load`]);function H(e,t){if(t.name!==`ruby`||e.type!==`call`)return!1;let n=e.childForFieldName(`method`);if(n?.type!==`identifier`)return!1;if(n.text===`autoload`){let t=e.childForFieldName(`receiver`);return t===null||t.type===`constant`||t.type===`scope_resolution`}return e.childForFieldName(`receiver`)===null&&Ft.has(n.text)}function It(e){let t=e.childForFieldName(`arguments`),n=e.childForFieldName(`method`)?.text===`autoload`,r=t?.namedChild(+!!n);if(!r||r.type!==`string`||r.namedChildren.some(e=>e.type===`interpolation`))return[];let i=r.namedChildren.filter(e=>e.type===`string_content`||e.type===`escape_sequence`),a=i.length>0?i.map(e=>e.type===`escape_sequence`?Rt(e.text):e.text).join(``):Z(r.text);return e.childForFieldName(`method`)?.text===`require_relative`?[a.startsWith(`.`)?a:`./${a}`]:[a.replace(/^(?:\.\.?\/)+/u,``)]}const Lt=new Map([[`n`,`
|
|
1
|
+
"use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./languages.cjs"),n=require("./duplication.cjs"),r=require("./nativeMetrics.cjs");let i=require("tree-sitter");i=e.__toESM(i,1);const a=new Set([`&&`,`||`,`and`,`or`]),o=new Set(`+,-,*,/,%,**,=,+=,-=,*=,/=,%=,==,!=,===,!==,<,<=,>,>=,!,~,&,|,^,++,--,<<,>>,>>>,=>,**=,<<=,>>=,>>>=,&=,|=,^=,&&=,||=,??=,??,?.,?,//,//=,@,@=,:=,<-,<=>,=~,..,...,..=,&&,||,!~,&^,&^=,&.,.,->,::,->*,.*,sizeof,alignof,defined?,as,bitand,bitor,xor,compl,and_eq,or_eq,xor_eq,not_eq,and,or,not,in,is,instanceof,typeof,new,delete,return,throw,raise,yield,await,co_await,co_yield,co_return,break,continue`.split(`,`)),s=new Set(`identifier.property_identifier.field_identifier.type_identifier.constant.instance_variable.class_variable.global_variable.simple_symbol.self.this.super.primitive_type.boolean_type.void_type.auto.number.integer.float.integer_literal.float_literal.int_literal.rune_literal.imaginary_literal.number_literal.decimal_integer_literal.hex_integer_literal.octal_integer_literal.binary_integer_literal.decimal_floating_point_literal.hex_floating_point_literal.string.string_literal.raw_string_literal.string_fragment.multiline_string_fragment.string_content.raw_string_content.template_string.character_literal.char_literal.character.true.false.null.null_literal.undefined.nil.none`.split(`.`)),c=new Set([`interpreted_string_literal`,`regex`,`user_defined_literal`,`integral_type`,`floating_point_type`,`sized_type_specifier`,`placeholder_type_specifier`]);var l=class{registry=t.createLanguageRegistry();registerLanguage(e){this.registry.set(e.name,e);for(let t of e.aliases??[])this.registry.set(t,e)}getSupportedLanguages(){return[...new Set([...this.registry.values()].map(e=>e.name))]}measure(e,t){let a=this.registry.get(t.language);if(!a)throw Error(`Unsupported language: ${t.language}`);let o=r.measureWithNativeBackend(e,a,t.includeSyntaxTree??!1);if(o)return f(o,t.includeSyntaxTree??!1);let s=new i.default;s.setLanguage(a.parserLanguage);let c=s.parse(e,void 0,{bufferSize:e.length+1}).rootNode,l=p(c,y(c,new Set(a.functionNodeTypes)).filter(e=>!ae(e)&&ie(e)),a),u=l.functions,d=se(c,a,0,!1),{lines:m,codeLineNumbers:h}=dt(e,c),g=mt(c,e);return{language:a.name,bytes:Buffer.byteLength(e),lines:m,functions:u,classCount:be(c,a),functionCount:u.length,cyclomaticComplexity:d.cyclomaticComplexity,maxCyclomaticComplexity:$t(u,`cyclomaticComplexity`),cognitiveComplexity:d.cognitiveComplexity,maxCognitiveComplexity:$t(u,`cognitiveComplexity`),nestingDepth:d.nestingDepth,callGraph:l.callGraph,coupling:l.coupling,module:l.module,cohesion:l.cohesion,syntaxFeatures:l.syntaxFeatures,typeComplexity:l.typeComplexity,duplication:n.measureDuplication(c,h),halstead:g,maintainabilityIndex:Qt(g.volume,d.cyclomaticComplexity,m.code),syntaxTree:t.includeSyntaxTree?c.toString():void 0}}};const u=new l;function d(e,t){return u.measure(e,t)}function f(e,t){let n=ht(e.halsteadCounts);return{language:e.language,bytes:e.bytes,lines:e.lines,functions:e.functions.map(e=>({name:e.name,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,returnsJsx:e.returnsJsx,cyclomaticComplexity:e.cyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,callCount:e.callCount,uniqueCalleeCount:e.uniqueCalleeCount,fanIn:e.fanIn,fanOut:e.fanOut,parameterCount:e.parameterCount,recursive:e.recursive})),classCount:e.classCount,functionCount:e.functionCount,cyclomaticComplexity:e.cyclomaticComplexity,maxCyclomaticComplexity:e.maxCyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,maxCognitiveComplexity:e.maxCognitiveComplexity,nestingDepth:e.nestingDepth,callGraph:e.callGraph,coupling:e.coupling,module:e.module,cohesion:e.cohesion,syntaxFeatures:e.syntaxFeatures,typeComplexity:e.typeComplexity,duplication:e.duplication,halstead:n,maintainabilityIndex:Qt(n.volume,e.cyclomaticComplexity,e.lines.code),syntaxTree:t?e.syntaxTree:void 0}}function p(e,t,n){let r=_e(e,n),i=t.map((e,t)=>m(e,n,t,r)),a=te(i);return{functions:i.map(e=>({name:e.name,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,returnsJsx:e.returnsJsx,cyclomaticComplexity:e.cyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,callCount:e.callCount,uniqueCalleeCount:e.callees.size,fanIn:a.fanInByIndex.get(e.index)??0,fanOut:a.fanOutByIndex.get(e.index)??0,parameterCount:e.parameterCount,recursive:a.recursiveIndexes.has(e.index)})),callGraph:a.metrics,coupling:Ge(e,n),module:ke(e,n),cohesion:lt(i),syntaxFeatures:Ke(e,n.name),typeComplexity:ut(e)}}function m(e,t,n,r){let i=se(e,t,0,!0),a=fe(e,t,r);return{index:n,name:gt(e),startLine:e.startPosition.row+1,startColumn:e.startPosition.column,endLine:e.endPosition.row+1,returnsJsx:Se(e,t),cyclomaticComplexity:i.cyclomaticComplexity,cognitiveComplexity:i.cognitiveComplexity,nestingDepth:i.nestingDepth,callCount:a.callCount,parameterCount:h(e),callees:a.callees,identifiers:ye(e)}}function h(e){if(e.childForFieldName(`parameter`))return 1;let t=ee(e);if(!t)return 0;if(t.type===`identifier`)return 1;let n=new Set(Y(t,`locals`).map(e=>e.id));return $(t.namedChildren.filter(e=>e.type!==`comment`&&e.type!==`self_parameter`&&e.type!==`receiver_parameter`&&e.type!==`positional_separator`&&e.type!==`keyword_separator`&&!n.has(e.id)&&!g(e)).map(e=>e.type===`parameter_declaration`?Math.max(1,Y(e,`name`).length):1))+t.children.filter(e=>!e.isNamed&&e.text===`...`).length}function g(e){return e.type===`parameter_declaration`&&e.childForFieldName(`declarator`)===null&&e.childForFieldName(`type`)?.text===`void`}function ee(e){let t=e.childForFieldName(`parameters`);if(t)return t;if(e.type===`compact_constructor_declaration`)return e.parent?.parent?.childForFieldName(`parameters`)??void 0;let n=e.childForFieldName(`declarator`);for(;n;){let e=n.childForFieldName(`parameters`);if(e)return e;n=L(n)}return e.namedChildren.find(e=>e.type===`formal_parameters`||e.type===`parameter_list`)}function te(e){let t=ne(e),n=new Set(t.keys()),r=new Map,i=new Map,a=new Map,o=0,s=0,c=new Set;for(let l of e){o+=l.callCount;for(let e of l.callees)c.add(e);let e=new Set([...l.callees].filter(e=>n.has(e))),u=new Set;for(let n of e){let e=t.get(n);e!==void 0&&u.add(e)}a.set(l.index,u),i.set(l.index,e.size),s+=e.size;for(let e of u)r.set(e,(r.get(e)??0)+1)}let l=qt(a);return{fanInByIndex:r,fanOutByIndex:i,recursiveIndexes:l,metrics:{callCount:o,uniqueCalleeCount:c.size,internalCallCount:s,internalEdgeCount:$([...a.values()].map(e=>e.size)),recursiveFunctionCount:l.size,maxFanIn:en(r),maxFanOut:en(i),maxCallDepth:Yt(a)}}}function ne(e){let t=new Map;for(let n of e)n.name&&t.set(n.name,t.has(n.name)?void 0:n.index);return new Map([...t.entries()].filter(e=>e[1]!==void 0))}const re=new Set([`function_definition`,`method_declaration`,`constructor_declaration`,`compact_constructor_declaration`,`function_signature_item`]);function ie(e){return!re.has(e.type)||e.childForFieldName(`body`)!==null||e.namedChildren.some(e=>e.type===`try_statement`)}function ae(e){return(e.type===`block`||e.type===`do_block`)&&e.parent?.type===`lambda`}function oe(e,t){return t.has(e.type)&&!ae(e)}function se(e,t,n,r){let i=1,a=0,o=n,s=new Set(t.functionNodeTypes),c=new Set(t.decisionNodeTypes),l=new Set(t.nestingNodeTypes);function u(e,t,n){if(r&&!n&&oe(e,s))return;let d=e.isNamed&&c.has(e.type)&&!_(e),f=e.isNamed&&l.has(e.type)&&!_(e),p=d&&le(e);d&&(i+=1,a+=p?1:1+t),de(e)&&(i+=1,a+=1),ce(e)&&(i+=1,a+=1);let m=f&&!p?t+1:t;o=Math.max(o,m);for(let t of e.children)u(t,m,!1)}for(let t of e.children)u(t,n,!1);return{cyclomaticComplexity:i,cognitiveComplexity:a,nestingDepth:o}}function ce(e){return e.isNamed?e.type===`guard`||e.type===`if_guard`||e.type===`unless_guard`||e.type===`if_clause`||e.type===`match_pattern`&&e.children.some(e=>!e.isNamed&&e.type===`if`):!1}function le(e){if(e.type===`elsif`||e.type===`elif_clause`)return!0;if(e.type!==`if_statement`&&e.type!==`if_expression`&&e.type!==`if`)return!1;let t=e.parent;return t?t.type===`else_clause`||t.childForFieldName(`alternative`)?.id===e.id:!1}function _(e){if(e.type===`case_statement`)return e.childForFieldName(`value`)===null;if(e.type===`switch_block_statement_group`||e.type===`switch_rule`){let t=e.namedChildren.find(e=>e.type===`switch_label`);return t!==void 0&&t.namedChildCount===0}if(e.type===`case_clause`||e.type===`match_arm`){let t=e.namedChildren.find(e=>e.type===`case_pattern`||e.type===`match_pattern`);if(!t)return!1;if(t.child(0)?.type===`_`&&(t.childCount===1||t.child(1)?.type===`if`))return!0;let n=t.namedChildCount===1?t.namedChild(0):void 0;return e.type===`case_clause`&&n?.type===`dotted_name`&&n.namedChildCount===1&&n.namedChild(0)?.type===`identifier`}return e.type===`in_clause`&&e.namedChild(0)?.type===`identifier`}const ue=new Set([`binary_expression`,`binary`,`boolean_operator`]);function de(e){if(e.isNamed||!a.has(e.text))return!1;let t=e.parent;return t!==null&&ue.has(t.type)}function fe(e,t,n=new Set){let r=new Set,i=new Set(t.functionNodeTypes),a=0;function o(e,s){if(!(!s&&oe(e,i))){if(!(t.name===`cpp`&&me(e)))if(R(e)){a+=1;let i=t.name===`cpp`&&(e.type===`new_expression`||e.type===`call_expression`&&n.has(v(e.childForFieldName(`function`))??``))?void 0:Et(e);if(i&&r.add(i),t.name===`ruby`&&e.type===`call`&&e.parent?.type===`operator_assignment`&&e.parent.childForFieldName(`left`)?.id===e.id){a+=1;let t=e.childForFieldName(`method`);t&&r.add(`${t.text}=`)}}else(ve(e,t)||he(e,n))&&(a+=1);for(let t of e.namedChildren)o(t,!1)}}return o(e,!0),{callCount:a,callees:r}}const pe=new Set([`static_cast`,`dynamic_cast`,`const_cast`,`reinterpret_cast`]);function me(e){if(e.type!==`call_expression`)return!1;let t=e.childForFieldName(`function`);if(t?.type===`primitive_type`)return!0;let n=t?.type===`template_function`?t.childForFieldName(`name`)?.text:t?.text;return n!==void 0&&pe.has(n)}function he(e,t){if(t.size===0)return!1;if(e.type===`compound_literal_expression`)return t.has(v(e.childForFieldName(`type`))??``);if(e.type===`init_declarator`){let n=e.childForFieldName(`value`);return n?.type!==`argument_list`&&n?.type!==`initializer_list`?!1:t.has(v(e.parent?.childForFieldName(`type`))??``)}if((e.type===`identifier`||e.type===`array_declarator`)&&e.parent?.type===`declaration`&&Y(e.parent,`declarator`).some(t=>t.id===e.id)&&!k(e.parent,`extern`)){let n=e;for(;n?.type===`array_declarator`;)n=n.childForFieldName(`declarator`);return n?.type===`identifier`&&t.has(v(e.parent.childForFieldName(`type`))??``)}if(e.type===`field_initializer`){let n=e.namedChild(0),r=n?.type===`field_identifier`?n.text:v(n);return t.has(r??``)}return!1}function v(e){let t=e;for(;t;){if(t.type===`type_identifier`||t.type===`identifier`)return t.text;if(t.type===`qualified_identifier`||t.type===`scoped_identifier`||t.type===`template_type`||t.type===`template_function`){t=t.childForFieldName(`name`);continue}return}}const ge=new Set([`class_specifier`,`struct_specifier`,`union_specifier`]);function _e(e,t){let n=new Set;if(t.name!==`cpp`)return n;for(let t of y(e,ge)){let e=t.childForFieldName(`name`)?.text;e&&t.childForFieldName(`body`)&&n.add(e)}return n}function ve(e,t){return t.name===`ruby`?e.type===`yield`||e.type===`super`&&e.parent?.type!==`call`:!1}function ye(e){let t=new Set;function n(e){(e.type===`identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`constant`||e.type===`instance_variable`||e.type===`class_variable`||e.type===`global_variable`)&&t.add(e.text);for(let t of e.namedChildren)n(t)}return n(e),t}function be(e,t){return y(e,new Set(t.classNodeTypes)).filter(xe).length}function xe(e){return e.type===`object_creation_expression`||e.type===`enum_constant`?e.namedChildren.some(e=>e.type===`class_body`):!e.type.endsWith(`_specifier`)||e.childForFieldName(`body`)!==null}function y(e,t){let n=[];function r(e){t.has(e.type)&&n.push(e);for(let t of e.namedChildren)r(t)}return r(e),n}function Se(e,t){let n=new Set(t.functionNodeTypes);function r(t,i){if(!i&&n.has(t.type))return!1;if(t.type===`return_statement`||e.type===`arrow_function`&&t.id===Ce(e)?.id&&t.type!==`statement_block`&&!n.has(t.type))return b(t,n)||x(t,n);for(let e of t.namedChildren)if(r(e,!1))return!0;return!1}return r(e,!0)}function Ce(e){return e.childForFieldName(`body`)??e.namedChild(e.namedChildCount-1)??void 0}function b(e,t){return we(e,t,e=>e.type.startsWith(`jsx_`)||Te(e,t))}function x(e,t){return we(e,t,At)}function we(e,t,n){function r(e,i){if(!i&&t.has(e.type))return!1;if(n(e))return!0;for(let t of e.namedChildren)if(r(t,!1))return!0;return!1}return r(e,!0)}function Te(e,t){return!R(e)||!Ee(e.childForFieldName(`function`)??e.namedChild(0))?!1:e.namedChildren.some(e=>S(e,t))}function Ee(e){if(!e)return!1;let t=z(e);return t===`map`||t===`flatMap`}function S(e,t){return t.has(e.type)?De(e,t):e.namedChildren.some(e=>S(e,t))}function De(e,t){let n=e.type===`arrow_function`?Ce(e):void 0;return n&&n.type!==`statement_block`&&!t.has(n.type)?b(n,t)||x(n,t):Oe(e,t,e=>b(e,t)||x(e,t))}function Oe(e,t,n){function r(e,i){if(!i&&t.has(e.type))return!1;if(e.type===`return_statement`&&n(e))return!0;for(let t of e.namedChildren)if(r(t,!1))return!0;return!1}return r(e,!0)}function ke(e,t){let n=new Set;function r(e){if(Mt(e,t))for(let r of Pt(e,t,{expandPythonSubmodules:!0}))n.add(r);for(let t of e.namedChildren)r(t)}return r(e),{declarations:Ae(e,t),importSources:[...n]}}function Ae(e,t){let n=Be(e),r=t.name===`java`?je(e):``;return e.namedChildren.flatMap(e=>w(e,!1,r,t.name===`cpp`)).map(e=>n.has(e.name)?{...e,exported:!0}:e)}function je(e){let t=e.namedChildren.find(e=>e.type===`package_declaration`)?.namedChildren.find(e=>e.type===`scoped_identifier`||e.type===`identifier`);return t?`${t.text}::`:``}const C=new Set([`module`,`class`,`singleton_class`]);function w(e,t,n=``,r=!1){if(N(e))return e.namedChildren.flatMap(e=>w(e,!0,n,r));if(e.type===`namespace_definition`){let i=e.childForFieldName(`name`)?.text;return i?(e.childForFieldName(`body`)?.namedChildren??[]).flatMap(e=>w(e,t,`${n}${i}::`,r)):[]}return Re(e)?e.namedChildren.flatMap(e=>w(e,t,n,r)):e.type===`declaration`?T(Pe(e,t,r),n):e.type===`type_definition`?T(Me(e,t),n):C.has(e.type)?E(e,t,n):e.type===`assignment`||e.type===`operator_assignment`?T(D(e,t),n,!0):T(M(e,t),n)}function T(e,t,n=!1){return t?e.map(e=>n&&e.name.includes(`::`)?e:{...e,name:`${t}${e.name}`}):e}function E(e,t,n=``){let r=T(M(e,t),n,!0),i=r[0]?`${r[0].name}::`:n,a=e.childForFieldName(`body`);for(let e of a?.namedChildren??[])C.has(e.type)?r.push(...E(e,t,i)):(e.type===`assignment`||e.type===`operator_assignment`)&&r.push(...T(D(e,t),i,!0));return r}function D(e,t){if(e.type===`operator_assignment`&&!e.children.some(e=>!e.isNamed&&e.text===`||=`))return[];let n=e.childForFieldName(`left`);return n?(n.type===`left_assignment_list`?n.namedChildren:[n]).filter(e=>e.type===`constant`||e.type===`scope_resolution`&&e.childForFieldName(`name`)?.type===`constant`).map(e=>({exported:t,name:e.text,startLine:e.startPosition.row+1})):[]}function Me(e,t){let n=e.childForFieldName(`type`),r=n?M(n,t):[],i=n?.type.endsWith(`_specifier`)&&!n.childForFieldName(`body`)?n.childForFieldName(`name`)?.text:void 0,a=new Set(r.map(e=>e.name));for(let n of Y(e,`declarator`)){let e=n.type===`type_identifier`?n.text:I(n);e&&e!==i&&!a.has(e)&&(a.add(e),r.push({exported:t,name:e,startLine:n.startPosition.row+1}))}return r}const Ne=new Set([`init_declarator`,`pointer_declarator`,`array_declarator`,`reference_declarator`,`identifier`,`field_identifier`]);function O(e){if(e.type===`pointer_declarator`||e.type===`reference_declarator`){let t=e;for(;t&&(t.type===`pointer_declarator`||t.type===`reference_declarator`||t.type===`array_declarator`);)t=L(t);return t?.type!==`function_declarator`||t.childForFieldName(`declarator`)?.type===`parenthesized_declarator`}return Ne.has(e.type)?!0:e.type===`function_declarator`&&e.childForFieldName(`declarator`)?.type===`parenthesized_declarator`}function k(e,t){return e.children.some(e=>e.type===`storage_class_specifier`&&e.text===t)}function A(e){let t=e.childForFieldName(`type`);return t?.type!==`type_identifier`||t.text!==`import`&&t.text!==`export`&&t.text!==`module`?!1:!j(e,t.text)}function j(e,t){let n=e;for(;n.parent;)n=n.parent;return y(n,new Set([`type_definition`,`alias_declaration`])).some(e=>(e.childForFieldName(`declarator`)??e.childForFieldName(`name`))?.text===t)}function Pe(e,t,n=!1){if(n&&A(e)||k(e,`static`))return[];let r=e.childForFieldName(`type`),i=r?M(r,t):[],a=new Set(i.map(e=>e.name)),o=k(e,`extern`);for(let r of e.namedChildren.filter(O)){if(o&&r.type!==`init_declarator`||n&&!o&&!k(e,`inline`)&&!Fe(r)&&!F(e,r))continue;let s=I(r);s&&!a.has(s)&&(a.add(s),i.push({exported:t,name:s,startLine:r.startPosition.row+1}))}return i}function Fe(e){let t=e.type===`init_declarator`?e.childForFieldName(`declarator`)??e:e;for(;t;){if(t.type===`reference_declarator`)return!0;t=L(t)}return!1}function M(e,t){if(!ze(e)||e.type.endsWith(`_specifier`)&&!e.childForFieldName(`body`)||k(e,`static`))return[];if(e.type===`enum_specifier`)return Ie(e,t);let n=Le(e);return n?[{exported:t,name:n,startLine:e.startPosition.row+1}]:[]}function Ie(e,t){let n=[],r=e.childForFieldName(`name`)?.text;r&&n.push({exported:t,name:r,startLine:e.startPosition.row+1});let i=e.children.some(e=>!e.isNamed&&(e.text===`class`||e.text===`struct`));for(let a of e.childForFieldName(`body`)?.namedChildren??[]){if(a.type!==`enumerator`)continue;let e=a.childForFieldName(`name`)?.text;e&&n.push({exported:t,name:i&&r?`${r}::${e}`:e,startLine:a.startPosition.row+1})}return n}function Le(e){if(e.type===`method_declaration`&&e.childForFieldName(`receiver`))return Ue(e);let t=e.childForFieldName(`name`);return t?.type===`template_type`&&(t=t.childForFieldName(`name`)),t?.type===`scope_resolution`?t.text:t?P(t)?t.text:void 0:I(e.childForFieldName(`declarator`),!0)||e.namedChildren.find(P)?.text}function N(e){return e.type===`export_statement`||e.type===`export_declaration`}function Re(e){return e.type===`lexical_declaration`||e.type===`variable_declaration`||e.type===`decorated_definition`||e.type===`type_declaration`||e.type===`const_declaration`||e.type===`var_declaration`||e.type===`var_spec_list`||e.type===`linkage_specification`||e.type===`template_declaration`||e.type===`declaration_list`||e.type===`preproc_ifdef`||e.type===`preproc_if`||e.type===`preproc_else`||e.type===`preproc_elif`}function ze(e){return e.type===`function_declaration`||e.type===`function_definition`||e.type===`function_item`||e.type===`method_declaration`||e.type===`class_declaration`||e.type===`class_definition`||e.type===`interface_declaration`||e.type===`type_alias_declaration`||e.type===`type_declaration`||e.type===`type_spec`||e.type===`const_spec`||e.type===`var_spec`||e.type===`variable_declarator`||e.type===`struct_item`||e.type===`enum_item`||e.type===`union_item`||e.type===`trait_item`||e.type===`type_item`||e.type===`const_item`||e.type===`static_item`||e.type===`mod_item`||e.type===`enum_declaration`||e.type===`record_declaration`||e.type===`annotation_type_declaration`||e.type===`method`||e.type===`singleton_method`||e.type===`class`||e.type===`module`||e.type===`alias_declaration`||e.type===`struct_specifier`||e.type===`class_specifier`||e.type===`enum_specifier`||e.type===`union_specifier`}function P(e){return e.type===`identifier`||e.type===`type_identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`constant`}function Be(e){let t=new Set;function n(e,r){if(!r&&Ve(e)){let n=He(e);n&&t.add(n)}let i=r||N(e)&&e.childForFieldName(`source`)!==null;for(let t of e.namedChildren)n(t,i)}return n(e,!1),t}function Ve(e){return e.type===`export_specifier`||e.type===`namespace_export`}function He(e){let t=e.childForFieldName(`name`)??e.childForFieldName(`alias`)??e.namedChildren.find(P);return t&&P(t)?t.text:void 0}function Ue(e){let t=e.childForFieldName(`name`),n=e.childForFieldName(`receiver`)?.namedChildren[0]?.childForFieldName(`type`);return!t||!P(t)||!n?t&&P(t)?t.text:void 0:`${We(n.text)}.${t.text}`}function We(e){return e.replaceAll(/\s+/gu,``).replace(/^\*+/u,``)}function Ge(e,t){let n=new Set,r=0,i=0;function a(e){if(!(t.name===`go`&&(e.type===`import_declaration`||e.type===`import_spec_list`))&&(jt(e)||Nt(e,t)||B(e,t)||V(e)||H(e,t))&&(r+=1),Mt(e,t))for(let r of Pt(e,t,{expandPythonSubmodules:!1}))n.add(r);Kt(e)&&(i+=1);for(let t of e.namedChildren)a(t)}a(e);let o=[...n].filter(e=>Bt(e,t.name)).length;return{importCount:r,importSourceCount:n.size,relativeImportCount:o,externalImportCount:n.size-o,exportCount:i}}function Ke(e,t){let n={assignmentCount:0,awaitExpressionCount:0,loopStatementCount:0,mutableBindingCount:0,returnStatementCount:0,throwStatementCount:0,tryStatementCount:0};function r(e){qe(e)&&(n.assignmentCount+=1),Je(e)&&(n.awaitExpressionCount+=1),Ye(e)&&(n.loopStatementCount+=1),n.mutableBindingCount+=Xe(e,t),it(e)&&(n.returnStatementCount+=1),at(e)&&(n.throwStatementCount+=1),st(e)&&(n.tryStatementCount+=1);for(let t of e.namedChildren)r(t)}return r(e),n}function qe(e){return e.type===`assignment_expression`||e.type===`augmented_assignment_expression`||e.type===`assignment_statement`||e.type===`assignment`||e.type===`augmented_assignment`||e.type===`operator_assignment`||e.type===`short_var_declaration`||e.type===`compound_assignment_expr`||e.type===`named_expression`||e.type===`update_expression`||e.type===`inc_statement`||e.type===`dec_statement`}function Je(e){return e.type===`await_expression`||e.type===`await`||e.type===`co_await_expression`}function Ye(e){return e.type===`for_statement`||e.type===`for_in_statement`||e.type===`enhanced_for_statement`||e.type===`for_range_loop`||e.type===`while_statement`||e.type===`do_statement`||e.type===`for_expression`||e.type===`while_expression`||e.type===`loop_expression`||e.type===`while`||e.type===`until`||e.type===`for`||e.type===`while_modifier`||e.type===`until_modifier`}function Xe(e,t){let n=t===`c`||t===`cpp`;if(e.type===`local_variable_declaration`||e.type===`field_declaration`&&t===`java`){let t=e.namedChildren.filter(e=>e.type===`variable_declarator`);return et(e)?t.length:0}if(n&&(e.type===`declaration`||e.type===`field_declaration`))return Ze(e,t===`cpp`);if(n&&e.type===`function_definition`){let n=e.childForFieldName(`declarator`);return n?.type===`field_identifier`||n?.type===`identifier`?Ze(e,t===`cpp`):0}if(e.type===`enhanced_for_statement`)return+!!et(e);if(t===`java`&&(e.type===`instanceof_expression`||e.type===`type_pattern`||e.type===`record_pattern_component`)){let t=e.type===`instanceof_expression`?e.childForFieldName(`name`)!==null:e.namedChildren.some(e=>e.type===`identifier`),n=e.children.some(e=>!e.isNamed&&e.text===`final`);return t&&!n?1:0}if(n&&e.type===`for_range_loop`){let t=e.childForFieldName(`declarator`);return t&&F(e,t)?Qe(t):0}return+!!$e(e)}function Ze(e,t){return t&&A(e)?0:$(e.namedChildren.filter(t=>O(t)&&F(e,t)).map(Qe))}function Qe(e){let t=e.type===`init_declarator`?e.childForFieldName(`declarator`)??e:e;return t.type===`structured_binding_declarator`?Math.max(1,t.namedChildren.filter(e=>e.type===`identifier`).length):1}function $e(e){return e.type===`lexical_declaration`&&e.firstChild?.text===`let`||e.type===`variable_declaration`&&e.firstChild?.text===`var`||e.type===`var_declaration`||e.type===`let_declaration`&&rt(e)}function et(e){return!e.namedChildren.find(e=>e.type===`modifiers`)?.children.some(e=>e.text===`final`)}function F(e,t){let n=t.type===`init_declarator`?t.childForFieldName(`declarator`)??t:t,r=!1;for(;n.type===`reference_declarator`||n.type===`pointer_declarator`||n.type===`array_declarator`||n.type===`parenthesized_declarator`||n.type===`function_declarator`;){if(n.type===`reference_declarator`)return!1;let e=L(n);if(!e)break;if(n.type===`pointer_declarator`&&(r=!0,nt(n)&&!tt(e)))return!1;n=e}return r||!nt(e)}function tt(e){let t=e;for(;t;){if(t.type===`pointer_declarator`)return!0;t=L(t)}return!1}function nt(e){return e.namedChildren.some(e=>e.type===`type_qualifier`&&(e.text===`const`||e.text===`constexpr`))}function rt(e){if(e.children.some(e=>e.type===`mutable_specifier`))return!0;let t=e.childForFieldName(`pattern`);return t?t.descendantsOfType(`mutable_specifier`).some(e=>e.parent?.type!==`reference_pattern`):!1}function it(e){return e.type===`return_statement`||e.type===`return_expression`||e.type===`return`||e.type===`co_return_statement`}function at(e){return e.type===`throw_statement`||e.type===`raise_statement`||ot(e)}function ot(e){if(e.type!==`call`||e.childForFieldName(`receiver`))return!1;let t=e.childForFieldName(`method`);return t?.type===`identifier`&&(t.text===`raise`||t.text===`fail`)}function st(e){return e.type===`try_statement`||e.type===`try_with_resources_statement`||e.type===`rescue_modifier`||ct(e)}function ct(e){return(e.type===`begin`||e.type===`body_statement`)&&e.namedChildren.some(e=>e.type===`rescue`||e.type===`ensure`)}function lt(e){let t=new Map;for(let n of e)for(let e of n.identifiers)t.set(e,(t.get(e)??0)+1);let n=0;for(let e of t.values())e>=2&&(n+=1);let r=e.length,i=r*(r-1)/2,a=Math.max(1,Math.ceil(i/25e4)),o=0,s=0,c=0,l=0,u=r-1;for(let t=0;t<i;t+=a){for(;t>=l+u;)l+=u,c+=1,u=r-1-c;let n=c+1+(t-l),i=e[c],a=e[n];if(!i||!a)continue;let d=Zt(i.identifiers,a.identifiers),f=i.identifiers.size+a.identifiers.size-d;o+=f===0?0:d/f,s+=1}return{averageFunctionIdentifierOverlap:s===0?1:o/s,sharedIdentifierCount:n,uniqueIdentifierCount:t.size}}function ut(e){let t={typeAnnotationCount:0,typeAliasCount:0,interfaceCount:0,genericParameterCount:0,unionTypeCount:0,intersectionTypeCount:0,conditionalTypeCount:0,typeAssertionCount:0,nonNullAssertionCount:0,satisfiesExpressionCount:0};function n(e){switch(e.type){case`type_annotation`:t.typeAnnotationCount+=1;break;case`type_alias_declaration`:t.typeAliasCount+=1;break;case`interface_declaration`:t.interfaceCount+=1;break;case`type_parameters`:case`type_parameter`:t.genericParameterCount+=+(e.type===`type_parameter`);break;case`union_type`:t.unionTypeCount+=1;break;case`intersection_type`:t.intersectionTypeCount+=1;break;case`conditional_type`:t.conditionalTypeCount+=1;break;case`as_expression`:case`type_assertion`:t.typeAssertionCount+=1;break;case`non_null_expression`:t.nonNullAssertionCount+=1;break;case`satisfies_expression`:t.satisfiesExpressionCount+=1;break}for(let t of e.namedChildren)n(t)}return n(e),t}function dt(e,t){let n=e.length===0?[]:e.split(/\r\n|\n|\r/),r=new Map;for(let e of ft(t)){let t=r.get(e.line)??[];t.push(e),r.set(e.line,t)}let i=0,a=0,o=new Set;for(let[e,t]of n.entries()){if(t.trim()===``){i+=1;continue}pt(t,r.get(e)??[])?a+=1:o.add(e+1)}return{lines:{total:n.length,code:o.size,comment:a,blank:i},codeLineNumbers:o}}function ft(e){let t=[];function n(e){if(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)for(let n=e.startPosition.row;n<=e.endPosition.row;n+=1)t.push({line:n,startColumn:n===e.startPosition.row?e.startPosition.column:0,endColumn:n===e.endPosition.row?e.endPosition.column:1/0});for(let t of e.namedChildren)n(t)}return n(e),t}function pt(e,t){if(t.length===0)return!1;for(let n=0;n<e.length;n+=1)if(!/\s/u.test(e[n]??` `)&&!t.some(e=>e.startColumn<=n&&n<e.endColumn))return!1;return!0}function mt(e,t){let n=new Map,r=new Map;function i(e){if(!(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)){if(c.has(e.type)){Q(r,t.slice(e.startIndex,e.endIndex));return}if(e.childCount===0){let i=t.slice(e.startIndex,e.endIndex);s.has(e.type)?Q(r,i):(o.has(i)||o.has(e.type))&&kt(e,i)&&Q(n,i||e.type);return}for(let t of e.children)i(t)}}return i(e),ht({distinctOperators:n.size,distinctOperands:r.size,totalOperators:$(n.values()),totalOperands:$(r.values())})}function ht(e){let{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i}=e,a=t+n,o=r+i,s=a===0?0:o*Math.log2(a),c=n===0?0:t/2*(i/n),l=c*s;return{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i,vocabulary:a,length:o,volume:s,difficulty:c,effort:l,time:l/18,bugs:s/3e3}}function gt(e){let t=St(e);if(t)return t;let n=e.childForFieldName(`name`);if(n)return n.text;let r=_t(e);if(r)return r;let i=e.parent;if(i){if(e.type===`closure_expression`&&i.type===`let_declaration`){let e=i.childForFieldName(`pattern`);return e?.type===`identifier`?e.text:void 0}return e.type===`lambda_expression`&&i.type===`init_declarator`?I(i.childForFieldName(`declarator`)):e.type===`func_literal`&&i.type===`expression_list`?bt(e,i):e.type===`lambda`&&i.type===`assignment`?vt(i):(e.type===`block`||e.type===`do_block`)&&yt(i)?i.parent?.type===`assignment`?vt(i.parent):void 0:i.childForFieldName(`name`)?.text}}function _t(e){return I(e.childForFieldName(`declarator`))}function I(e,t=!1){let n=e,r=``;for(;n;)switch(n.type){case`identifier`:case`field_identifier`:case`type_identifier`:case`destructor_name`:case`operator_name`:return r?`${r}::${n.text}`:n.text;case`operator_cast`:{let e=`operator ${n.childForFieldName(`type`)?.text??``}`.trimEnd();return r?`${r}::${e}`:e}case`template_function`:n=n.childForFieldName(`name`);break;case`qualified_identifier`:if(t){let e=n.childForFieldName(`scope`)?.text.replaceAll(/\s+/gu,``);e&&(r=r?`${r}::${e}`:e)}n=n.childForFieldName(`name`);break;default:n=L(n)}}function L(e){let t=e.childForFieldName(`declarator`);if(t)return t;if(e.type===`reference_declarator`||e.type===`parenthesized_declarator`)return e.namedChild(0)??void 0}function vt(e){let t=e.childForFieldName(`left`);return t?.type===`identifier`||t?.type===`constant`?t.text:void 0}function yt(e){if(e.type!==`call`||e.childForFieldName(`receiver`))return!1;let t=e.childForFieldName(`method`);return t?.type===`identifier`&&(t.text===`lambda`||t.text===`proc`)}function bt(e,t){let n=t.parent,r=t.namedChildren.filter(e=>e.type!==`comment`).findIndex(t=>t.id===e.id);if(!(!n||r===-1)){if(n.type===`short_var_declaration`){let e=n.childForFieldName(`left`)?.namedChildren.filter(e=>e.type!==`comment`);return xt(e?.[r])}if(n.type===`var_spec`){let e=Y(n,`name`)[r];return xt(e)}}}function xt(e){return e?.type===`identifier`&&e.text!==`_`?e.text:void 0}function St(e){let t=e;for(;t;){let e=t.parent,n=e?.parent;if(e?.type!==`arguments`||n?.type!==`call_expression`||!Ct(n))return;let r=n.parent;if(r?.type===`variable_declarator`)return r.childForFieldName(`name`)?.text;t=n}}function Ct(e){let t=e.childForFieldName(`function`)??e.namedChild(0);return t?.text===`memo`||t?.text===`React.memo`||t?.text===`forwardRef`||t?.text===`React.forwardRef`}function R(e){return e.type===`call_expression`||e.type===`call`||e.type===`method_invocation`||e.type===`macro_invocation`||e.type===`new_expression`||e.type===`object_creation_expression`||e.type===`explicit_constructor_invocation`}function wt(e){for(let t of e.children)if(t.type===`ERROR`){let e=t.children.find(e=>e.type===`operator_name`);if(e)return e.text}let t=e.childForFieldName(`function`);if(t?.type===`field_expression`){let e=t.children.findIndex(e=>e.type===`ERROR`&&e.text===`operator`),n=e===-1?void 0:t.children[e+1];if(n?.type===`field_identifier`||n?.type===`primitive_type`)return`operator ${n.text}`}}const Tt=new Set([`arrow_function`,`function_expression`,`function`,`lambda`,`lambda_expression`,`closure_expression`,`func_literal`,`anonymous_function`]);function Et(e){if(e.type===`call`){let t=e.childForFieldName(`method`),n=e.childForFieldName(`receiver`);if(t?.text===`call`&&n?.type===`identifier`)return n.text;if(t&&e.parent?.type===`assignment`&&e.parent.childForFieldName(`left`)?.id===e.id)return`${t.text}=`;if(t?.type===`operator`)return t.text}if(e.type===`call_expression`){let t=wt(e);if(t)return t}let t=e.childForFieldName(`function`)??e.childForFieldName(`name`)??e.childForFieldName(`method`)??e.childForFieldName(`constructor`)??e.childForFieldName(`type`)??e.namedChild(0);if(!t)return;let n=Dt(t);if(!Tt.has(n.type))return z(n)}function Dt(e){let t=e;for(;t.type===`parenthesized_expression`&&t.namedChildCount===1;){let e=t.namedChild(0);if(!e)break;t=e}return t}const Ot=new Set([`ternary_expression`,`conditional_expression`,`conditional`,`try_expression`,`conditional_type`]);function kt(e,t){if(t===`@`){let t=e.parent?.type;return t===`binary_operator`||t===`augmented_assignment`}if(t!==`?`)return!0;let n=e.parent?.type;return n!==void 0&&Ot.has(n)}function z(e){if(e.type===`generic_function`||e.type===`template_function`||e.type===`template_method`){let t=e.childForFieldName(`function`)??e.childForFieldName(`name`);if(t)return z(t)}if(e.type===`destructor_name`)return e.text;if(e.type===`generic_type`){let t=e.namedChildren.find(e=>e.type===`type_identifier`||e.type===`scoped_type_identifier`);if(t)return z(t)}if(e.type===`identifier`||e.type===`property_identifier`||e.type===`field_identifier`||e.type===`type_identifier`||e.type===`attribute`)return e.text;for(let t=e.namedChildCount-1;t>=0;--t){let n=e.namedChild(t);if(!n)continue;let r=z(n);if(r)return r}}function At(e){if(!R(e))return!1;let t=e.childForFieldName(`function`)??e.namedChild(0);return t?.text===`React.createElement`||t?.text===`createElement`}function jt(e){return e.type===`import_statement`||e.type===`import_declaration`||e.type===`import_from_statement`||e.type===`import_spec`||e.type===`import_spec_list`||e.type===`use_declaration`||e.type===`extern_crate_declaration`||e.type===`requires_module_directive`||e.type===`preproc_include`}function Mt(e,t){return jt(e)||Nt(e,t)||B(e,t)||V(e)||H(e,t)||Kt(e)&&e.childForFieldName(`source`)!==null}function B(e,t){if(t.name!==`cpp`)return!1;if(e.type===`declaration`){let t=e.childForFieldName(`type`);return t?.type===`type_identifier`?t.text===`import`?!j(e,`import`):t.text===`export`&&/^export\s+import\b/u.test(e.text):!1}return e.type===`labeled_statement`||e.type===`expression_statement`?e.parent?.type===`translation_unit`&&/^import\s+[:"<]/u.test(e.text):!1}function Nt(e,t){return t.name===`rust`&&e.type===`mod_item`&&!e.childForFieldName(`body`)}function V(e){return R(e)?(e.childForFieldName(`function`)??e.namedChild(0))?.text===`import`:!1}function Pt(e,t,n){if(t.name===`python`){let t=Ht(e,n);if(t.length>0)return t}if(t.name===`rust`)return Vt(e);if(t.name===`java`&&e.type===`requires_module_directive`){let t=e.childForFieldName(`module`);return t?[X(t.text)]:[]}if(t.name===`java`&&e.type===`import_declaration`){let t=e.namedChild(0);if(!t)return[];let n=e.children.some(e=>e.type===`static`),r=e.namedChildren.some(e=>e.type===`asterisk`),i=X(t.text);return[r&&!n?`${i}.*`:i]}if(B(e,t)){let t=/^(?:export\s+)?import\s+([\w.:]+|"[^"]+"|<[^>]+>)/u.exec(e.text)?.[1];return t?t.startsWith(`"`)?[`./${Z(t)}`]:[t]:[]}if(H(e,t))return It(e);if(e.type===`preproc_include`){let t=e.childForFieldName(`path`);if(!t)return[];let n=Z(t.text);return[t.type===`string_literal`&&!n.startsWith(`.`)&&!n.startsWith(`/`)?`./${n}`:n]}if(V(e))return zt(e);let r=e.childForFieldName(`source`)??Wt(e);return r?[Z(r.text)]:[]}const Ft=new Set([`require`,`require_relative`,`load`]);function H(e,t){if(t.name!==`ruby`||e.type!==`call`)return!1;let n=e.childForFieldName(`method`);if(n?.type!==`identifier`)return!1;if(n.text===`autoload`){let t=e.childForFieldName(`receiver`);return t===null||t.type===`constant`||t.type===`scope_resolution`}return e.childForFieldName(`receiver`)===null&&Ft.has(n.text)}function It(e){let t=e.childForFieldName(`arguments`),n=e.childForFieldName(`method`)?.text===`autoload`,r=t?.namedChild(+!!n);if(!r||r.type!==`string`||r.namedChildren.some(e=>e.type===`interpolation`))return[];let i=r.namedChildren.filter(e=>e.type===`string_content`||e.type===`escape_sequence`),a=i.length>0?i.map(e=>e.type===`escape_sequence`?Rt(e.text):e.text).join(``):Z(r.text);return e.childForFieldName(`method`)?.text===`require_relative`?[a.startsWith(`.`)?a:`./${a}`]:[a.replace(/^(?:\.\.?\/)+/u,``)]}const Lt=new Map([[`n`,`
|
|
2
2
|
`],[`t`,` `],[`r`,`\r`],[`s`,` `],[`0`,`\0`]]);function Rt(e){let t=e.slice(1);return Lt.get(t)??t}function zt(e){let t=e.childForFieldName(`arguments`)?.namedChild(0);return t&&Gt(t)?[Z(t.text)]:[]}function Bt(e,t){return e.startsWith(`.`)||e.startsWith(`/`)?!0:t===`rust`&&U(e)}function U(e){return/^(?:crate|self|super)(?:::|$)/u.test(e)}function Vt(e){if(e.type===`mod_item`){let t=e.childForFieldName(`name`);return t?[`self::${X(t.text)}`]:[]}if(e.type===`extern_crate_declaration`){let t=e.childForFieldName(`name`);return t?[X(t.text)]:[]}let t=e.childForFieldName(`argument`);return t?W(t,``):[]}function W(e,t){switch(e.type){case`use_list`:return e.namedChildren.flatMap(e=>W(e,t));case`scoped_use_list`:{let n=e.childForFieldName(`list`),r=K(t,G(e.childForFieldName(`path`)));return n?W(n,r):q(r)}case`scoped_identifier`:{let n=K(t,X(e.text));return U(n)?q(n):q(K(t,G(e.childForFieldName(`path`))))}case`use_wildcard`:return q(K(t,G(e.namedChild(0))));case`use_as_clause`:{let n=e.childForFieldName(`path`);return n?W(n,t):[]}case`self`:return q(t);case`identifier`:case`crate`:case`super`:return e.type===`identifier`&&U(t)?q(K(t,X(e.text))):q(t===``?X(e.text):t);default:return[]}}function G(e){return e?X(e.text):``}function K(e,t){return t?e?`${e}::${t}`:t:e}function q(e){return e?[e]:[]}function Ht(e,t){if(e.type===`import_from_statement`){let n=e.childForFieldName(`module_name`);if(!n)return[];let r=X(n.text),i=Y(e,`name`);if(!t.expandPythonSubmodules||!r.startsWith(`.`))return[r];if(/^\.+$/u.test(r)&&i.length>0)return i.flatMap(J).map(e=>`${r}${e}`);let a=i.flatMap(J).map(e=>`${r}.${e}`);return a.length>0?[r,...a]:[r]}return e.type===`import_statement`?e.namedChildren.map(e=>Ut(e)).filter(e=>e!==void 0):[]}function J(e){if(e.type===`aliased_import`){let t=e.childForFieldName(`name`);return t?J(t):[]}return e.type===`identifier`?[e.text]:e.type===`dotted_name`?[X(e.text)]:e.namedChildren.flatMap(J)}function Y(e,t){let n=[];for(let r=0;r<e.childCount;r+=1){let i=e.child(r);i&&e.fieldNameForChild(r)===t&&n.push(i)}return n}function Ut(e){if(e.type===`dotted_name`||e.type===`relative_import`)return X(e.text);let t=e.childForFieldName(`name`);if(t)return X(t.text);for(let t of e.namedChildren){let e=Ut(t);if(e)return e}}function X(e){return e.replaceAll(/\s+/gu,``)}function Wt(e){if(Gt(e))return e;for(let t of e.namedChildren){let e=Wt(t);if(e)return e}}function Gt(e){return e.type===`string`||e.type===`string_literal`||e.type===`interpreted_string_literal`}function Z(e){return e.replaceAll(/^['"`<]|['"`>]$/gu,``)}function Kt(e){return e.type.startsWith(`export`)&&e.type!==`exports_module_directive`||e.type===`public_field_definition`}function qt(e){let t=new Set;for(let n of e.keys())Jt(n,n,e,new Set)&&t.add(n);return t}function Jt(e,t,n,r){let i=n.get(e);if(!i)return!1;for(let e of i)if(e===t||!r.has(e)&&(r.add(e),Jt(e,t,n,r)))return!0;return!1}function Yt(e){let t=new Map,n=0;for(let r of e.keys())n=Math.max(n,Xt(r,e,new Set,t).depth);return n}function Xt(e,t,n,r){let i=r.get(e);if(i!==void 0)return{depth:i,tainted:!1};let a=t.get(e);if(!a||a.size===0)return{depth:0,tainted:!1};if(n.has(e))return{depth:0,tainted:!0};n.add(e);let o=0,s=!1;for(let e of a){let i=Xt(e,t,n,r);o=Math.max(o,1+i.depth),s||=i.tainted}return n.delete(e),s||r.set(e,o),{depth:o,tainted:s}}function Zt(e,t){let[n,r]=e.size<=t.size?[e,t]:[t,e],i=0;for(let e of n)r.has(e)&&(i+=1);return i}function Qt(e,t,n){if(n===0)return 100;let r=171-5.2*Math.log(Math.max(e,1))-.23*t-16.2*Math.log(n);return Math.max(0,Math.min(100,r*100/171))}function Q(e,t){e.set(t,(e.get(t)??0)+1)}function $t(e,t){return e.length===0?0:Math.max(...e.map(e=>e[t]))}function en(e){let t=0;for(let n of e.values())t=Math.max(t,n);return t}function $(e){let t=0;for(let n of e)t+=n;return t}exports.TreeMeasurer=l,exports.defaultMeasurer=u,exports.measureCode=d;
|
|
3
3
|
//# sourceMappingURL=metrics.cjs.map
|