code-gauge 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scan.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"scan.cjs","names":["os","path","stat","realpath","lstat","readFile","readdir","measureCode","NativeAddonError","measureCodeWithCrossFileDataAsync","measureCrossFileDuplication","detectLanguage"],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n /**\n * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function 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). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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 {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files: [], errors: [fatalError], warnings: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats?.isSymbolicLink()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = formatError(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${formatError(error)}` });\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n recordError(context, target, error);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\n */\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${formatError(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: formatError(error) };\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): 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\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, 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)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n return detectLanguage(file);\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"sTAyCA,MAAM,kBAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eAEA,MACA,SACA,gBACA,SACA,MACF,CAAC,EAEK,kBAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAwB,2BAE9B,SAAgB,EAAc,EAAwB,CASpD,OARI,IAAW,IACNA,EAAAA,QAAG,QAAQ,EAGhB,EAAO,WAAW,IAAI,EACjBC,EAAAA,QAAK,KAAKD,EAAAA,QAAG,QAAQ,EAAG,EAAO,MAAM,CAAC,CAAC,EAGzCC,EAAAA,QAAK,QAAQ,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,CAC3E,GAAI,CAEF,OAAO,MAAA,EADkBC,EAAAA,KAAAA,CAAK,CAAM,EAAA,CAClB,YAAY,EAAI,EAASD,EAAAA,QAAK,QAAQ,CAAM,CAChE,MAAQ,CACN,OAAOA,EAAAA,QAAK,QAAQ,CAAM,CAC5B,CACF,CAyCA,MAAM,EAA0BD,EAAAA,QAAG,qBAAqB,EAAI,EAE5D,eAAsB,EAAW,EAAgB,EAA2C,CAC1F,IAAI,EAAkB,EACtB,GAAI,CACF,EAAkB,MAAA,EAAMG,EAAAA,SAAAA,CAAS,CAAM,CACzC,MAAQ,CAER,CAEA,IAAM,EAAsBF,EAAAA,QAAK,QAAQ,CAAe,EACpD,EAEJ,GAAI,CACF,EAAa,MAAA,EAAMC,EAAAA,KAAAA,CAAK,CAAe,CACzC,OAAS,EAAO,CACd,IAAM,EAAa,GAAG,EAAW,EAAiB,CAAmB,EAAE,IAAI,EAAY,CAAK,IAC5F,MAAO,CACL,YAAa,EACb,MAAO,CAAC,EACR,OAAQ,CAAC,CAAU,EACnB,SAAU,CAAC,EACX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Code","NativeAddonError","measureCodeWithCrossFileDataAsync","measureCrossFileDuplication","detectLanguage"],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n /**\n * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function 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). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files: [], errors: [fatalError], warnings: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats?.isSymbolicLink()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n recordError(context, target, error);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\n */\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(error) };\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): 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\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, 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)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n return detectLanguage(file);\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n"],"mappings":"2VA0CA,MAAM,kBAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,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AK,KAAK,GAAK,CAACA,EAAAA,QAAK,WAAW,CAAQ,CACpH,CASA,SAAgB,EAAc,EAAsB,EAAsB,EAAiB,GAAgB,CACzG,GAAI,EACF,OAAO,EAAY,EAAc,EAAS,EAAI,IAAM,IAAA,GAEtD,IAAM,EAAW,EAAa,MAAM,GAAG,EACvC,IAAK,IAAM,KAAW,EAAS,MAAM,EAAG,EAAE,EACxC,GAAI,EAAsB,IAAI,CAAO,GAAM,CAAC,EAAQ,cAAgB,EAAmB,IAAI,CAAO,EAChG,MAAO,GAGX,OAAO,EAAY,EAAc,CAAO,IAAM,IAAA,EAChD,CAEA,SAAgB,EAAY,EAAc,EAAsB,EAAiB,GAAiC,CAChH,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAK9F,OAAOW,EAAAA,eAAe,CAAI,CAC5B,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAOX,EAAAA,QAAK,SAAS,EAAM,CAAI,GAAKA,EAAAA,QAAK,SAAS,CAAI,CACxD,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B"}
package/dist/scan.d.ts CHANGED
@@ -72,4 +72,3 @@ export declare function getLanguage(file: string, options: ScanOptions, explicit
72
72
  export declare function formatPath(file: string, base: string): string;
73
73
  export declare function writeStdout(message: string): void;
74
74
  export declare function writeStderr(message: string): void;
75
- export declare function formatError(error: unknown): string;
package/dist/scan.js CHANGED
@@ -1,2 +1,2 @@
1
- import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{detectLanguage as t}from"./languages.js";import{NativeAddonError as n}from"./nativeMetrics.js";import{measureCode as r,measureCodeWithCrossFileDataAsync as i}from"./metrics.js";import{lstat as a,readFile as o,readdir as s,realpath as c,stat as l}from"node:fs/promises";import u from"node:path";import d from"node:os";const f=/* @__PURE__ */ new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`obj`,`target`,`test-fixtures`,`vendor`,`venv`]),p=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),m=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,h=/Tests?\.(?:java|kt|cs)$/u;function g(e){return e===`~`?d.homedir():e.startsWith(`~/`)?u.join(d.homedir(),e.slice(2)):u.resolve(e)}async function _(e){try{return(await l(e)).isDirectory()?e:u.dirname(e)}catch{return u.dirname(e)}}const v=d.availableParallelism()*2;async function y(e,t){let n=e;try{n=await c(e)}catch{}let r=u.dirname(n),i;try{i=await l(n)}catch(e){let t=`${B(n,r)}: ${U(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=u.dirname(n),r=z(n,t,!0);if(!r){let t=`${B(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=w(t,e);return await j(n,r,`single-file`,i,n),C(i,e)}let a=w(t,n);return await O(n,a),await x(a),C(a,n)}async function b(e,t,n,r=/* @__PURE__ */ new Set){let i=w(n,e);for(let o of t){let t=u.join(e,o),s=R(o,n,r.has(t))?z(o,n,r.has(t)):void 0;s&&((await a(t).catch(()=>{}))?.isSymbolicLink()||i.candidates.push({file:t,language:s}))}return await x(i),C(i,e)}async function x(e){let t=await e.options.loadExclusion?.(e.candidates.flatMap(({file:e,realFile:t})=>t===void 0?[e]:[e,t]));e.exclusion=t;let n=/* @__PURE__ */ new Map;for(let t of e.candidates){let r;try{r=t.realFile??await c(t.file)}catch(n){T(e,t.file,n);continue}n.set(r,[...n.get(r)??[],t])}for(let[r,i]of n){if(e.fatalSeen)return;let n=await S(r,i,t);n!==void 0&&await j(n.file,n.language,`directory`,e,r)}}async function S(e,t,n){if(n===void 0)return t[0];if(n.isExcludedPath(e))return;let r=t.filter(({file:e})=>!n.isExcludedPath(e)),i=r.find(({file:t})=>t===e);if(i!==void 0||r.length<=1)return i??r[0];let a=await o(e,`utf8`).catch(()=>{});return r.find(({file:e})=>a!==void 0&&!n.isGeneratedCode(e,a))??r[0]}async function C(e,t){let n=[],r=[],i=[],a=[];for(let o of e.outcomes){let e=await o;if(`fatal`in e){let o=U(e.fatal);return{displayRoot:t,files:n,errors:[...r,o],warnings:i,generatedFiles:a,fatalError:o}}if(`generatedFile`in e){a.push(e.generatedFile);continue}if(`error`in e){r.push(e.error);continue}n.push(e.file),e.warning!==void 0&&i.push(e.warning)}return{displayRoot:t,files:n,errors:r,warnings:i,generatedFiles:a}}function w(e,t){return{options:e,outcomes:[],inFlight:/* @__PURE__ */ new Set,fatalSeen:!1,visitedDirectories:/* @__PURE__ */ new Set,visitedFiles:/* @__PURE__ */ new Set,rootDirectory:t,candidates:[]}}function T(e,t,n){e.outcomes.push({error:`${B(t,e.rootDirectory)}: ${U(n)}`})}async function E(e,t,n){try{return await e()}catch(e){T(n,t,e);return}}async function D(e,t){let n=await E(()=>c(e),e,t);return n!==void 0&&L(n,t.rootDirectory)?n:void 0}async function O(e,t){let n=await D(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await E(()=>s(e,{withFileTypes:!0}),e,t);if(r!==void 0){r.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let i of r){let r=u.join(e,i.name);if(i.isSymbolicLink()){await k(i.name,r,t);continue}if(i.isDirectory()){if(I(i.name,t.options))continue;await O(r,t);continue}i.isFile()&&A(r,t,r,n===e?void 0:u.join(n,i.name))}}}async function k(e,t,n){let r=await D(t,n);if(r===void 0)return;let i=await E(()=>l(t),t,n);if(i!==void 0){if(i.isDirectory()){if(I(e,n.options)||I(u.basename(r),n.options))return;await O(t,n);return}i.isFile()&&A(t,n,r,r)}}function A(e,t,n=e,r){let i=z(n,t.options);i&&t.candidates.push({file:e,language:i,realFile:r})}async function j(e,t,n,r,i){if(r.fatalSeen)return;let a;try{a=i??await c(e)}catch(t){T(r,e,t);return}if(r.visitedFiles.has(a))return;for(r.visitedFiles.add(a);r.inFlight.size>=v;)await Promise.race(r.inFlight);let o=M(e,a,t,n,r);r.inFlight.add(o),o.then(()=>r.inFlight.delete(o)),r.outcomes.push(o)}async function M(e,t,i,a,s){try{let n=await o(e,`utf8`),c={language:i,duplication:s.options.duplication};if(a===`single-file`)return{file:{file:e,metrics:r(n,c)}};let l=s.exclusion;if(l&&(l.isGeneratedCode(e,n)||l.isGeneratedCode(t,n)))return{generatedFile:e};let{metrics:u,crossFileData:d,crossFileError:f}=await N(n,c);return{file:{file:e,metrics:u,duplicationCandidates:d},warning:f===void 0?void 0:`${B(e,s.rootDirectory)}: cross-file duplication candidates unavailable: ${f}`}}catch(t){return t instanceof n?(s.fatalSeen=!0,{fatal:t}):{error:`${B(e,s.rootDirectory)}: ${U(t)}`}}}async function N(e,t){try{return await i(e,t)}catch(i){if(i instanceof n)throw i;return{metrics:r(e,t),crossFileError:U(i)}}}function P(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:B(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function F(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function I(e,t){return f.has(e)?!0:!t.includeTests&&p.has(e)}function L(e,t){let n=u.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${u.sep}`)&&!u.isAbsolute(n)}function R(e,t,n=!1){if(n)return z(e,t,!0)!==void 0;let r=e.split(`/`);for(let e of r.slice(0,-1))if(f.has(e)||!t.includeTests&&p.has(e))return!1;return z(e,t)!==void 0}function z(e,n,r=!1){let i=e.toLowerCase();if(!(!r&&(i.endsWith(`.d.ts`)||i.endsWith(`.d.mts`)||i.endsWith(`.d.cts`)||i.endsWith(`.min.js`)||i.endsWith(`.pnp.cjs`)))&&(r||n.includeTests||!m.test(u.basename(e))&&!h.test(u.basename(e))))return t(e)}function B(e,t){return u.relative(t,e)||u.basename(e)}function V(e){process.stdout.write(e)}function H(e){process.stderr.write(e)}function U(e){return e instanceof Error?e.message:String(e)}export{P as addCrossFileDuplication,F as collectDuplicatedLineNumbers,_ as configSearchDirectory,U as formatError,B as formatPath,z as getLanguage,R as isScannedPath,N as measureWithCrossFileData,g as resolveTarget,b as scanListedFiles,y as scanTarget,H as writeStderr,V as writeStdout};
1
+ import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{detectLanguage as t}from"./languages.js";import{NativeAddonError as n}from"./nativeMetrics.js";import{measureCode as r,measureCodeWithCrossFileDataAsync as i}from"./metrics.js";import{getErrorMessage as a}from"@willbooster/shared-lib";import{lstat as o,readFile as s,readdir as c,realpath as l,stat as u}from"node:fs/promises";import d from"node:path";import f from"node:os";const p=/* @__PURE__ */ new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`obj`,`target`,`test-fixtures`,`vendor`,`venv`]),m=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),h=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,g=/Tests?\.(?:java|kt|cs)$/u;function _(e){return e===`~`?f.homedir():e.startsWith(`~/`)?d.join(f.homedir(),e.slice(2)):d.resolve(e)}async function v(e){try{return(await u(e)).isDirectory()?e:d.dirname(e)}catch{return d.dirname(e)}}const y=f.availableParallelism()*2;async function b(e,t){let n=e;try{n=await l(e)}catch{}let r=d.dirname(n),i;try{i=await u(n)}catch(e){let t=`${V(n,r)}: ${a(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=d.dirname(n),r=B(n,t,!0);if(!r){let t=`${V(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=T(t,e);return await M(n,r,`single-file`,i,n),w(i,e)}let o=T(t,n);return await k(n,o),await S(o),w(o,n)}async function x(e,t,n,r=/* @__PURE__ */ new Set){let i=T(n,e);for(let a of t){let t=d.join(e,a),s=z(a,n,r.has(t))?B(a,n,r.has(t)):void 0;s&&((await o(t).catch(()=>{}))?.isSymbolicLink()||i.candidates.push({file:t,language:s}))}return await S(i),w(i,e)}async function S(e){let t=await e.options.loadExclusion?.(e.candidates.flatMap(({file:e,realFile:t})=>t===void 0?[e]:[e,t]));e.exclusion=t;let n=/* @__PURE__ */ new Map;for(let t of e.candidates){let r;try{r=t.realFile??await l(t.file)}catch(n){E(e,t.file,n);continue}n.set(r,[...n.get(r)??[],t])}for(let[r,i]of n){if(e.fatalSeen)return;let n=await C(r,i,t);n!==void 0&&await M(n.file,n.language,`directory`,e,r)}}async function C(e,t,n){if(n===void 0)return t[0];if(n.isExcludedPath(e))return;let r=t.filter(({file:e})=>!n.isExcludedPath(e)),i=r.find(({file:t})=>t===e);if(i!==void 0||r.length<=1)return i??r[0];let a=await s(e,`utf8`).catch(()=>{});return r.find(({file:e})=>a!==void 0&&!n.isGeneratedCode(e,a))??r[0]}async function w(e,t){let n=[],r=[],i=[],o=[];for(let s of e.outcomes){let e=await s;if(`fatal`in e){let s=a(e.fatal);return{displayRoot:t,files:n,errors:[...r,s],warnings:i,generatedFiles:o,fatalError:s}}if(`generatedFile`in e){o.push(e.generatedFile);continue}if(`error`in e){r.push(e.error);continue}n.push(e.file),e.warning!==void 0&&i.push(e.warning)}return{displayRoot:t,files:n,errors:r,warnings:i,generatedFiles:o}}function T(e,t){return{options:e,outcomes:[],inFlight:/* @__PURE__ */ new Set,fatalSeen:!1,visitedDirectories:/* @__PURE__ */ new Set,visitedFiles:/* @__PURE__ */ new Set,rootDirectory:t,candidates:[]}}function E(e,t,n){e.outcomes.push({error:`${V(t,e.rootDirectory)}: ${a(n)}`})}async function D(e,t,n){try{return await e()}catch(e){E(n,t,e);return}}async function O(e,t){let n=await D(()=>l(e),e,t);return n!==void 0&&R(n,t.rootDirectory)?n:void 0}async function k(e,t){let n=await O(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await D(()=>c(e,{withFileTypes:!0}),e,t);if(r!==void 0){r.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let i of r){let r=d.join(e,i.name);if(i.isSymbolicLink()){await A(i.name,r,t);continue}if(i.isDirectory()){if(L(i.name,t.options))continue;await k(r,t);continue}i.isFile()&&j(r,t,r,n===e?void 0:d.join(n,i.name))}}}async function A(e,t,n){let r=await O(t,n);if(r===void 0)return;let i=await D(()=>u(t),t,n);if(i!==void 0){if(i.isDirectory()){if(L(e,n.options)||L(d.basename(r),n.options))return;await k(t,n);return}i.isFile()&&j(t,n,r,r)}}function j(e,t,n=e,r){let i=B(n,t.options);i&&t.candidates.push({file:e,language:i,realFile:r})}async function M(e,t,n,r,i){if(r.fatalSeen)return;let a;try{a=i??await l(e)}catch(t){E(r,e,t);return}if(r.visitedFiles.has(a))return;for(r.visitedFiles.add(a);r.inFlight.size>=y;)await Promise.race(r.inFlight);let o=N(e,a,t,n,r);r.inFlight.add(o),o.then(()=>r.inFlight.delete(o)),r.outcomes.push(o)}async function N(e,t,i,o,c){try{let n=await s(e,`utf8`),a={language:i,duplication:c.options.duplication};if(o===`single-file`)return{file:{file:e,metrics:r(n,a)}};let l=c.exclusion;if(l&&(l.isGeneratedCode(e,n)||l.isGeneratedCode(t,n)))return{generatedFile:e};let{metrics:u,crossFileData:d,crossFileError:f}=await P(n,a);return{file:{file:e,metrics:u,duplicationCandidates:d},warning:f===void 0?void 0:`${V(e,c.rootDirectory)}: cross-file duplication candidates unavailable: ${f}`}}catch(t){return t instanceof n?(c.fatalSeen=!0,{fatal:t}):{error:`${V(e,c.rootDirectory)}: ${a(t)}`}}}async function P(e,t){try{return await i(e,t)}catch(i){if(i instanceof n)throw i;return{metrics:r(e,t),crossFileError:a(i)}}}function F(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:V(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function I(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function L(e,t){return p.has(e)?!0:!t.includeTests&&m.has(e)}function R(e,t){let n=d.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${d.sep}`)&&!d.isAbsolute(n)}function z(e,t,n=!1){if(n)return B(e,t,!0)!==void 0;let r=e.split(`/`);for(let e of r.slice(0,-1))if(p.has(e)||!t.includeTests&&m.has(e))return!1;return B(e,t)!==void 0}function B(e,n,r=!1){let i=e.toLowerCase();if(!(!r&&(i.endsWith(`.d.ts`)||i.endsWith(`.d.mts`)||i.endsWith(`.d.cts`)||i.endsWith(`.min.js`)||i.endsWith(`.pnp.cjs`)))&&(r||n.includeTests||!h.test(d.basename(e))&&!g.test(d.basename(e))))return t(e)}function V(e,t){return d.relative(t,e)||d.basename(e)}function H(e){process.stdout.write(e)}function U(e){process.stderr.write(e)}export{F as addCrossFileDuplication,I as collectDuplicatedLineNumbers,v as configSearchDirectory,V as formatPath,B as getLanguage,z as isScannedPath,P as measureWithCrossFileData,_ as resolveTarget,x as scanListedFiles,b as scanTarget,U as writeStderr,H as writeStdout};
2
2
  //# sourceMappingURL=scan.js.map
package/dist/scan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"scan.js","names":[],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n /**\n * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function 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). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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 {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files: [], errors: [fatalError], warnings: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats?.isSymbolicLink()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = formatError(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${formatError(error)}` });\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n recordError(context, target, error);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\n */\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${formatError(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: formatError(error) };\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): 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\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, 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)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n return detectLanguage(file);\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"m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sB,EAAiB,GAAiC,CAChH,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAK,EAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAK,EAAK,SAAS,CAAI,CAAC,GAK9F,OAAO,EAAe,CAAI,CAC5B,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAO,EAAK,SAAS,EAAM,CAAI,GAAK,EAAK,SAAS,CAAI,CACxD,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAwB,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"scan.js","names":[],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n /**\n * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function 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). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files: [], errors: [fatalError], warnings: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats?.isSymbolicLink()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n recordError(context, target, error);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\n */\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(error) };\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): 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\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, 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)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n return detectLanguage(file);\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n"],"mappings":"scA0CA,MAAM,kBAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eAEA,MACA,SACA,gBACA,SACA,MACF,CAAC,EAEK,kBAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAwB,2BAE9B,SAAgB,EAAc,EAAwB,CASpD,OARI,IAAW,IACN,EAAG,QAAQ,EAGhB,EAAO,WAAW,IAAI,EACjB,EAAK,KAAK,EAAG,QAAQ,EAAG,EAAO,MAAM,CAAC,CAAC,EAGzC,EAAK,QAAQ,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,CAC3E,GAAI,CAEF,OAAO,MADkB,EAAK,CAAM,EAAA,CAClB,YAAY,EAAI,EAAS,EAAK,QAAQ,CAAM,CAChE,MAAQ,CACN,OAAO,EAAK,QAAQ,CAAM,CAC5B,CACF,CAyCA,MAAM,EAA0B,EAAG,qBAAqB,EAAI,EAE5D,eAAsB,EAAW,EAAgB,EAA2C,CAC1F,IAAI,EAAkB,EACtB,GAAI,CACF,EAAkB,MAAM,EAAS,CA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EAAW,CAAS,EACnD,OAAO,IAAa,IAAO,IAAa,MAAQ,CAAC,EAAS,WAAW,KAAK,EAAK,KAAK,GAAK,CAAC,EAAK,WAAW,CAAQ,CACpH,CASA,SAAgB,EAAc,EAAsB,EAAsB,EAAiB,GAAgB,CACzG,GAAI,EACF,OAAO,EAAY,EAAc,EAAS,EAAI,IAAM,IAAA,GAEtD,IAAM,EAAW,EAAa,MAAM,GAAG,EACvC,IAAK,IAAM,KAAW,EAAS,MAAM,EAAG,EAAE,EACxC,GAAI,EAAsB,IAAI,CAAO,GAAM,CAAC,EAAQ,cAAgB,EAAmB,IAAI,CAAO,EAChG,MAAO,GAGX,OAAO,EAAY,EAAc,CAAO,IAAM,IAAA,EAChD,CAEA,SAAgB,EAAY,EAAc,EAAsB,EAAiB,GAAiC,CAChH,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAK,EAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAK,EAAK,SAAS,CAAI,CAAC,GAK9F,OAAO,EAAe,CAAI,CAC5B,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAO,EAAK,SAAS,EAAM,CAAI,GAAK,EAAK,SAAS,CAAI,CACxD,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B"}
package/native/Cargo.lock CHANGED
@@ -45,18 +45,18 @@ dependencies = [
45
45
  "rustc-hash",
46
46
  "serde",
47
47
  "serde_json",
48
- "tree-sitter",
49
- "tree-sitter-c",
50
- "tree-sitter-c-sharp",
51
- "tree-sitter-cpp",
52
48
  "tree-sitter-go",
53
49
  "tree-sitter-java",
54
- "tree-sitter-javascript",
55
50
  "tree-sitter-python",
56
51
  "tree-sitter-ruby",
57
- "tree-sitter-rust",
58
- "tree-sitter-typescript",
52
+ "willbooster-tree-sitter",
53
+ "willbooster-tree-sitter-c",
54
+ "willbooster-tree-sitter-c-sharp",
55
+ "willbooster-tree-sitter-cpp",
56
+ "willbooster-tree-sitter-javascript",
59
57
  "willbooster-tree-sitter-kotlin",
58
+ "willbooster-tree-sitter-rust",
59
+ "willbooster-tree-sitter-typescript",
60
60
  ]
61
61
 
62
62
  [[package]]
@@ -425,141 +425,141 @@ dependencies = [
425
425
  ]
426
426
 
427
427
  [[package]]
428
- name = "tree-sitter"
429
- version = "0.25.10"
428
+ name = "tree-sitter-go"
429
+ version = "0.25.0"
430
430
  source = "registry+https://github.com/rust-lang/crates.io-index"
431
- checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
431
+ checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea"
432
432
  dependencies = [
433
433
  "cc",
434
- "regex",
435
- "regex-syntax",
436
- "serde_json",
437
- "streaming-iterator",
438
434
  "tree-sitter-language",
439
435
  ]
440
436
 
441
437
  [[package]]
442
- name = "tree-sitter-c"
443
- version = "0.21.4"
438
+ name = "tree-sitter-java"
439
+ version = "0.23.5"
444
440
  source = "registry+https://github.com/rust-lang/crates.io-index"
445
- checksum = "f956d5351d62652864a4ff3ae861747e7a1940dc96c9998ae400ac0d3ce30427"
441
+ checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"
446
442
  dependencies = [
447
443
  "cc",
448
- "tree-sitter",
444
+ "tree-sitter-language",
449
445
  ]
450
446
 
451
447
  [[package]]
452
- name = "tree-sitter-c-sharp"
453
- version = "0.21.3"
448
+ name = "tree-sitter-language"
449
+ version = "0.1.8"
454
450
  source = "registry+https://github.com/rust-lang/crates.io-index"
455
- checksum = "8997ad04502208449025114e434c9024a33a74e700513c702a9d2cac6522a771"
456
- dependencies = [
457
- "cc",
458
- "tree-sitter",
459
- ]
451
+ checksum = "ca0d1bf6fdd806e43ae5198f82f527056d359def39e54e67a0f478ac09dac081"
460
452
 
461
453
  [[package]]
462
- name = "tree-sitter-cpp"
463
- version = "0.22.3"
454
+ name = "tree-sitter-python"
455
+ version = "0.25.0"
464
456
  source = "registry+https://github.com/rust-lang/crates.io-index"
465
- checksum = "1d509a22a992790d38f2c291961ff8a1ff016c437c7ec6befc9220b8eec8918c"
457
+ checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c"
466
458
  dependencies = [
467
459
  "cc",
468
- "tree-sitter",
460
+ "tree-sitter-language",
469
461
  ]
470
462
 
471
463
  [[package]]
472
- name = "tree-sitter-go"
473
- version = "0.21.2"
464
+ name = "tree-sitter-ruby"
465
+ version = "0.23.1"
474
466
  source = "registry+https://github.com/rust-lang/crates.io-index"
475
- checksum = "b8d702a98d3c7e70e466456e58ff2b1ac550bf1e29b97e5770676d2fdabec00d"
467
+ checksum = "be0484ea4ef6bb9c575b4fdabde7e31340a8d2dbc7d52b321ac83da703249f95"
476
468
  dependencies = [
477
469
  "cc",
478
- "tree-sitter",
470
+ "tree-sitter-language",
479
471
  ]
480
472
 
481
473
  [[package]]
482
- name = "tree-sitter-java"
483
- version = "0.21.0"
474
+ name = "unicode-ident"
475
+ version = "1.0.24"
484
476
  source = "registry+https://github.com/rust-lang/crates.io-index"
485
- checksum = "33bc21adf831a773c075d9d00107ab43965e6a6ea7607b47fd9ec6f3db4b481b"
486
- dependencies = [
487
- "cc",
488
- "tree-sitter",
489
- ]
477
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
490
478
 
491
479
  [[package]]
492
- name = "tree-sitter-javascript"
493
- version = "0.25.0"
480
+ name = "unicode-segmentation"
481
+ version = "1.13.3"
494
482
  source = "registry+https://github.com/rust-lang/crates.io-index"
495
- checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5"
483
+ checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
484
+
485
+ [[package]]
486
+ name = "willbooster-tree-sitter"
487
+ version = "1.0.5"
488
+ source = "registry+https://github.com/rust-lang/crates.io-index"
489
+ checksum = "7c6ca3007235ade028b793d6090a5ea16618ea3ab9b53427d1f782b15bf64064"
496
490
  dependencies = [
497
491
  "cc",
492
+ "regex",
493
+ "serde_json",
494
+ "streaming-iterator",
498
495
  "tree-sitter-language",
499
496
  ]
500
497
 
501
498
  [[package]]
502
- name = "tree-sitter-language"
503
- version = "0.1.8"
499
+ name = "willbooster-tree-sitter-c"
500
+ version = "1.1.0"
504
501
  source = "registry+https://github.com/rust-lang/crates.io-index"
505
- checksum = "ca0d1bf6fdd806e43ae5198f82f527056d359def39e54e67a0f478ac09dac081"
502
+ checksum = "5cee6f1a4e0f64f337d28aeaed73879d7e8a87d77c287afb989ce29adea54700"
503
+ dependencies = [
504
+ "cc",
505
+ "tree-sitter-language",
506
+ ]
506
507
 
507
508
  [[package]]
508
- name = "tree-sitter-python"
509
- version = "0.21.0"
509
+ name = "willbooster-tree-sitter-c-sharp"
510
+ version = "1.0.3"
510
511
  source = "registry+https://github.com/rust-lang/crates.io-index"
511
- checksum = "b4066c6cf678f962f8c2c4561f205945c84834cce73d981e71392624fdc390a9"
512
+ checksum = "99b224dcd59cda9b24b588557cca3827abaccaf10da72d125c31e7cdb2e6f7fb"
512
513
  dependencies = [
513
514
  "cc",
514
- "tree-sitter",
515
+ "tree-sitter-language",
515
516
  ]
516
517
 
517
518
  [[package]]
518
- name = "tree-sitter-ruby"
519
- version = "0.21.0"
519
+ name = "willbooster-tree-sitter-cpp"
520
+ version = "1.1.1"
520
521
  source = "registry+https://github.com/rust-lang/crates.io-index"
521
- checksum = "c0031f687c0772f2dad7b77104c43428611099a1804c81244ada21560f41f0b1"
522
+ checksum = "72b92a9fcb0dc27bd4af18e06fe6c085dd14d91f009f60ecd92c0308b9cbd068"
522
523
  dependencies = [
523
524
  "cc",
524
- "tree-sitter",
525
+ "tree-sitter-language",
525
526
  ]
526
527
 
527
528
  [[package]]
528
- name = "tree-sitter-rust"
529
- version = "0.21.2"
529
+ name = "willbooster-tree-sitter-javascript"
530
+ version = "1.0.3"
530
531
  source = "registry+https://github.com/rust-lang/crates.io-index"
531
- checksum = "277690f420bf90741dea984f3da038ace46c4fe6047cba57a66822226cde1c93"
532
+ checksum = "e6c40d41b303b525194daa503a71ec94d8269fe8d1648b2d9138fe902623beff"
532
533
  dependencies = [
533
534
  "cc",
534
- "tree-sitter",
535
+ "tree-sitter-language",
535
536
  ]
536
537
 
537
538
  [[package]]
538
- name = "tree-sitter-typescript"
539
- version = "0.21.2"
539
+ name = "willbooster-tree-sitter-kotlin"
540
+ version = "1.4.0"
540
541
  source = "registry+https://github.com/rust-lang/crates.io-index"
541
- checksum = "ecb35d98a688378e56c18c9c159824fd16f730ccbea19aacf4f206e5d5438ed9"
542
+ checksum = "529ae914939b559754e6dd8b34d2705f04d6dcb73f09cb52f024b49eda9b5b88"
542
543
  dependencies = [
543
544
  "cc",
544
- "tree-sitter",
545
+ "tree-sitter-language",
545
546
  ]
546
547
 
547
548
  [[package]]
548
- name = "unicode-ident"
549
- version = "1.0.24"
549
+ name = "willbooster-tree-sitter-rust"
550
+ version = "1.1.1"
550
551
  source = "registry+https://github.com/rust-lang/crates.io-index"
551
- checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
552
+ checksum = "324c9f18cfc29e4da7335ad8cb76beb6ac1ae91a8037a44724bc55fce04f26f7"
553
+ dependencies = [
554
+ "cc",
555
+ "tree-sitter-language",
556
+ ]
552
557
 
553
558
  [[package]]
554
- name = "unicode-segmentation"
555
- version = "1.13.3"
559
+ name = "willbooster-tree-sitter-typescript"
560
+ version = "1.1.1"
556
561
  source = "registry+https://github.com/rust-lang/crates.io-index"
557
- checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
558
-
559
- [[package]]
560
- name = "willbooster-tree-sitter-kotlin"
561
- version = "0.0.0"
562
- source = "git+https://github.com/WillBooster/tree-sitter-kotlin?tag=v1.1.0#a05912e6f07e2cedd44bfb117940361089d4c3e3"
562
+ checksum = "f8c51b6c9e10d6ae34c2f84c4d44fff79a0210890ede63fda558a6a0f042eb28"
563
563
  dependencies = [
564
564
  "cc",
565
565
  "tree-sitter-language",