code-gauge 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/cliConfig.cjs +1 -1
- package/dist/cliConfig.js +1 -1
- package/dist/languages.cjs +1 -1
- package/dist/languages.cjs.map +1 -1
- package/dist/languages.js +1 -1
- package/dist/languages.js.map +1 -1
- package/dist/metrics.cjs +2 -2
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.js +2 -2
- package/dist/metrics.js.map +1 -1
- package/dist/ncss.cjs +2 -0
- package/dist/ncss.cjs.map +1 -0
- package/dist/ncss.d.ts +11 -0
- package/dist/ncss.js +2 -0
- package/dist/ncss.js.map +1 -0
- package/dist/types.d.ts +22 -0
- 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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C3C,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}, NCSS ${summary.ncssCount}, functions ${summary.functionCount}, max cyclomatic ${summary.maxCyclomaticComplexity}, max cognitive ${summary.maxCognitiveComplexity}\\n`\n );\n writeStdout(\n `Calls ${summary.callCount}, internal edges ${summary.internalCallCount}, max call depth ${summary.maxCallDepth}, imports ${summary.importSourceCount}, exports ${summary.exportCount}\\n`\n );\n writeStdout(\n `Type annotations ${summary.typeAnnotationCount}, type aliases ${summary.typeAliasCount}, interfaces ${summary.interfaceCount}, avg cohesion ${summary.averageFunctionIdentifierOverlap.toFixed(2)}\\n`\n );\n if (result.architecture) {\n writeStdout(`${formatArchitectureMetrics(result.architecture)}\\n`);\n }\n if (result.typeScriptProject) {\n writeStdout(`${formatTypeScriptProjectMetrics(result.typeScriptProject)}\\n`);\n }\n writeStdout(\n `Risk thresholds: file LOC >= ${thresholds.fileLoc}, function LOC >= ${thresholds.functionLoc}, component LOC >= ${thresholds.componentLoc}, cognitive >= ${thresholds.cognitive}, cyclomatic >= ${thresholds.cyclomatic}, calls >= ${thresholds.call}, imports >= ${thresholds.import}, fan-out >= ${thresholds.fanOut}, parameters >= ${thresholds.parameter}, duplicated blocks >= ${thresholds.duplicateBlock}, duplicated lines (%) >= ${thresholds.duplicationRatioPercent}\\n`\n );\n const profileOverrides = formatProfileOverrides(options.profileThresholds);\n if (profileOverrides) {\n writeStdout(`Per-language overrides: ${profileOverrides}\\n`);\n }\n\n if (risks.length === 0) {\n writeStdout('No high-risk findings found.\\n');\n } else {\n const reportedRisks = risks.slice(0, options.maxFindings);\n const totalSuffix = risks.length > reportedRisks.length ? ` of ${risks.length}` : '';\n writeStdout(`\\nHigh-risk findings (top ${reportedRisks.length}${totalSuffix}):\\n`);\n for (const risk of reportedRisks) {\n writeStdout(`${formatRiskLocation(risk)} ${formatRiskName(risk)} ${formatRiskMetrics(risk)}\\n`);\n }\n }\n\n const duplicateSymbolGroups = result.architecture?.duplicateSymbolGroups ?? [];\n if (duplicateSymbolGroups.length > 0) {\n const reportedGroups = duplicateSymbolGroups\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name))\n .slice(0, maxDuplicateSymbolGroupLines);\n const totalSuffix =\n duplicateSymbolGroups.length > reportedGroups.length ? ` of ${duplicateSymbolGroups.length}` : '';\n writeStdout(`\\nDuplicate symbols (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.name}: ${group.declarations.map((declaration) => `${declaration.file}:${declaration.line}`).join(', ')}\\n`\n );\n }\n }\n\n if (options.largestFiles > 0) {\n const largestFiles = findLargestFiles(result.files, options.largestFiles, result.displayRoot);\n writeStdout(`\\nLargest files by code LOC (top ${largestFiles.length}):\\n`);\n for (const { file, codeLoc } of largestFiles) {\n writeStdout(`${file} (code LOC ${codeLoc})\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\nfunction findLargestFiles(\n files: FileMetrics[],\n count: number,\n displayRoot: string\n): { file: string; codeLoc: number }[] {\n return files\n .map(({ file, metrics }) => ({ file: formatPath(file, displayRoot), codeLoc: metrics.lines.code }))\n .toSorted((left, right) => right.codeLoc - left.codeLoc || left.file.localeCompare(right.file))\n .slice(0, count);\n}\n\nfunction formatProfileOverrides(profileThresholds: ResolvedOptions['profileThresholds']): string {\n return Object.entries(profileThresholds)\n .map(\n ([profile, overrides]) =>\n `${profile} { ${Object.entries(overrides)\n .map(([metric, value]) => `${metric} ${value}`)\n .join(', ')} }`\n )\n .join('; ');\n}\n\nfunction formatRiskLocation(risk: RiskFinding): string {\n return risk.startLine === undefined || risk.endLine === undefined\n ? risk.file\n : `${risk.file}:${risk.startLine}-${risk.endLine}`;\n}\n\nfunction formatRiskName(risk: RiskFinding): string {\n return risk.name ? `${risk.kind} ${risk.name}` : risk.kind;\n}\n\nfunction formatRiskMetrics(risk: RiskFinding): string {\n const triggerText = risk.triggers\n .map(\n (trigger) =>\n `${trigger.metric} ${formatMetricValue(trigger.value)} >= ${formatMetricValue(trigger.threshold)}${trigger.detail ? ` [${trigger.detail}]` : ''}`\n )\n .join(', ');\n return `(${triggerText}; cyclomatic ${risk.cyclomaticComplexity}, cognitive ${risk.cognitiveComplexity})`;\n}\n\nfunction formatMetricValue(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(2);\n}\n\nfunction formatArchitectureMetrics(metrics: ArchitectureMetrics): string {\n const maxStateMutationScore = Math.max(\n 0,\n ...metrics.files.map((file) => file.structuralCoordination.stateMutationScore)\n );\n return `Architecture max reachable files ${metrics.maxTransitiveLocalDependencyCount}, max structural breadth ${metrics.maxStructuralBreadthScore}, max structural coordination ${metrics.maxStructuralCoordinationScore}, max state mutation ${maxStateMutationScore}, duplicate symbol groups ${metrics.duplicateSymbolGroups.length}`;\n}\n\nfunction formatTypeScriptProjectMetrics(metrics: TypeScriptProjectMetrics): string {\n return `TypeScript project root files ${metrics.rootFileCount}, measured roots ${metrics.measuredRootFileCount}, semantic diagnostics ${metrics.semanticDiagnosticCount}, resolved calls ${metrics.resolvedCallExpressionCount}/${metrics.callExpressionCount} (${(metrics.resolvedCallExpressionRatio * 100).toFixed(1)}%)`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n maxCyclomaticComplexity: number;\n ncssCount: number;\n callCount: number;\n internalCallCount: number;\n maxCallDepth: number;\n importSourceCount: number;\n relativeImportCount: number;\n externalImportCount: number;\n exportCount: number;\n averageFunctionIdentifierOverlap: number;\n typeAnnotationCount: number;\n typeAliasCount: number;\n interfaceCount: number;\n genericParameterCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCyclomaticComplexity = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n let callCount = 0;\n let internalCallCount = 0;\n let maxCallDepth = 0;\n let importSourceCount = 0;\n let relativeImportCount = 0;\n let externalImportCount = 0;\n let exportCount = 0;\n let cohesionTotal = 0;\n let typeAnnotationCount = 0;\n let typeAliasCount = 0;\n let interfaceCount = 0;\n let genericParameterCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functionCount;\n linesOfCode += file.metrics.lines.code;\n maxCyclomaticComplexity = Math.max(maxCyclomaticComplexity, file.metrics.maxCyclomaticComplexity);\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n callCount += file.metrics.callGraph.callCount;\n internalCallCount += file.metrics.callGraph.internalCallCount;\n maxCallDepth = Math.max(maxCallDepth, file.metrics.callGraph.maxCallDepth);\n importSourceCount += file.metrics.coupling.importSourceCount;\n relativeImportCount += file.metrics.coupling.relativeImportCount;\n externalImportCount += file.metrics.coupling.externalImportCount;\n exportCount += file.metrics.coupling.exportCount;\n cohesionTotal += file.metrics.cohesion.averageFunctionIdentifierOverlap;\n typeAnnotationCount += file.metrics.typeComplexity.typeAnnotationCount;\n typeAliasCount += file.metrics.typeComplexity.typeAliasCount;\n interfaceCount += file.metrics.typeComplexity.interfaceCount;\n genericParameterCount += file.metrics.typeComplexity.genericParameterCount;\n }\n\n return {\n fileCount: files.length,\n functionCount,\n linesOfCode,\n maxCyclomaticComplexity,\n maxCognitiveComplexity,\n ncssCount,\n callCount,\n internalCallCount,\n maxCallDepth,\n importSourceCount,\n relativeImportCount,\n externalImportCount,\n exportCount,\n averageFunctionIdentifierOverlap: files.length === 0 ? 0 : cohesionTotal / files.length,\n typeAnnotationCount,\n typeAliasCount,\n interfaceCount,\n genericParameterCount,\n };\n}\n\nfunction shouldSkipDirectory(name: string, options: ResolvedOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\nfunction getLanguage(file: string, options: ResolvedOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number {\n if (!/^[1-9]\\d*$/u.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n\nfunction formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nfunction writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nfunction writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";sdA0DA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eACA,SACA,gBACA,SACA,MACF,CAAC,EAKK,EAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,GAAsB,eAGvB,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAY,UAAU,EAAY,CAAK,EAAE,GAAG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,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"}
|
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/languages.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const e=require("./_virtual/_rolldown/runtime.cjs");let t=require("tree-sitter-c");t=e.__toESM(t,1);let n=require("tree-sitter-cpp");n=e.__toESM(n,1);let r=require("tree-sitter-go");r=e.__toESM(r,1);let i=require("tree-sitter-java");i=e.__toESM(i,1);let a=require("tree-sitter-javascript");a=e.__toESM(a,1);let o=require("tree-sitter-python");o=e.__toESM(o,1);let s=require("tree-sitter-ruby");s=e.__toESM(s,1);let c=require("tree-sitter-rust");c=e.__toESM(c,1);let l=require("tree-sitter-typescript");l=e.__toESM(l,1);const u=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],d=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],f=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],p=[...f,`expression_case`,`type_case`,`communication_case`],m=[...u,`constructor_declaration`,`compact_constructor_declaration`],
|
|
1
|
+
"use strict";const e=require("./_virtual/_rolldown/runtime.cjs");let t=require("tree-sitter-c");t=e.__toESM(t,1);let n=require("tree-sitter-cpp");n=e.__toESM(n,1);let r=require("tree-sitter-go");r=e.__toESM(r,1);let i=require("tree-sitter-java");i=e.__toESM(i,1);let a=require("tree-sitter-javascript");a=e.__toESM(a,1);let o=require("tree-sitter-python");o=e.__toESM(o,1);let s=require("tree-sitter-ruby");s=e.__toESM(s,1);let c=require("tree-sitter-rust");c=e.__toESM(c,1);let l=require("tree-sitter-typescript");l=e.__toESM(l,1);const u=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],d=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],f=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],p=[...f,`expression_case`,`type_case`,`communication_case`],m=[...f,`switch_default`],h=[...p,`default_case`],g=[...u,`constructor_declaration`,`compact_constructor_declaration`],_=[...d,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],v=[...f,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],y=[...v,`throw_statement`],b=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],x=[`class`,`module`],S=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],C=[`function_definition`,`lambda_expression`],w=[`struct_specifier`,`enum_specifier`,`union_specifier`],T=[...f,`case_statement`],E=[...w,`class_specifier`],D=[...T,`for_range_loop`],O=`import_statement.export_statement.lexical_declaration.variable_declaration.function_declaration.function_signature.generator_function_declaration.class_declaration.abstract_class_declaration.module.method_definition.abstract_method_signature.class_static_block.field_definition.public_field_definition.type_alias_declaration.interface_declaration.enum_declaration.expression_statement.if_statement.else_clause.switch_statement.switch_case.switch_default.for_statement.for_in_statement.while_statement.do_statement.catch_clause.finally_clause.labeled_statement.return_statement.break_statement.continue_statement.throw_statement.debugger_statement.with_statement`.split(`.`),k=`import_statement.import_from_statement.future_import_statement.print_statement.exec_statement.assert_statement.expression_statement.return_statement.delete_statement.raise_statement.pass_statement.break_statement.continue_statement.global_statement.nonlocal_statement.if_statement.elif_clause.else_clause.for_statement.while_statement.except_clause.except_group_clause.finally_clause.with_statement.match_statement.case_clause.function_definition.class_definition.type_alias_statement`.split(`.`),A=`package_clause.import_spec.type_spec.type_alias.const_spec.var_spec.function_declaration.method_declaration.short_var_declaration.expression_statement.send_statement.inc_statement.dec_statement.assignment_statement.if_statement.for_statement.expression_switch_statement.type_switch_statement.select_statement.expression_case.type_case.communication_case.default_case.return_statement.break_statement.continue_statement.goto_statement.fallthrough_statement.defer_statement.go_statement.labeled_statement`.split(`.`),j=[`use_declaration`,`extern_crate_declaration`,`foreign_mod_item`,`mod_item`,`const_item`,`static_item`,`struct_item`,`enum_item`,`union_item`,`trait_item`,`impl_item`,`function_item`,`function_signature_item`,`type_item`,`associated_type`,`macro_definition`,`field_declaration`,`let_declaration`,`expression_statement`,`else_clause`,`match_arm`],M=`package_declaration.import_declaration.module_declaration.requires_module_directive.exports_module_directive.opens_module_directive.uses_module_directive.provides_module_directive.class_declaration.interface_declaration.enum_declaration.annotation_type_declaration.annotation_type_element_declaration.record_declaration.field_declaration.constant_declaration.method_declaration.constructor_declaration.compact_constructor_declaration.static_initializer.explicit_constructor_invocation.local_variable_declaration.expression_statement.if_statement.while_statement.do_statement.for_statement.enhanced_for_statement.switch_statement.switch_expression.switch_label.break_statement.continue_statement.return_statement.throw_statement.assert_statement.synchronized_statement.labeled_statement.yield_statement.resource.catch_clause.finally_clause`.split(`.`),N=[`elsif`,`else`,`when`,`in_clause`,`rescue`,`ensure`],P=[`program`,`body_statement`,`then`,`else`,`do`,`block_body`,`begin`,`ensure`],F=[`preproc_include`,`preproc_def`,`preproc_function_def`,`declaration`,`type_definition`,`field_declaration`,`function_definition`,`struct_specifier`,`enum_specifier`,`union_specifier`,`expression_statement`,`if_statement`,`else_clause`,`switch_statement`,`case_statement`,`for_statement`,`while_statement`,`do_statement`,`return_statement`,`break_statement`,`continue_statement`,`goto_statement`,`labeled_statement`],I=[...F,`class_specifier`,`namespace_definition`,`using_declaration`,`alias_declaration`,`namespace_alias_definition`,`concept_definition`,`static_assert_declaration`,`for_range_loop`,`catch_clause`,`throw_statement`,`co_return_statement`,`co_yield_statement`];function L(e){return z(e,`default`)?e.default:e}function R(e){return l.default[e]}function z(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const B=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:L(a.default)},{name:`jsx`,parserLanguage:L(a.default)},{name:`typescript`,aliases:[`ts`],parserLanguage:R(`typescript`)},{name:`tsx`,parserLanguage:R(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:L(o.default),ncssNodeTypes:k},{name:`go`,parserLanguage:L(r.default),decisionNodeTypes:p,nestingNodeTypes:h,ncssNodeTypes:A},{name:`rust`,aliases:[`rs`],parserLanguage:L(c.default),ncssNodeTypes:j,ncssContainerNodeTypes:[`block`,`else_clause`]},{name:`java`,parserLanguage:L(i.default),functionNodeTypes:g,classNodeTypes:_,decisionNodeTypes:y,nestingNodeTypes:v,ncssNodeTypes:M},{name:`ruby`,aliases:[`rb`],parserLanguage:L(s.default),functionNodeTypes:b,classNodeTypes:x,decisionNodeTypes:S,nestingNodeTypes:S,ncssNodeTypes:N,ncssContainerNodeTypes:P},{name:`c`,parserLanguage:L(t.default),functionNodeTypes:C,classNodeTypes:w,decisionNodeTypes:T,nestingNodeTypes:T,ncssNodeTypes:F},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:L(n.default),functionNodeTypes:C,classNodeTypes:E,decisionNodeTypes:D,nestingNodeTypes:D,ncssNodeTypes:I}].map(e=>({functionNodeTypes:u,classNodeTypes:d,decisionNodeTypes:f,nestingNodeTypes:m,ncssNodeTypes:O,...e}));function V(e=B){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const H=B.map(e=>e.name);exports.createLanguageRegistry=V,exports.defaultLanguages=B,exports.supportedLanguages=H;
|
|
2
2
|
//# sourceMappingURL=languages.cjs.map
|
package/dist/languages.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"languages.cjs","names":["grammars","JavaScript","Python","Go","Rust","Java","Ruby","C","Cpp"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goDecisionNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonDecisionNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"ohBAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,C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KAAK,CAC5C,EACA,CACE,KAAM,SACN,QAAS,CAAC,IAAI,EACd,eAAgB,EAAiBC,EAAAA,OAAkC,CACrE,EACA,CACE,KAAM,KACN,eAAgB,EAAiBC,EAAAA,OAA8B,EAC/D,kBAAmB,EACnB,iBAAkB,CACpB,EACA,CACE,KAAM,OACN,QAAS,CAAC,IAAI,EACd,eAAgB,EAAiBC,EAAAA,OAAgC,CACnE,EACA,CACE,KAAM,OACN,eAAgB,EAAiBC,EAAAA,OAAgC,EACjE,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,CACpB,EACA,CACE,KAAM,OACN,QAAS,CAAC,IAAI,EACd,eAAgB,EAAiBC,EAAAA,OAAgC,EACjE,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,CACpB,EACA,CACE,KAAM,IACN,eAAgB,EAAiBC,EAAAA,OAA6B,EAC9D,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,CACpB,EACA,CACE,KAAM,MACN,QAAS,CAAC,MAAO,KAAK,EACtB,eAAgB,EAAiBC,EAAAA,OAA+B,EAChE,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,CACpB,CACF,CAAC,CAAC,IAAK,IAAc,CACnB,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,EAClB,GAAG,CACL,EAAE,EAEF,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
|
|
1
|
+
{"version":3,"file":"languages.cjs","names":["grammars","JavaScript","Python","Go","Rust","Java","Ruby","C","Cpp"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\n// Default switch branches add no decision, but their contents are nested inside the switch like\n// any other arm, so they appear in the nesting sets only.\nconst commonNestingNodes = [...commonDecisionNodes, 'switch_default'] as const;\nconst goNestingNodes = [...goDecisionNodes, 'default_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n// PMD's standard cyclomatic complexity charges `throw` one path (verified against PMD 7.26.0);\n// it stays out of the nesting set (its argument expressions are not nested) and adds no\n// cognitive point (see cyclomaticOnlyNodeTypes in metrics.ts). Other languages follow their own\n// reference tools (lizard/radon), which do not count throw/raise.\nconst javaCyclomaticDecisionNodes = [...javaDecisionNodes, 'throw_statement'] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\n// NCSS node sets: every listed type counts as one non-commenting source statement. The Java set is\n// calibrated against PMD's NcssCount rule (`try` counts 0; `else`, `case`/`default` labels,\n// `catch`, `finally`, and try-with-resources resources count 1 each); the other languages follow\n// the same conventions with their grammar's node types.\nconst jsNcssNodes = [\n 'import_statement',\n 'export_statement',\n 'lexical_declaration',\n 'variable_declaration',\n 'function_declaration',\n 'function_signature',\n 'generator_function_declaration',\n 'class_declaration',\n 'abstract_class_declaration',\n 'module',\n 'method_definition',\n 'abstract_method_signature',\n 'class_static_block',\n 'field_definition',\n 'public_field_definition',\n 'type_alias_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'switch_case',\n 'switch_default',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'finally_clause',\n 'labeled_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'throw_statement',\n 'debugger_statement',\n 'with_statement',\n] as const;\n\nconst pythonNcssNodes = [\n 'import_statement',\n 'import_from_statement',\n 'future_import_statement',\n 'print_statement',\n 'exec_statement',\n 'assert_statement',\n 'expression_statement',\n 'return_statement',\n 'delete_statement',\n 'raise_statement',\n 'pass_statement',\n 'break_statement',\n 'continue_statement',\n 'global_statement',\n 'nonlocal_statement',\n 'if_statement',\n 'elif_clause',\n 'else_clause',\n 'for_statement',\n 'while_statement',\n 'except_clause',\n 'except_group_clause',\n 'finally_clause',\n 'with_statement',\n 'match_statement',\n 'case_clause',\n 'function_definition',\n 'class_definition',\n 'type_alias_statement',\n] as const;\n\nconst goNcssNodes = [\n 'package_clause',\n 'import_spec',\n 'type_spec',\n 'type_alias',\n 'const_spec',\n 'var_spec',\n 'function_declaration',\n 'method_declaration',\n // Struct fields and interface members count contextually (see ncss.ts): only inside a named\n // `type T struct/interface { ... }`, not in inline anonymous types, which are part of one\n // declaration.\n 'short_var_declaration',\n 'expression_statement',\n 'send_statement',\n 'inc_statement',\n 'dec_statement',\n 'assignment_statement',\n 'if_statement',\n 'for_statement',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'fallthrough_statement',\n 'defer_statement',\n 'go_statement',\n 'labeled_statement',\n] as const;\n\nconst rustNcssNodes = [\n 'use_declaration',\n 'extern_crate_declaration',\n 'foreign_mod_item',\n 'mod_item',\n 'const_item',\n 'static_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n 'trait_item',\n 'impl_item',\n 'function_item',\n 'function_signature_item',\n 'type_item',\n 'associated_type',\n 'macro_definition',\n 'field_declaration',\n 'let_declaration',\n 'expression_statement',\n 'else_clause',\n 'match_arm',\n] as const;\n\nconst javaNcssNodes = [\n 'package_declaration',\n 'import_declaration',\n 'module_declaration',\n 'requires_module_directive',\n 'exports_module_directive',\n 'opens_module_directive',\n 'uses_module_directive',\n 'provides_module_directive',\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'annotation_type_declaration',\n 'annotation_type_element_declaration',\n 'record_declaration',\n 'field_declaration',\n 'constant_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n 'static_initializer',\n 'explicit_constructor_invocation',\n 'local_variable_declaration',\n 'expression_statement',\n 'if_statement',\n 'while_statement',\n 'do_statement',\n 'for_statement',\n 'enhanced_for_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_label',\n 'break_statement',\n 'continue_statement',\n 'return_statement',\n 'throw_statement',\n 'assert_statement',\n 'synchronized_statement',\n 'labeled_statement',\n 'yield_statement',\n 'resource',\n 'catch_clause',\n 'finally_clause',\n] as const;\n\n// Ruby statements have no wrapper node types, so bodies are counted positionally (see\n// ncssContainerNodeTypes); only clause nodes hanging off non-container parents need listing.\nconst rubyNcssNodes = ['elsif', 'else', 'when', 'in_clause', 'rescue', 'ensure'] as const;\nconst rubyNcssContainers = [\n 'program',\n 'body_statement',\n 'then',\n 'else',\n 'do',\n 'block_body',\n 'begin',\n 'ensure',\n] as const;\n\nconst cNcssNodes = [\n 'preproc_include',\n 'preproc_def',\n 'preproc_function_def',\n 'declaration',\n 'type_definition',\n 'field_declaration',\n 'function_definition',\n // Counted only when they carry a body (see bodylessNcssSpecifierTypes in ncss.ts).\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'case_statement',\n 'for_statement',\n 'while_statement',\n 'do_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'labeled_statement',\n] as const;\nconst cppNcssNodes = [\n ...cNcssNodes,\n 'class_specifier',\n 'namespace_definition',\n 'using_declaration',\n 'alias_declaration',\n 'namespace_alias_definition',\n 'concept_definition',\n 'static_assert_declaration',\n 'for_range_loop',\n 'catch_clause',\n 'throw_statement',\n 'co_return_statement',\n 'co_yield_statement',\n] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n ncssNodeTypes: pythonNcssNodes,\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goNestingNodes,\n ncssNodeTypes: goNcssNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n ncssNodeTypes: rustNcssNodes,\n // `else_clause` is a container so `else if` chains count the nested if_expression; a plain\n // `else { ... }` is unaffected because its only child is a `block`, itself a container.\n ncssContainerNodeTypes: ['block', 'else_clause'],\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaCyclomaticDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n ncssNodeTypes: javaNcssNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n ncssNodeTypes: rubyNcssNodes,\n ncssContainerNodeTypes: rubyNcssContainers,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n ncssNodeTypes: cNcssNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n ncssNodeTypes: cppNcssNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonNestingNodes,\n ncssNodeTypes: jsNcssNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"ohBAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAI/F,EAAqB,CAAC,GAAG,EAAqB,gBAAgB,EAC9D,EAAiB,CAAC,GAAG,EAAiB,cAAc,EAEpD,EAAoB,CACxB,GAAG,EACH,0BACA,iCACF,EACM,EAAiB,CACrB,GAAG,EACH,mBACA,qBACA,8BAEA,6BACA,eACF,EACM,EAAoB,CACxB,GAAG,EACH,yBACA,+BACA,aACF,EAKM,EAA8B,CAAC,GAAG,EAAmB,iBAAiB,EAKtE,EAAoB,CAAC,SAAU,mBAAoB,SAAU,QAAS,UAAU,EAEhF,EAAiB,CAAC,QAAS,QAAQ,EACnC,EAAoB,CACxB,KACA,QACA,SACA,QACA,QACA,MACA,OACA,YACA,SACA,cACA,cACA,kBACA,iBACA,iBACA,iBACF,EAIM,EAAiB,CAAC,sBAAuB,mBAAmB,EAC5D,EAAc,CAAC,mBAAoB,iBAAkB,iB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CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
|
package/dist/languages.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"tree-sitter-c";import t from"tree-sitter-cpp";import n from"tree-sitter-go";import r from"tree-sitter-java";import i from"tree-sitter-javascript";import a from"tree-sitter-python";import o from"tree-sitter-ruby";import s from"tree-sitter-rust";import c from"tree-sitter-typescript";const l=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],u=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],d=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],f=[...d,`expression_case`,`type_case`,`communication_case`],p=[...l,`constructor_declaration`,`compact_constructor_declaration`],
|
|
1
|
+
import e from"tree-sitter-c";import t from"tree-sitter-cpp";import n from"tree-sitter-go";import r from"tree-sitter-java";import i from"tree-sitter-javascript";import a from"tree-sitter-python";import o from"tree-sitter-ruby";import s from"tree-sitter-rust";import c from"tree-sitter-typescript";const l=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],u=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],d=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],f=[...d,`expression_case`,`type_case`,`communication_case`],p=[...d,`switch_default`],m=[...f,`default_case`],h=[...l,`constructor_declaration`,`compact_constructor_declaration`],g=[...u,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],_=[...d,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],v=[..._,`throw_statement`],y=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],b=[`class`,`module`],x=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],S=[`function_definition`,`lambda_expression`],C=[`struct_specifier`,`enum_specifier`,`union_specifier`],w=[...d,`case_statement`],T=[...C,`class_specifier`],E=[...w,`for_range_loop`],D=`import_statement.export_statement.lexical_declaration.variable_declaration.function_declaration.function_signature.generator_function_declaration.class_declaration.abstract_class_declaration.module.method_definition.abstract_method_signature.class_static_block.field_definition.public_field_definition.type_alias_declaration.interface_declaration.enum_declaration.expression_statement.if_statement.else_clause.switch_statement.switch_case.switch_default.for_statement.for_in_statement.while_statement.do_statement.catch_clause.finally_clause.labeled_statement.return_statement.break_statement.continue_statement.throw_statement.debugger_statement.with_statement`.split(`.`),O=`import_statement.import_from_statement.future_import_statement.print_statement.exec_statement.assert_statement.expression_statement.return_statement.delete_statement.raise_statement.pass_statement.break_statement.continue_statement.global_statement.nonlocal_statement.if_statement.elif_clause.else_clause.for_statement.while_statement.except_clause.except_group_clause.finally_clause.with_statement.match_statement.case_clause.function_definition.class_definition.type_alias_statement`.split(`.`),k=`package_clause.import_spec.type_spec.type_alias.const_spec.var_spec.function_declaration.method_declaration.short_var_declaration.expression_statement.send_statement.inc_statement.dec_statement.assignment_statement.if_statement.for_statement.expression_switch_statement.type_switch_statement.select_statement.expression_case.type_case.communication_case.default_case.return_statement.break_statement.continue_statement.goto_statement.fallthrough_statement.defer_statement.go_statement.labeled_statement`.split(`.`),A=[`use_declaration`,`extern_crate_declaration`,`foreign_mod_item`,`mod_item`,`const_item`,`static_item`,`struct_item`,`enum_item`,`union_item`,`trait_item`,`impl_item`,`function_item`,`function_signature_item`,`type_item`,`associated_type`,`macro_definition`,`field_declaration`,`let_declaration`,`expression_statement`,`else_clause`,`match_arm`],j=`package_declaration.import_declaration.module_declaration.requires_module_directive.exports_module_directive.opens_module_directive.uses_module_directive.provides_module_directive.class_declaration.interface_declaration.enum_declaration.annotation_type_declaration.annotation_type_element_declaration.record_declaration.field_declaration.constant_declaration.method_declaration.constructor_declaration.compact_constructor_declaration.static_initializer.explicit_constructor_invocation.local_variable_declaration.expression_statement.if_statement.while_statement.do_statement.for_statement.enhanced_for_statement.switch_statement.switch_expression.switch_label.break_statement.continue_statement.return_statement.throw_statement.assert_statement.synchronized_statement.labeled_statement.yield_statement.resource.catch_clause.finally_clause`.split(`.`),M=[`elsif`,`else`,`when`,`in_clause`,`rescue`,`ensure`],N=[`program`,`body_statement`,`then`,`else`,`do`,`block_body`,`begin`,`ensure`],P=[`preproc_include`,`preproc_def`,`preproc_function_def`,`declaration`,`type_definition`,`field_declaration`,`function_definition`,`struct_specifier`,`enum_specifier`,`union_specifier`,`expression_statement`,`if_statement`,`else_clause`,`switch_statement`,`case_statement`,`for_statement`,`while_statement`,`do_statement`,`return_statement`,`break_statement`,`continue_statement`,`goto_statement`,`labeled_statement`],F=[...P,`class_specifier`,`namespace_definition`,`using_declaration`,`alias_declaration`,`namespace_alias_definition`,`concept_definition`,`static_assert_declaration`,`for_range_loop`,`catch_clause`,`throw_statement`,`co_return_statement`,`co_yield_statement`];function I(e){return R(e,`default`)?e.default:e}function L(e){return c[e]}function R(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const z=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:I(i)},{name:`jsx`,parserLanguage:I(i)},{name:`typescript`,aliases:[`ts`],parserLanguage:L(`typescript`)},{name:`tsx`,parserLanguage:L(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:I(a),ncssNodeTypes:O},{name:`go`,parserLanguage:I(n),decisionNodeTypes:f,nestingNodeTypes:m,ncssNodeTypes:k},{name:`rust`,aliases:[`rs`],parserLanguage:I(s),ncssNodeTypes:A,ncssContainerNodeTypes:[`block`,`else_clause`]},{name:`java`,parserLanguage:I(r),functionNodeTypes:h,classNodeTypes:g,decisionNodeTypes:v,nestingNodeTypes:_,ncssNodeTypes:j},{name:`ruby`,aliases:[`rb`],parserLanguage:I(o),functionNodeTypes:y,classNodeTypes:b,decisionNodeTypes:x,nestingNodeTypes:x,ncssNodeTypes:M,ncssContainerNodeTypes:N},{name:`c`,parserLanguage:I(e),functionNodeTypes:S,classNodeTypes:C,decisionNodeTypes:w,nestingNodeTypes:w,ncssNodeTypes:P},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:I(t),functionNodeTypes:S,classNodeTypes:T,decisionNodeTypes:E,nestingNodeTypes:E,ncssNodeTypes:F}].map(e=>({functionNodeTypes:l,classNodeTypes:u,decisionNodeTypes:d,nestingNodeTypes:p,ncssNodeTypes:D,...e}));function B(e=z){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const V=z.map(e=>e.name);export{B as createLanguageRegistry,z as defaultLanguages,V as supportedLanguages};
|
|
2
2
|
//# sourceMappingURL=languages.js.map
|
package/dist/languages.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"languages.js","names":["grammars"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goDecisionNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonDecisionNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"wSAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAE/F,EAAoB,CACxB,GAAG,EACH,0BACA,iCACF,EACM,EAAiB,CACrB,GAAG,EACH,mBACA,qBACA,8BAEA,6BACA,eACF,EACM,EAAoB,CACxB,GAAG,EACH,yBACA,+BACA,aACF,EAKM,EAAoB,CAAC,SAAU,mBAAoB,SAAU,QAAS,UAAU,EAEhF,EAAiB,CAAC,QAAS,QAAQ,EACnC,EAAoB,CACxB,KACA,QACA,SACA,QACA,QACA,MACA,OACA,YACA,SACA,cACA,cACA,kBACA,iBACA,iBACA,iBACF,EAIM,EAAiB,CAAC,sBAAuB,mBAAmB,EAC5D,EAAc,CAAC,mBAAoB,iBAAkB,iBAAiB,EACtE,EAAiB,CAAC,GAAG,EAAqB,gBAAgB,EAC1D,EAAgB,CAAC,GAAG,EAAa,iBAAiB,EAClD,EAAmB,CAAC,GAAG,EAAgB,gBAAgB,EAE7D,SAAS,EAAiB,EAAuC,CAK/D,OAJI,EAAiB,EAAQ,SAAS,EAC7B,EAAO,QAGT,CACT,CAEA,SAAS,EAAqB,EAA4C,CAExE,OAAOA,EAAS,EAClB,CAEA,SAAS,EAAiB,EAAsB,EAA6D,CAK3G,OAJI,OAAO,GAAU,WAAY,GAAkB,EAAE,KAAO,GACnD,GAGF,EAAS,EAAyC,EAC3D,CAEA,MAAa,EAAkD,CAC7D,CACE,KAAM,aACN,QAA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CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
|
|
1
|
+
{"version":3,"file":"languages.js","names":["grammars"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\n// Default switch branches add no decision, but their contents are nested inside the switch like\n// any other arm, so they appear in the nesting sets only.\nconst commonNestingNodes = [...commonDecisionNodes, 'switch_default'] as const;\nconst goNestingNodes = [...goDecisionNodes, 'default_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n// PMD's standard cyclomatic complexity charges `throw` one path (verified against PMD 7.26.0);\n// it stays out of the nesting set (its argument expressions are not nested) and adds no\n// cognitive point (see cyclomaticOnlyNodeTypes in metrics.ts). Other languages follow their own\n// reference tools (lizard/radon), which do not count throw/raise.\nconst javaCyclomaticDecisionNodes = [...javaDecisionNodes, 'throw_statement'] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\n// NCSS node sets: every listed type counts as one non-commenting source statement. The Java set is\n// calibrated against PMD's NcssCount rule (`try` counts 0; `else`, `case`/`default` labels,\n// `catch`, `finally`, and try-with-resources resources count 1 each); the other languages follow\n// the same conventions with their grammar's node types.\nconst jsNcssNodes = [\n 'import_statement',\n 'export_statement',\n 'lexical_declaration',\n 'variable_declaration',\n 'function_declaration',\n 'function_signature',\n 'generator_function_declaration',\n 'class_declaration',\n 'abstract_class_declaration',\n 'module',\n 'method_definition',\n 'abstract_method_signature',\n 'class_static_block',\n 'field_definition',\n 'public_field_definition',\n 'type_alias_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'switch_case',\n 'switch_default',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'finally_clause',\n 'labeled_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'throw_statement',\n 'debugger_statement',\n 'with_statement',\n] as const;\n\nconst pythonNcssNodes = [\n 'import_statement',\n 'import_from_statement',\n 'future_import_statement',\n 'print_statement',\n 'exec_statement',\n 'assert_statement',\n 'expression_statement',\n 'return_statement',\n 'delete_statement',\n 'raise_statement',\n 'pass_statement',\n 'break_statement',\n 'continue_statement',\n 'global_statement',\n 'nonlocal_statement',\n 'if_statement',\n 'elif_clause',\n 'else_clause',\n 'for_statement',\n 'while_statement',\n 'except_clause',\n 'except_group_clause',\n 'finally_clause',\n 'with_statement',\n 'match_statement',\n 'case_clause',\n 'function_definition',\n 'class_definition',\n 'type_alias_statement',\n] as const;\n\nconst goNcssNodes = [\n 'package_clause',\n 'import_spec',\n 'type_spec',\n 'type_alias',\n 'const_spec',\n 'var_spec',\n 'function_declaration',\n 'method_declaration',\n // Struct fields and interface members count contextually (see ncss.ts): only inside a named\n // `type T struct/interface { ... }`, not in inline anonymous types, which are part of one\n // declaration.\n 'short_var_declaration',\n 'expression_statement',\n 'send_statement',\n 'inc_statement',\n 'dec_statement',\n 'assignment_statement',\n 'if_statement',\n 'for_statement',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'fallthrough_statement',\n 'defer_statement',\n 'go_statement',\n 'labeled_statement',\n] as const;\n\nconst rustNcssNodes = [\n 'use_declaration',\n 'extern_crate_declaration',\n 'foreign_mod_item',\n 'mod_item',\n 'const_item',\n 'static_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n 'trait_item',\n 'impl_item',\n 'function_item',\n 'function_signature_item',\n 'type_item',\n 'associated_type',\n 'macro_definition',\n 'field_declaration',\n 'let_declaration',\n 'expression_statement',\n 'else_clause',\n 'match_arm',\n] as const;\n\nconst javaNcssNodes = [\n 'package_declaration',\n 'import_declaration',\n 'module_declaration',\n 'requires_module_directive',\n 'exports_module_directive',\n 'opens_module_directive',\n 'uses_module_directive',\n 'provides_module_directive',\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'annotation_type_declaration',\n 'annotation_type_element_declaration',\n 'record_declaration',\n 'field_declaration',\n 'constant_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n 'static_initializer',\n 'explicit_constructor_invocation',\n 'local_variable_declaration',\n 'expression_statement',\n 'if_statement',\n 'while_statement',\n 'do_statement',\n 'for_statement',\n 'enhanced_for_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_label',\n 'break_statement',\n 'continue_statement',\n 'return_statement',\n 'throw_statement',\n 'assert_statement',\n 'synchronized_statement',\n 'labeled_statement',\n 'yield_statement',\n 'resource',\n 'catch_clause',\n 'finally_clause',\n] as const;\n\n// Ruby statements have no wrapper node types, so bodies are counted positionally (see\n// ncssContainerNodeTypes); only clause nodes hanging off non-container parents need listing.\nconst rubyNcssNodes = ['elsif', 'else', 'when', 'in_clause', 'rescue', 'ensure'] as const;\nconst rubyNcssContainers = [\n 'program',\n 'body_statement',\n 'then',\n 'else',\n 'do',\n 'block_body',\n 'begin',\n 'ensure',\n] as const;\n\nconst cNcssNodes = [\n 'preproc_include',\n 'preproc_def',\n 'preproc_function_def',\n 'declaration',\n 'type_definition',\n 'field_declaration',\n 'function_definition',\n // Counted only when they carry a body (see bodylessNcssSpecifierTypes in ncss.ts).\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'case_statement',\n 'for_statement',\n 'while_statement',\n 'do_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'labeled_statement',\n] as const;\nconst cppNcssNodes = [\n ...cNcssNodes,\n 'class_specifier',\n 'namespace_definition',\n 'using_declaration',\n 'alias_declaration',\n 'namespace_alias_definition',\n 'concept_definition',\n 'static_assert_declaration',\n 'for_range_loop',\n 'catch_clause',\n 'throw_statement',\n 'co_return_statement',\n 'co_yield_statement',\n] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n ncssNodeTypes: pythonNcssNodes,\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goNestingNodes,\n ncssNodeTypes: goNcssNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n ncssNodeTypes: rustNcssNodes,\n // `else_clause` is a container so `else if` chains count the nested if_expression; a plain\n // `else { ... }` is unaffected because its only child is a `block`, itself a container.\n ncssContainerNodeTypes: ['block', 'else_clause'],\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaCyclomaticDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n ncssNodeTypes: javaNcssNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n ncssNodeTypes: rubyNcssNodes,\n ncssContainerNodeTypes: rubyNcssContainers,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n ncssNodeTypes: cNcssNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n ncssNodeTypes: cppNcssNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonNestingNodes,\n ncssNodeTypes: jsNcssNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"wSAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAI/F,EAAqB,CAAC,GAAG,EAAqB,gBAAgB,EAC9D,EAAiB,CAAC,GAAG,EAAiB,cAAc,EAEpD,EAAoB,CACxB,GAAG,EACH,0BACA,iCACF,EACM,EAAiB,CACrB,GAAG,EACH,mBACA,qBACA,8BAEA,6BACA,eACF,EACM,EAAoB,CACxB,GAAG,EACH,yBACA,+BACA,aACF,EAKM,EAA8B,CAAC,GAAG,EAAmB,iBAAiB,EAKtE,EAAoB,CAAC,SAAU,mBAAoB,SAAU,QAAS,UAAU,EAEhF,EAAiB,CAAC,QAAS,QAAQ,EACnC,EAAoB,CACxB,KACA,QACA,SACA,QACA,QACA,MACA,OACA,YACA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