code-gauge 2.0.0 → 3.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.
Files changed (74) hide show
  1. package/README.md +156 -106
  2. package/dist/cli.cjs +3 -3
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +3 -3
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cliConfig.cjs +1 -1
  7. package/dist/cliConfig.cjs.map +1 -1
  8. package/dist/cliConfig.d.ts +27 -84
  9. package/dist/cliConfig.js +1 -1
  10. package/dist/cliConfig.js.map +1 -1
  11. package/dist/crossFileDuplication.cjs +1 -1
  12. package/dist/crossFileDuplication.cjs.map +1 -1
  13. package/dist/crossFileDuplication.d.ts +9 -0
  14. package/dist/crossFileDuplication.js +1 -1
  15. package/dist/crossFileDuplication.js.map +1 -1
  16. package/dist/depDegree.cjs +2 -0
  17. package/dist/depDegree.cjs.map +1 -0
  18. package/dist/depDegree.d.ts +12 -0
  19. package/dist/depDegree.js +2 -0
  20. package/dist/depDegree.js.map +1 -0
  21. package/dist/diffCommand.cjs +5 -0
  22. package/dist/diffCommand.cjs.map +1 -0
  23. package/dist/diffCommand.d.ts +17 -0
  24. package/dist/diffCommand.js +5 -0
  25. package/dist/diffCommand.js.map +1 -0
  26. package/dist/duplication.cjs +1 -1
  27. package/dist/duplication.cjs.map +1 -1
  28. package/dist/duplication.d.ts +23 -2
  29. package/dist/duplication.js +1 -1
  30. package/dist/duplication.js.map +1 -1
  31. package/dist/git.cjs +2 -0
  32. package/dist/git.cjs.map +1 -0
  33. package/dist/git.d.ts +27 -0
  34. package/dist/git.js +2 -0
  35. package/dist/git.js.map +1 -0
  36. package/dist/index.cjs +1 -1
  37. package/dist/index.d.ts +4 -2
  38. package/dist/index.js +1 -1
  39. package/dist/languages.cjs +1 -1
  40. package/dist/languages.cjs.map +1 -1
  41. package/dist/languages.js +1 -1
  42. package/dist/languages.js.map +1 -1
  43. package/dist/metrics.cjs +1 -2
  44. package/dist/metrics.cjs.map +1 -1
  45. package/dist/metrics.d.ts +11 -0
  46. package/dist/metrics.js +1 -2
  47. package/dist/metrics.js.map +1 -1
  48. package/dist/nativeMetrics.cjs +1 -1
  49. package/dist/nativeMetrics.cjs.map +1 -1
  50. package/dist/nativeMetrics.d.ts +7 -3
  51. package/dist/nativeMetrics.js +1 -1
  52. package/dist/nativeMetrics.js.map +1 -1
  53. package/dist/regressionGate.cjs +2 -0
  54. package/dist/regressionGate.cjs.map +1 -0
  55. package/dist/regressionGate.d.ts +106 -0
  56. package/dist/regressionGate.js +2 -0
  57. package/dist/regressionGate.js.map +1 -0
  58. package/dist/scan.cjs +2 -0
  59. package/dist/scan.cjs.map +1 -0
  60. package/dist/scan.d.ts +55 -0
  61. package/dist/scan.js +2 -0
  62. package/dist/scan.js.map +1 -0
  63. package/dist/types.d.ts +24 -76
  64. package/package.json +7 -5
  65. package/dist/architectureMetrics.cjs +0 -2
  66. package/dist/architectureMetrics.cjs.map +0 -1
  67. package/dist/architectureMetrics.d.ts +0 -41
  68. package/dist/architectureMetrics.js +0 -2
  69. package/dist/architectureMetrics.js.map +0 -1
  70. package/dist/typescriptProject.cjs +0 -3
  71. package/dist/typescriptProject.cjs.map +0 -1
  72. package/dist/typescriptProject.d.ts +0 -24
  73. package/dist/typescriptProject.js +0 -3
  74. package/dist/typescriptProject.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{collectCrossFileDuplicationFileData as t,measureCode as n}from"./metrics.js";import{measureArchitecture as r}from"./architectureMetrics.js";import{configFileName as i,loadConfig as a,resolveOptions as o,resolveThresholds as s}from"./cliConfig.js";import{measureTypeScriptProject as c}from"./typescriptProject.js";import{readFile as l,readdir as u,realpath as d,stat as f}from"node:fs/promises";import p from"node:os";import m from"node:path";import{Command as h,InvalidArgumentError as g}from"commander";const _=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),v=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`target`,`test-fixtures`,`vendor`,`venv`]),y=new Set([`__tests__`,`test`,`tests`,`spec`]),ee=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,te=/Test\.java$/u;ne().catch(e=>{Q(`Error: ${$(e)}\n`),process.exitCode=1});async function ne(){let e=new h().name(`code-gauge`).description(`Measure code metrics and list high-risk findings.`).argument(`[target]`,`file or directory to measure`,`.`).option(`--config <path>`,`config file to use instead of the auto-detected ${i}`).option(`--file-loc-threshold <number>`,`minimum file code LOC to report`,Y).option(`--function-loc-threshold <number>`,`minimum function physical LOC span to report`,Y).option(`--component-loc-threshold <number>`,`minimum React component physical LOC span to report`,Y).option(`--cognitive-threshold <number>`,`minimum cognitive complexity to report`,Y).option(`--cyclomatic-threshold <number>`,`minimum cyclomatic complexity to report`,Y).option(`--call-threshold <number>`,`minimum function call count to report`,Y).option(`--import-threshold <number>`,`minimum unique import sources per file to report`,Y).option(`--fan-out-threshold <number>`,`minimum intra-file fan-out per function to report`,Y).option(`--parameter-threshold <number>`,`minimum function parameter count to report`,Y).option(`--duplicate-block-threshold <number>`,`minimum count of duplicated code blocks per file to report`,Y).option(`--duplication-ratio-percent-threshold <number>`,`minimum percentage (1-100) of duplicated lines per file to report`,J).option(`--cross-file-duplicate-block-threshold <number>`,`minimum count of cross-file duplicate block groups per file to report`,Y).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,Y).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,he).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,J).option(`--transitive-dependency-threshold <number>`,`minimum transitively reachable local files to report`,Y).option(`--structural-breadth-threshold <number>`,`minimum structural breadth score to report`,Y).option(`--structural-coordination-threshold <number>`,`minimum structural coordination score to report`,Y).option(`--state-mutation-threshold <number>`,`minimum state mutation score to report`,Y).option(`--duplicate-symbol-group-threshold <number>`,`minimum duplicate symbol group count to report`,Y).option(`--max-findings <number>`,`maximum number of risk findings to print`,Y).option(`--largest-files <number>`,`number of largest files by code LOC to list`,Y).option(`--include-tests`,`include test files and test directories`).option(`--tsconfig <path>`,`TypeScript project file to use instead of auto-detected tsconfig.json`).option(`--json`,`print JSON output`).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`).option(`--fail-on-risk`,`exit with code 1 when high-risk findings are found`);e.action(async(e,t)=>{let n=b(e),r=await a(t.config,await re(n)),i=o(t,r),s=await ie(n,i);A(s,i),await T(s),await ae(s,i,n);let c=oe(s.files,s.architecture,s.crossFileDuplication,s.componentFunctionKeys,s.namedComponentFunctionKeys,i,s.displayRoot);i.json?R(s,c,i):z(n,s,c,i),(s.fatalError||i.failOnError&&s.errors.length>0||i.failOnRisk&&c.length>0)&&(process.exitCode=1)}),await e.parseAsync()}function b(e){return e===`~`?p.homedir():e.startsWith(`~/`)?m.join(p.homedir(),e.slice(2)):m.resolve(e)}async function re(e){try{return(await f(e)).isDirectory()?e:m.dirname(e)}catch{return m.dirname(e)}}async function ie(e,t){let n=[],r=[],i=[],a=e;try{a=await d(e)}catch{}let o=m.dirname(a),s;try{s=await f(a)}catch(e){let t=`${X(a,o)}: ${$(e)}`;return{displayRoot:o,files:n,errors:[t],warnings:i,fatalError:t}}if(s.isFile()){let e=m.dirname(a),o=q(a,t,!0);if(!o){let t=`${X(a,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:i,fatalError:t}}let s=x(t,n,r,i,e);return await k(a,o,`single-file`,s,a),{displayRoot:e,files:n,errors:r,warnings:i}}return await E(a,x(t,n,r,i,a)),{displayRoot:a,files:n,errors:r,warnings:i}}function x(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function ae(e,t,n){if(e.fatalError||e.files.length===0)return;let r=t.tsconfig,i=r!==void 0;if(!i&&!e.files.some(({file:e})=>S(e)))return;let a=r?b(r):await C(n);if(a)try{e.typeScriptProject=await c(a,e.files.map(({file:e})=>e)),e.componentFunctionKeys=new Set(e.typeScriptProject.reactComponentFunctions.map(e=>P(e.file,e.startLine,e.startColumn))),e.namedComponentFunctionKeys=new Set(e.typeScriptProject.reactComponentFunctions.flatMap(e=>e.name?[F(e.file,e.name,e.startLine)]:[]))}catch(t){i&&e.errors.push(`${X(a,e.displayRoot)}: ${$(t)}`)}}function S(e){return[`.cjs`,`.cts`,`.js`,`.jsx`,`.mjs`,`.mts`,`.ts`,`.tsx`].includes(m.extname(e))}async function C(e){let t=(await f(e)).isDirectory()?e:m.dirname(e);for(;;){let e=m.join(t,`tsconfig.json`);if(await w(e))return e;let n=m.dirname(t);if(n===t)return;t=n}}async function w(e){try{return(await f(e)).isFile()}catch{return!1}}async function T(e){if(!e.fatalError)try{e.architecture=r(e.files.map(({file:e,metrics:t})=>({file:e,metrics:t})),e.displayRoot)}catch(t){e.errors.push(`architecture metrics: ${$(t)}`)}}async function E(e,t){let n;try{n=await d(e)}catch(n){t.errors.push(`${X(e,t.rootDirectory)}: ${$(n)}`);return}if(!K(n,t.rootDirectory)||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r;try{r=await u(e,{withFileTypes:!0})}catch(n){t.errors.push(`${X(e,t.rootDirectory)}: ${$(n)}`);return}for(let n of r){let r=m.join(e,n.name);if(n.isSymbolicLink()){await D(n.name,r,t);continue}if(n.isDirectory()){if(G(n.name,t.options))continue;await E(r,t);continue}n.isFile()&&await O(r,t)}}async function D(e,t,n){let r;try{r=await d(t)}catch(e){n.errors.push(`${X(t,n.rootDirectory)}: ${$(e)}`);return}if(!K(r,n.rootDirectory))return;let i;try{i=await f(t)}catch(e){n.errors.push(`${X(t,n.rootDirectory)}: ${$(e)}`);return}if(i.isDirectory()){if(G(e,n.options)||G(m.basename(r),n.options))return;await E(t,n);return}i.isFile()&&await O(t,n,r,r)}async function O(e,t,n=e,r){let i=q(n,t.options);i&&await k(e,i,`directory`,t,r)}async function k(e,r,i,a,o){try{let s=o??await d(e);if(a.visitedFiles.has(s))return;a.visitedFiles.add(s);let c=await l(e,`utf8`),u={language:r,duplication:a.options.duplication},f={file:e,metrics:n(c,u)};if(i===`directory`)try{f.duplicationCandidates=t(c,u)}catch(t){a.warnings.push(`${X(e,a.rootDirectory)}: cross-file duplication candidates unavailable: ${$(t)}`)}a.files.push(f)}catch(t){a.errors.push(`${X(e,a.rootDirectory)}: ${$(t)}`)}}function A(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:X(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function oe(e,t,n,r,i,a,o){let c=new Map(t?.files.map(e=>[e.file,e])),l=e.flatMap(({file:e,metrics:t})=>{let l=t.functions.some(t=>t.returnsJsx||M(e,t,r,i)),u=s(a,t.language,l);return[...se(e,t,c.get(X(e,o)),n,u,o),...t.functions.flatMap(n=>ce(e,t.language,n,u,o,r,i))]});return l.sort(L),l}function se(e,t,n,r,i,a){let o=[],s=X(e,a);j(o,`file LOC`,t.lines.code,i.fileLoc),j(o,`import sources`,t.coupling.importSourceCount,i.import);let c=ue(t.duplication.duplicateBlockGroups);return j(o,`duplicated blocks`,t.duplication.duplicateBlockCount,i.duplicateBlock,c),j(o,`duplicated lines (%)`,Math.floor(t.duplication.duplicationRatio*100),i.duplicationRatioPercent,c),r&&j(o,`cross-file duplicated blocks`,Object.hasOwn(r.duplicateBlockGroupCountByFile,s)?r.duplicateBlockGroupCountByFile[s]??0:0,i.crossFileDuplicateBlock,le(r,s)),n&&((t.lines.code>=100||n.directLocalDependencyCount>=8)&&j(o,`transitive local dependencies`,n.transitiveLocalDependencyCount,i.transitiveDependency),(o.length>0||n.directLocalDependencyCount>=8||n.structuralCoordination.score>=i.structuralCoordination)&&j(o,`structural breadth`,n.structuralBreadthScore,i.structuralBreadth),j(o,`structural coordination`,n.structuralCoordination.score,i.structuralCoordination),j(o,`state mutation`,n.structuralCoordination.stateMutationScore,i.stateMutation),j(o,`duplicate symbol groups`,n.duplicateSymbolGroupCount,i.duplicateSymbolGroup)),o.length===0?[]:[{file:s,language:t.language,kind:`file`,cyclomaticComplexity:t.cyclomaticComplexity,cognitiveComplexity:t.cognitiveComplexity,triggers:o,score:I(o)}]}function ce(e,t,n,r,i,a,o){let s=n.endLine-n.startLine+1,c=M(e,n,a,o),l=c?`component`:`function`,u=[];return j(u,`cognitive complexity`,n.cognitiveComplexity,r.cognitive),j(u,`cyclomatic complexity`,n.cyclomaticComplexity,r.cyclomatic),j(u,c?`component LOC`:`function LOC`,s,N(c,r)),j(u,`function calls`,n.callCount,r.call),j(u,`fan-out`,n.fanOut,r.fanOut),j(u,`parameters`,n.parameterCount,r.parameter),u.length===0?[]:[{file:X(e,i),language:t,kind:l,name:n.name??`<anonymous>`,startLine:n.startLine,endLine:n.endLine,cyclomaticComplexity:n.cyclomaticComplexity,cognitiveComplexity:n.cognitiveComplexity,triggers:u,score:I(u)}]}function j(e,t,n,r,i){n<r||e.push({metric:t,value:n,threshold:r,score:n/r,detail:i})}function le(e,t){let n=e.groups.filter(e=>e.files.includes(t));if(n.length!==0)return`${n.slice(0,3).map(e=>e.occurrences.map(({file:e,startLine:n,endLine:r})=>e===t?`${n}-${r}`:`${e}:${n}-${r}`).join(` ~ `)).join(`; `)}${n.length>3?`; ...`:``}`}function ue(e){if(e.length!==0)return e.map(e=>e.map(({startLine:e,endLine:t})=>`${e}-${t}`).join(` ~ `)).join(`; `)}function M(e,t,n,r){return n?.has(P(e,t.startLine,t.startColumn))||(t.name?r?.has(F(e,t.name,t.startLine)):!1)||!1}function N(e,t){return e?t.componentLoc:t.functionLoc}function P(e,t,n){return`${m.resolve(e)}:${t}:${n}`}function F(e,t,n){return`${m.resolve(e)}:${t}:${n}`}function I(e){return Math.max(...e.map(e=>e.score))}function L(e,t){return t.score-e.score||e.file.localeCompare(t.file)||(e.startLine??0)-(t.startLine??0)||(e.endLine??0)-(t.endLine??0)||e.kind.localeCompare(t.kind)}function R(e,t,n){let r=W(e.files),i=t.slice(0,n.maxFindings);Z(JSON.stringify({summary:r,thresholds:n.thresholds,profileThresholds:n.profileThresholds,totalRisks:t.length,truncated:i.length<t.length,largestFiles:n.largestFiles>0?B(e.files,n.largestFiles,e.displayRoot):void 0,architecture:e.architecture,crossFileDuplication:e.crossFileDuplication,typeScriptProject:e.typeScriptProject,risks:i,errors:e.errors,warnings:e.warnings},void 0,2)+`
3
- `)}function z(e,t,n,r){if(t.fatalError){Q(`Error: ${t.fatalError}\n`);return}let{thresholds:i}=r,a=W(t.files);Z(`Measured ${a.fileCount} files under ${e}\n`),Z(`LOC ${a.linesOfCode}, NCSS ${a.ncssCount}, functions ${a.functionCount}, max cyclomatic ${a.maxCyclomaticComplexity}, max cognitive ${a.maxCognitiveComplexity}\n`),Z(`Calls ${a.callCount}, internal edges ${a.internalEdgeCount}, max call depth ${a.maxCallDepth}, imports ${a.importSourceCount}, exports ${a.exportCount}\n`),Z(`Type annotations ${a.typeAnnotationCount}, type aliases ${a.typeAliasCount}, interfaces ${a.interfaceCount}, avg cohesion ${a.averageFunctionIdentifierOverlap.toFixed(2)}\n`),t.architecture&&Z(`${pe(t.architecture)}\n`),t.typeScriptProject&&Z(`${me(t.typeScriptProject)}\n`),Z(`Risk thresholds: file LOC >= ${i.fileLoc}, function LOC >= ${i.functionLoc}, component LOC >= ${i.componentLoc}, cognitive >= ${i.cognitive}, cyclomatic >= ${i.cyclomatic}, calls >= ${i.call}, imports >= ${i.import}, fan-out >= ${i.fanOut}, parameters >= ${i.parameter}, duplicated blocks >= ${i.duplicateBlock}, duplicated lines (%) >= ${i.duplicationRatioPercent}, cross-file duplicated blocks >= ${i.crossFileDuplicateBlock}\n`);let o=V(r.profileThresholds);if(o&&Z(`Per-language overrides: ${o}\n`),n.length===0)Z(`No high-risk findings found.
4
- `);else{let e=n.slice(0,r.maxFindings),t=n.length>e.length?` of ${n.length}`:``;Z(`\nHigh-risk findings (top ${e.length}${t}):\n`);for(let t of e)Z(`${H(t)} ${de(t)} ${fe(t)}\n`)}let s=t.crossFileDuplication?.groups??[];if(s.length>0){let e=s.slice(0,10),t=s.length>e.length?` of ${s.length}`:``;Z(`\nCross-file duplicate blocks (top ${e.length}${t}):\n`);for(let t of e)Z(`${t.tokenCount} tokens: ${t.occurrences.map(({file:e,startLine:t,endLine:n})=>`${e}:${t}-${n}`).join(`, `)}\n`)}let c=t.architecture?.duplicateSymbolGroups??[];if(c.length>0){let e=c.toSorted((e,t)=>t.files.length-e.files.length||e.name.localeCompare(t.name)).slice(0,10),t=c.length>e.length?` of ${c.length}`:``;Z(`\nDuplicate symbols (top ${e.length}${t}):\n`);for(let t of e)Z(`${t.name}: ${t.declarations.map(e=>`${e.file}:${e.line}`).join(`, `)}\n`)}if(r.largestFiles>0){let e=B(t.files,r.largestFiles,t.displayRoot);Z(`\nLargest files by code LOC (top ${e.length}):\n`);for(let{file:t,codeLoc:n}of e)Z(`${t} (code LOC ${n})\n`)}if(t.warnings.length>0){Q(`\nDegraded ${t.warnings.length} files (measured, but excluded from cross-file matching):\n`);for(let e of t.warnings.slice(0,10))Q(`- ${e}\n`);t.warnings.length>10&&Q(`- ... ${t.warnings.length-10} more\n`)}if(t.errors.length>0){Q(`\nSkipped ${t.errors.length} files or directories:\n`);for(let e of t.errors.slice(0,10))Q(`- ${e}\n`);t.errors.length>10&&Q(`- ... ${t.errors.length-10} more\n`)}}function B(e,t,n){return e.map(({file:e,metrics:t})=>({file:X(e,n),codeLoc:t.lines.code})).toSorted((e,t)=>t.codeLoc-e.codeLoc||e.file.localeCompare(t.file)).slice(0,t)}function V(e){return Object.entries(e).map(([e,t])=>`${e} { ${Object.entries(t).map(([e,t])=>`${e} ${t}`).join(`, `)} }`).join(`; `)}function H(e){return e.startLine===void 0||e.endLine===void 0?e.file:`${e.file}:${e.startLine}-${e.endLine}`}function de(e){return e.name?`${e.kind} ${e.name}`:e.kind}function fe(e){return`(${e.triggers.map(e=>`${e.metric} ${U(e.value)} >= ${U(e.threshold)}${e.detail?` [${e.detail}]`:``}`).join(`, `)}; cyclomatic ${e.cyclomaticComplexity}, cognitive ${e.cognitiveComplexity})`}function U(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function pe(e){let t=Math.max(0,...e.files.map(e=>e.structuralCoordination.stateMutationScore));return`Architecture max reachable files ${e.maxTransitiveLocalDependencyCount}, max structural breadth ${e.maxStructuralBreadthScore}, max structural coordination ${e.maxStructuralCoordinationScore}, max state mutation ${t}, duplicate symbol groups ${e.duplicateSymbolGroups.length}`}function me(e){return`TypeScript project root files ${e.rootFileCount}, measured roots ${e.measuredRootFileCount}, semantic diagnostics ${e.semanticDiagnosticCount}, resolved calls ${e.resolvedCallExpressionCount}/${e.callExpressionCount} (${(e.resolvedCallExpressionRatio*100).toFixed(1)}%)`}function W(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0;for(let v of e)t+=v.metrics.functionCount,n+=v.metrics.lines.code,r=Math.max(r,v.metrics.maxCyclomaticComplexity),i=Math.max(i,v.metrics.maxCognitiveComplexity),a+=v.metrics.ncssCount,o+=v.metrics.callGraph.callCount,s+=v.metrics.callGraph.internalEdgeCount,c=Math.max(c,v.metrics.callGraph.maxCallDepth),l+=v.metrics.coupling.importSourceCount,u+=v.metrics.coupling.relativeImportCount,d+=v.metrics.coupling.externalImportCount,f+=v.metrics.coupling.exportCount,p+=v.metrics.cohesion.averageFunctionIdentifierOverlap,m+=v.metrics.typeComplexity.typeAnnotationCount,h+=v.metrics.typeComplexity.typeAliasCount,g+=v.metrics.typeComplexity.interfaceCount,_+=v.metrics.typeComplexity.genericParameterCount;return{fileCount:e.length,functionCount:t,linesOfCode:n,maxCyclomaticComplexity:r,maxCognitiveComplexity:i,ncssCount:a,callCount:o,internalEdgeCount:s,maxCallDepth:c,importSourceCount:l,relativeImportCount:u,externalImportCount:d,exportCount:f,averageFunctionIdentifierOverlap:e.length===0?0:p/e.length,typeAnnotationCount:m,typeAliasCount:h,interfaceCount:g,genericParameterCount:_}}function G(e,t){return v.has(e)?!0:!t.includeTests&&y.has(e)}function K(e,t){let n=m.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${m.sep}`)&&!m.isAbsolute(n)}function q(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(ee.test(m.basename(e))||te.test(m.basename(e)))))return m.extname(e)===`.C`?`cpp`:_.get(m.extname(r))}function J(e){let t=Y(e);if(t>100)throw new g(`Expected an integer between 1 and 100.`);return t}function he(e){if(!/^\d+$/u.test(e))throw new g(`Expected a non-negative integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new g(`Expected a non-negative integer.`);return t}function Y(e){if(!/^[1-9]\d*$/u.test(e))throw new g(`Expected a positive integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<1)throw new g(`Expected a positive integer.`);return t}function X(e,t){return m.relative(t,e)||m.basename(e)}function Z(e){process.stdout.write(e)}function Q(e){process.stderr.write(e)}function $(e){return e instanceof Error?e.message:String(e)}
2
+ import{configFileName as e,loadConfig as t,resolveOptions as n}from"./cliConfig.js";import{addCrossFileDuplication as r,collectDuplicatedLineNumbers as i,configSearchDirectory as a,formatError as o,formatPath as s,resolveTarget as c,scanTarget as l,writeStderr as u,writeStdout as d}from"./scan.js";import{runDiffCommand as f}from"./diffCommand.js";import{Command as p,InvalidArgumentError as m}from"commander";g().catch(e=>{u(`Error: ${o(e)}\n`),process.exitCode=1});function h(t){return t.option(`--config <path>`,`config file to use instead of the auto-detected ${e}`).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,D).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,E).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,T).option(`--include-tests`,`include test files and test directories`).option(`--json`,`print JSON output`)}async function g(){let e=h(new p().name(`code-gauge`).description(`Rank the files of a project by refactoring priority.`).argument(`[target]`,`file or directory to measure`,`.`)).option(`--top <number>`,`number of top-ranked files to report (default: 10)`,D).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`);e.action(async(e,i)=>{let o=c(e),s=await t(i.config,await a(o)),u=n(i,s),d=await l(o,u);r(d,u);let f=_(d,u.top);u.json?x(d,f,u):S(o,d,f,u),(d.fatalError||u.failOnError&&d.errors.length>0)&&(process.exitCode=1)}),h(e.command(`diff`).description(`Gate the working tree against a base ref: report only metric regressions in changed files (exit 1 on violations)`).argument(`[target]`,`directory whose changed files are gated`,`.`).requiredOption(`--base <ref>`,`base git ref; changes are measured against its merge-base with HEAD`)).option(`--full`,`also print the passing gate values of every checked function and file`).action(async(e,t,n)=>{await f(e,n.optsWithGlobals())}),await e.parseAsync()}function _(e,t){let n=e.files.map(({file:t,metrics:n})=>{let r=s(t,e.displayRoot),a=i(n,e.crossFileDuplication,r);return{file:r,worstFunction:b(n.functions),duplicatedLineCount:a.size,duplicatedLineRatio:n.lines.code===0?0:a.size/n.lines.code,crossFilePartners:[],ncss:n.ncssCount,codeLines:n.lines.code}}),r=y(n.map(e=>e.worstFunction?.cognitiveComplexity??0)),a=y(n.map(e=>e.duplicatedLineCount)),o=y(n.map(e=>e.ncss)),c=n.map(e=>({...e,score:r(e.worstFunction?.cognitiveComplexity??0)+a(e.duplicatedLineCount)+o(e.ncss)})).toSorted((e,t)=>t.score-e.score||t.ncss-e.ncss||e.file.localeCompare(t.file));return v(c.slice(0,t),e.crossFileDuplication),c}function v(e,t){if(!t)return;let n=new Map(e.map(e=>[e.file,new Set]));for(let e of t.groups)for(let t of e.files){let r=n.get(t);if(r)for(let n of e.files)n!==t&&r.add(n)}for(let t of e)t.crossFilePartners=[...n.get(t.file)??[]].toSorted()}function y(e){let t=e.toSorted((e,t)=>e-t);return e=>{let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i]<e?n=i+1:r=i}return t.length===0?0:n/t.length}}function b(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity||n.cognitiveComplexity===t.cognitiveComplexity&&n.ncss>t.ncss)&&(t=n);if(t)return{name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,cognitiveComplexity:t.cognitiveComplexity,ncss:t.ncss,nestingDepth:t.nestingDepth}}function x(e,t,n){let r=t.slice(0,n.top);d(JSON.stringify({summary:w(e.files),totalRankedFiles:t.length,truncated:r.length<t.length,files:r,errors:e.errors,warnings:e.warnings},void 0,2)+`
3
+ `)}function S(e,t,n,r){if(t.fatalError){u(`Error: ${t.fatalError}\n`);return}let i=w(t.files);if(d(`Measured ${i.fileCount} files under ${e} (code LOC ${i.linesOfCode}, NCSS ${i.ncssCount}, functions ${i.functionCount})\n`),n.length===0)d(`No measurable files found.
4
+ `);else{let e=n.slice(0,r.top),t=n.length>e.length?` of ${n.length}`:``;d(`\nRefactoring candidates (top ${e.length}${t}):\n`);for(let[t,n]of e.entries())d(`${t+1}. ${C(n)}\n`)}if(t.warnings.length>0){u(`\nDegraded ${t.warnings.length} files (measured, but excluded from cross-file matching):\n`);for(let e of t.warnings.slice(0,10))u(`- ${e}\n`);t.warnings.length>10&&u(`- ... ${t.warnings.length-10} more\n`)}if(t.errors.length>0){u(`\nSkipped ${t.errors.length} files or directories:\n`);for(let e of t.errors.slice(0,10))u(`- ${e}\n`);t.errors.length>10&&u(`- ... ${t.errors.length-10} more\n`)}}function C(e){let t=[];if(e.worstFunction){let n=e.worstFunction;t.push(`worst function ${n.name} (L${n.startLine}-${n.endLine}) cognitive ${n.cognitiveComplexity}, NCSS ${n.ncss}, nesting ${n.nestingDepth}`)}if(e.duplicatedLineCount>0){let n=e.crossFilePartners.length>0?`, shared with ${e.crossFilePartners.slice(0,3).join(`, `)}${e.crossFilePartners.length>3?`, ...`:``}`:``;t.push(`duplicated lines ${e.duplicatedLineCount} (${Math.round(e.duplicatedLineRatio*100)}%${n})`)}return t.push(`file NCSS ${e.ncss}`),`${e.file} (score ${e.score.toFixed(2)}): ${t.join(`; `)}`}function w(e){let t=0,n=0,r=0,i=0;for(let a of e)t+=a.metrics.functions.length,n+=a.metrics.lines.code,r=Math.max(r,a.metrics.maxCognitiveComplexity),i+=a.metrics.ncssCount;return{fileCount:e.length,functionCount:t,linesOfCode:n,maxCognitiveComplexity:r,ncssCount:i}}function T(e){let t=D(e);if(t>100)throw new m(`Expected an integer between 1 and 100.`);return t}function E(e){if(!/^\d+$/u.test(e))throw new m(`Expected a non-negative integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new m(`Expected a non-negative integer.`);return t}function D(e){if(!/^[1-9]\d*$/u.test(e))throw new m(`Expected a positive integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<1)throw new m(`Expected a positive integer.`);return t}
5
5
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { measureArchitecture, type ArchitectureFileMetrics, type ArchitectureMetrics } from './architectureMetrics.js';\nimport {\n type CliOptions,\n configFileName,\n loadConfig,\n type ResolvedOptions,\n resolveOptions,\n resolveThresholds,\n type Thresholds,\n} from './cliConfig.js';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport { measureTypeScriptProject, type TypeScriptProjectMetrics } from './typescriptProject.js';\nimport type { CodeMetrics, FunctionMetrics, LanguageName } from './types.js';\n\ninterface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\ninterface RiskTrigger {\n /** Optional location hint (e.g. duplicated block line ranges) appended to the printed trigger. */\n detail?: string;\n metric: string;\n score: number;\n threshold: number;\n value: number;\n}\n\ninterface RiskFinding {\n cognitiveComplexity: number;\n cyclomaticComplexity: number;\n endLine?: number;\n file: string;\n kind: 'component' | 'file' | 'function';\n language: LanguageName;\n name?: string;\n score: number;\n startLine?: number;\n triggers: RiskTrigger[];\n}\n\ninterface ScanResult {\n architecture?: ArchitectureMetrics;\n componentFunctionKeys?: Set<string>;\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n namedComponentFunctionKeys?: Set<string>;\n typeScriptProject?: TypeScriptProjectMetrics;\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\n/** Caps the `Duplicate symbols` section so large repositories do not flood the report. */\nconst maxDuplicateSymbolGroupLines = 10;\n/** Caps the `Cross-file duplicate blocks` section so large repositories do not flood the report. */\nconst maxCrossFileDuplicateGroupLines = 10;\n/** Caps how many cross-file group locations a single risk finding repeats as detail. */\nconst maxCrossFileDuplicateDetailGroups = 3;\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics and list high-risk findings.')\n .argument('[target]', 'file or directory to measure', '.')\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option('--file-loc-threshold <number>', 'minimum file code LOC to report', parsePositiveInteger)\n .option('--function-loc-threshold <number>', 'minimum function physical LOC span to report', parsePositiveInteger)\n .option(\n '--component-loc-threshold <number>',\n 'minimum React component physical LOC span to report',\n parsePositiveInteger\n )\n .option('--cognitive-threshold <number>', 'minimum cognitive complexity to report', parsePositiveInteger)\n .option('--cyclomatic-threshold <number>', 'minimum cyclomatic complexity to report', parsePositiveInteger)\n .option('--call-threshold <number>', 'minimum function call count to report', parsePositiveInteger)\n .option('--import-threshold <number>', 'minimum unique import sources per file to report', parsePositiveInteger)\n .option('--fan-out-threshold <number>', 'minimum intra-file fan-out per function to report', parsePositiveInteger)\n .option('--parameter-threshold <number>', 'minimum function parameter count to report', parsePositiveInteger)\n .option(\n '--duplicate-block-threshold <number>',\n 'minimum count of duplicated code blocks per file to report',\n parsePositiveInteger\n )\n .option(\n '--duplication-ratio-percent-threshold <number>',\n 'minimum percentage (1-100) of duplicated lines per file to report',\n parsePercentInteger\n )\n .option(\n '--cross-file-duplicate-block-threshold <number>',\n 'minimum count of cross-file duplicate block groups per file to report',\n parsePositiveInteger\n )\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveInteger\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option(\n '--transitive-dependency-threshold <number>',\n 'minimum transitively reachable local files to report',\n parsePositiveInteger\n )\n .option(\n '--structural-breadth-threshold <number>',\n 'minimum structural breadth score to report',\n parsePositiveInteger\n )\n .option(\n '--structural-coordination-threshold <number>',\n 'minimum structural coordination score to report',\n parsePositiveInteger\n )\n .option('--state-mutation-threshold <number>', 'minimum state mutation score to report', parsePositiveInteger)\n .option(\n '--duplicate-symbol-group-threshold <number>',\n 'minimum duplicate symbol group count to report',\n parsePositiveInteger\n )\n .option('--max-findings <number>', 'maximum number of risk findings to print', parsePositiveInteger)\n .option('--largest-files <number>', 'number of largest files by code LOC to list', parsePositiveInteger)\n .option('--include-tests', 'include test files and test directories')\n .option('--tsconfig <path>', 'TypeScript project file to use instead of auto-detected tsconfig.json')\n .option('--json', 'print JSON output')\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .option('--fail-on-risk', 'exit with code 1 when high-risk findings are found');\n\n program.action(async (target: string, cliOptions: CliOptions) => {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, options);\n addCrossFileDuplication(result, options);\n await addArchitectureMetrics(result);\n await addTypeScriptProjectMetrics(result, options, resolvedTarget);\n const risks = findRiskyFunctions(\n result.files,\n result.architecture,\n result.crossFileDuplication,\n result.componentFunctionKeys,\n result.namedComponentFunctionKeys,\n options,\n result.displayRoot\n );\n\n if (options.json) {\n printJson(result, risks, options);\n } else {\n printTextReport(resolvedTarget, result, risks, options);\n }\n\n if (\n result.fatalError ||\n (options.failOnError && result.errors.length > 0) ||\n (options.failOnRisk && risks.length > 0)\n ) {\n process.exitCode = 1;\n }\n });\n\n await program.parseAsync();\n}\n\nfunction resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nasync function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ResolvedOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nasync function scanTarget(target: string, options: ResolvedOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return { displayRoot, files, errors, warnings };\n }\n\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\nfunction makeScanContext(\n options: ResolvedOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\nasync function addTypeScriptProjectMetrics(\n result: ScanResult,\n options: ResolvedOptions,\n resolvedTarget: string\n): Promise<void> {\n if (result.fatalError) {\n return;\n }\n if (result.files.length === 0) {\n return;\n }\n\n const explicitConfigFile = options.tsconfig;\n const isExplicitConfig = explicitConfigFile !== undefined;\n if (!isExplicitConfig && !result.files.some(({ file }) => isTypeScriptProjectCandidateFile(file))) {\n return;\n }\n\n const configFile = explicitConfigFile ? resolveTarget(explicitConfigFile) : await findNearestTsconfig(resolvedTarget);\n if (!configFile) {\n return;\n }\n\n try {\n result.typeScriptProject = await measureTypeScriptProject(\n configFile,\n result.files.map(({ file }) => file)\n );\n result.componentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.map((component) =>\n functionLocationKey(component.file, component.startLine, component.startColumn)\n )\n );\n result.namedComponentFunctionKeys = new Set(\n result.typeScriptProject.reactComponentFunctions.flatMap((component) =>\n component.name ? [functionNameLocationKey(component.file, component.name, component.startLine)] : []\n )\n );\n } catch (error) {\n if (isExplicitConfig) {\n result.errors.push(`${formatPath(configFile, result.displayRoot)}: ${formatError(error)}`);\n }\n }\n}\n\nfunction isTypeScriptProjectCandidateFile(file: string): boolean {\n return ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'].includes(path.extname(file));\n}\n\nasync function findNearestTsconfig(target: string): Promise<string | undefined> {\n const targetStat = await stat(target);\n let currentDirectory = targetStat.isDirectory() ? target : path.dirname(target);\n while (true) {\n const configFile = path.join(currentDirectory, 'tsconfig.json');\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nasync function addArchitectureMetrics(result: ScanResult): Promise<void> {\n if (result.fatalError) {\n return;\n }\n\n try {\n result.architecture = measureArchitecture(\n result.files.map(({ file, metrics }) => ({ file, metrics })),\n result.displayRoot\n );\n } catch (error) {\n result.errors.push(`architecture metrics: ${formatError(error)}`);\n }\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n let resolvedDirectory;\n try {\n resolvedDirectory = await realpath(directory);\n } catch (error) {\n context.errors.push(`${formatPath(directory, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedDirectory, context.rootDirectory)) {\n return;\n }\n\n if (context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n let entries;\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n context.errors.push(`${formatPath(directory, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n let resolvedPath;\n try {\n resolvedPath = await realpath(entryPath);\n } catch (error) {\n context.errors.push(`${formatPath(entryPath, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (!isWithinDirectory(resolvedPath, context.rootDirectory)) {\n return;\n }\n\n let entryStat;\n try {\n entryStat = await stat(entryPath);\n } catch (error) {\n context.errors.push(`${formatPath(entryPath, context.rootDirectory)}: ${formatError(error)}`);\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection failing (it always parses with the JavaScript binding, which can give\n // up where the native backend measured fine) must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nfunction addCrossFileDuplication(result: ScanResult, options: ResolvedOptions): 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\nfunction findRiskyFunctions(\n files: FileMetrics[],\n architecture: ArchitectureMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined,\n options: ResolvedOptions,\n displayRoot: string\n): RiskFinding[] {\n const architectureByFile = new Map(architecture?.files.map((file) => [file.file, file]));\n const findings = files.flatMap(({ file, metrics }) => {\n const isReactFile = metrics.functions.some(\n (fn) => fn.returnsJsx || isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys)\n );\n const thresholds = resolveThresholds(options, metrics.language, isReactFile);\n return [\n ...findRiskyFileMetrics(\n file,\n metrics,\n architectureByFile.get(formatPath(file, displayRoot)),\n crossFileDuplication,\n thresholds,\n displayRoot\n ),\n ...metrics.functions.flatMap((fn) =>\n findRiskyFunctionMetrics(\n file,\n metrics.language,\n fn,\n thresholds,\n displayRoot,\n componentFunctionKeys,\n namedComponentFunctionKeys\n )\n ),\n ];\n });\n\n findings.sort(compareRiskFindings);\n return findings;\n}\n\nfunction findRiskyFileMetrics(\n file: string,\n metrics: CodeMetrics,\n architecture: ArchitectureFileMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n thresholds: Thresholds,\n displayRoot: string\n): RiskFinding[] {\n const triggers: RiskTrigger[] = [];\n const formattedFile = formatPath(file, displayRoot);\n addTrigger(triggers, 'file LOC', metrics.lines.code, thresholds.fileLoc);\n addTrigger(triggers, 'import sources', metrics.coupling.importSourceCount, thresholds.import);\n const duplicateBlockDetail = formatDuplicateBlockGroups(metrics.duplication.duplicateBlockGroups);\n addTrigger(\n triggers,\n 'duplicated blocks',\n metrics.duplication.duplicateBlockCount,\n thresholds.duplicateBlock,\n duplicateBlockDetail\n );\n // Maximal-region selection deliberately compresses adjacent clones into few blocks, so severity\n // must track line coverage, not the block count. Flooring compares like the unrounded ratio\n // against the integer threshold (29.5% must not trigger a >= 30 threshold). The block ranges are\n // repeated as detail because this trigger can fire alone, and a percentage without locations is\n // not actionable.\n addTrigger(\n triggers,\n 'duplicated lines (%)',\n Math.floor(metrics.duplication.duplicationRatio * 100),\n thresholds.duplicationRatioPercent,\n duplicateBlockDetail\n );\n if (crossFileDuplication) {\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n addTrigger(\n triggers,\n 'cross-file duplicated blocks',\n Object.hasOwn(crossFileDuplication.duplicateBlockGroupCountByFile, formattedFile)\n ? (crossFileDuplication.duplicateBlockGroupCountByFile[formattedFile] ?? 0)\n : 0,\n thresholds.crossFileDuplicateBlock,\n formatCrossFileDuplicateDetail(crossFileDuplication, formattedFile)\n );\n }\n if (architecture) {\n const hasFileScaleRisk = metrics.lines.code >= 100 || architecture.directLocalDependencyCount >= 8;\n if (hasFileScaleRisk) {\n addTrigger(\n triggers,\n 'transitive local dependencies',\n architecture.transitiveLocalDependencyCount,\n thresholds.transitiveDependency\n );\n }\n if (\n triggers.length > 0 ||\n architecture.directLocalDependencyCount >= 8 ||\n architecture.structuralCoordination.score >= thresholds.structuralCoordination\n ) {\n addTrigger(triggers, 'structural breadth', architecture.structuralBreadthScore, thresholds.structuralBreadth);\n }\n addTrigger(\n triggers,\n 'structural coordination',\n architecture.structuralCoordination.score,\n thresholds.structuralCoordination\n );\n addTrigger(\n triggers,\n 'state mutation',\n architecture.structuralCoordination.stateMutationScore,\n thresholds.stateMutation\n );\n addTrigger(\n triggers,\n 'duplicate symbol groups',\n architecture.duplicateSymbolGroupCount,\n thresholds.duplicateSymbolGroup\n );\n }\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formattedFile,\n language: metrics.language,\n kind: 'file',\n cyclomaticComplexity: metrics.cyclomaticComplexity,\n cognitiveComplexity: metrics.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction findRiskyFunctionMetrics(\n file: string,\n language: LanguageName,\n fn: FunctionMetrics,\n thresholds: Thresholds,\n displayRoot: string,\n componentFunctionKeys?: Set<string>,\n namedComponentFunctionKeys?: Set<string>\n): RiskFinding[] {\n const loc = fn.endLine - fn.startLine + 1;\n const isComponent = isReactComponent(file, fn, componentFunctionKeys, namedComponentFunctionKeys);\n const kind = isComponent ? 'component' : 'function';\n const triggers: RiskTrigger[] = [];\n addTrigger(triggers, 'cognitive complexity', fn.cognitiveComplexity, thresholds.cognitive);\n addTrigger(triggers, 'cyclomatic complexity', fn.cyclomaticComplexity, thresholds.cyclomatic);\n addTrigger(triggers, isComponent ? 'component LOC' : 'function LOC', loc, getLocThreshold(isComponent, thresholds));\n addTrigger(triggers, 'function calls', fn.callCount, thresholds.call);\n addTrigger(triggers, 'fan-out', fn.fanOut, thresholds.fanOut);\n addTrigger(triggers, 'parameters', fn.parameterCount, thresholds.parameter);\n if (triggers.length === 0) {\n return [];\n }\n\n return [\n {\n file: formatPath(file, displayRoot),\n language,\n kind,\n name: fn.name ?? '<anonymous>',\n startLine: fn.startLine,\n endLine: fn.endLine,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n cognitiveComplexity: fn.cognitiveComplexity,\n triggers,\n score: maxTriggerScore(triggers),\n },\n ];\n}\n\nfunction addTrigger(triggers: RiskTrigger[], metric: string, value: number, threshold: number, detail?: string): void {\n if (value < threshold) {\n return;\n }\n\n triggers.push({ metric, value, threshold, score: value / threshold, detail });\n}\n\n/** Formats the cross-file groups a file participates in as `12-34 ~ b.ts:56-78; ...` (capped). */\nfunction formatCrossFileDuplicateDetail(\n crossFileDuplication: CrossFileDuplicationMetrics,\n formattedFile: string\n): string | undefined {\n const involved = crossFileDuplication.groups.filter((group) => group.files.includes(formattedFile));\n if (involved.length === 0) {\n return undefined;\n }\n const formatted = involved\n .slice(0, maxCrossFileDuplicateDetailGroups)\n .map((group) =>\n group.occurrences\n .map(({ file, startLine, endLine }) =>\n file === formattedFile ? `${startLine}-${endLine}` : `${file}:${startLine}-${endLine}`\n )\n .join(' ~ ')\n )\n .join('; ');\n const truncatedSuffix = involved.length > maxCrossFileDuplicateDetailGroups ? '; ...' : '';\n return `${formatted}${truncatedSuffix}`;\n}\n\n/** Formats duplicated block groups as `12-34 ~ 56-78; 90-99 ~ 100-109` (copies joined by ` ~ `, groups by `; `). */\nfunction formatDuplicateBlockGroups(groups: { endLine: number; startLine: number }[][]): string | undefined {\n if (groups.length === 0) {\n return undefined;\n }\n\n return groups.map((group) => group.map(({ startLine, endLine }) => `${startLine}-${endLine}`).join(' ~ ')).join('; ');\n}\n\nfunction isReactComponent(\n file: string,\n fn: FunctionMetrics,\n componentFunctionKeys: Set<string> | undefined,\n namedComponentFunctionKeys: Set<string> | undefined\n): boolean {\n return (\n componentFunctionKeys?.has(functionLocationKey(file, fn.startLine, fn.startColumn)) ||\n (fn.name ? namedComponentFunctionKeys?.has(functionNameLocationKey(file, fn.name, fn.startLine)) : false) ||\n false\n );\n}\n\nfunction getLocThreshold(isComponent: boolean, thresholds: Thresholds): number {\n return isComponent ? thresholds.componentLoc : thresholds.functionLoc;\n}\n\nfunction functionLocationKey(file: string, startLine: number, startColumn: number): string {\n return `${path.resolve(file)}:${startLine}:${startColumn}`;\n}\n\nfunction functionNameLocationKey(file: string, name: string, startLine: number): string {\n return `${path.resolve(file)}:${name}:${startLine}`;\n}\n\nfunction maxTriggerScore(triggers: RiskTrigger[]): number {\n return Math.max(...triggers.map((trigger) => trigger.score));\n}\n\nfunction compareRiskFindings(left: RiskFinding, right: RiskFinding): number {\n return (\n right.score - left.score ||\n left.file.localeCompare(right.file) ||\n (left.startLine ?? 0) - (right.startLine ?? 0) ||\n (left.endLine ?? 0) - (right.endLine ?? 0) ||\n left.kind.localeCompare(right.kind)\n );\n}\n\nfunction printJson(result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n const summary = summarize(result.files);\n const reportedRisks = risks.slice(0, options.maxFindings);\n writeStdout(\n JSON.stringify(\n {\n summary,\n thresholds: options.thresholds,\n profileThresholds: options.profileThresholds,\n totalRisks: risks.length,\n truncated: reportedRisks.length < risks.length,\n largestFiles:\n options.largestFiles > 0\n ? findLargestFiles(result.files, options.largestFiles, result.displayRoot)\n : undefined,\n architecture: result.architecture,\n crossFileDuplication: result.crossFileDuplication,\n typeScriptProject: result.typeScriptProject,\n risks: reportedRisks,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(target: string, result: ScanResult, risks: RiskFinding[], options: ResolvedOptions): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const { thresholds } = options;\n const summary = summarize(result.files);\n writeStdout(`Measured ${summary.fileCount} files under ${target}\\n`);\n writeStdout(\n `LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount}, max cyclomatic ${summary.maxCyclomaticComplexity}, max cognitive ${summary.maxCognitiveComplexity}\\n`\n );\n writeStdout(\n `Calls ${summary.callCount}, internal edges ${summary.internalEdgeCount}, max call depth ${summary.maxCallDepth}, imports ${summary.importSourceCount}, exports ${summary.exportCount}\\n`\n );\n writeStdout(\n `Type annotations ${summary.typeAnnotationCount}, type aliases ${summary.typeAliasCount}, interfaces ${summary.interfaceCount}, avg cohesion ${summary.averageFunctionIdentifierOverlap.toFixed(2)}\\n`\n );\n if (result.architecture) {\n writeStdout(`${formatArchitectureMetrics(result.architecture)}\\n`);\n }\n if (result.typeScriptProject) {\n writeStdout(`${formatTypeScriptProjectMetrics(result.typeScriptProject)}\\n`);\n }\n writeStdout(\n `Risk thresholds: file LOC >= ${thresholds.fileLoc}, function LOC >= ${thresholds.functionLoc}, component LOC >= ${thresholds.componentLoc}, cognitive >= ${thresholds.cognitive}, cyclomatic >= ${thresholds.cyclomatic}, calls >= ${thresholds.call}, imports >= ${thresholds.import}, fan-out >= ${thresholds.fanOut}, parameters >= ${thresholds.parameter}, duplicated blocks >= ${thresholds.duplicateBlock}, duplicated lines (%) >= ${thresholds.duplicationRatioPercent}, cross-file duplicated blocks >= ${thresholds.crossFileDuplicateBlock}\\n`\n );\n const profileOverrides = formatProfileOverrides(options.profileThresholds);\n if (profileOverrides) {\n writeStdout(`Per-language overrides: ${profileOverrides}\\n`);\n }\n\n if (risks.length === 0) {\n writeStdout('No high-risk findings found.\\n');\n } else {\n const reportedRisks = risks.slice(0, options.maxFindings);\n const totalSuffix = risks.length > reportedRisks.length ? ` of ${risks.length}` : '';\n writeStdout(`\\nHigh-risk findings (top ${reportedRisks.length}${totalSuffix}):\\n`);\n for (const risk of reportedRisks) {\n writeStdout(`${formatRiskLocation(risk)} ${formatRiskName(risk)} ${formatRiskMetrics(risk)}\\n`);\n }\n }\n\n const crossFileGroups = result.crossFileDuplication?.groups ?? [];\n if (crossFileGroups.length > 0) {\n const reportedGroups = crossFileGroups.slice(0, maxCrossFileDuplicateGroupLines);\n const totalSuffix = crossFileGroups.length > reportedGroups.length ? ` of ${crossFileGroups.length}` : '';\n writeStdout(`\\nCross-file duplicate blocks (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.tokenCount} tokens: ${group.occurrences\n .map(({ file, startLine, endLine }) => `${file}:${startLine}-${endLine}`)\n .join(', ')}\\n`\n );\n }\n }\n\n const duplicateSymbolGroups = result.architecture?.duplicateSymbolGroups ?? [];\n if (duplicateSymbolGroups.length > 0) {\n const reportedGroups = duplicateSymbolGroups\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name))\n .slice(0, maxDuplicateSymbolGroupLines);\n const totalSuffix =\n duplicateSymbolGroups.length > reportedGroups.length ? ` of ${duplicateSymbolGroups.length}` : '';\n writeStdout(`\\nDuplicate symbols (top ${reportedGroups.length}${totalSuffix}):\\n`);\n for (const group of reportedGroups) {\n writeStdout(\n `${group.name}: ${group.declarations.map((declaration) => `${declaration.file}:${declaration.line}`).join(', ')}\\n`\n );\n }\n }\n\n if (options.largestFiles > 0) {\n const largestFiles = findLargestFiles(result.files, options.largestFiles, result.displayRoot);\n writeStdout(`\\nLargest files by code LOC (top ${largestFiles.length}):\\n`);\n for (const { file, codeLoc } of largestFiles) {\n writeStdout(`${file} (code LOC ${codeLoc})\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\nfunction findLargestFiles(\n files: FileMetrics[],\n count: number,\n displayRoot: string\n): { file: string; codeLoc: number }[] {\n return files\n .map(({ file, metrics }) => ({ file: formatPath(file, displayRoot), codeLoc: metrics.lines.code }))\n .toSorted((left, right) => right.codeLoc - left.codeLoc || left.file.localeCompare(right.file))\n .slice(0, count);\n}\n\nfunction formatProfileOverrides(profileThresholds: ResolvedOptions['profileThresholds']): string {\n return Object.entries(profileThresholds)\n .map(\n ([profile, overrides]) =>\n `${profile} { ${Object.entries(overrides)\n .map(([metric, value]) => `${metric} ${value}`)\n .join(', ')} }`\n )\n .join('; ');\n}\n\nfunction formatRiskLocation(risk: RiskFinding): string {\n return risk.startLine === undefined || risk.endLine === undefined\n ? risk.file\n : `${risk.file}:${risk.startLine}-${risk.endLine}`;\n}\n\nfunction formatRiskName(risk: RiskFinding): string {\n return risk.name ? `${risk.kind} ${risk.name}` : risk.kind;\n}\n\nfunction formatRiskMetrics(risk: RiskFinding): string {\n const triggerText = risk.triggers\n .map(\n (trigger) =>\n `${trigger.metric} ${formatMetricValue(trigger.value)} >= ${formatMetricValue(trigger.threshold)}${trigger.detail ? ` [${trigger.detail}]` : ''}`\n )\n .join(', ');\n return `(${triggerText}; cyclomatic ${risk.cyclomaticComplexity}, cognitive ${risk.cognitiveComplexity})`;\n}\n\nfunction formatMetricValue(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(2);\n}\n\nfunction formatArchitectureMetrics(metrics: ArchitectureMetrics): string {\n const maxStateMutationScore = Math.max(\n 0,\n ...metrics.files.map((file) => file.structuralCoordination.stateMutationScore)\n );\n return `Architecture max reachable files ${metrics.maxTransitiveLocalDependencyCount}, max structural breadth ${metrics.maxStructuralBreadthScore}, max structural coordination ${metrics.maxStructuralCoordinationScore}, max state mutation ${maxStateMutationScore}, duplicate symbol groups ${metrics.duplicateSymbolGroups.length}`;\n}\n\nfunction formatTypeScriptProjectMetrics(metrics: TypeScriptProjectMetrics): string {\n return `TypeScript project root files ${metrics.rootFileCount}, measured roots ${metrics.measuredRootFileCount}, semantic diagnostics ${metrics.semanticDiagnosticCount}, resolved calls ${metrics.resolvedCallExpressionCount}/${metrics.callExpressionCount} (${(metrics.resolvedCallExpressionRatio * 100).toFixed(1)}%)`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n maxCyclomaticComplexity: number;\n ncssCount: number;\n callCount: number;\n internalEdgeCount: number;\n maxCallDepth: number;\n importSourceCount: number;\n relativeImportCount: number;\n externalImportCount: number;\n exportCount: number;\n averageFunctionIdentifierOverlap: number;\n typeAnnotationCount: number;\n typeAliasCount: number;\n interfaceCount: number;\n genericParameterCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCyclomaticComplexity = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n let callCount = 0;\n let internalEdgeCount = 0;\n let maxCallDepth = 0;\n let importSourceCount = 0;\n let relativeImportCount = 0;\n let externalImportCount = 0;\n let exportCount = 0;\n let cohesionTotal = 0;\n let typeAnnotationCount = 0;\n let typeAliasCount = 0;\n let interfaceCount = 0;\n let genericParameterCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functionCount;\n linesOfCode += file.metrics.lines.code;\n maxCyclomaticComplexity = Math.max(maxCyclomaticComplexity, file.metrics.maxCyclomaticComplexity);\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n callCount += file.metrics.callGraph.callCount;\n internalEdgeCount += file.metrics.callGraph.internalEdgeCount;\n maxCallDepth = Math.max(maxCallDepth, file.metrics.callGraph.maxCallDepth);\n importSourceCount += file.metrics.coupling.importSourceCount;\n relativeImportCount += file.metrics.coupling.relativeImportCount;\n externalImportCount += file.metrics.coupling.externalImportCount;\n exportCount += file.metrics.coupling.exportCount;\n cohesionTotal += file.metrics.cohesion.averageFunctionIdentifierOverlap;\n typeAnnotationCount += file.metrics.typeComplexity.typeAnnotationCount;\n typeAliasCount += file.metrics.typeComplexity.typeAliasCount;\n interfaceCount += file.metrics.typeComplexity.interfaceCount;\n genericParameterCount += file.metrics.typeComplexity.genericParameterCount;\n }\n\n return {\n fileCount: files.length,\n functionCount,\n linesOfCode,\n maxCyclomaticComplexity,\n maxCognitiveComplexity,\n ncssCount,\n callCount,\n internalEdgeCount,\n maxCallDepth,\n importSourceCount,\n relativeImportCount,\n externalImportCount,\n exportCount,\n averageFunctionIdentifierOverlap: files.length === 0 ? 0 : cohesionTotal / files.length,\n typeAnnotationCount,\n typeAliasCount,\n interfaceCount,\n genericParameterCount,\n };\n}\n\nfunction shouldSkipDirectory(name: string, options: ResolvedOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\nfunction getLanguage(file: string, options: ResolvedOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number {\n if (!/^[1-9]\\d*$/u.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n\nfunction formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nfunction writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nfunction writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";ukBAiEA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,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CAAO,CAC9B,CAEA,SAAS,EAAY,EAAuB,CAC1C,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runDiffCommand, type DiffCliOptions } from './diffCommand.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatError,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 1;\n});\n\n/** Registers the options shared by the ranking command and the diff gate. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveInteger\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nasync function main(): Promise<void> {\n const program = addSharedOptions(\n new Command()\n .name('code-gauge')\n .description('Rank the files of a project by refactoring priority.')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveInteger)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned');\n\n program.action(async (target: string, cliOptions: CliOptions) => {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, options);\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n });\n\n addSharedOptions(\n program\n .command('diff')\n .description(\n 'Gate the working tree against a base ref: report only metric regressions in changed files (exit 1 on violations)'\n )\n .argument('[target]', 'directory whose changed files are gated', '.')\n .requiredOption('--base <ref>', 'base git ref; changes are measured against its merge-base with HEAD')\n )\n .option('--full', 'also print the passing gate values of every checked function and file')\n .action(async (target: string, _cliOptions: DiffCliOptions, command: Command) => {\n // Options sharing a name with a root option (--json, --config, ...) land in the root's\n // option store, so the merged view is required to see them.\n await runDiffCommand(target, command.optsWithGlobals() as DiffCliOptions);\n });\n\n await program.parseAsync();\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: worst.name ?? '<anonymous>',\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number {\n if (!/^[1-9]\\d*$/u.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";2ZAuDK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAY,UAAU,EAAY,CAAK,EAAE,GAAG,EA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8B,EAE/D,OAAO,CACT"}
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./duplication.cjs");let n=require("node:fs/promises"),r=require("node:path");r=e.__toESM(r,1);const i={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,crossFileDuplicateBlock:2,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},a=`code-gauge.config.json`,o=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],s={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function c(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const l={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,crossFileDuplicateBlock:`crossFileDuplicateBlockThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function u(e,n){let r={...i};for(let t of Object.keys(r))r[t]=e[l[t]]??n.thresholds?.[t]??r[t];return{thresholds:r,duplication:{minTokens:e.duplicationMinTokens??n.duplication?.minTokens??t.defaultDuplicationOptions.minTokens,maxGapTokens:e.duplicationMaxGapTokens??n.duplication?.maxGapTokens??t.defaultDuplicationOptions.maxGapTokens,minSimilarityPercent:e.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??t.defaultDuplicationOptions.minSimilarityPercent},profileThresholds:d(s,n.languageThresholds),maxFindings:e.maxFindings??n.maxFindings??20,largestFiles:e.largestFiles??n.largestFiles??0,includeTests:e.includeTests??n.includeTests??!1,failOnRisk:e.failOnRisk??n.failOnRisk??!1,failOnError:e.failOnError??n.failOnError??!1,json:e.json??!1,tsconfig:e.tsconfig??n.tsconfig}}function d(e,t){let n={};for(let r of o){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function f(e,t){let r=e??await p(t);if(!r)return{};let i;try{i=await(0,n.readFile)(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${x(e)}`)}return h(a,r)}async function p(e){let t=e;for(;;){let e=r.default.join(t,a);if(await m(e))return e;let n=r.default.dirname(t);if(n===t)return;t=n}}async function m(e){try{return(await(0,n.stat)(e)).isFile()}catch{return!1}}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=g(n.thresholds,`thresholds`,t)),n.duplication!==void 0&&(r.duplication=_(n.duplication,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!o.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${o.join(`, `)}).`);e[r]=g(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=y(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=y(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=b(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function g(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let r={};for(let[a,o]of Object.entries(e)){if(!(a in i))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=y(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);r[a]=e}return r}function _(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=y(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=v(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=y(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function v(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`Config file "${n}": "${t}" must be a non-negative integer.`);return e}function y(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}exports.configFileName=a,exports.defaultProfileThresholds=s,exports.defaultThresholds=i,exports.loadConfig=f,exports.profileKeys=o,exports.resolveOptions=u,exports.resolveThresholds=c;
1
+ "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./duplication.cjs"),n=require("./regressionGate.cjs");let r=require("node:fs/promises"),i=require("node:path");i=e.__toESM(i,1);const a=`code-gauge.config.json`;function o(e,n){return{duplication:{minTokens:e.duplicationMinTokens??n.duplication?.minTokens??t.defaultDuplicationOptions.minTokens,maxGapTokens:e.duplicationMaxGapTokens??n.duplication?.maxGapTokens??t.defaultDuplicationOptions.maxGapTokens,minSimilarityPercent:e.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??t.defaultDuplicationOptions.minSimilarityPercent},top:e.top??n.rank?.top??10,includeTests:e.includeTests??n.includeTests??!1,failOnError:e.failOnError??n.failOnError??!1,json:e.json??!1}}function s(e){return{newFunction:{...n.defaultGateOptions.newFunction,...e.gate?.newFunction},tolerance:{...n.defaultGateOptions.tolerance,...e.gate?.tolerance},matchSimilarityPercent:e.gate?.matchSimilarityPercent??n.defaultGateOptions.matchSimilarityPercent}}async function c(e,t){let n=e??await l(t);if(!n)return{};let i;try{i=await(0,r.readFile)(n,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${n}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${n}": ${x(e)}`)}return d(a,n)}async function l(e){let t=e;for(;;){let e=i.default.join(t,a);if(await u(e))return e;let n=i.default.dirname(t);if(n===t)return;t=n}}async function u(e){try{return(await(0,r.stat)(e)).isFile()}catch{return!1}}function d(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r=new Set([`duplication`,`rank`,`gate`,`includeTests`,`failOnError`]);for(let e of Object.keys(n))if(!r.has(e))throw Error(`Config file "${t}": unknown setting "${e}" (expected ${[...r].join(`, `)}).`);let i={};n.duplication!==void 0&&(i.duplication=h(n.duplication,t)),n.rank!==void 0&&(i.rank=f(n.rank,t)),n.gate!==void 0&&(i.gate=p(n.gate,t));for(let e of[`includeTests`,`failOnError`])n[e]!==void 0&&(i[e]=b(n[e],e,t));return i}function f(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=v(i,`rank.top`,t)}return n}function p(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "gate" must be an object.`);let r={};for(let[i,a]of Object.entries(e))if(i===`newFunction`)r.newFunction=m(a,`gate.newFunction`,Object.keys(n.defaultGateOptions.newFunction),t,_);else if(i===`tolerance`)r.tolerance=m(a,`gate.tolerance`,Object.keys(n.defaultGateOptions.tolerance),t,g);else if(i===`matchSimilarityPercent`){let e=v(a,`gate.matchSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "gate.matchSimilarityPercent" must be between 1 and 100.`);r.matchSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${i}" in "gate" (expected newFunction, tolerance, or matchSimilarityPercent).`);return r}function m(e,t,n,r,i){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${r}": "${t}" must be an object.`);let a={};for(let[o,s]of Object.entries(e)){if(!n.includes(o))throw Error(`Config file "${r}": unknown setting "${o}" in "${t}" (expected ${n.join(`, `)}).`);a[o]=i(s,`${t}.${o}`,r)}return a}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=v(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=_(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=v(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function g(e,t,n){return y(e,t,n,Number.isFinite,`a non-negative number`)}function _(e,t,n){return y(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function v(e,t,n){let r=y(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function y(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}exports.configFileName=a,exports.loadConfig=c,exports.resolveGateOptions=s,exports.resolveOptions=o;
2
2
  //# sourceMappingURL=cliConfig.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","path","stat"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\n/** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */\nexport interface Thresholds {\n fileLoc: number;\n functionLoc: number;\n componentLoc: number;\n cognitive: number;\n cyclomatic: number;\n call: number;\n import: number;\n fanOut: number;\n parameter: number;\n duplicateBlock: number;\n /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */\n duplicationRatioPercent: number;\n /** Number of cross-file duplicate block groups a file participates in. */\n crossFileDuplicateBlock: number;\n transitiveDependency: number;\n structuralBreadth: number;\n structuralCoordination: number;\n stateMutation: number;\n duplicateSymbolGroup: number;\n}\n\n// Defaults tuned against blind human labels across five representative WillBooster/WillBoosterLab\n// repositories to maximize F1 (precision without sacrificing recall); see PR for the evaluation.\nexport const defaultThresholds: Thresholds = {\n fileLoc: 500,\n functionLoc: 120,\n componentLoc: 350,\n cognitive: 25,\n cyclomatic: 20,\n call: 50,\n import: 25,\n fanOut: 10,\n parameter: 8,\n duplicateBlock: 2,\n duplicationRatioPercent: 30,\n crossFileDuplicateBlock: 2,\n transitiveDependency: 25,\n structuralBreadth: 8,\n structuralCoordination: 300,\n stateMutation: 50,\n duplicateSymbolGroup: 5,\n};\n\nexport const defaultMaxFindings = 20;\nexport const configFileName = 'code-gauge.config.json';\n\n/**\n * Profile keys for per-language and React-specific threshold overrides. A file resolves its\n * thresholds as base → its language profile → the `react` profile (when it contains a component).\n */\nexport const profileKeys = [\n 'javascript',\n 'jsx',\n 'typescript',\n 'tsx',\n 'python',\n 'go',\n 'rust',\n 'java',\n 'ruby',\n 'c',\n 'cpp',\n 'react',\n] as const;\nexport type ProfileKey = (typeof profileKeys)[number];\n\n/**\n * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by\n * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)\n * and coordinates more per file, while React files import roughly twice as many sources as pure TS.\n */\nexport const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {\n python: { stateMutation: 90, structuralCoordination: 350 },\n // Ruby scores state mutation via assignments like Python (bindings are assignments).\n ruby: { stateMutation: 90, structuralCoordination: 350 },\n react: { import: 30 },\n};\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n thresholds?: Partial<Thresholds>;\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */\n languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n tsconfig?: string;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n thresholds: Thresholds;\n duplication: Required<DuplicationOptions>;\n profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;\n maxFindings: number;\n /** Number of largest files by code LOC to list; 0 disables the section. */\n largestFiles: number;\n includeTests: boolean;\n failOnRisk: boolean;\n failOnError: boolean;\n json: boolean;\n tsconfig?: string;\n}\n\n/**\n * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile\n * and then, when the file contains a React component, the `react` profile.\n */\nexport function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds {\n let thresholds = options.thresholds;\n const languageOverride = options.profileThresholds[language as ProfileKey];\n if (languageOverride) {\n thresholds = { ...thresholds, ...languageOverride };\n }\n if (isReact && options.profileThresholds.react) {\n thresholds = { ...thresholds, ...options.profileThresholds.react };\n }\n return thresholds;\n}\n\n/** Raw command-line options; every threshold is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n fileLocThreshold?: number;\n functionLocThreshold?: number;\n componentLocThreshold?: number;\n cognitiveThreshold?: number;\n cyclomaticThreshold?: number;\n callThreshold?: number;\n importThreshold?: number;\n fanOutThreshold?: number;\n parameterThreshold?: number;\n duplicateBlockThreshold?: number;\n duplicationRatioPercentThreshold?: number;\n crossFileDuplicateBlockThreshold?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n transitiveDependencyThreshold?: number;\n structuralBreadthThreshold?: number;\n structuralCoordinationThreshold?: number;\n stateMutationThreshold?: number;\n duplicateSymbolGroupThreshold?: number;\n maxFindings?: number;\n largestFiles?: number;\n includeTests?: boolean;\n failOnRisk?: boolean;\n failOnError?: boolean;\n json?: boolean;\n tsconfig?: string;\n}\n\n/** Maps each threshold to the matching command-line flag; the config key equals the flag without the `-threshold` suffix. */\nconst thresholdCliKeys: Record<keyof Thresholds, keyof CliOptions> = {\n fileLoc: 'fileLocThreshold',\n functionLoc: 'functionLocThreshold',\n componentLoc: 'componentLocThreshold',\n cognitive: 'cognitiveThreshold',\n cyclomatic: 'cyclomaticThreshold',\n call: 'callThreshold',\n import: 'importThreshold',\n fanOut: 'fanOutThreshold',\n parameter: 'parameterThreshold',\n duplicateBlock: 'duplicateBlockThreshold',\n duplicationRatioPercent: 'duplicationRatioPercentThreshold',\n crossFileDuplicateBlock: 'crossFileDuplicateBlockThreshold',\n transitiveDependency: 'transitiveDependencyThreshold',\n structuralBreadth: 'structuralBreadthThreshold',\n structuralCoordination: 'structuralCoordinationThreshold',\n stateMutation: 'stateMutationThreshold',\n duplicateSymbolGroup: 'duplicateSymbolGroupThreshold',\n};\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n const thresholds = { ...defaultThresholds };\n for (const key of Object.keys(thresholds) as (keyof Thresholds)[]) {\n thresholds[key] = (cli[thresholdCliKeys[key]] as number | undefined) ?? config.thresholds?.[key] ?? thresholds[key];\n }\n\n return {\n thresholds,\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n profileThresholds: mergeProfileThresholds(defaultProfileThresholds, config.languageThresholds),\n maxFindings: cli.maxFindings ?? config.maxFindings ?? defaultMaxFindings,\n largestFiles: cli.largestFiles ?? config.largestFiles ?? 0,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnRisk: cli.failOnRisk ?? config.failOnRisk ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n tsconfig: cli.tsconfig ?? config.tsconfig,\n };\n}\n\n/** Merges user-supplied per-profile overrides on top of the built-in ones, per profile. */\nfunction mergeProfileThresholds(\n defaults: Partial<Record<ProfileKey, Partial<Thresholds>>>,\n overrides: Partial<Record<ProfileKey, Partial<Thresholds>>> | undefined\n): Partial<Record<ProfileKey, Partial<Thresholds>>> {\n const merged: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const key of profileKeys) {\n const combined = { ...defaults[key], ...overrides?.[key] };\n if (Object.keys(combined).length > 0) {\n merged[key] = combined;\n }\n }\n return merged;\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const config: CodeGaugeConfig = {};\n\n if (raw.thresholds !== undefined) {\n config.thresholds = validateThresholdObject(raw.thresholds, 'thresholds', configFile);\n }\n\n if (raw.duplication !== undefined) {\n config.duplication = validateDuplicationObject(raw.duplication, configFile);\n }\n\n if (raw.languageThresholds !== undefined) {\n if (\n typeof raw.languageThresholds !== 'object' ||\n raw.languageThresholds === null ||\n Array.isArray(raw.languageThresholds)\n ) {\n throw new Error(`Config file \"${configFile}\": \"languageThresholds\" must be an object.`);\n }\n const languageThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>> = {};\n for (const [profile, thresholds] of Object.entries(raw.languageThresholds as Record<string, unknown>)) {\n if (!(profileKeys as readonly string[]).includes(profile)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language profile \"${profile}\" (expected one of ${profileKeys.join(', ')}).`\n );\n }\n languageThresholds[profile as ProfileKey] = validateThresholdObject(\n thresholds,\n `languageThresholds.${profile}`,\n configFile\n );\n }\n config.languageThresholds = languageThresholds;\n }\n\n if (raw.maxFindings !== undefined) {\n config.maxFindings = requirePositiveInteger(raw.maxFindings, 'maxFindings', configFile);\n }\n if (raw.largestFiles !== undefined) {\n config.largestFiles = requirePositiveInteger(raw.largestFiles, 'largestFiles', configFile);\n }\n for (const key of ['includeTests', 'failOnRisk', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n if (raw.tsconfig !== undefined) {\n if (typeof raw.tsconfig !== 'string') {\n throw new TypeError(`Config file \"${configFile}\": \"tsconfig\" must be a string.`);\n }\n config.tsconfig = raw.tsconfig;\n }\n\n return config;\n}\n\nfunction validateThresholdObject(value: unknown, label: string, configFile: string): Partial<Thresholds> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${label}\" must be an object.`);\n }\n const thresholds: Partial<Thresholds> = {};\n for (const [key, threshold] of Object.entries(value as Record<string, unknown>)) {\n if (!(key in defaultThresholds)) {\n throw new Error(`Config file \"${configFile}\": unknown threshold \"${key}\" in \"${label}\".`);\n }\n const parsed = requirePositiveInteger(threshold, `${label}.${key}`, configFile);\n if (key === 'duplicationRatioPercent' && parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"${label}.${key}\" must be between 1 and 100.`);\n }\n thresholds[key as keyof Thresholds] = parsed;\n }\n return thresholds;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a non-negative integer.`);\n }\n return value;\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"0KA8BA,MAAa,EAAgC,CAC3C,QAAS,IACT,YAAa,IACb,aAAc,IACd,UAAW,GACX,WAAY,GACZ,KAAM,GACN,OAAQ,GACR,OAAQ,GACR,UAAW,EACX,eAAgB,EAChB,wBAAyB,GACzB,wBAAyB,EACzB,qBAAsB,GACtB,kBAAmB,EACnB,uBAAwB,IACxB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,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,kCAAkC,EAEzF,OAAO,CACT,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","defaultGateOptions","readFile","path","stat"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport {\n defaultGateOptions,\n type GateOptions,\n type GateTolerances,\n type NewFunctionThresholds,\n} from './regressionGate.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Regression-gate settings for `code-gauge diff`; unset fields use the built-in defaults. */\nexport interface GateConfig {\n newFunction?: Partial<NewFunctionThresholds>;\n tolerance?: Partial<GateTolerances>;\n matchSimilarityPercent?: number;\n}\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Regression-gate settings for `code-gauge diff`. */\n gate?: GateConfig;\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/** Resolves the regression-gate settings with precedence configuration file > built-in defaults. */\nexport function resolveGateOptions(config: CodeGaugeConfig): GateOptions {\n return {\n newFunction: { ...defaultGateOptions.newFunction, ...config.gate?.newFunction },\n tolerance: { ...defaultGateOptions.tolerance, ...config.gate?.tolerance },\n matchSimilarityPercent: config.gate?.matchSimilarityPercent ?? defaultGateOptions.matchSimilarityPercent,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<CodeGaugeConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return {};\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${formatError(error)}`);\n }\n return {};\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${formatError(error)}`);\n }\n\n return validateConfig(parsed, configFile);\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const raw = value as Record<string, unknown>;\n const knownKeys = new Set(['duplication', 'rank', 'gate', 'includeTests', 'failOnError']);\n for (const key of Object.keys(raw)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (raw.duplication !== undefined) {\n config.duplication = validateDuplicationObject(raw.duplication, configFile);\n }\n\n if (raw.rank !== undefined) {\n config.rank = validateRankObject(raw.rank, configFile);\n }\n\n if (raw.gate !== undefined) {\n config.gate = validateGateObject(raw.gate, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (raw[key] !== undefined) {\n config[key] = requireBoolean(raw[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateGateObject(value: unknown, configFile: string): GateConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"gate\" must be an object.`);\n }\n const gate: GateConfig = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'newFunction') {\n // Zero is a meaningful upper bound (branch-free or unnested new functions), so the limits\n // are validated as non-negative rather than positive.\n gate.newFunction = validateGateNumberObject(\n setting,\n 'gate.newFunction',\n Object.keys(defaultGateOptions.newFunction),\n configFile,\n requireNonNegativeInteger\n ) as Partial<NewFunctionThresholds>;\n } else if (key === 'tolerance') {\n gate.tolerance = validateGateNumberObject(\n setting,\n 'gate.tolerance',\n Object.keys(defaultGateOptions.tolerance),\n configFile,\n requireNonNegativeNumber\n ) as Partial<GateTolerances>;\n } else if (key === 'matchSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'gate.matchSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"gate.matchSimilarityPercent\" must be between 1 and 100.`);\n }\n gate.matchSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"gate\" (expected newFunction, tolerance, or matchSimilarityPercent).`\n );\n }\n }\n return gate;\n}\n\nfunction validateGateNumberObject(\n value: unknown,\n settingName: string,\n knownKeys: string[],\n configFile: string,\n requireNumber: (value: unknown, key: string, configFile: string) => number\n): Record<string, number> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n const validated: Record<string, number> = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${knownKeys.join(', ')}).`\n );\n }\n validated[key] = requireNumber(setting, `${settingName}.${key}`, configFile);\n }\n return validated;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\n/** Tolerances may be fractional (e.g. Halstead volume), so only finiteness and sign are checked. */\nfunction requireNonNegativeNumber(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isFinite, 'a non-negative number');\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"4MAWA,MAAa,EAAiB,yBA6C9B,SAAgB,EAAe,EAAiB,EAA0C,CACxF,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAaA,EAAAA,0BAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgBA,EAAAA,0BAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpBA,EAAAA,0BAA0B,oBAC9B,EACA,IAAK,EAAI,KAAO,EAAO,MAAM,KAAA,GAC7B,aAAc,EAAI,cAAgB,EAAO,cAAgB,GACzD,YAAa,EAAI,aAAe,EAAO,aAAe,GACtD,KAAM,EAAI,MAAQ,EACpB,CACF,CAGA,SAAgB,EAAmB,EAAsC,CACvE,MAAO,CACL,YAAa,CAAE,GAAGC,EAAAA,mBAAmB,YAAa,GAAG,EAAO,MAAM,WAAY,EAC9E,UAAW,CAAE,GAAGA,EAAAA,mBAAmB,UAAW,GAAG,EAAO,MAAM,SAAU,EACxE,uBAAwB,EAAO,MAAM,wBAA0BA,EAAAA,mBAAmB,sBACpF,CACF,CAMA,eAAsB,EAAW,EAAkC,EAAmD,CACpH,IAAM,EAAa,GAAiB,MAAM,EAAkB,CAAe,EAC3E,GAAI,CAAC,EACH,MAAO,CAAC,EAGV,IAAI,EACJ,GAAI,CACF,EAAU,MAAA,EAAMC,EA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EAAY,OAAO,cAAe,wBAAwB,CAC7F,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAM,EAAS,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAI,EAAS,EACX,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO,GAAU,UAAY,CAAC,EAAY,CAAK,GAAK,EAAQ,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
@@ -1,107 +1,50 @@
1
+ import { type GateOptions, type GateTolerances, type NewFunctionThresholds } from './regressionGate.js';
1
2
  import type { DuplicationOptions } from './types.js';
2
- /** Risk thresholds; a finding is reported when the measured value is greater than or equal to the threshold. */
3
- export interface Thresholds {
4
- fileLoc: number;
5
- functionLoc: number;
6
- componentLoc: number;
7
- cognitive: number;
8
- cyclomatic: number;
9
- call: number;
10
- import: number;
11
- fanOut: number;
12
- parameter: number;
13
- duplicateBlock: number;
14
- /** Percentage (1-100) of a file's code lines (comments/blanks excluded) covered by duplicates. */
15
- duplicationRatioPercent: number;
16
- /** Number of cross-file duplicate block groups a file participates in. */
17
- crossFileDuplicateBlock: number;
18
- transitiveDependency: number;
19
- structuralBreadth: number;
20
- structuralCoordination: number;
21
- stateMutation: number;
22
- duplicateSymbolGroup: number;
23
- }
24
- export declare const defaultThresholds: Thresholds;
25
- export declare const defaultMaxFindings = 20;
26
3
  export declare const configFileName = "code-gauge.config.json";
27
- /**
28
- * Profile keys for per-language and React-specific threshold overrides. A file resolves its
29
- * thresholds as base → its language profile → the `react` profile (when it contains a component).
30
- */
31
- export declare const profileKeys: readonly ['javascript', 'jsx', 'typescript', 'tsx', 'python', 'go', 'rust', 'java', 'ruby', 'c', 'cpp', 'react'];
32
- export type ProfileKey = (typeof profileKeys)[number];
33
- /**
34
- * Built-in per-profile overrides, calibrated because some metric distributions differ sharply by
35
- * language/type: Python treats every binding as an assignment (so `stateMutation` runs ~10x higher)
36
- * and coordinates more per file, while React files import roughly twice as many sources as pure TS.
37
- */
38
- export declare const defaultProfileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;
4
+ export declare const defaultTopFileCount = 10;
5
+ /** Regression-gate settings for `code-gauge diff`; unset fields use the built-in defaults. */
6
+ export interface GateConfig {
7
+ newFunction?: Partial<NewFunctionThresholds>;
8
+ tolerance?: Partial<GateTolerances>;
9
+ matchSimilarityPercent?: number;
10
+ }
39
11
  /** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */
40
12
  export interface CodeGaugeConfig {
41
- thresholds?: Partial<Thresholds>;
42
13
  /** Duplication detection settings applied to every measured file. */
43
14
  duplication?: DuplicationOptions;
44
- /** Per-profile overrides keyed by language name or `react`; merged over `thresholds` for matching files. */
45
- languageThresholds?: Partial<Record<ProfileKey, Partial<Thresholds>>>;
46
- maxFindings?: number;
47
- largestFiles?: number;
15
+ /** Refactoring-candidate ranking settings. */
16
+ rank?: {
17
+ top?: number;
18
+ };
19
+ /** Regression-gate settings for `code-gauge diff`. */
20
+ gate?: GateConfig;
48
21
  includeTests?: boolean;
49
- failOnRisk?: boolean;
50
22
  failOnError?: boolean;
51
- tsconfig?: string;
52
- }
53
- /** Options after merging command-line flags, the configuration file, and the built-in defaults. */
54
- export interface ResolvedOptions {
55
- thresholds: Thresholds;
56
- duplication: Required<DuplicationOptions>;
57
- profileThresholds: Partial<Record<ProfileKey, Partial<Thresholds>>>;
58
- maxFindings: number;
59
- /** Number of largest files by code LOC to list; 0 disables the section. */
60
- largestFiles: number;
61
- includeTests: boolean;
62
- failOnRisk: boolean;
63
- failOnError: boolean;
64
- json: boolean;
65
- tsconfig?: string;
66
23
  }
67
- /**
68
- * Resolves the thresholds for a single file: the base thresholds overlaid with its language profile
69
- * and then, when the file contains a React component, the `react` profile.
70
- */
71
- export declare function resolveThresholds(options: ResolvedOptions, language: string, isReact: boolean): Thresholds;
72
- /** Raw command-line options; every threshold is undefined unless the user passed the flag. */
24
+ /** Raw command-line options; every field is undefined unless the user passed the flag. */
73
25
  export interface CliOptions {
74
26
  config?: string;
75
- fileLocThreshold?: number;
76
- functionLocThreshold?: number;
77
- componentLocThreshold?: number;
78
- cognitiveThreshold?: number;
79
- cyclomaticThreshold?: number;
80
- callThreshold?: number;
81
- importThreshold?: number;
82
- fanOutThreshold?: number;
83
- parameterThreshold?: number;
84
- duplicateBlockThreshold?: number;
85
- duplicationRatioPercentThreshold?: number;
86
- crossFileDuplicateBlockThreshold?: number;
27
+ top?: number;
87
28
  duplicationMinTokens?: number;
88
29
  duplicationMaxGapTokens?: number;
89
30
  duplicationMinSimilarityPercent?: number;
90
- transitiveDependencyThreshold?: number;
91
- structuralBreadthThreshold?: number;
92
- structuralCoordinationThreshold?: number;
93
- stateMutationThreshold?: number;
94
- duplicateSymbolGroupThreshold?: number;
95
- maxFindings?: number;
96
- largestFiles?: number;
97
31
  includeTests?: boolean;
98
- failOnRisk?: boolean;
99
32
  failOnError?: boolean;
100
33
  json?: boolean;
101
- tsconfig?: string;
34
+ }
35
+ /** Options after merging command-line flags, the configuration file, and the built-in defaults. */
36
+ export interface ResolvedOptions {
37
+ duplication: Required<DuplicationOptions>;
38
+ /** Number of top-ranked files to report. */
39
+ top: number;
40
+ includeTests: boolean;
41
+ failOnError: boolean;
42
+ json: boolean;
102
43
  }
103
44
  /** Resolves options with precedence command-line flags > configuration file > built-in defaults. */
104
45
  export declare function resolveOptions(cli: CliOptions, config: CodeGaugeConfig): ResolvedOptions;
46
+ /** Resolves the regression-gate settings with precedence configuration file > built-in defaults. */
47
+ export declare function resolveGateOptions(config: CodeGaugeConfig): GateOptions;
105
48
  /**
106
49
  * Loads the configuration file. An explicit path must exist; otherwise the nearest
107
50
  * `code-gauge.config.json` is searched by walking up from the target directory.
package/dist/cliConfig.js CHANGED
@@ -1,2 +1,2 @@
1
- import{defaultDuplicationOptions as e}from"./duplication.js";import{readFile as t,stat as n}from"node:fs/promises";import r from"node:path";const i={fileLoc:500,functionLoc:120,componentLoc:350,cognitive:25,cyclomatic:20,call:50,import:25,fanOut:10,parameter:8,duplicateBlock:2,duplicationRatioPercent:30,crossFileDuplicateBlock:2,transitiveDependency:25,structuralBreadth:8,structuralCoordination:300,stateMutation:50,duplicateSymbolGroup:5},a=`code-gauge.config.json`,o=[`javascript`,`jsx`,`typescript`,`tsx`,`python`,`go`,`rust`,`java`,`ruby`,`c`,`cpp`,`react`],s={python:{stateMutation:90,structuralCoordination:350},ruby:{stateMutation:90,structuralCoordination:350},react:{import:30}};function c(e,t,n){let r=e.thresholds,i=e.profileThresholds[t];return i&&(r={...r,...i}),n&&e.profileThresholds.react&&(r={...r,...e.profileThresholds.react}),r}const l={fileLoc:`fileLocThreshold`,functionLoc:`functionLocThreshold`,componentLoc:`componentLocThreshold`,cognitive:`cognitiveThreshold`,cyclomatic:`cyclomaticThreshold`,call:`callThreshold`,import:`importThreshold`,fanOut:`fanOutThreshold`,parameter:`parameterThreshold`,duplicateBlock:`duplicateBlockThreshold`,duplicationRatioPercent:`duplicationRatioPercentThreshold`,crossFileDuplicateBlock:`crossFileDuplicateBlockThreshold`,transitiveDependency:`transitiveDependencyThreshold`,structuralBreadth:`structuralBreadthThreshold`,structuralCoordination:`structuralCoordinationThreshold`,stateMutation:`stateMutationThreshold`,duplicateSymbolGroup:`duplicateSymbolGroupThreshold`};function u(t,n){let r={...i};for(let e of Object.keys(r))r[e]=t[l[e]]??n.thresholds?.[e]??r[e];return{thresholds:r,duplication:{minTokens:t.duplicationMinTokens??n.duplication?.minTokens??e.minTokens,maxGapTokens:t.duplicationMaxGapTokens??n.duplication?.maxGapTokens??e.maxGapTokens,minSimilarityPercent:t.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??e.minSimilarityPercent},profileThresholds:d(s,n.languageThresholds),maxFindings:t.maxFindings??n.maxFindings??20,largestFiles:t.largestFiles??n.largestFiles??0,includeTests:t.includeTests??n.includeTests??!1,failOnRisk:t.failOnRisk??n.failOnRisk??!1,failOnError:t.failOnError??n.failOnError??!1,json:t.json??!1,tsconfig:t.tsconfig??n.tsconfig}}function d(e,t){let n={};for(let r of o){let i={...e[r],...t?.[r]};Object.keys(i).length>0&&(n[r]=i)}return n}async function f(e,n){let r=e??await p(n);if(!r)return{};let i;try{i=await t(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${x(e)}`)}return h(a,r)}async function p(e){let t=e;for(;;){let e=r.join(t,a);if(await m(e))return e;let n=r.dirname(t);if(n===t)return;t=n}}async function m(e){try{return(await n(e)).isFile()}catch{return!1}}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r={};if(n.thresholds!==void 0&&(r.thresholds=g(n.thresholds,`thresholds`,t)),n.duplication!==void 0&&(r.duplication=_(n.duplication,t)),n.languageThresholds!==void 0){if(typeof n.languageThresholds!=`object`||n.languageThresholds===null||Array.isArray(n.languageThresholds))throw Error(`Config file "${t}": "languageThresholds" must be an object.`);let e={};for(let[r,i]of Object.entries(n.languageThresholds)){if(!o.includes(r))throw Error(`Config file "${t}": unknown language profile "${r}" (expected one of ${o.join(`, `)}).`);e[r]=g(i,`languageThresholds.${r}`,t)}r.languageThresholds=e}n.maxFindings!==void 0&&(r.maxFindings=y(n.maxFindings,`maxFindings`,t)),n.largestFiles!==void 0&&(r.largestFiles=y(n.largestFiles,`largestFiles`,t));for(let e of[`includeTests`,`failOnRisk`,`failOnError`])n[e]!==void 0&&(r[e]=b(n[e],e,t));if(n.tsconfig!==void 0){if(typeof n.tsconfig!=`string`)throw TypeError(`Config file "${t}": "tsconfig" must be a string.`);r.tsconfig=n.tsconfig}return r}function g(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "${t}" must be an object.`);let r={};for(let[a,o]of Object.entries(e)){if(!(a in i))throw Error(`Config file "${n}": unknown threshold "${a}" in "${t}".`);let e=y(o,`${t}.${a}`,n);if(a===`duplicationRatioPercent`&&e>100)throw Error(`Config file "${n}": "${t}.${a}" must be between 1 and 100.`);r[a]=e}return r}function _(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=y(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=v(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=y(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function v(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`Config file "${n}": "${t}" must be a non-negative integer.`);return e}function y(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}export{a as configFileName,s as defaultProfileThresholds,i as defaultThresholds,f as loadConfig,o as profileKeys,u as resolveOptions,c as resolveThresholds};
1
+ import{defaultDuplicationOptions as e}from"./duplication.js";import{defaultGateOptions as t}from"./regressionGate.js";import{readFile as n,stat as r}from"node:fs/promises";import i from"node:path";const a=`code-gauge.config.json`;function o(t,n){return{duplication:{minTokens:t.duplicationMinTokens??n.duplication?.minTokens??e.minTokens,maxGapTokens:t.duplicationMaxGapTokens??n.duplication?.maxGapTokens??e.maxGapTokens,minSimilarityPercent:t.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??e.minSimilarityPercent},top:t.top??n.rank?.top??10,includeTests:t.includeTests??n.includeTests??!1,failOnError:t.failOnError??n.failOnError??!1,json:t.json??!1}}function s(e){return{newFunction:{...t.newFunction,...e.gate?.newFunction},tolerance:{...t.tolerance,...e.gate?.tolerance},matchSimilarityPercent:e.gate?.matchSimilarityPercent??t.matchSimilarityPercent}}async function c(e,t){let r=e??await l(t);if(!r)return{};let i;try{i=await n(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${x(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${x(e)}`)}return d(a,r)}async function l(e){let t=e;for(;;){let e=i.join(t,a);if(await u(e))return e;let n=i.dirname(t);if(n===t)return;t=n}}async function u(e){try{return(await r(e)).isFile()}catch{return!1}}function d(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=e,r=new Set([`duplication`,`rank`,`gate`,`includeTests`,`failOnError`]);for(let e of Object.keys(n))if(!r.has(e))throw Error(`Config file "${t}": unknown setting "${e}" (expected ${[...r].join(`, `)}).`);let i={};n.duplication!==void 0&&(i.duplication=h(n.duplication,t)),n.rank!==void 0&&(i.rank=f(n.rank,t)),n.gate!==void 0&&(i.gate=p(n.gate,t));for(let e of[`includeTests`,`failOnError`])n[e]!==void 0&&(i[e]=b(n[e],e,t));return i}function f(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=v(i,`rank.top`,t)}return n}function p(e,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${n}": "gate" must be an object.`);let r={};for(let[i,a]of Object.entries(e))if(i===`newFunction`)r.newFunction=m(a,`gate.newFunction`,Object.keys(t.newFunction),n,_);else if(i===`tolerance`)r.tolerance=m(a,`gate.tolerance`,Object.keys(t.tolerance),n,g);else if(i===`matchSimilarityPercent`){let e=v(a,`gate.matchSimilarityPercent`,n);if(e>100)throw Error(`Config file "${n}": "gate.matchSimilarityPercent" must be between 1 and 100.`);r.matchSimilarityPercent=e}else throw Error(`Config file "${n}": unknown setting "${i}" in "gate" (expected newFunction, tolerance, or matchSimilarityPercent).`);return r}function m(e,t,n,r,i){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${r}": "${t}" must be an object.`);let a={};for(let[o,s]of Object.entries(e)){if(!n.includes(o))throw Error(`Config file "${r}": unknown setting "${o}" in "${t}" (expected ${n.join(`, `)}).`);a[o]=i(s,`${t}.${o}`,r)}return a}function h(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=v(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=_(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=v(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function g(e,t,n){return y(e,t,n,Number.isFinite,`a non-negative number`)}function _(e,t,n){return y(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function v(e,t,n){let r=y(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function y(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function b(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function x(e){return e instanceof Error?e.message:String(e)}export{a as configFileName,c as loadConfig,s as resolveGateOptions,o as resolveOptions};
2
2
  //# sourceMappingURL=cliConfig.js.map