code-gauge 3.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 (55) hide show
  1. package/README.md +67 -6
  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 +11 -0
  9. package/dist/cliConfig.js +1 -1
  10. package/dist/cliConfig.js.map +1 -1
  11. package/dist/depDegree.cjs +2 -0
  12. package/dist/depDegree.cjs.map +1 -0
  13. package/dist/depDegree.d.ts +12 -0
  14. package/dist/depDegree.js +2 -0
  15. package/dist/depDegree.js.map +1 -0
  16. package/dist/diffCommand.cjs +5 -0
  17. package/dist/diffCommand.cjs.map +1 -0
  18. package/dist/diffCommand.d.ts +17 -0
  19. package/dist/diffCommand.js +5 -0
  20. package/dist/diffCommand.js.map +1 -0
  21. package/dist/duplication.cjs +1 -1
  22. package/dist/duplication.cjs.map +1 -1
  23. package/dist/duplication.d.ts +10 -0
  24. package/dist/duplication.js +1 -1
  25. package/dist/duplication.js.map +1 -1
  26. package/dist/git.cjs +2 -0
  27. package/dist/git.cjs.map +1 -0
  28. package/dist/git.d.ts +27 -0
  29. package/dist/git.js +2 -0
  30. package/dist/git.js.map +1 -0
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +1 -1
  34. package/dist/metrics.cjs +1 -1
  35. package/dist/metrics.cjs.map +1 -1
  36. package/dist/metrics.d.ts +11 -0
  37. package/dist/metrics.js +1 -1
  38. package/dist/metrics.js.map +1 -1
  39. package/dist/nativeMetrics.cjs +1 -1
  40. package/dist/nativeMetrics.cjs.map +1 -1
  41. package/dist/nativeMetrics.d.ts +6 -2
  42. package/dist/nativeMetrics.js +1 -1
  43. package/dist/nativeMetrics.js.map +1 -1
  44. package/dist/regressionGate.cjs +2 -0
  45. package/dist/regressionGate.cjs.map +1 -0
  46. package/dist/regressionGate.d.ts +106 -0
  47. package/dist/regressionGate.js +2 -0
  48. package/dist/regressionGate.js.map +1 -0
  49. package/dist/scan.cjs +2 -0
  50. package/dist/scan.cjs.map +1 -0
  51. package/dist/scan.d.ts +55 -0
  52. package/dist/scan.js +2 -0
  53. package/dist/scan.js.map +1 -0
  54. package/dist/types.d.ts +13 -0
  55. package/package.json +1 -1
@@ -1,6 +1,13 @@
1
+ import { type GateOptions, type GateTolerances, type NewFunctionThresholds } from './regressionGate.js';
1
2
  import type { DuplicationOptions } from './types.js';
2
3
  export declare const configFileName = "code-gauge.config.json";
3
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
+ }
4
11
  /** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */
5
12
  export interface CodeGaugeConfig {
6
13
  /** Duplication detection settings applied to every measured file. */
@@ -9,6 +16,8 @@ export interface CodeGaugeConfig {
9
16
  rank?: {
10
17
  top?: number;
11
18
  };
19
+ /** Regression-gate settings for `code-gauge diff`. */
20
+ gate?: GateConfig;
12
21
  includeTests?: boolean;
13
22
  failOnError?: boolean;
14
23
  }
@@ -34,6 +43,8 @@ export interface ResolvedOptions {
34
43
  }
35
44
  /** Resolves options with precedence command-line flags > configuration file > built-in defaults. */
36
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;
37
48
  /**
38
49
  * Loads the configuration file. An explicit path must exist; otherwise the nearest
39
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=`code-gauge.config.json`;function a(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}}async function o(e,n){let r=e??await s(n);if(!r)return{};let i;try{i=await t(r,`utf8`)}catch(t){if(e)throw Error(`Cannot read config file "${r}": ${h(t)}`);return{}}let a;try{a=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${r}": ${h(e)}`)}return l(a,r)}async function s(e){let t=e;for(;;){let e=r.join(t,i);if(await c(e))return e;let n=r.dirname(t);if(n===t)return;t=n}}async function c(e){try{return(await n(e)).isFile()}catch{return!1}}function l(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`,`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=d(n.duplication,t)),n.rank!==void 0&&(i.rank=u(n.rank,t));for(let e of[`includeTests`,`failOnError`])n[e]!==void 0&&(i[e]=m(n[e],e,t));return i}function u(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=p(i,`rank.top`,t)}return n}function d(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=p(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=f(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=p(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 f(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 p(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 m(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}function h(e){return e instanceof Error?e.message:String(e)}export{i as configFileName,o as loadConfig,a as resolveOptions};
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
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\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 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/**\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', '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 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 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":"4IAKA,MAAa,EAAiB,yBAoC9B,SAAgB,EAAe,EAAiB,EAA0C,CACxF,MAAO,CACL,YAAa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F,GAAI,IAAQ,eAEjB,EAAY,aAAe,EAA0B,EAAS,2BAA4B,CAAU,OAC/F,GAAI,IAAQ,uBAAwB,CACzC,IAAM,EAAS,EAAuB,EAAS,mCAAoC,CAAU,EAC7F,GAAI,EAAS,IACX,MAAU,MAAM,gBAAgB,EAAW,iEAAiE,EAE9G,EAAY,qBAAuB,CACrC,MACE,MAAU,MACR,gBAAgB,EAAW,sBAAsB,EAAI,gFACvD,EAGJ,OAAO,CACT,CAEA,SAAS,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,kCAAkC,EAEzF,OAAO,CACT,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,GAAI,OAAO,GAAU,UAAY,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EACvE,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT,CAEA,SAAS,EAAY,EAAwB,CAC3C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport {\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":"qMAWA,MAAa,EAAiB,yBA6C9B,SAAgB,EAAe,EAAiB,EAA0C,CACxF,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAa,EAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgB,EAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpB,EAA0B,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,GAAG,EAAmB,YAAa,GAAG,EAAO,MAAM,WAAY,EAC9E,UAAW,CAAE,GAAG,EAAmB,UAAW,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S,EAAyB,EAAgB,EAAa,EAA4B,CACzF,OAAO,EAAc,EAAO,EAAK,EAAY,OAAO,SAAU,uBAAuB,CACvF,CAEA,SAAS,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,OAAO,EAAc,EAAO,EAAK,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"}
@@ -0,0 +1,2 @@
1
+ "use strict";const e=new Set([`identifier`,`instance_variable`,`class_variable`,`global_variable`]),t=new Set([`=`,`:=`]),n=new Set([`+=`,`-=`,`*=`,`/=`,`%=`,`**=`,`//=`,`<<=`,`>>=`,`>>>=`,`&=`,`|=`,`^=`,`&&=`,`||=`,`??=`,`@=`,`&^=`]),r=new Map([[`variable_declarator`,`name`],[`let_declaration`,`pattern`],[`assignment`,`left`],[`var_spec`,`name`],[`init_declarator`,`declarator`],[`enhanced_for_statement`,`name`],[`for_statement`,`left`],[`for_in_statement`,`left`],[`for_in_clause`,`left`],[`for_range_loop`,`declarator`],[`for_expression`,`pattern`]]),i=new Set([`expression_list`,`pattern_list`,`tuple_pattern`]),a=new Set([`assignment`,`assignment_statement`,`short_var_declaration`,`for_statement`,`for_in_clause`,`range_clause`]),o=new Set([`type`,`value`]);function s(r,i){let a=[];c(r,void 0,``,{nextScopeId:0},i,a,!0);let o=new Map,s=0;for(let[r,i]of a.entries()){if(!e.has(i.node.type))continue;let c=i.node.text,p=a[r+1]?.node.text;if(p!==void 0&&n.has(p)){u(o.get(c),i.scope)&&(s+=1),l(o,c,i.scope);continue}if(p!==void 0&&t.has(p)||d(i)||f(i)){l(o,c,i.scope);continue}u(o.get(c),i.scope)&&(s+=1)}return s}function c(e,t,n,r,i,a,o){if(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)return;if(e.childCount===0){a.push({node:e,fieldName:t,scope:n});return}let s=!o&&i(e)?`${n}/${r.nextScopeId++}`:n,l=e.walk();if(l.gotoFirstChild())do c(l.currentNode,l.currentFieldName??void 0,s,r,i,a,!1);while(l.gotoNextSibling())}function l(e,t,n){let r=e.get(t)??[];r.includes(n)||(r.push(n),e.set(t,r))}function u(e,t){return e!==void 0&&e.some(e=>t===e||t.startsWith(`${e}/`))}function d(e){let t=e.node.parent;if(!t)return!1;let n=r.get(t.type);if(n!==void 0&&n===e.fieldName)return!0;if(!i.has(t.type))return!1;let o=t.parent;return o!==null&&a.has(o.type)&&p(t,o)===`left`}function f(e){let t=e.node;for(let n=0;;n+=1){let r=t.parent;if(!r)return!1;let i=r.type.includes(`parameter`);if(n>=1&&!i&&!r.type.includes(`declarator`))return!1;let a=n===0?e.fieldName:p(t,r);if(a!==void 0&&o.has(a))return!1;if(i||n===0&&(a?.includes(`parameter`)??!1))return!0;t=r}}function p(e,t){for(let n=0;n<t.childCount;n+=1)if(t.child(n)?.id===e.id)return t.fieldNameForChild(n)??void 0}exports.measureDepDegree=s;
2
+ //# sourceMappingURL=depDegree.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"depDegree.cjs","names":[],"sources":["../src/depDegree.ts"],"sourcesContent":["import type Parser from 'tree-sitter';\n\n/** Leaf node types treated as variable references by the def-use approximation. */\nconst variableNodeTypes = new Set(['identifier', 'instance_variable', 'class_variable', 'global_variable']);\n\n/** Tokens directly after a variable that write it without reading it (`x = 1`, `x := 1`). */\nconst pureAssignmentOperators = new Set(['=', ':=']);\n\n/** Tokens directly after a variable that read then write it (`x += 1` depends on x's definition). */\nconst compoundAssignmentOperators = new Set([\n '+=',\n '-=',\n '*=',\n '/=',\n '%=',\n '**=',\n '//=',\n '<<=',\n '>>=',\n '>>>=',\n '&=',\n '|=',\n '^=',\n '&&=',\n '||=',\n '??=',\n '@=',\n '&^=',\n]);\n\n/**\n * Parent type -> field under which an identifier is a definition target even when a type\n * annotation separates it from the `=` token (`const x: T = ...`, `let x: T = ...`,\n * `x: int = ...`, `var x T = ...`), plus loop bindings that carry no assignment token at all.\n */\nconst definitionFieldByParentType = new Map([\n ['variable_declarator', 'name'],\n ['let_declaration', 'pattern'],\n ['assignment', 'left'],\n ['var_spec', 'name'],\n ['init_declarator', 'declarator'],\n ['enhanced_for_statement', 'name'],\n ['for_statement', 'left'],\n ['for_in_statement', 'left'],\n ['for_in_clause', 'left'],\n ['for_range_loop', 'declarator'],\n ['for_expression', 'pattern'],\n]);\n\n/** Multi-target lists (`a, b = ...`, `a, b := ...`) whose holder's `left` field marks definitions. */\nconst definitionListNodeTypes = new Set(['expression_list', 'pattern_list', 'tuple_pattern']);\nconst definitionListHolderTypes = new Set([\n 'assignment',\n 'assignment_statement',\n 'short_var_declaration',\n 'for_statement',\n 'for_in_clause',\n 'range_clause',\n]);\n\n/** Parameter-position fields that annotate or initialize rather than bind (`x: T`, `x = default`). */\nconst nonBindingParameterFields = new Set(['type', 'value']);\n\n/** One leaf of the def-use walk: its field in the parent and its function-scope chain. */\ninterface DepDegreeLeaf {\n node: Parser.SyntaxNode;\n fieldName: string | undefined;\n /** Chain of nested-function scope ids below the measured function: '' for its own body, then '/0', '/0/1', ... */\n scope: string;\n}\n\n/**\n * Approximate def-use pairs of the function's subtree (see FunctionMetrics.depDegree): the number\n * of variable reads with a preceding same-name definition visible at the read. Definitions are\n * recognized token-wise (a variable directly followed by an assignment operator), structurally\n * (declarator/assignment/loop-binding fields, so annotated declarations count), and positionally\n * (parameters). Nested function subtrees are included, but their definitions are scoped: an inner\n * function's parameters and locals cannot reach reads outside it, while inner reads still see\n * outer definitions (closure captures). Reads through destructuring patterns and member accesses\n * are not modeled; the approximation only needs to be stable, since the gate compares deltas.\n */\nexport function measureDepDegree(\n functionNode: Parser.SyntaxNode,\n isNestedFunctionBoundary: (node: Parser.SyntaxNode) => boolean\n): number {\n const leaves: DepDegreeLeaf[] = [];\n collectDepDegreeLeaves(functionNode, undefined, '', { nextScopeId: 0 }, isNestedFunctionBoundary, leaves, true);\n const definitionScopesByName = new Map<string, string[]>();\n let pairs = 0;\n for (const [index, leaf] of leaves.entries()) {\n if (!variableNodeTypes.has(leaf.node.type)) {\n continue;\n }\n const name = leaf.node.text;\n const nextText = leaves[index + 1]?.node.text;\n if (nextText !== undefined && compoundAssignmentOperators.has(nextText)) {\n if (isDefinitionVisible(definitionScopesByName.get(name), leaf.scope)) {\n pairs += 1;\n }\n addDefinition(definitionScopesByName, name, leaf.scope);\n continue;\n }\n if (\n (nextText !== undefined && pureAssignmentOperators.has(nextText)) ||\n isStructuralDefinition(leaf) ||\n isParameterDefinition(leaf)\n ) {\n addDefinition(definitionScopesByName, name, leaf.scope);\n continue;\n }\n if (isDefinitionVisible(definitionScopesByName.get(name), leaf.scope)) {\n pairs += 1;\n }\n }\n return pairs;\n}\n\n/**\n * Collects non-comment leaves with their parent field — taken from one cursor pass, so a child of\n * a high-arity node (a long array literal) costs O(1) instead of an O(children) scan — and their\n * function-scope chain (each nested function boundary below the measured function opens a child\n * scope).\n */\nfunction collectDepDegreeLeaves(\n node: Parser.SyntaxNode,\n fieldName: string | undefined,\n scope: string,\n state: { nextScopeId: number },\n isNestedFunctionBoundary: (node: Parser.SyntaxNode) => boolean,\n leaves: DepDegreeLeaf[],\n isMeasuredRoot: boolean\n): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n if (node.childCount === 0) {\n leaves.push({ node, fieldName, scope });\n return;\n }\n const childScope = !isMeasuredRoot && isNestedFunctionBoundary(node) ? `${scope}/${state.nextScopeId++}` : scope;\n const cursor = node.walk();\n if (cursor.gotoFirstChild()) {\n do {\n collectDepDegreeLeaves(\n cursor.currentNode,\n cursor.currentFieldName ?? undefined,\n childScope,\n state,\n isNestedFunctionBoundary,\n leaves,\n false\n );\n } while (cursor.gotoNextSibling());\n }\n}\n\nfunction addDefinition(definitionScopesByName: Map<string, string[]>, name: string, scope: string): void {\n const scopes = definitionScopesByName.get(name) ?? [];\n if (!scopes.includes(scope)) {\n scopes.push(scope);\n definitionScopesByName.set(name, scopes);\n }\n}\n\n/** A definition reaches a read only from the read's own or an enclosing function scope. */\nfunction isDefinitionVisible(definitionScopes: string[] | undefined, scope: string): boolean {\n return (\n definitionScopes !== undefined &&\n definitionScopes.some((definitionScope) => scope === definitionScope || scope.startsWith(`${definitionScope}/`))\n );\n}\n\nfunction isStructuralDefinition(leaf: DepDegreeLeaf): boolean {\n const parent = leaf.node.parent;\n if (!parent) {\n return false;\n }\n const definitionField = definitionFieldByParentType.get(parent.type);\n if (definitionField !== undefined && definitionField === leaf.fieldName) {\n return true;\n }\n if (!definitionListNodeTypes.has(parent.type)) {\n return false;\n }\n const holder = parent.parent;\n return holder !== null && definitionListHolderTypes.has(holder.type) && fieldNameInParent(parent, holder) === 'left';\n}\n\n/**\n * Whether the identifier binds a parameter: an ancestor reached through declarator wrappers (C/C++\n * function-pointer or array parameters) is a parameter-ish node, or it directly occupies a\n * parameter field (bare arrow-function/lambda parameters, catch-clause bindings). Type annotations\n * and default values inside parameter nodes bind nothing.\n */\nfunction isParameterDefinition(leaf: DepDegreeLeaf): boolean {\n let current = leaf.node;\n for (let depth = 0; ; depth += 1) {\n const parent = current.parent;\n if (!parent) {\n return false;\n }\n const parentIsParameterish = parent.type.includes('parameter');\n // Beyond the grandparent, only declarator wrappers keep climbing; checking this before the\n // field lookup also keeps reads inside high-arity nodes (long array literals) O(1).\n if (depth >= 1 && !parentIsParameterish && !parent.type.includes('declarator')) {\n return false;\n }\n const field = depth === 0 ? leaf.fieldName : fieldNameInParent(current, parent);\n if (field !== undefined && nonBindingParameterFields.has(field)) {\n return false;\n }\n if (parentIsParameterish || (depth === 0 && (field?.includes('parameter') ?? false))) {\n return true;\n }\n current = parent;\n }\n}\n\n/** Only called with small-arity parents (declarator wrappers, definition-list holders). */\nfunction fieldNameInParent(node: Parser.SyntaxNode, parent: Parser.SyntaxNode): string | undefined {\n for (let index = 0; index < parent.childCount; index += 1) {\n if (parent.child(index)?.id === node.id) {\n return parent.fieldNameForChild(index) ?? undefined;\n }\n }\n return undefined;\n}\n"],"mappings":"aAGA,MAAM,EAAoB,IAAI,IAAI,CAAC,aAAc,oBAAqB,iBAAkB,iBAAiB,CAAC,EAGpG,EAA0B,IAAI,IAAI,CAAC,IAAK,IAAI,CAAC,EAG7C,EAA8B,IAAI,IAAI,CAC1C,KACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,KACA,KACA,KACA,MACA,MACA,MACA,KACA,KACF,CAAC,EAOK,EAA8B,IAAI,IAAI,CAC1C,CAAC,sBAAuB,MAAM,EAC9B,CAAC,kBAAmB,SAAS,EAC7B,CAAC,aAAc,MAAM,EACrB,CAAC,WAAY,MAAM,EACnB,CAAC,kBAAmB,YAAY,EAChC,CAAC,yBAA0B,MAAM,EACjC,CAAC,gBAAiB,MAAM,EACxB,CAAC,mBAAoB,MAAM,EAC3B,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,YAAY,EAC/B,CAAC,iBAAkB,SAAS,CAC9B,CAAC,EAGK,EAA0B,IAAI,IAAI,CAAC,kBAAmB,eAAgB,eAAe,CAAC,EACtF,EAA4B,IAAI,IAAI,CACxC,aACA,uBACA,wBACA,gBACA,gBACA,cACF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,IAAI,EAAQ,EAAG,EAAQ,EAAO,WAAY,GAAS,EACtD,GAAI,EAAO,MAAM,CAAK,CAAC,EAAE,KAAO,EAAK,GACnC,OAAO,EAAO,kBAAkB,CAAK,GAAK,IAAA,EAIhD"}
@@ -0,0 +1,12 @@
1
+ import type Parser from 'tree-sitter';
2
+ /**
3
+ * Approximate def-use pairs of the function's subtree (see FunctionMetrics.depDegree): the number
4
+ * of variable reads with a preceding same-name definition visible at the read. Definitions are
5
+ * recognized token-wise (a variable directly followed by an assignment operator), structurally
6
+ * (declarator/assignment/loop-binding fields, so annotated declarations count), and positionally
7
+ * (parameters). Nested function subtrees are included, but their definitions are scoped: an inner
8
+ * function's parameters and locals cannot reach reads outside it, while inner reads still see
9
+ * outer definitions (closure captures). Reads through destructuring patterns and member accesses
10
+ * are not modeled; the approximation only needs to be stable, since the gate compares deltas.
11
+ */
12
+ export declare function measureDepDegree(functionNode: Parser.SyntaxNode, isNestedFunctionBoundary: (node: Parser.SyntaxNode) => boolean): number;
@@ -0,0 +1,2 @@
1
+ const e=new Set([`identifier`,`instance_variable`,`class_variable`,`global_variable`]),t=new Set([`=`,`:=`]),n=new Set([`+=`,`-=`,`*=`,`/=`,`%=`,`**=`,`//=`,`<<=`,`>>=`,`>>>=`,`&=`,`|=`,`^=`,`&&=`,`||=`,`??=`,`@=`,`&^=`]),r=new Map([[`variable_declarator`,`name`],[`let_declaration`,`pattern`],[`assignment`,`left`],[`var_spec`,`name`],[`init_declarator`,`declarator`],[`enhanced_for_statement`,`name`],[`for_statement`,`left`],[`for_in_statement`,`left`],[`for_in_clause`,`left`],[`for_range_loop`,`declarator`],[`for_expression`,`pattern`]]),i=new Set([`expression_list`,`pattern_list`,`tuple_pattern`]),a=new Set([`assignment`,`assignment_statement`,`short_var_declaration`,`for_statement`,`for_in_clause`,`range_clause`]),o=new Set([`type`,`value`]);function s(r,i){let a=[];c(r,void 0,``,{nextScopeId:0},i,a,!0);let o=new Map,s=0;for(let[r,i]of a.entries()){if(!e.has(i.node.type))continue;let c=i.node.text,p=a[r+1]?.node.text;if(p!==void 0&&n.has(p)){u(o.get(c),i.scope)&&(s+=1),l(o,c,i.scope);continue}if(p!==void 0&&t.has(p)||d(i)||f(i)){l(o,c,i.scope);continue}u(o.get(c),i.scope)&&(s+=1)}return s}function c(e,t,n,r,i,a,o){if(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)return;if(e.childCount===0){a.push({node:e,fieldName:t,scope:n});return}let s=!o&&i(e)?`${n}/${r.nextScopeId++}`:n,l=e.walk();if(l.gotoFirstChild())do c(l.currentNode,l.currentFieldName??void 0,s,r,i,a,!1);while(l.gotoNextSibling())}function l(e,t,n){let r=e.get(t)??[];r.includes(n)||(r.push(n),e.set(t,r))}function u(e,t){return e!==void 0&&e.some(e=>t===e||t.startsWith(`${e}/`))}function d(e){let t=e.node.parent;if(!t)return!1;let n=r.get(t.type);if(n!==void 0&&n===e.fieldName)return!0;if(!i.has(t.type))return!1;let o=t.parent;return o!==null&&a.has(o.type)&&p(t,o)===`left`}function f(e){let t=e.node;for(let n=0;;n+=1){let r=t.parent;if(!r)return!1;let i=r.type.includes(`parameter`);if(n>=1&&!i&&!r.type.includes(`declarator`))return!1;let a=n===0?e.fieldName:p(t,r);if(a!==void 0&&o.has(a))return!1;if(i||n===0&&(a?.includes(`parameter`)??!1))return!0;t=r}}function p(e,t){for(let n=0;n<t.childCount;n+=1)if(t.child(n)?.id===e.id)return t.fieldNameForChild(n)??void 0}export{s as measureDepDegree};
2
+ //# sourceMappingURL=depDegree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"depDegree.js","names":[],"sources":["../src/depDegree.ts"],"sourcesContent":["import type Parser from 'tree-sitter';\n\n/** Leaf node types treated as variable references by the def-use approximation. */\nconst variableNodeTypes = new Set(['identifier', 'instance_variable', 'class_variable', 'global_variable']);\n\n/** Tokens directly after a variable that write it without reading it (`x = 1`, `x := 1`). */\nconst pureAssignmentOperators = new Set(['=', ':=']);\n\n/** Tokens directly after a variable that read then write it (`x += 1` depends on x's definition). */\nconst compoundAssignmentOperators = new Set([\n '+=',\n '-=',\n '*=',\n '/=',\n '%=',\n '**=',\n '//=',\n '<<=',\n '>>=',\n '>>>=',\n '&=',\n '|=',\n '^=',\n '&&=',\n '||=',\n '??=',\n '@=',\n '&^=',\n]);\n\n/**\n * Parent type -> field under which an identifier is a definition target even when a type\n * annotation separates it from the `=` token (`const x: T = ...`, `let x: T = ...`,\n * `x: int = ...`, `var x T = ...`), plus loop bindings that carry no assignment token at all.\n */\nconst definitionFieldByParentType = new Map([\n ['variable_declarator', 'name'],\n ['let_declaration', 'pattern'],\n ['assignment', 'left'],\n ['var_spec', 'name'],\n ['init_declarator', 'declarator'],\n ['enhanced_for_statement', 'name'],\n ['for_statement', 'left'],\n ['for_in_statement', 'left'],\n ['for_in_clause', 'left'],\n ['for_range_loop', 'declarator'],\n ['for_expression', 'pattern'],\n]);\n\n/** Multi-target lists (`a, b = ...`, `a, b := ...`) whose holder's `left` field marks definitions. */\nconst definitionListNodeTypes = new Set(['expression_list', 'pattern_list', 'tuple_pattern']);\nconst definitionListHolderTypes = new Set([\n 'assignment',\n 'assignment_statement',\n 'short_var_declaration',\n 'for_statement',\n 'for_in_clause',\n 'range_clause',\n]);\n\n/** Parameter-position fields that annotate or initialize rather than bind (`x: T`, `x = default`). */\nconst nonBindingParameterFields = new Set(['type', 'value']);\n\n/** One leaf of the def-use walk: its field in the parent and its function-scope chain. */\ninterface DepDegreeLeaf {\n node: Parser.SyntaxNode;\n fieldName: string | undefined;\n /** Chain of nested-function scope ids below the measured function: '' for its own body, then '/0', '/0/1', ... */\n scope: string;\n}\n\n/**\n * Approximate def-use pairs of the function's subtree (see FunctionMetrics.depDegree): the number\n * of variable reads with a preceding same-name definition visible at the read. Definitions are\n * recognized token-wise (a variable directly followed by an assignment operator), structurally\n * (declarator/assignment/loop-binding fields, so annotated declarations count), and positionally\n * (parameters). Nested function subtrees are included, but their definitions are scoped: an inner\n * function's parameters and locals cannot reach reads outside it, while inner reads still see\n * outer definitions (closure captures). Reads through destructuring patterns and member accesses\n * are not modeled; the approximation only needs to be stable, since the gate compares deltas.\n */\nexport function measureDepDegree(\n functionNode: Parser.SyntaxNode,\n isNestedFunctionBoundary: (node: Parser.SyntaxNode) => boolean\n): number {\n const leaves: DepDegreeLeaf[] = [];\n collectDepDegreeLeaves(functionNode, undefined, '', { nextScopeId: 0 }, isNestedFunctionBoundary, leaves, true);\n const definitionScopesByName = new Map<string, string[]>();\n let pairs = 0;\n for (const [index, leaf] of leaves.entries()) {\n if (!variableNodeTypes.has(leaf.node.type)) {\n continue;\n }\n const name = leaf.node.text;\n const nextText = leaves[index + 1]?.node.text;\n if (nextText !== undefined && compoundAssignmentOperators.has(nextText)) {\n if (isDefinitionVisible(definitionScopesByName.get(name), leaf.scope)) {\n pairs += 1;\n }\n addDefinition(definitionScopesByName, name, leaf.scope);\n continue;\n }\n if (\n (nextText !== undefined && pureAssignmentOperators.has(nextText)) ||\n isStructuralDefinition(leaf) ||\n isParameterDefinition(leaf)\n ) {\n addDefinition(definitionScopesByName, name, leaf.scope);\n continue;\n }\n if (isDefinitionVisible(definitionScopesByName.get(name), leaf.scope)) {\n pairs += 1;\n }\n }\n return pairs;\n}\n\n/**\n * Collects non-comment leaves with their parent field — taken from one cursor pass, so a child of\n * a high-arity node (a long array literal) costs O(1) instead of an O(children) scan — and their\n * function-scope chain (each nested function boundary below the measured function opens a child\n * scope).\n */\nfunction collectDepDegreeLeaves(\n node: Parser.SyntaxNode,\n fieldName: string | undefined,\n scope: string,\n state: { nextScopeId: number },\n isNestedFunctionBoundary: (node: Parser.SyntaxNode) => boolean,\n leaves: DepDegreeLeaf[],\n isMeasuredRoot: boolean\n): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n if (node.childCount === 0) {\n leaves.push({ node, fieldName, scope });\n return;\n }\n const childScope = !isMeasuredRoot && isNestedFunctionBoundary(node) ? `${scope}/${state.nextScopeId++}` : scope;\n const cursor = node.walk();\n if (cursor.gotoFirstChild()) {\n do {\n collectDepDegreeLeaves(\n cursor.currentNode,\n cursor.currentFieldName ?? undefined,\n childScope,\n state,\n isNestedFunctionBoundary,\n leaves,\n false\n );\n } while (cursor.gotoNextSibling());\n }\n}\n\nfunction addDefinition(definitionScopesByName: Map<string, string[]>, name: string, scope: string): void {\n const scopes = definitionScopesByName.get(name) ?? [];\n if (!scopes.includes(scope)) {\n scopes.push(scope);\n definitionScopesByName.set(name, scopes);\n }\n}\n\n/** A definition reaches a read only from the read's own or an enclosing function scope. */\nfunction isDefinitionVisible(definitionScopes: string[] | undefined, scope: string): boolean {\n return (\n definitionScopes !== undefined &&\n definitionScopes.some((definitionScope) => scope === definitionScope || scope.startsWith(`${definitionScope}/`))\n );\n}\n\nfunction isStructuralDefinition(leaf: DepDegreeLeaf): boolean {\n const parent = leaf.node.parent;\n if (!parent) {\n return false;\n }\n const definitionField = definitionFieldByParentType.get(parent.type);\n if (definitionField !== undefined && definitionField === leaf.fieldName) {\n return true;\n }\n if (!definitionListNodeTypes.has(parent.type)) {\n return false;\n }\n const holder = parent.parent;\n return holder !== null && definitionListHolderTypes.has(holder.type) && fieldNameInParent(parent, holder) === 'left';\n}\n\n/**\n * Whether the identifier binds a parameter: an ancestor reached through declarator wrappers (C/C++\n * function-pointer or array parameters) is a parameter-ish node, or it directly occupies a\n * parameter field (bare arrow-function/lambda parameters, catch-clause bindings). Type annotations\n * and default values inside parameter nodes bind nothing.\n */\nfunction isParameterDefinition(leaf: DepDegreeLeaf): boolean {\n let current = leaf.node;\n for (let depth = 0; ; depth += 1) {\n const parent = current.parent;\n if (!parent) {\n return false;\n }\n const parentIsParameterish = parent.type.includes('parameter');\n // Beyond the grandparent, only declarator wrappers keep climbing; checking this before the\n // field lookup also keeps reads inside high-arity nodes (long array literals) O(1).\n if (depth >= 1 && !parentIsParameterish && !parent.type.includes('declarator')) {\n return false;\n }\n const field = depth === 0 ? leaf.fieldName : fieldNameInParent(current, parent);\n if (field !== undefined && nonBindingParameterFields.has(field)) {\n return false;\n }\n if (parentIsParameterish || (depth === 0 && (field?.includes('parameter') ?? false))) {\n return true;\n }\n current = parent;\n }\n}\n\n/** Only called with small-arity parents (declarator wrappers, definition-list holders). */\nfunction fieldNameInParent(node: Parser.SyntaxNode, parent: Parser.SyntaxNode): string | undefined {\n for (let index = 0; index < parent.childCount; index += 1) {\n if (parent.child(index)?.id === node.id) {\n return parent.fieldNameForChild(index) ?? undefined;\n }\n }\n return undefined;\n}\n"],"mappings":"AAGA,MAAM,EAAoB,IAAI,IAAI,CAAC,aAAc,oBAAqB,iBAAkB,iBAAiB,CAAC,EAGpG,EAA0B,IAAI,IAAI,CAAC,IAAK,IAAI,CAAC,EAG7C,EAA8B,IAAI,IAAI,CAC1C,KACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,KACA,KACA,KACA,MACA,MACA,MACA,KACA,KACF,CAAC,EAOK,EAA8B,IAAI,IAAI,CAC1C,CAAC,sBAAuB,MAAM,EAC9B,CAAC,kBAAmB,SAAS,EAC7B,CAAC,aAAc,MAAM,EACrB,CAAC,WAAY,MAAM,EACnB,CAAC,kBAAmB,YAAY,EAChC,CAAC,yBAA0B,MAAM,EACjC,CAAC,gBAAiB,MAAM,EACxB,CAAC,mBAAoB,MAAM,EAC3B,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,YAAY,EAC/B,CAAC,iBAAkB,SAAS,CAC9B,CAAC,EAGK,EAA0B,IAAI,IAAI,CAAC,kBAAmB,eAAgB,eAAe,CAAC,EACtF,EAA4B,IAAI,IAAI,CACxC,aACA,uBACA,wBACA,gBACA,gBACA,cACF,CAAC,EAGK,EAA4B,IAAI,IAAI,CAAC,OAAQ,OAAO,CAAC,EAoB3D,SAAgB,EACd,EACA,EACQ,CACR,IAAM,EAA0B,CAAC,EACjC,EAAuB,EAAc,IAAA,GAAW,GAAI,CAAE,YAAa,CAAE,EAAG,EA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 "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./crossFileDuplication.cjs"),n=require("./metrics.cjs"),r=require("./regressionGate.cjs"),i=require("./cliConfig.cjs"),a=require("./git.cjs"),o=require("./scan.cjs");let s=require("node:fs/promises"),c=require("node:path");c=e.__toESM(c,1);async function l(e,t){try{await u(e,t)}catch(e){o.writeStderr(`Error: ${o.formatError(e)}\n`),process.exitCode=2}}async function u(e,t){let n=o.resolveTarget(e),c=await i.loadConfig(t.config,await o.configSearchDirectory(n)),l=i.resolveOptions(t,c),u=i.resolveGateOptions(c),p=await(0,s.realpath)(await a.resolveRepoRoot(await v(await o.configSearchDirectory(n)))),m=await a.resolveMergeBase(p,t.base),h=await a.listChangedFiles(p,m),g=await a.listRepositoryFiles(p),_=await a.listSymlinkPathsAtRevision(p,m),y=await o.scanListedFiles(p,g,l),S=y.files.map(e=>({relativePath:o.formatPath(e.file,y.displayRoot),file:e})),C=new Set(h.flatMap(e=>[e.headPath,...e.basePath===void 0?[]:[e.basePath]]).filter(e=>o.isScannedPath(e,l))),T=[],E=[...y.warnings];for(let e of y.errors)[...C].some(t=>e.startsWith(`${t}:`))?T.push(e):E.push(e);let{canonicalTarget:D,targetExists:k}=await d(n),A=await f(h,{repoRoot:p,mergeBase:m,canonicalTarget:D,options:l,scannedFiles:S,baseSymlinkPaths:_},T,E);if(!k&&!A.some(e=>e.gated))throw Error(`target "${e}" does not exist and matches no changed file`);let{baseCross:j,headCross:M}=b(A,S,l),N=A.map(e=>x(e,j,M)),P=r.evaluateRegressionGate(N,u);t.json?O(t,m,P,N,T,E):w(t,m,P,T,E),T.length>0?process.exitCode=2:P.violations.length>0&&(process.exitCode=1)}async function d(e){try{return{canonicalTarget:await(0,s.realpath)(e),targetExists:!0}}catch{return{canonicalTarget:e,targetExists:!1}}}async function f(e,t,n,r){let i=new Map(t.scannedFiles.map(({relativePath:e,file:t})=>[e,t])),a=[];for(let o of e){let e=await p(o,t,i,n,r);e&&a.push(e)}return a}async function p(e,t,n,r,i){let a=e.status!==`deleted`&&o.isScannedPath(e.headPath,t.options)&&!await _(c.default.join(t.repoRoot,e.headPath)),s=e.basePath!==void 0&&o.isScannedPath(e.basePath,t.options)&&!t.baseSymlinkPaths.has(e.basePath);if(!a&&!s)return;let l=e.status===`deleted`?e.basePath:e.headPath,u=a?n.get(e.headPath):void 0;if(a&&!u){m(e.headPath,r);return}let d={changed:e,displayFile:l,gated:a||e.status===`deleted`?y(c.default.join(t.repoRoot,l),t.canonicalTarget):!1,headFile:u};if(!(s&&!await g(d,e.basePath,t,r,i)))return u&&await h(d,u,t,i),d}function m(e,t){t.some(t=>t.startsWith(`${e}:`))||t.push(`${e}: changed file was not measured`)}async function h(e,t,r,i){try{let i=await(0,s.readFile)(t.file,`utf8`);e.headFunctionTokens=n.collectFunctionTokenSequences(i,{language:o.getLanguage(e.changed.headPath,r.options),duplication:r.options.duplication})}catch(t){i.push(`${e.displayFile}: function token sequences unavailable: ${o.formatError(t)}`)}}async function g(e,t,r,i,s){let c={language:o.getLanguage(t,r.options),duplication:r.options.duplication},l;try{l=await a.readFileAtRevision(r.repoRoot,r.mergeBase,t),e.baseMetrics=n.measureCode(l,c)}catch(e){return i.push(`${t} (at merge-base): ${o.formatError(e)}`),!1}try{e.baseCandidates=n.collectCrossFileDuplicationFileData(l,c),e.baseFunctionTokens=n.collectFunctionTokenSequences(l,c)}catch(e){s.push(`${t} (at merge-base): duplication candidates and token sequences unavailable: ${o.formatError(e)}`)}return!0}async function _(e){return(await(0,s.lstat)(e).catch(()=>{}))?.isSymbolicLink()??!1}async function v(e){let t=e;for(;;){if((await(0,s.stat)(t).catch(()=>{}))?.isDirectory())return t;let e=c.default.dirname(t);if(e===t)return t;t=e}}function y(e,t){let n=c.default.relative(t,e);return n===``||!n.startsWith(`..${c.default.sep}`)&&n!==`..`&&!c.default.isAbsolute(n)}function b(e,n,r){let i=n.flatMap(({relativePath:e,file:t})=>t.duplicationCandidates?[{file:e,...t.duplicationCandidates}]:[]),a=new Set(e.flatMap(e=>e.changed.status===`deleted`?[]:[e.changed.headPath])),o=i.filter(e=>!a.has(e.file));for(let t of e)t.baseCandidates&&t.changed.basePath!==void 0&&o.push({file:t.changed.basePath,...t.baseCandidates});return{baseCross:o.length>=2?t.measureCrossFileDuplication(o,r.duplication):void 0,headCross:i.length>=2?t.measureCrossFileDuplication(i,r.duplication):void 0}}function x(e,t,n){return{file:e.displayFile,baseMetrics:e.baseMetrics,headMetrics:e.headFile?.metrics,baseFunctionTokens:e.baseFunctionTokens,headFunctionTokens:e.headFunctionTokens,baseDuplicatedLineCount:e.baseMetrics===void 0||e.changed.basePath===void 0?0:S(e.baseMetrics,t,e.changed.basePath),headDuplicatedLineCount:e.changed.status===`deleted`?0:S(e.headFile?.metrics,n,e.changed.headPath),duplicationPartners:C(n,e.changed.headPath),gated:e.gated}}function S(e,t,n){return o.collectDuplicatedLineNumbers(e,t,n).size}function C(e,t){if(!e)return[];let n=new Set;for(let r of e.groups)if(r.files.includes(t))for(let e of r.files)e!==t&&n.add(e);return[...n].toSorted()}function w(e,t,n,r,i){let a=t.slice(0,12);r.length>0?(o.writeStdout(`Regression gate could not complete: ${r.length} measurement failures (details on stderr)${n.violations.length>0?`; ${n.violations.length} violations in the measured files`:``} (base ${e.base}, merge-base ${a}).\n`),T(n)):n.violations.length===0?o.writeStdout(`Regression gate passed: ${n.checkedFileCount} changed files, ${n.checkedFunctionCount} functions checked (base ${e.base}, merge-base ${a}).\n`):(o.writeStdout(`Regression gate vs ${e.base} (merge-base ${a}): ${n.violations.length} violations\n`),T(n)),e.full&&E(n);for(let e of i)o.writeStderr(`Warning: ${e}\n`);for(let e of r)o.writeStderr(`Error: ${e}\n`)}function T(e){for(let[t,n]of e.violations.entries())o.writeStdout(`${t+1}. ${n.message}\n`)}function E(e){if(e.checkedFunctions.length!==0){o.writeStdout(`
2
+ Checked functions (base -> head):
3
+ `);for(let t of e.checkedFunctions)o.writeStdout(`- ${D(t)}\n`)}}function D(e){let t=(t,n=String)=>{let r=n(t(e.head));return e.base?`${n(t(e.base))} -> ${r}`:r},n=[`cognitive ${t(e=>e.cognitiveComplexity)}`,`NCSS ${t(e=>e.ncss)}`,`nesting ${t(e=>e.nestingDepth)}`,`DepDegree ${t(e=>e.depDegree)}`,`volume ${t(e=>e.halsteadVolume,e=>e.toFixed(1))}`];return`${e.file}:${e.startLine}-${e.endLine} ${e.name}${e.base?``:` (new)`}: ${n.join(`, `)}`}function O(e,t,n,r,i,a){let s={base:e.base,mergeBase:t,passed:n.violations.length===0&&i.length===0,violations:n.violations,checkedFileCount:n.checkedFileCount,checkedFunctionCount:n.checkedFunctionCount,newFunctionCount:n.newFunctionCount,errors:i,warnings:a};e.full&&(s.files=r.filter(e=>e.gated!==!1).map(e=>({file:e.file,baseFunctionCount:e.baseMetrics?.functions.length??0,headFunctionCount:e.headMetrics?.functions.length??0,baseNcss:e.baseMetrics?.ncssCount??0,headNcss:e.headMetrics?.ncssCount??0,baseMaxCognitiveComplexity:e.baseMetrics?.maxCognitiveComplexity??0,headMaxCognitiveComplexity:e.headMetrics?.maxCognitiveComplexity??0,baseDuplicatedLineCount:e.baseDuplicatedLineCount,headDuplicatedLineCount:e.headDuplicatedLineCount,duplicationPartners:e.duplicationPartners,functions:n.checkedFunctions.filter(t=>t.file===e.file)}))),o.writeStdout(JSON.stringify(s,void 0,2)+`
4
+ `)}exports.runDiffCommand=l;
5
+ //# sourceMappingURL=diffCommand.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diffCommand.cjs","names":["formatError","resolveTarget","loadConfig","configSearchDirectory","resolveOptions","resolveGateOptions","realpath","resolveRepoRoot","resolveMergeBase","listChangedFiles","listRepositoryFiles","listSymlinkPathsAtRevision","scanListedFiles","formatPath","isScannedPath","evaluateRegressionGate","path","readFile","collectFunctionTokenSequences","getLanguage","readFileAtRevision","measureCode","collectCrossFileDuplicationFileData","lstat","stat","measureCrossFileDuplication","collectDuplicatedLineNumbers"],"sources":["../src/diffCommand.ts"],"sourcesContent":["import { lstat, readFile, realpath, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { loadConfig, resolveGateOptions, resolveOptions, type ResolvedOptions } from './cliConfig.js';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport {\n listChangedFiles,\n listRepositoryFiles,\n listSymlinkPathsAtRevision,\n readFileAtRevision,\n resolveMergeBase,\n resolveRepoRoot,\n type ChangedFile,\n} from './git.js';\nimport { collectCrossFileDuplicationFileData, collectFunctionTokenSequences, measureCode } from './metrics.js';\nimport {\n evaluateRegressionGate,\n type CheckedFunctionReport,\n type GateFileInput,\n type GateFunctionValues,\n type GateResult,\n} from './regressionGate.js';\nimport {\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatError,\n formatPath,\n getLanguage,\n isScannedPath,\n resolveTarget,\n scanListedFiles,\n writeStderr,\n writeStdout,\n type FileMetrics,\n} from './scan.js';\nimport type { CodeMetrics, LanguageName } from './types.js';\n\n/** Raw options of the `diff` subcommand; every field but base is undefined unless the flag was passed. */\nexport interface DiffCliOptions {\n base: string;\n config?: string;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n json?: boolean;\n full?: boolean;\n}\n\n/** One changed file measured at both revisions, plus its duplication-universe contribution. */\ninterface PreparedFile {\n changed: ChangedFile;\n /** Repository-relative display path: the head path, or the base path for deleted files. */\n displayFile: string;\n /** Whether the file is gated (under the target directory); others only feed the base universe. */\n gated: boolean;\n headFile?: FileMetrics;\n baseMetrics?: CodeMetrics;\n baseCandidates?: CrossFileDuplicationFileData;\n baseFunctionTokens?: Int32Array[];\n headFunctionTokens?: Int32Array[];\n}\n\n/** A scanned file that git considers part of the project, keyed by its repository-relative path. */\ninterface ScannedFile {\n relativePath: string;\n file: FileMetrics;\n}\n\n/**\n * Runs the regression gate: measures the files changed relative to the merge-base with the base\n * ref, at both revisions (`git cat-file`; no checkout, no persisted baseline), and reports only\n * violations. Exit codes: 0 all gates passed, 1 violations, 2 changed files could not be measured.\n */\nexport async function runDiffCommand(target: string, cliOptions: DiffCliOptions): Promise<void> {\n try {\n await runGate(target, cliOptions);\n } catch (error) {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 2;\n }\n}\n\nasync function runGate(target: string, cliOptions: DiffCliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const gateOptions = resolveGateOptions(config);\n\n // The target may be a typo'd path whose ancestors don't exist either; repository discovery must\n // still run so the mistyped target gets its own diagnostic instead of a git spawn failure.\n const repoRoot = await realpath(\n await resolveRepoRoot(await firstExistingDirectory(await configSearchDirectory(resolvedTarget)))\n );\n const mergeBase = await resolveMergeBase(repoRoot, cliOptions.base);\n const changedFiles = await listChangedFiles(repoRoot, mergeBase);\n\n // Every git-visible file (tracked or untracked non-ignored) is measured at head: that provides\n // the head metrics of changed files and the project-wide duplication universe, so copy-paste\n // from unchanged code into changed files is caught. Scanning the explicit git list (instead of\n // walking the tree) keeps ignored artifact directories from ever being parsed: they exist in\n // neither the base commit nor CI, so they would only cost time and skew duplication counts.\n // Unchanged files are byte-identical at both revisions, so the base universe is the same scan\n // with the changed files' contents swapped for their merge-base blobs.\n const repositoryFiles = await listRepositoryFiles(repoRoot);\n const baseSymlinkPaths = await listSymlinkPathsAtRevision(repoRoot, mergeBase);\n const scan = await scanListedFiles(repoRoot, repositoryFiles, options);\n const scannedFiles: ScannedFile[] = scan.files.map((file) => ({\n relativePath: formatPath(file.file, scan.displayRoot),\n file,\n }));\n\n // A measurement failure on ANY scannable changed file forces exit 2 — deliberately including\n // files outside a scoped target, because cross-file function matching and the base duplication\n // universe for the gated files depend on them. Failures elsewhere (unchanged files) and\n // unsupported changed paths degrade to warnings.\n const changedPaths = new Set(\n changedFiles\n .flatMap((changed) => [changed.headPath, ...(changed.basePath === undefined ? [] : [changed.basePath])])\n .filter((changedPath) => isScannedPath(changedPath, options))\n );\n const errors: string[] = [];\n const warnings = [...scan.warnings];\n for (const error of scan.errors) {\n if ([...changedPaths].some((changedPath) => error.startsWith(`${changedPath}:`))) {\n errors.push(error);\n } else {\n warnings.push(error);\n }\n }\n\n const { canonicalTarget, targetExists } = await canonicalizeTarget(resolvedTarget);\n const prepared = await prepareChangedFiles(\n changedFiles,\n { repoRoot, mergeBase, canonicalTarget, options, scannedFiles, baseSymlinkPaths },\n errors,\n warnings\n );\n // A gate must not fail open on a mistyped target: a nonexistent path is only acceptable when it\n // still matches changed files (e.g. a fully deleted directory).\n if (!targetExists && !prepared.some((file) => file.gated)) {\n throw new Error(`target \"${target}\" does not exist and matches no changed file`);\n }\n\n // Non-gated files (outside the target, or renamed out of scan scope) still feed function\n // matching and the duplication universes; the evaluator reports nothing for them.\n const { baseCross, headCross } = measureDuplicationUniverses(prepared, scannedFiles, options);\n const inputs = prepared.map((file) => toGateInput(file, baseCross, headCross));\n const result = evaluateRegressionGate(inputs, gateOptions);\n\n if (cliOptions.json) {\n printJsonReport(cliOptions, mergeBase, result, inputs, errors, warnings);\n } else {\n printTextReport(cliOptions, mergeBase, result, errors, warnings);\n }\n\n if (errors.length > 0) {\n process.exitCode = 2;\n } else if (result.violations.length > 0) {\n process.exitCode = 1;\n }\n}\n\n/** The target may not exist (e.g. only deleted files under it); fall back to the resolved path. */\nasync function canonicalizeTarget(resolvedTarget: string): Promise<{ canonicalTarget: string; targetExists: boolean }> {\n try {\n return { canonicalTarget: await realpath(resolvedTarget), targetExists: true };\n } catch {\n return { canonicalTarget: resolvedTarget, targetExists: false };\n }\n}\n\ninterface GateContext {\n repoRoot: string;\n mergeBase: string;\n canonicalTarget: string;\n options: ResolvedOptions;\n scannedFiles: ScannedFile[];\n /** Paths that are symbolic links at the merge-base; like head symlinks, they are not gated. */\n baseSymlinkPaths: Set<string>;\n}\n\nasync function prepareChangedFiles(\n changedFiles: ChangedFile[],\n context: GateContext,\n errors: string[],\n warnings: string[]\n): Promise<PreparedFile[]> {\n const headByPath = new Map(context.scannedFiles.map(({ relativePath, file }) => [relativePath, file]));\n const prepared: PreparedFile[] = [];\n for (const changed of changedFiles) {\n const file = await prepareChangedFile(changed, context, headByPath, errors, warnings);\n if (file) {\n prepared.push(file);\n }\n }\n return prepared;\n}\n\nasync function prepareChangedFile(\n changed: ChangedFile,\n context: GateContext,\n headByPath: Map<string, FileMetrics>,\n errors: string[],\n warnings: string[]\n): Promise<PreparedFile | undefined> {\n // Symbolic links are skipped on both sides, mirroring scanListedFiles: git stores only the\n // target string, so a symlink blob is not measurable source.\n const headScannable =\n changed.status !== 'deleted' &&\n isScannedPath(changed.headPath, context.options) &&\n !(await isSymbolicLink(path.join(context.repoRoot, changed.headPath)));\n // A base path outside the scan scope (renamed from a test/ignored directory, or an unsupported\n // extension) was never measurable code: its content gates as new code instead of ratcheting\n // against a blob the scanner would not have measured.\n const baseScannable =\n changed.basePath !== undefined &&\n isScannedPath(changed.basePath, context.options) &&\n !context.baseSymlinkPaths.has(changed.basePath);\n if (!headScannable && !baseScannable) {\n return undefined;\n }\n\n const displayFile = changed.status === 'deleted' ? (changed.basePath as string) : changed.headPath;\n const headFile = headScannable ? headByPath.get(changed.headPath) : undefined;\n if (headScannable && !headFile) {\n reportUnmeasuredChangedFile(changed.headPath, errors);\n return undefined;\n }\n\n const file: PreparedFile = {\n changed,\n displayFile,\n // A file whose head left the scan scope still contributes its base functions to matching and\n // its base blob to the base universe, but nothing about it is gated or reported.\n gated:\n headScannable || changed.status === 'deleted'\n ? isWithinTarget(path.join(context.repoRoot, displayFile), context.canonicalTarget)\n : false,\n headFile,\n };\n\n if (baseScannable && !(await measureBaseRevision(file, changed.basePath as string, context, errors, warnings))) {\n return undefined;\n }\n\n if (headFile) {\n await collectHeadFunctionTokens(file, headFile, context, warnings);\n }\n\n return file;\n}\n\n/**\n * The scan covers exactly the git-visible list, so a scannable changed path can only be missing\n * after a measurement failure (already recorded as an error) or a silent exclusion (an alias of\n * an already-visited file, or absence from the git list). Failing loudly keeps the gate from\n * passing with the file unchecked.\n */\nfunction reportUnmeasuredChangedFile(headPath: string, errors: string[]): void {\n if (!errors.some((error) => error.startsWith(`${headPath}:`))) {\n errors.push(`${headPath}: changed file was not measured`);\n }\n}\n\nasync function collectHeadFunctionTokens(\n file: PreparedFile,\n headFile: FileMetrics,\n context: GateContext,\n warnings: string[]\n): Promise<void> {\n try {\n const headContent = await readFile(headFile.file, 'utf8');\n file.headFunctionTokens = collectFunctionTokenSequences(headContent, {\n language: getLanguage(file.changed.headPath, context.options) as LanguageName,\n duplication: context.options.duplication,\n });\n } catch (error) {\n // Only rename re-matching degrades without token sequences; the head metrics still gate.\n warnings.push(`${file.displayFile}: function token sequences unavailable: ${formatError(error)}`);\n }\n}\n\n/**\n * Measures the merge-base blob into `file`; false (with an error recorded) only when the metrics\n * themselves cannot be measured. The auxiliary collections (duplication candidates, token\n * sequences) always parse with the JavaScript binding, which can give up where the native backend\n * measured fine, so their failure only degrades duplication data and rename re-matching — the\n * function-level ratchets still run.\n */\nasync function measureBaseRevision(\n file: PreparedFile,\n basePath: string,\n context: GateContext,\n errors: string[],\n warnings: string[]\n): Promise<boolean> {\n const measureOptions = {\n language: getLanguage(basePath, context.options) as LanguageName,\n duplication: context.options.duplication,\n };\n let baseContent;\n try {\n baseContent = await readFileAtRevision(context.repoRoot, context.mergeBase, basePath);\n file.baseMetrics = measureCode(baseContent, measureOptions);\n } catch (error) {\n errors.push(`${basePath} (at merge-base): ${formatError(error)}`);\n return false;\n }\n try {\n file.baseCandidates = collectCrossFileDuplicationFileData(baseContent, measureOptions);\n file.baseFunctionTokens = collectFunctionTokenSequences(baseContent, measureOptions);\n } catch (error) {\n warnings.push(\n `${basePath} (at merge-base): duplication candidates and token sequences unavailable: ${formatError(error)}`\n );\n }\n return true;\n}\n\nasync function isSymbolicLink(absolutePath: string): Promise<boolean> {\n const stats = await lstat(absolutePath).catch(() => {});\n return stats?.isSymbolicLink() ?? false;\n}\n\n/** Walks up to the nearest existing DIRECTORY, so git commands never spawn in a missing or non-directory cwd. */\nasync function firstExistingDirectory(directory: string): Promise<string> {\n let current = directory;\n while (true) {\n const stats = await stat(current).catch(() => {});\n if (stats?.isDirectory()) {\n return current;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n return current;\n }\n current = parent;\n }\n}\n\nfunction isWithinTarget(candidate: string, targetDirectory: string): boolean {\n const relative = path.relative(targetDirectory, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nfunction measureDuplicationUniverses(\n prepared: PreparedFile[],\n scannedFiles: ScannedFile[],\n options: ResolvedOptions\n): { baseCross?: CrossFileDuplicationMetrics; headCross?: CrossFileDuplicationMetrics } {\n const headSources = scannedFiles.flatMap(({ relativePath, file }) =>\n file.duplicationCandidates ? [{ file: relativePath, ...file.duplicationCandidates }] : []\n );\n\n const changedHeadPaths = new Set(\n prepared.flatMap((file) => (file.changed.status === 'deleted' ? [] : [file.changed.headPath]))\n );\n const baseSources = headSources.filter((source) => !changedHeadPaths.has(source.file));\n for (const file of prepared) {\n if (file.baseCandidates && file.changed.basePath !== undefined) {\n baseSources.push({ file: file.changed.basePath, ...file.baseCandidates });\n }\n }\n\n return {\n baseCross: baseSources.length >= 2 ? measureCrossFileDuplication(baseSources, options.duplication) : undefined,\n headCross: headSources.length >= 2 ? measureCrossFileDuplication(headSources, options.duplication) : undefined,\n };\n}\n\nfunction toGateInput(\n file: PreparedFile,\n baseCross: CrossFileDuplicationMetrics | undefined,\n headCross: CrossFileDuplicationMetrics | undefined\n): GateFileInput {\n return {\n file: file.displayFile,\n baseMetrics: file.baseMetrics,\n headMetrics: file.headFile?.metrics,\n baseFunctionTokens: file.baseFunctionTokens,\n headFunctionTokens: file.headFunctionTokens,\n baseDuplicatedLineCount:\n file.baseMetrics === undefined || file.changed.basePath === undefined\n ? 0\n : countDuplicatedLines(file.baseMetrics, baseCross, file.changed.basePath),\n headDuplicatedLineCount:\n file.changed.status === 'deleted'\n ? 0\n : countDuplicatedLines(file.headFile?.metrics, headCross, file.changed.headPath),\n duplicationPartners: collectPartners(headCross, file.changed.headPath),\n gated: file.gated,\n };\n}\n\nfunction countDuplicatedLines(\n metrics: CodeMetrics | undefined,\n cross: CrossFileDuplicationMetrics | undefined,\n file: string\n): number {\n return collectDuplicatedLineNumbers(metrics, cross, file).size;\n}\n\nfunction collectPartners(cross: CrossFileDuplicationMetrics | undefined, file: string): string[] {\n if (!cross) {\n return [];\n }\n const partners = new Set<string>();\n for (const group of cross.groups) {\n if (group.files.includes(file)) {\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n return [...partners].toSorted();\n}\n\nfunction printTextReport(\n cliOptions: DiffCliOptions,\n mergeBase: string,\n result: GateResult,\n errors: string[],\n warnings: string[]\n): void {\n const shortBase = mergeBase.slice(0, 12);\n if (errors.length > 0) {\n // Unmeasured files were not gated, so \"0 violations\" would be vacuous; never claim a pass.\n writeStdout(\n `Regression gate could not complete: ${errors.length} measurement failures (details on stderr)` +\n `${result.violations.length > 0 ? `; ${result.violations.length} violations in the measured files` : ''} (base ${cliOptions.base}, merge-base ${shortBase}).\\n`\n );\n printViolations(result);\n } else if (result.violations.length === 0) {\n writeStdout(\n `Regression gate passed: ${result.checkedFileCount} changed files, ${result.checkedFunctionCount} functions checked (base ${cliOptions.base}, merge-base ${shortBase}).\\n`\n );\n } else {\n writeStdout(\n `Regression gate vs ${cliOptions.base} (merge-base ${shortBase}): ${result.violations.length} violations\\n`\n );\n printViolations(result);\n }\n\n if (cliOptions.full) {\n printFullDetails(result);\n }\n\n for (const warning of warnings) {\n writeStderr(`Warning: ${warning}\\n`);\n }\n for (const error of errors) {\n writeStderr(`Error: ${error}\\n`);\n }\n}\n\nfunction printViolations(result: GateResult): void {\n for (const [index, violation] of result.violations.entries()) {\n writeStdout(`${index + 1}. ${violation.message}\\n`);\n }\n}\n\n/** Base -> head values of every checked function; kept behind --full for humans and trending. */\nfunction printFullDetails(result: GateResult): void {\n if (result.checkedFunctions.length === 0) {\n return;\n }\n writeStdout('\\nChecked functions (base -> head):\\n');\n for (const report of result.checkedFunctions) {\n writeStdout(`- ${formatFunctionReport(report)}\\n`);\n }\n}\n\nfunction formatFunctionReport(report: CheckedFunctionReport): string {\n const range = (\n select: (values: GateFunctionValues) => number,\n format: (value: number) => string = String\n ): string => {\n const head = format(select(report.head));\n return report.base ? `${format(select(report.base))} -> ${head}` : head;\n };\n const values = [\n `cognitive ${range((fn) => fn.cognitiveComplexity)}`,\n `NCSS ${range((fn) => fn.ncss)}`,\n `nesting ${range((fn) => fn.nestingDepth)}`,\n `DepDegree ${range((fn) => fn.depDegree)}`,\n `volume ${range(\n (fn) => fn.halsteadVolume,\n (value) => value.toFixed(1)\n )}`,\n ];\n return `${report.file}:${report.startLine}-${report.endLine} ${report.name}${report.base ? '' : ' (new)'}: ${values.join(', ')}`;\n}\n\nfunction printJsonReport(\n cliOptions: DiffCliOptions,\n mergeBase: string,\n result: GateResult,\n inputs: GateFileInput[],\n errors: string[],\n warnings: string[]\n): void {\n const report: Record<string, unknown> = {\n base: cliOptions.base,\n mergeBase,\n passed: result.violations.length === 0 && errors.length === 0,\n violations: result.violations,\n checkedFileCount: result.checkedFileCount,\n checkedFunctionCount: result.checkedFunctionCount,\n newFunctionCount: result.newFunctionCount,\n errors,\n warnings,\n };\n if (cliOptions.full) {\n report.files = inputs\n .filter((input) => input.gated !== false)\n .map((input) => ({\n file: input.file,\n baseFunctionCount: input.baseMetrics?.functions.length ?? 0,\n headFunctionCount: input.headMetrics?.functions.length ?? 0,\n baseNcss: input.baseMetrics?.ncssCount ?? 0,\n headNcss: input.headMetrics?.ncssCount ?? 0,\n baseMaxCognitiveComplexity: input.baseMetrics?.maxCognitiveComplexity ?? 0,\n headMaxCognitiveComplexity: input.headMetrics?.maxCognitiveComplexity ?? 0,\n baseDuplicatedLineCount: input.baseDuplicatedLineCount,\n headDuplicatedLineCount: input.headDuplicatedLineCount,\n duplicationPartners: input.duplicationPartners,\n functions: result.checkedFunctions.filter((fn) => fn.file === input.file),\n }));\n }\n writeStdout(JSON.stringify(report, undefined, 2) + '\\n');\n}\n"],"mappings":"4TA0EA,eAAsB,EAAe,EAAgB,EAA2C,CAC9F,GAAI,CACF,MAAM,EAAQ,EAAQ,CAAU,CAClC,OAAS,EAAO,CACd,EAAA,YAAY,UAAUA,EAAAA,YAAY,CAAK,EAAE,GAAG,EAC5C,QAAQ,SAAW,CACrB,CACF,CAEA,eAAe,EAAQ,EAAgB,EAA2C,CAChF,IAAM,EAAiBC,EAAAA,cAAc,CAAM,EACrC,EAAS,MAAMC,EAAAA,WAAW,EAAW,OAAQ,MAAMC,EAAAA,sBAAsB,CAAc,CAAC,EACxF,EAAUC,EAAAA,eAAe,EAAY,CAAM,EAC3C,EAAcC,EAAAA,mBAAmB,CAAM,EAIvC,EAAW,MAAA,EAAMC,EAAAA,SAAAA,CACrB,MAAMC,EAAAA,gBAAgB,MAAM,EAAuB,MAAMJ,EAAAA,sBAAsB,CAAc,CAAC,CAAC,CACjG,EACM,EAAY,MAAMK,EAAAA,iBAAiB,EAAU,EAAW,IAAI,EAC5D,EAAe,MAAMC,EAAAA,iBAAiB,EAAU,CAAS,EASzD,EAAkB,MAAMC,EAAAA,oBAAoB,CAAQ,EACpD,EAAmB,MAAMC,EAAAA,2BAA2B,EAAU,CAAS,EACvE,EAAO,MAAMC,EAAAA,gBAAgB,EAAU,EAAiB,CAAO,EAC/D,EAA8B,EAAK,MAAM,IAAK,IAAU,CAC5D,aAAcC,EAAAA,WAAW,EAAK,KAAM,EAAK,WAAW,EACpD,MACF,EAAE,EAMI,EAAe,IAAI,IACvB,EACG,QAAS,GAAY,CAAC,EAAQ,SAAU,GAAI,EAAQ,WAAa,IAAA,GAAY,CAAC,EAAI,CAAC,EAAQ,QAAQ,C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AC1D,SAAU,EAAM,aAAa,WAAa,EAC1C,SAAU,EAAM,aAAa,WAAa,EAC1C,2BAA4B,EAAM,aAAa,wBAA0B,EACzE,2BAA4B,EAAM,aAAa,wBAA0B,EACzE,wBAAyB,EAAM,wBAC/B,wBAAyB,EAAM,wBAC/B,oBAAqB,EAAM,oBAC3B,UAAW,EAAO,iBAAiB,OAAQ,GAAO,EAAG,OAAS,EAAM,IAAI,CAC1E,EAAE,GAEN,EAAA,YAAY,KAAK,UAAU,EAAQ,IAAA,GAAW,CAAC,EAAI;CAAI,CACzD"}
@@ -0,0 +1,17 @@
1
+ /** Raw options of the `diff` subcommand; every field but base is undefined unless the flag was passed. */
2
+ export interface DiffCliOptions {
3
+ base: string;
4
+ config?: string;
5
+ duplicationMinTokens?: number;
6
+ duplicationMaxGapTokens?: number;
7
+ duplicationMinSimilarityPercent?: number;
8
+ includeTests?: boolean;
9
+ json?: boolean;
10
+ full?: boolean;
11
+ }
12
+ /**
13
+ * Runs the regression gate: measures the files changed relative to the merge-base with the base
14
+ * ref, at both revisions (`git cat-file`; no checkout, no persisted baseline), and reports only
15
+ * violations. Exit codes: 0 all gates passed, 1 violations, 2 changed files could not be measured.
16
+ */
17
+ export declare function runDiffCommand(target: string, cliOptions: DiffCliOptions): Promise<void>;
@@ -0,0 +1,5 @@
1
+ import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{collectCrossFileDuplicationFileData as t,collectFunctionTokenSequences as n,measureCode as r}from"./metrics.js";import{evaluateRegressionGate as i}from"./regressionGate.js";import{loadConfig as a,resolveGateOptions as o,resolveOptions as s}from"./cliConfig.js";import{listChangedFiles as c,listRepositoryFiles as l,listSymlinkPathsAtRevision as u,readFileAtRevision as d,resolveMergeBase as f,resolveRepoRoot as p}from"./git.js";import{collectDuplicatedLineNumbers as m,configSearchDirectory as h,formatError as g,formatPath as _,getLanguage as v,isScannedPath as y,resolveTarget as b,scanListedFiles as x,writeStderr as S,writeStdout as C}from"./scan.js";import{lstat as w,readFile as T,realpath as E,stat as D}from"node:fs/promises";import O from"node:path";async function k(e,t){try{await A(e,t)}catch(e){S(`Error: ${g(e)}\n`),process.exitCode=2}}async function A(e,t){let n=b(e),r=await a(t.config,await h(n)),d=s(t,r),m=o(r),g=await E(await p(await R(await h(n)))),v=await f(g,t.base),S=await c(g,v),C=await l(g),w=await u(g,v),T=await x(g,C,d),D=T.files.map(e=>({relativePath:_(e.file,T.displayRoot),file:e})),O=new Set(S.flatMap(e=>[e.headPath,...e.basePath===void 0?[]:[e.basePath]]).filter(e=>y(e,d))),k=[],A=[...T.warnings];for(let e of T.errors)[...O].some(t=>e.startsWith(`${t}:`))?k.push(e):A.push(e);let{canonicalTarget:N,targetExists:P}=await j(n),F=await M(S,{repoRoot:g,mergeBase:v,canonicalTarget:N,options:d,scannedFiles:D,baseSymlinkPaths:w},k,A);if(!P&&!F.some(e=>e.gated))throw Error(`target "${e}" does not exist and matches no changed file`);let{baseCross:I,headCross:L}=B(F,D,d),z=F.map(e=>V(e,I,L)),H=i(z,m);t.json?J(t,v,H,z,k,A):W(t,v,H,k,A),k.length>0?process.exitCode=2:H.violations.length>0&&(process.exitCode=1)}async function j(e){try{return{canonicalTarget:await E(e),targetExists:!0}}catch{return{canonicalTarget:e,targetExists:!1}}}async function M(e,t,n,r){let i=new Map(t.scannedFiles.map(({relativePath:e,file:t})=>[e,t])),a=[];for(let o of e){let e=await N(o,t,i,n,r);e&&a.push(e)}return a}async function N(e,t,n,r,i){let a=e.status!==`deleted`&&y(e.headPath,t.options)&&!await L(O.join(t.repoRoot,e.headPath)),o=e.basePath!==void 0&&y(e.basePath,t.options)&&!t.baseSymlinkPaths.has(e.basePath);if(!a&&!o)return;let s=e.status===`deleted`?e.basePath:e.headPath,c=a?n.get(e.headPath):void 0;if(a&&!c){P(e.headPath,r);return}let l={changed:e,displayFile:s,gated:a||e.status===`deleted`?z(O.join(t.repoRoot,s),t.canonicalTarget):!1,headFile:c};if(!(o&&!await I(l,e.basePath,t,r,i)))return c&&await F(l,c,t,i),l}function P(e,t){t.some(t=>t.startsWith(`${e}:`))||t.push(`${e}: changed file was not measured`)}async function F(e,t,r,i){try{let i=await T(t.file,`utf8`);e.headFunctionTokens=n(i,{language:v(e.changed.headPath,r.options),duplication:r.options.duplication})}catch(t){i.push(`${e.displayFile}: function token sequences unavailable: ${g(t)}`)}}async function I(e,i,a,o,s){let c={language:v(i,a.options),duplication:a.options.duplication},l;try{l=await d(a.repoRoot,a.mergeBase,i),e.baseMetrics=r(l,c)}catch(e){return o.push(`${i} (at merge-base): ${g(e)}`),!1}try{e.baseCandidates=t(l,c),e.baseFunctionTokens=n(l,c)}catch(e){s.push(`${i} (at merge-base): duplication candidates and token sequences unavailable: ${g(e)}`)}return!0}async function L(e){return(await w(e).catch(()=>{}))?.isSymbolicLink()??!1}async function R(e){let t=e;for(;;){if((await D(t).catch(()=>{}))?.isDirectory())return t;let e=O.dirname(t);if(e===t)return t;t=e}}function z(e,t){let n=O.relative(t,e);return n===``||!n.startsWith(`..${O.sep}`)&&n!==`..`&&!O.isAbsolute(n)}function B(t,n,r){let i=n.flatMap(({relativePath:e,file:t})=>t.duplicationCandidates?[{file:e,...t.duplicationCandidates}]:[]),a=new Set(t.flatMap(e=>e.changed.status===`deleted`?[]:[e.changed.headPath])),o=i.filter(e=>!a.has(e.file));for(let e of t)e.baseCandidates&&e.changed.basePath!==void 0&&o.push({file:e.changed.basePath,...e.baseCandidates});return{baseCross:o.length>=2?e(o,r.duplication):void 0,headCross:i.length>=2?e(i,r.duplication):void 0}}function V(e,t,n){return{file:e.displayFile,baseMetrics:e.baseMetrics,headMetrics:e.headFile?.metrics,baseFunctionTokens:e.baseFunctionTokens,headFunctionTokens:e.headFunctionTokens,baseDuplicatedLineCount:e.baseMetrics===void 0||e.changed.basePath===void 0?0:H(e.baseMetrics,t,e.changed.basePath),headDuplicatedLineCount:e.changed.status===`deleted`?0:H(e.headFile?.metrics,n,e.changed.headPath),duplicationPartners:U(n,e.changed.headPath),gated:e.gated}}function H(e,t,n){return m(e,t,n).size}function U(e,t){if(!e)return[];let n=new Set;for(let r of e.groups)if(r.files.includes(t))for(let e of r.files)e!==t&&n.add(e);return[...n].toSorted()}function W(e,t,n,r,i){let a=t.slice(0,12);r.length>0?(C(`Regression gate could not complete: ${r.length} measurement failures (details on stderr)${n.violations.length>0?`; ${n.violations.length} violations in the measured files`:``} (base ${e.base}, merge-base ${a}).\n`),G(n)):n.violations.length===0?C(`Regression gate passed: ${n.checkedFileCount} changed files, ${n.checkedFunctionCount} functions checked (base ${e.base}, merge-base ${a}).\n`):(C(`Regression gate vs ${e.base} (merge-base ${a}): ${n.violations.length} violations\n`),G(n)),e.full&&K(n);for(let e of i)S(`Warning: ${e}\n`);for(let e of r)S(`Error: ${e}\n`)}function G(e){for(let[t,n]of e.violations.entries())C(`${t+1}. ${n.message}\n`)}function K(e){if(e.checkedFunctions.length!==0){C(`
2
+ Checked functions (base -> head):
3
+ `);for(let t of e.checkedFunctions)C(`- ${q(t)}\n`)}}function q(e){let t=(t,n=String)=>{let r=n(t(e.head));return e.base?`${n(t(e.base))} -> ${r}`:r},n=[`cognitive ${t(e=>e.cognitiveComplexity)}`,`NCSS ${t(e=>e.ncss)}`,`nesting ${t(e=>e.nestingDepth)}`,`DepDegree ${t(e=>e.depDegree)}`,`volume ${t(e=>e.halsteadVolume,e=>e.toFixed(1))}`];return`${e.file}:${e.startLine}-${e.endLine} ${e.name}${e.base?``:` (new)`}: ${n.join(`, `)}`}function J(e,t,n,r,i,a){let o={base:e.base,mergeBase:t,passed:n.violations.length===0&&i.length===0,violations:n.violations,checkedFileCount:n.checkedFileCount,checkedFunctionCount:n.checkedFunctionCount,newFunctionCount:n.newFunctionCount,errors:i,warnings:a};e.full&&(o.files=r.filter(e=>e.gated!==!1).map(e=>({file:e.file,baseFunctionCount:e.baseMetrics?.functions.length??0,headFunctionCount:e.headMetrics?.functions.length??0,baseNcss:e.baseMetrics?.ncssCount??0,headNcss:e.headMetrics?.ncssCount??0,baseMaxCognitiveComplexity:e.baseMetrics?.maxCognitiveComplexity??0,headMaxCognitiveComplexity:e.headMetrics?.maxCognitiveComplexity??0,baseDuplicatedLineCount:e.baseDuplicatedLineCount,headDuplicatedLineCount:e.headDuplicatedLineCount,duplicationPartners:e.duplicationPartners,functions:n.checkedFunctions.filter(t=>t.file===e.file)}))),C(JSON.stringify(o,void 0,2)+`
4
+ `)}export{k as runDiffCommand};
5
+ //# sourceMappingURL=diffCommand.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diffCommand.js","names":[],"sources":["../src/diffCommand.ts"],"sourcesContent":["import { lstat, readFile, realpath, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { loadConfig, resolveGateOptions, resolveOptions, type ResolvedOptions } from './cliConfig.js';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport {\n listChangedFiles,\n listRepositoryFiles,\n listSymlinkPathsAtRevision,\n readFileAtRevision,\n resolveMergeBase,\n resolveRepoRoot,\n type ChangedFile,\n} from './git.js';\nimport { collectCrossFileDuplicationFileData, collectFunctionTokenSequences, measureCode } from './metrics.js';\nimport {\n evaluateRegressionGate,\n type CheckedFunctionReport,\n type GateFileInput,\n type GateFunctionValues,\n type GateResult,\n} from './regressionGate.js';\nimport {\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatError,\n formatPath,\n getLanguage,\n isScannedPath,\n resolveTarget,\n scanListedFiles,\n writeStderr,\n writeStdout,\n type FileMetrics,\n} from './scan.js';\nimport type { CodeMetrics, LanguageName } from './types.js';\n\n/** Raw options of the `diff` subcommand; every field but base is undefined unless the flag was passed. */\nexport interface DiffCliOptions {\n base: string;\n config?: string;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n json?: boolean;\n full?: boolean;\n}\n\n/** One changed file measured at both revisions, plus its duplication-universe contribution. */\ninterface PreparedFile {\n changed: ChangedFile;\n /** Repository-relative display path: the head path, or the base path for deleted files. */\n displayFile: string;\n /** Whether the file is gated (under the target directory); others only feed the base universe. */\n gated: boolean;\n headFile?: FileMetrics;\n baseMetrics?: CodeMetrics;\n baseCandidates?: CrossFileDuplicationFileData;\n baseFunctionTokens?: Int32Array[];\n headFunctionTokens?: Int32Array[];\n}\n\n/** A scanned file that git considers part of the project, keyed by its repository-relative path. */\ninterface ScannedFile {\n relativePath: string;\n file: FileMetrics;\n}\n\n/**\n * Runs the regression gate: measures the files changed relative to the merge-base with the base\n * ref, at both revisions (`git cat-file`; no checkout, no persisted baseline), and reports only\n * violations. Exit codes: 0 all gates passed, 1 violations, 2 changed files could not be measured.\n */\nexport async function runDiffCommand(target: string, cliOptions: DiffCliOptions): Promise<void> {\n try {\n await runGate(target, cliOptions);\n } catch (error) {\n writeStderr(`Error: ${formatError(error)}\\n`);\n process.exitCode = 2;\n }\n}\n\nasync function runGate(target: string, cliOptions: DiffCliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const config = await loadConfig(cliOptions.config, await configSearchDirectory(resolvedTarget));\n const options = resolveOptions(cliOptions, config);\n const gateOptions = resolveGateOptions(config);\n\n // The target may be a typo'd path whose ancestors don't exist either; repository discovery must\n // still run so the mistyped target gets its own diagnostic instead of a git spawn failure.\n const repoRoot = await realpath(\n await resolveRepoRoot(await firstExistingDirectory(await configSearchDirectory(resolvedTarget)))\n );\n const mergeBase = await resolveMergeBase(repoRoot, cliOptions.base);\n const changedFiles = await listChangedFiles(repoRoot, mergeBase);\n\n // Every git-visible file (tracked or untracked non-ignored) is measured at head: that provides\n // the head metrics of changed files and the project-wide duplication universe, so copy-paste\n // from unchanged code into changed files is caught. Scanning the explicit git list (instead of\n // walking the tree) keeps ignored artifact directories from ever being parsed: they exist in\n // neither the base commit nor CI, so they would only cost time and skew duplication counts.\n // Unchanged files are byte-identical at both revisions, so the base universe is the same scan\n // with the changed files' contents swapped for their merge-base blobs.\n const repositoryFiles = await listRepositoryFiles(repoRoot);\n const baseSymlinkPaths = await listSymlinkPathsAtRevision(repoRoot, mergeBase);\n const scan = await scanListedFiles(repoRoot, repositoryFiles, options);\n const scannedFiles: ScannedFile[] = scan.files.map((file) => ({\n relativePath: formatPath(file.file, scan.displayRoot),\n file,\n }));\n\n // A measurement failure on ANY scannable changed file forces exit 2 — deliberately including\n // files outside a scoped target, because cross-file function matching and the base duplication\n // universe for the gated files depend on them. Failures elsewhere (unchanged files) and\n // unsupported changed paths degrade to warnings.\n const changedPaths = new Set(\n changedFiles\n .flatMap((changed) => [changed.headPath, ...(changed.basePath === undefined ? [] : [changed.basePath])])\n .filter((changedPath) => isScannedPath(changedPath, options))\n );\n const errors: string[] = [];\n const warnings = [...scan.warnings];\n for (const error of scan.errors) {\n if ([...changedPaths].some((changedPath) => error.startsWith(`${changedPath}:`))) {\n errors.push(error);\n } else {\n warnings.push(error);\n }\n }\n\n const { canonicalTarget, targetExists } = await canonicalizeTarget(resolvedTarget);\n const prepared = await prepareChangedFiles(\n changedFiles,\n { repoRoot, mergeBase, canonicalTarget, options, scannedFiles, baseSymlinkPaths },\n errors,\n warnings\n );\n // A gate must not fail open on a mistyped target: a nonexistent path is only acceptable when it\n // still matches changed files (e.g. a fully deleted directory).\n if (!targetExists && !prepared.some((file) => file.gated)) {\n throw new Error(`target \"${target}\" does not exist and matches no changed file`);\n }\n\n // Non-gated files (outside the target, or renamed out of scan scope) still feed function\n // matching and the duplication universes; the evaluator reports nothing for them.\n const { baseCross, headCross } = measureDuplicationUniverses(prepared, scannedFiles, options);\n const inputs = prepared.map((file) => toGateInput(file, baseCross, headCross));\n const result = evaluateRegressionGate(inputs, gateOptions);\n\n if (cliOptions.json) {\n printJsonReport(cliOptions, mergeBase, result, inputs, errors, warnings);\n } else {\n printTextReport(cliOptions, mergeBase, result, errors, warnings);\n }\n\n if (errors.length > 0) {\n process.exitCode = 2;\n } else if (result.violations.length > 0) {\n process.exitCode = 1;\n }\n}\n\n/** The target may not exist (e.g. only deleted files under it); fall back to the resolved path. */\nasync function canonicalizeTarget(resolvedTarget: string): Promise<{ canonicalTarget: string; targetExists: boolean }> {\n try {\n return { canonicalTarget: await realpath(resolvedTarget), targetExists: true };\n } catch {\n return { canonicalTarget: resolvedTarget, targetExists: false };\n }\n}\n\ninterface GateContext {\n repoRoot: string;\n mergeBase: string;\n canonicalTarget: string;\n options: ResolvedOptions;\n scannedFiles: ScannedFile[];\n /** Paths that are symbolic links at the merge-base; like head symlinks, they are not gated. */\n baseSymlinkPaths: Set<string>;\n}\n\nasync function prepareChangedFiles(\n changedFiles: ChangedFile[],\n context: GateContext,\n errors: string[],\n warnings: string[]\n): Promise<PreparedFile[]> {\n const headByPath = new Map(context.scannedFiles.map(({ relativePath, file }) => [relativePath, file]));\n const prepared: PreparedFile[] = [];\n for (const changed of changedFiles) {\n const file = await prepareChangedFile(changed, context, headByPath, errors, warnings);\n if (file) {\n prepared.push(file);\n }\n }\n return prepared;\n}\n\nasync function prepareChangedFile(\n changed: ChangedFile,\n context: GateContext,\n headByPath: Map<string, FileMetrics>,\n errors: string[],\n warnings: string[]\n): Promise<PreparedFile | undefined> {\n // Symbolic links are skipped on both sides, mirroring scanListedFiles: git stores only the\n // target string, so a symlink blob is not measurable source.\n const headScannable =\n changed.status !== 'deleted' &&\n isScannedPath(changed.headPath, context.options) &&\n !(await isSymbolicLink(path.join(context.repoRoot, changed.headPath)));\n // A base path outside the scan scope (renamed from a test/ignored directory, or an unsupported\n // extension) was never measurable code: its content gates as new code instead of ratcheting\n // against a blob the scanner would not have measured.\n const baseScannable =\n changed.basePath !== undefined &&\n isScannedPath(changed.basePath, context.options) &&\n !context.baseSymlinkPaths.has(changed.basePath);\n if (!headScannable && !baseScannable) {\n return undefined;\n }\n\n const displayFile = changed.status === 'deleted' ? (changed.basePath as string) : changed.headPath;\n const headFile = headScannable ? headByPath.get(changed.headPath) : undefined;\n if (headScannable && !headFile) {\n reportUnmeasuredChangedFile(changed.headPath, errors);\n return undefined;\n }\n\n const file: PreparedFile = {\n changed,\n displayFile,\n // A file whose head left the scan scope still contributes its base functions to matching and\n // its base blob to the base universe, but nothing about it is gated or reported.\n gated:\n headScannable || changed.status === 'deleted'\n ? isWithinTarget(path.join(context.repoRoot, displayFile), context.canonicalTarget)\n : false,\n headFile,\n };\n\n if (baseScannable && !(await measureBaseRevision(file, changed.basePath as string, context, errors, warnings))) {\n return undefined;\n }\n\n if (headFile) {\n await collectHeadFunctionTokens(file, headFile, context, warnings);\n }\n\n return file;\n}\n\n/**\n * The scan covers exactly the git-visible list, so a scannable changed path can only be missing\n * after a measurement failure (already recorded as an error) or a silent exclusion (an alias of\n * an already-visited file, or absence from the git list). Failing loudly keeps the gate from\n * passing with the file unchecked.\n */\nfunction reportUnmeasuredChangedFile(headPath: string, errors: string[]): void {\n if (!errors.some((error) => error.startsWith(`${headPath}:`))) {\n errors.push(`${headPath}: changed file was not measured`);\n }\n}\n\nasync function collectHeadFunctionTokens(\n file: PreparedFile,\n headFile: FileMetrics,\n context: GateContext,\n warnings: string[]\n): Promise<void> {\n try {\n const headContent = await readFile(headFile.file, 'utf8');\n file.headFunctionTokens = collectFunctionTokenSequences(headContent, {\n language: getLanguage(file.changed.headPath, context.options) as LanguageName,\n duplication: context.options.duplication,\n });\n } catch (error) {\n // Only rename re-matching degrades without token sequences; the head metrics still gate.\n warnings.push(`${file.displayFile}: function token sequences unavailable: ${formatError(error)}`);\n }\n}\n\n/**\n * Measures the merge-base blob into `file`; false (with an error recorded) only when the metrics\n * themselves cannot be measured. The auxiliary collections (duplication candidates, token\n * sequences) always parse with the JavaScript binding, which can give up where the native backend\n * measured fine, so their failure only degrades duplication data and rename re-matching — the\n * function-level ratchets still run.\n */\nasync function measureBaseRevision(\n file: PreparedFile,\n basePath: string,\n context: GateContext,\n errors: string[],\n warnings: string[]\n): Promise<boolean> {\n const measureOptions = {\n language: getLanguage(basePath, context.options) as LanguageName,\n duplication: context.options.duplication,\n };\n let baseContent;\n try {\n baseContent = await readFileAtRevision(context.repoRoot, context.mergeBase, basePath);\n file.baseMetrics = measureCode(baseContent, measureOptions);\n } catch (error) {\n errors.push(`${basePath} (at merge-base): ${formatError(error)}`);\n return false;\n }\n try {\n file.baseCandidates = collectCrossFileDuplicationFileData(baseContent, measureOptions);\n file.baseFunctionTokens = collectFunctionTokenSequences(baseContent, measureOptions);\n } catch (error) {\n warnings.push(\n `${basePath} (at merge-base): duplication candidates and token sequences unavailable: ${formatError(error)}`\n );\n }\n return true;\n}\n\nasync function isSymbolicLink(absolutePath: string): Promise<boolean> {\n const stats = await lstat(absolutePath).catch(() => {});\n return stats?.isSymbolicLink() ?? false;\n}\n\n/** Walks up to the nearest existing DIRECTORY, so git commands never spawn in a missing or non-directory cwd. */\nasync function firstExistingDirectory(directory: string): Promise<string> {\n let current = directory;\n while (true) {\n const stats = await stat(current).catch(() => {});\n if (stats?.isDirectory()) {\n return current;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n return current;\n }\n current = parent;\n }\n}\n\nfunction isWithinTarget(candidate: string, targetDirectory: string): boolean {\n const relative = path.relative(targetDirectory, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nfunction measureDuplicationUniverses(\n prepared: PreparedFile[],\n scannedFiles: ScannedFile[],\n options: ResolvedOptions\n): { baseCross?: CrossFileDuplicationMetrics; headCross?: CrossFileDuplicationMetrics } {\n const headSources = scannedFiles.flatMap(({ relativePath, file }) =>\n file.duplicationCandidates ? [{ file: relativePath, ...file.duplicationCandidates }] : []\n );\n\n const changedHeadPaths = new Set(\n prepared.flatMap((file) => (file.changed.status === 'deleted' ? [] : [file.changed.headPath]))\n );\n const baseSources = headSources.filter((source) => !changedHeadPaths.has(source.file));\n for (const file of prepared) {\n if (file.baseCandidates && file.changed.basePath !== undefined) {\n baseSources.push({ file: file.changed.basePath, ...file.baseCandidates });\n }\n }\n\n return {\n baseCross: baseSources.length >= 2 ? measureCrossFileDuplication(baseSources, options.duplication) : undefined,\n headCross: headSources.length >= 2 ? measureCrossFileDuplication(headSources, options.duplication) : undefined,\n };\n}\n\nfunction toGateInput(\n file: PreparedFile,\n baseCross: CrossFileDuplicationMetrics | undefined,\n headCross: CrossFileDuplicationMetrics | undefined\n): GateFileInput {\n return {\n file: file.displayFile,\n baseMetrics: file.baseMetrics,\n headMetrics: file.headFile?.metrics,\n baseFunctionTokens: file.baseFunctionTokens,\n headFunctionTokens: file.headFunctionTokens,\n baseDuplicatedLineCount:\n file.baseMetrics === undefined || file.changed.basePath === undefined\n ? 0\n : countDuplicatedLines(file.baseMetrics, baseCross, file.changed.basePath),\n headDuplicatedLineCount:\n file.changed.status === 'deleted'\n ? 0\n : countDuplicatedLines(file.headFile?.metrics, headCross, file.changed.headPath),\n duplicationPartners: collectPartners(headCross, file.changed.headPath),\n gated: file.gated,\n };\n}\n\nfunction countDuplicatedLines(\n metrics: CodeMetrics | undefined,\n cross: CrossFileDuplicationMetrics | undefined,\n file: string\n): number {\n return collectDuplicatedLineNumbers(metrics, cross, file).size;\n}\n\nfunction collectPartners(cross: CrossFileDuplicationMetrics | undefined, file: string): string[] {\n if (!cross) {\n return [];\n }\n const partners = new Set<string>();\n for (const group of cross.groups) {\n if (group.files.includes(file)) {\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n return [...partners].toSorted();\n}\n\nfunction printTextReport(\n cliOptions: DiffCliOptions,\n mergeBase: string,\n result: GateResult,\n errors: string[],\n warnings: string[]\n): void {\n const shortBase = mergeBase.slice(0, 12);\n if (errors.length > 0) {\n // Unmeasured files were not gated, so \"0 violations\" would be vacuous; never claim a pass.\n writeStdout(\n `Regression gate could not complete: ${errors.length} measurement failures (details on stderr)` +\n `${result.violations.length > 0 ? `; ${result.violations.length} violations in the measured files` : ''} (base ${cliOptions.base}, merge-base ${shortBase}).\\n`\n );\n printViolations(result);\n } else if (result.violations.length === 0) {\n writeStdout(\n `Regression gate passed: ${result.checkedFileCount} changed files, ${result.checkedFunctionCount} functions checked (base ${cliOptions.base}, merge-base ${shortBase}).\\n`\n );\n } else {\n writeStdout(\n `Regression gate vs ${cliOptions.base} (merge-base ${shortBase}): ${result.violations.length} violations\\n`\n );\n printViolations(result);\n }\n\n if (cliOptions.full) {\n printFullDetails(result);\n }\n\n for (const warning of warnings) {\n writeStderr(`Warning: ${warning}\\n`);\n }\n for (const error of errors) {\n writeStderr(`Error: ${error}\\n`);\n }\n}\n\nfunction printViolations(result: GateResult): void {\n for (const [index, violation] of result.violations.entries()) {\n writeStdout(`${index + 1}. ${violation.message}\\n`);\n }\n}\n\n/** Base -> head values of every checked function; kept behind --full for humans and trending. */\nfunction printFullDetails(result: GateResult): void {\n if (result.checkedFunctions.length === 0) {\n return;\n }\n writeStdout('\\nChecked functions (base -> head):\\n');\n for (const report of result.checkedFunctions) {\n writeStdout(`- ${formatFunctionReport(report)}\\n`);\n }\n}\n\nfunction formatFunctionReport(report: CheckedFunctionReport): string {\n const range = (\n select: (values: GateFunctionValues) => number,\n format: (value: number) => string = String\n ): string => {\n const head = format(select(report.head));\n return report.base ? `${format(select(report.base))} -> ${head}` : head;\n };\n const values = [\n `cognitive ${range((fn) => fn.cognitiveComplexity)}`,\n `NCSS ${range((fn) => fn.ncss)}`,\n `nesting ${range((fn) => fn.nestingDepth)}`,\n `DepDegree ${range((fn) => fn.depDegree)}`,\n `volume ${range(\n (fn) => fn.halsteadVolume,\n (value) => value.toFixed(1)\n )}`,\n ];\n return `${report.file}:${report.startLine}-${report.endLine} ${report.name}${report.base ? '' : ' (new)'}: ${values.join(', ')}`;\n}\n\nfunction printJsonReport(\n cliOptions: DiffCliOptions,\n mergeBase: string,\n result: GateResult,\n inputs: GateFileInput[],\n errors: string[],\n warnings: string[]\n): void {\n const report: Record<string, unknown> = {\n base: cliOptions.base,\n mergeBase,\n passed: result.violations.length === 0 && errors.length === 0,\n violations: result.violations,\n checkedFileCount: result.checkedFileCount,\n checkedFunctionCount: result.checkedFunctionCount,\n newFunctionCount: result.newFunctionCount,\n errors,\n warnings,\n };\n if (cliOptions.full) {\n report.files = inputs\n .filter((input) => input.gated !== false)\n .map((input) => ({\n file: input.file,\n baseFunctionCount: input.baseMetrics?.functions.length ?? 0,\n headFunctionCount: input.headMetrics?.functions.length ?? 0,\n baseNcss: input.baseMetrics?.ncssCount ?? 0,\n headNcss: input.headMetrics?.ncssCount ?? 0,\n baseMaxCognitiveComplexity: input.baseMetrics?.maxCognitiveComplexity ?? 0,\n headMaxCognitiveComplexity: input.headMetrics?.maxCognitiveComplexity ?? 0,\n baseDuplicatedLineCount: input.baseDuplicatedLineCount,\n headDuplicatedLineCount: input.headDuplicatedLineCount,\n duplicationPartners: input.duplicationPartners,\n functions: result.checkedFunctions.filter((fn) => fn.file === input.file),\n }));\n }\n writeStdout(JSON.stringify(report, undefined, 2) + '\\n');\n}\n"],"mappings":"u0BA0EA,eAAsB,EAAe,EAAgB,EAA2C,CAC9F,GAAI,CACF,MAAM,EAAQ,EAAQ,CAAU,CAClC,OAAS,EAAO,CACd,EAAY,UAAU,EAAY,CAAK,EAAE,GAAG,EAC5C,QAAQ,SAAW,CACrB,CACF,CAEA,eAAe,EAAQ,EAAgB,EAA2C,CAChF,IAAM,EAAiB,EAAc,CAAM,EACrC,EAAS,MAAM,EAAW,EAAW,OAAQ,MAAM,EAAsB,CAAc,CAAC,EACxF,EAAU,EAAe,EAAY,CAAM,EAC3C,EAAc,EAAmB,CAAM,EAIvC,EAAW,MAAM,EACrB,MAAM,EAAgB,MAAM,EAAuB,MAAM,EAAsB,CAAc,CAAC,CAAC,CACjG,EACM,EAAY,MAAM,EAAiB,EAAU,EAAW,IAAI,EAC5D,EAAe,MAAM,EAAiB,EAAU,CAAS,EASzD,EAAkB,MAAM,EAAoB,CAAQ,EACpD,EAAmB,MAAM,EAA2B,EAAU,CAAS,EACvE,EAAO,MAAM,EAAgB,EAAU,EAAiB,CAAO,EAC/D,EAA8B,EA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E,wBAAyB,EAAM,wBAC/B,wBAAyB,EAAM,wBAC/B,oBAAqB,EAAM,oBAC3B,UAAW,EAAO,iBAAiB,OAAQ,GAAO,EAAG,OAAS,EAAM,IAAI,CAC1E,EAAE,GAEN,EAAY,KAAK,UAAU,EAAQ,IAAA,GAAW,CAAC,EAAI;CAAI,CACzD"}
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./duplicateSelection.cjs"),t=new Set(`statement_block.block.compound_statement.body_statement.constructor_body.do_block.if_statement.for_statement.for_in_statement.enhanced_for_statement.for_range_loop.while_statement.do_statement.try_statement.try_with_resources_statement.with_statement.switch_statement.switch_expression.switch_case.switch_block_statement_group.switch_rule.case_clause.case_statement.match_statement.match_arm.except_clause.catch_clause.finally_clause.elif_clause.ensure.expression_statement.return_statement.return_expression.if_expression.for_expression.while_expression.loop_expression.match_expression.jsx_element.jsx_self_closing_element.if.unless.case.case_match.while.until.for.begin.when`.split(`.`)),n=new Set([`program`,`source_file`,`translation_unit`,`module`,`statement_block`,`block`,`compound_statement`,`body_statement`,`constructor_body`,`class_body`,`block_body`,`do_block`,`do`,`ensure`,`then`,`else`,`case_statement`,`switch_block_statement_group`,`switch_rule`,`expression_case`,`type_case`,`communication_case`,`default_case`]),r=new Set([`identifier`,`constant`,`instance_variable`,`class_variable`,`global_variable`]),i=new Set([`shorthand_property_identifier`,`shorthand_property_identifier_pattern`]),a=new Map([[`number`,`#num`],[`number_literal`,`#num`],[`integer`,`#num`],[`float`,`#num`],[`integer_literal`,`#num`],[`float_literal`,`#num`],[`int_literal`,`#num`],[`rune_literal`,`#char`],[`imaginary_literal`,`#num`],[`decimal_integer_literal`,`#num`],[`hex_integer_literal`,`#num`],[`octal_integer_literal`,`#num`],[`binary_integer_literal`,`#num`],[`decimal_floating_point_literal`,`#num`],[`hex_floating_point_literal`,`#num`],[`string_fragment`,`#str`],[`multiline_string_fragment`,`#str`],[`string_content`,`#str`],[`raw_string_content`,`#str`],[`heredoc_content`,`#str`],[`heredoc_beginning`,`#heredoc`],[`heredoc_end`,`#heredoc`],[`string`,`#str`],[`template_string`,`#str`],[`string_literal`,`#str`],[`interpreted_string_literal`,`#str`],[`raw_string_literal`,`#str`],[`raw_string`,`#str`],[`escape_sequence`,`#str`],[`char_literal`,`#char`],[`character_literal`,`#char`],[`character`,`#char`],[`regex_pattern`,`#regex`]]),o=new Set([`#num`,`#str`,`#char`,`#regex`]),s=new Set([`comment`,`line_comment`,`block_comment`]),c=new Set([`string_fragment`,`multiline_string_fragment`,`string_content`,`raw_string_content`,`escape_sequence`,`heredoc_content`]),l=new Set([`string_fragment`,`multiline_string_fragment`,`string_content`,`raw_string_content`,`escape_sequence`,`heredoc_content`,`string_start`,`string_end`]),u=new Map([[`call_expression`,`function`],[`method_invocation`,`name`],[`call`,`method`],[`attribute`,`attribute`],[`macro_invocation`,`macro`],[`field_access`,`field`],[`new_expression`,`constructor`],[`keyword_argument`,`name`],[`element_value_pair`,`key`],[`generic_function`,`function`],[`template_function`,`name`]]),d={minTokens:40,maxGapTokens:30,minSimilarityPercent:70};function f(e,t){return e*5>=t}function p(t,n,r){let i=r?.minTokens??d.minTokens,a=r?.maxGapTokens??d.maxGapTokens,o=r?.minSimilarityPercent??d.minSimilarityPercent,s=[],c=[],l=[];h(t,s,c,l);let u=b(s),f=[...S(s,u,c,i),...C(s,u,l,i)],p=Y(re(e.selectMaximalGroups(f,e=>e.length>=2)),a),m=D(s,u,c,i,o,p);return ie([...p.filter(e=>e.length>0),...m],n,s)}function m(t,n){let r=n?.minTokens??d.minTokens,i=[],a=[],o=[];h(t,i,a,o);let s=b(i),c=S(i,s,a,r);for(let e of o){let t=e[0],n=e.at(-1);!t||!n||n.endTokenIndex-t.startTokenIndex<r||c.push(z(`s:${W(i,s,t.startTokenIndex,n.endTokenIndex)}`,t.startTokenIndex,n.endTokenIndex,t,n))}return{candidates:e.dedupeByRegion(c),tokens:i,containerStatements:o}}function h(e,r,i,a){function o(e){let c=r.length,l=e.childCount===0?void 0:g(e);if(e.childCount===0)ee(e,r);else if(l!==void 0)r.push(_(l,v(e,l),e.startPosition.row,e.endPosition.row));else if(!s.has(e.type)){let t=[],r=e.isNamed&&n.has(e.type);for(let n of e.children){let e=o(n);r&&n.isNamed&&!s.has(n.type)&&t.push(e)}r&&t.length>0&&a.push(t)}let u={startTokenIndex:c,endTokenIndex:r.length,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1};return e.isNamed&&t.has(e.type)&&i.push(u),u}o(e)}function g(e){let t=e.isNamed?a.get(e.type):void 0;if(t!==void 0)return e.namedChildren.every(e=>l.has(e.type))?t:void 0}function ee(e,t){if(s.has(e.type))return;let n=e.startPosition.row,o=e.endPosition.row;if(e.isNamed&&i.has(e.type)){t.push(_(e.text,void 0,n,o,!0),_(`:`,void 0,n,o),{kind:`id`,text:e.text,textHash:0,textHash2:0,startRow:n,endRow:o});return}if(e.isNamed&&r.has(e.type)&&!x(e)){t.push({kind:`id`,text:e.text,textHash:0,textHash2:0,startRow:n,endRow:o});return}let c=e.isNamed?a.get(e.type):void 0;c===void 0?t.push(_(e.text,void 0,n,o,e.isNamed)):t.push(_(c,v(e,c),n,o))}function _(e,t,n,r,i=!1){let a={kind:`text`,text:e,textHash:K(e),textHash2:q(e),startRow:n,endRow:r};return t!==void 0&&o.has(e)&&(a.literalHash=K(t),a.literalHash2=q(t)),i&&(a.isName=!0),a}function v(e,t){if(t!==`#str`&&t!==`#char`||c.has(e.type))return e.text;let n=e.namedChildren.filter(e=>c.has(e.type));return n.length>0?n.map(e=>e.text).join(``):te(e.text)}const y=new Set([`"`,`'`,"`"]);function te(e){let t=e[0];return e.length>=2&&t!==void 0&&y.has(t)&&e.endsWith(t)?e.slice(1,-1):e}function b(e){let t=new Int32Array(e.length+1);for(let[n,r]of e.entries())t[n+1]=(t[n]??0)+(r.literalHash===void 0?0:1);return t}function x(e){let t=e.parent;if(!t)return!1;if(t.type===`method_reference`||t.type===`call`&&t.childForFieldName(`function`)?.id===e.id||e.type===`constant`&&t.type===`call`&&t.childForFieldName(`receiver`)?.id===e.id||t.type===`method_invocation`&&t.childForFieldName(`object`)?.id===e.id&&/^\p{Lu}/u.test(e.text))return!0;if((t.type===`scoped_identifier`||t.type===`qualified_identifier`)&&(t.childForFieldName(`name`)?.id===e.id||t.childForFieldName(`path`)?.id===e.id)){let e=t;for(;e.parent&&(e.parent.type===`scoped_identifier`||e.parent.type===`qualified_identifier`||e.parent.type===`generic_function`||e.parent.type===`template_function`);)e=e.parent;if(e.parent?.type===`call_expression`&&e.parent.childForFieldName(`function`)?.id===e.id)return!0}if(t.type===`literal_element`&&t.parent?.type===`keyed_element`&&t.parent.namedChild(0)?.id===t.id)return!0;let n=u.get(t.type);return n!==void 0&&t.childForFieldName(n)?.id===e.id}function S(e,t,n,r){let i=[];for(let a of n)a.endTokenIndex-a.startTokenIndex<r||i.push(z(`b:${W(e,t,a.startTokenIndex,a.endTokenIndex)}`,a.startTokenIndex,a.endTokenIndex,a,a));return i}function C(e,t,n,r){return w([{tokens:e,literalCountPrefix:t,containers:n}],r,!1).map(({candidate:e})=>e)}function w(e,t,n){let r=[],i=[],a=[];for(let[t,n]of e.entries())for(let e of n.containers)i.push(t),a.push(e);let o=t=>e[i[t]??0],s=new Map,c=a.map((e,n)=>E(o(n)?.tokens??[],e,t));for(let[e,t]of c.entries()){let n=i[e]??0;for(let[r,i]of t.windowKeysByStart.entries())for(let t of i){if(t===void 0)continue;let i=s.get(t);i?(i.count+=1,i.containerIndex!==e&&(i.containerIndex=-1),i.contextIndex!==n&&(i.contextIndex=-1),i.minStart=Math.min(i.minStart,r),i.maxStart=Math.max(i.maxStart,r)):s.set(t,{count:1,containerIndex:e,contextIndex:n,minStart:r,maxStart:r})}}let l=(e,t)=>{if(e===void 0)return!1;let r=s.get(e);return r===void 0||r.count<2?!1:n?r.contextIndex===-1:r.containerIndex===-1||r.maxStart-r.minStart>=t},u=e=>{let t=c[e.containerIndex]?.statementHashes??[],n=t[e.start];for(let r=e.start+1;r<e.start+e.length;r+=1)if(t[r]!==n)return!0;return!1},d=[];for(let[e,t]of c.entries())for(let[n,r]of t.windowKeysByStart.entries())for(let[i,a]of r.entries()){if(!l(a,i)||!u({containerIndex:e,start:n,length:i}))continue;let r=t.windowKeysByStart[n]?.[i+1],o=t.windowKeysByStart[n-1]?.[i+1];l(r,i+1)||l(o,i+1)||d.push({containerIndex:e,start:n,length:i})}let f=new Set(d.map(T)),p=d;for(;p.length>0;){let e=[];for(let t of p){let n=a[t.containerIndex],s=n?.[t.start],c=n?.[t.start+t.length-1],l=o(t.containerIndex);if(!s||!c||!l)continue;let u=`s:${W(l.tokens,l.literalCountPrefix,s.startTokenIndex,c.endTokenIndex)}`;r.push({candidate:z(u,s.startTokenIndex,c.endTokenIndex,s,c),contextIndex:i[t.containerIndex]??0}),e.push(t)}p=[];for(let t of e)for(let e of[t.start,t.start+1]){let n={containerIndex:t.containerIndex,start:e,length:t.length-1},r=c[t.containerIndex]?.windowKeysByStart[e]?.[n.length];f.has(T(n))||!l(r,n.length)||!u(n)||(f.add(T(n)),p.push(n))}}return r}function T(e){return`${e.containerIndex}:${e.start}:${e.length}`}function E(e,t,n){let r=t.map(t=>ne(e,t.startTokenIndex,t.endTokenIndex)),i=[];for(let e=0;e<t.length;e+=1){let a=[],o=5381,s=0,c=Math.min(t.length,e+100);for(let i=e;i<c;i+=1){let c=t[i],l=r[i];if(!c||l===void 0)break;o=J(o,l),s+=c.endTokenIndex-c.startTokenIndex;let u=i-e+1;a[u]=u>=2&&s>=n?J(o,u):void 0}i.push(a)}return{windowKeysByStart:i,statementHashes:r}}function D(e,t,n,r,i,a){if(i>=100)return[];let o=O(n.filter(e=>{let n=e.endTokenIndex-e.startTokenIndex,i=(t[e.endTokenIndex]??0)-(t[e.startTokenIndex]??0);return n>=r&&!f(i,n)}).toSorted((e,t)=>e.startTokenIndex-t.startTokenIndex||t.endTokenIndex-e.endTokenIndex));if(o.length<2)return[];let s=o.map(e=>{let t=[];for(let[n,r]of a.entries())r.some(t=>t.startTokenIndex<e.endTokenIndex&&e.startTokenIndex<t.endTokenIndex)&&t.push(n);return t}),c=new Map,l=o.map(t=>N(e,t,c)),u=l.map(({sequence:e})=>F(e)),d=I(u),p=o.map((e,t)=>t),m=e=>{let t=e;for(;p[t]!==t;)t=p[t]??t;for(;p[e]!==t;){let n=p[e]??t;p[e]=t,e=n}return t};for(let[e,t]of d){let n=Math.floor(e/u.length),r=e%u.length,a=l[n],o=l[r],c=u[n],d=u[r];if(!(!a||!o||!c||!d)&&!((s[n]?.length??0)>0&&(s[r]?.length??0)>0)&&!(t*100<10*Math.min(c.size,d.size))&&!(P(a,o)*100<=50*Math.max(a.contentTotal,o.contentTotal))&&L(a.sequence,o.sequence)*100>=i*Math.max(a.sequence.length,o.sequence.length)){let e=m(n),t=m(r);p[Math.max(e,t)]=Math.min(e,t)}}let h=new Map;for(let e of o.keys()){let t=m(e),n=h.get(t)??[];n.push(e),h.set(t,n)}let g=[];for(let e of h.values()){if(e.length<2)continue;let t=e.filter(e=>(s[e]?.length??0)===0),n=e.filter(e=>(s[e]?.length??0)>0);if(n.length===0){g.push(e.flatMap(e=>o[e]?[M(o[e])]:[]));continue}if(t.length===0)continue;let r=t=>e.some(e=>{let n=o[e];return n!==void 0&&t.startTokenIndex<n.endTokenIndex&&n.startTokenIndex<t.endTokenIndex}),i=[...new Set(n.flatMap(e=>s[e]??[]))].filter(e=>{let t=a[e];return t!==void 0&&t.length>0&&t.every(r)}).toSorted((e,t)=>e-t),[c,...l]=i;if(c!==void 0){let t=new Set,n=[];for(let r of e){let e=o[r];if(!e)continue;let c=[];for(let n of i)for(let r of a[n]??[])!t.has(r)&&r.startTokenIndex<e.endTokenIndex&&e.startTokenIndex<r.endTokenIndex&&(t.add(r),c.push({occurrence:r,groupIndex:n}));c.sort((e,t)=>e.occurrence.startTokenIndex-t.occurrence.startTokenIndex||e.occurrence.endTokenIndex-t.occurrence.endTokenIndex);let l=[],u=new Set;for(let{occurrence:e,groupIndex:t}of c)u.has(t)&&(n.push(A(l)),l=[],u.clear()),l.push(e),u.add(t);l.length>0&&n.push(A(l)),c.length===0&&(s[r]?.length??0)===0&&n.push(M(e))}n.sort((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex);for(let e of n)e.sharedWithMergedGroup=void 0;a[c]=n;for(let e of l)a[e]=[]}else t.length>=2&&g.push(t.flatMap(e=>o[e]?[M(o[e])]:[]))}return g.sort(X),g}function O(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n.at(-1).range.endTokenIndex<=r.startTokenIndex;)n.pop();let e=n.at(-1);if(e&&e.range.startTokenIndex===r.startTokenIndex&&e.range.endTokenIndex===r.endTokenIndex)continue;let i={range:r,children:[]};e?e.children.push(i):t.push(i),n.push(i)}let r=[],i=e=>{if(k(e))for(let t of e.children)i(t);else r.push(e.range)};for(let e of t)i(e);return r}function k(e){let[t]=e.children;return e.children.length>=2||t!==void 0&&k(t)}function A(e){let t=e[0];if(!t||e.length===1)return t??j();let n=[];for(let t of e.flatMap(e=>e.segments).toSorted((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex)){let e=n.at(-1);e&&t.startTokenIndex<e.endTokenIndex?e.endTokenIndex=Math.max(e.endTokenIndex,t.endTokenIndex):n.push({...t})}return{segments:n,tokenCount:n.reduce((e,t)=>e+t.endTokenIndex-t.startTokenIndex,0),startTokenIndex:Math.min(...e.map(e=>e.startTokenIndex)),endTokenIndex:Math.max(...e.map(e=>e.endTokenIndex)),startIndex:Math.min(...e.map(e=>e.startIndex)),endIndex:Math.max(...e.map(e=>e.endIndex)),startLine:Math.min(...e.map(e=>e.startLine)),endLine:Math.max(...e.map(e=>e.endLine))}}function j(){return{segments:[],tokenCount:0,startTokenIndex:0,endTokenIndex:0,startIndex:0,endIndex:0,startLine:0,endLine:0}}function M(e){return{segments:[{startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex}],tokenCount:e.endTokenIndex-e.startTokenIndex,startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startLine,endLine:e.endLine}}function N(e,t,n){let r=new Int32Array(t.endTokenIndex-t.startTokenIndex),i=new Map,a=new Map,o=0;for(let s=t.startTokenIndex;s<t.endTokenIndex;s+=1){let c=e[s];if(!c)continue;let l;if(c.kind===`id`){let e=i.get(c.text);e===void 0&&(e=i.size,i.set(c.text,e)),l=-(e+1)}else{let e=`${c.textHash}:${c.textHash2}:${c.literalHash??0}:${c.literalHash2??0}`,t=n.get(e);t===void 0&&(t=n.size,n.set(e,t)),l=t,(c.isName===!0||c.literalHash!==void 0)&&(a.set(l,(a.get(l)??0)+1),o+=1)}r[s-t.startTokenIndex]=l}return{sequence:r,contentCountBySymbol:a,contentTotal:o}}function P(e,t){let[n,r]=e.contentCountBySymbol.size<=t.contentCountBySymbol.size?[e,t]:[t,e],i=0;for(let[e,t]of n.contentCountBySymbol)i+=Math.min(t,r.contentCountBySymbol.get(e)??0);return i}function F(e){let t=new Set;for(let n=0;n+5<=e.length;n+=1){let r=5381;for(let t=0;t<5;t+=1)r=Math.imul(r,31)+(e[n+t]??0)|0;t.add(r)}return t}function I(e){let t=new Map;for(let[n,r]of e.entries())for(let e of r){let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}let n=new Map;for(let r of t.values())for(let t=0;t<r.length;t+=1){let i=r[t]??0;for(let a=t+1;a<r.length;a+=1){let t=i*e.length+(r[a]??0);n.set(t,(n.get(t)??0)+1)}}return n}function L(e,t){let n=e.length+31>>>5,r=new Map;for(let[t,i]of e.entries()){let e=r.get(i);e||(e=new Uint32Array(n),r.set(i,e));let a=t>>>5;e[a]=(e[a]??0)|1<<(t&31)}let i=new Uint32Array(n);for(let e of t){let t=r.get(e),a=1,o=0;for(let e=0;e<n;e+=1){let n=i[e]??0,r=((t?.[e]??0)|n)>>>0,s=(n<<1|a)>>>0;a=n>>>31;let c=r-s-o;o=+(c<0),i[e]=r&~c}}let a=0;for(let e of i)a+=R(e);return a}function R(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),Math.imul(t+(t>>>4)&252645135,16843009)>>>24&255}function z(e,t,n,r,i){return{fingerprint:e,tokenCount:n-t,startTokenIndex:t,endTokenIndex:n,startIndex:r.startIndex,endIndex:i.endIndex,startLine:r.startLine,endLine:i.endLine}}const B=[],V=[];function H(e){let t=B[e];return t===void 0&&(t=K(`$${e}`),B[e]=t),t}function U(e){let t=V[e];return t===void 0&&(t=q(`$${e}`),V[e]=t),t}function W(e,t,n,r){let[i,a]=G(e,n,r,f((t[r]??0)-(t[n]??0),r-n));return`${i}:${a}:${r-n}`}function ne(e,t,n){let[r,i]=G(e,t,n,!1);return r^Math.imul(i,31)}function G(e,t,n,r){let i=new Map,a=5381,o=52711;for(let s=t;s<n;s+=1){let t=e[s];if(!t)continue;let n,c;if(t.kind===`id`){let e=i.get(t.text);e===void 0&&(e=i.size,i.set(t.text,e)),n=H(e),c=U(e)}else n=t.textHash,c=t.textHash2;a=Math.imul(a,31)+n|0,o=Math.imul(o,37)^c,r&&t.literalHash!==void 0&&t.literalHash2!==void 0&&(a=Math.imul(a,31)+t.literalHash|0,o=Math.imul(o,37)^t.literalHash2)}return[a,o]}function K(e){let t=5381;for(let n=0;n<e.length;n+=1)t=Math.imul(t,33)^e.charCodeAt(n);return t}function q(e){let t=-2128831035;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return t}function J(e,t){return Math.imul(e,31)+t}function re(e){let t=[];for(let n of e.values()){let e=n.map(e=>({segments:[{startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex}],tokenCount:e.tokenCount,startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startLine,endLine:e.endLine}));e.sort((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex),t.push(e)}return t}function Y(e,t){if(t<=0||e.length<2)return e;e.sort(X);for(let n=!0;n;){n=!1;for(let r=0;r<e.length&&!n;r+=1)for(let i=r+1;i<e.length;i+=1){let a=e[r],o=e[i];if(!a||!o)continue;let s=Z(a,o,t),c=s??Z(o,a,t);if(!c)continue;let l=s?c.firstConsumed:c.secondConsumed,u=s?c.secondConsumed:c.firstConsumed;l&&u?(e[r]=c.merged,e.splice(i,1)):u?e[i]=c.merged:e[r]=c.merged;for(let e of c.pairedRetained)e.sharedWithMergedGroup=!0;e.sort(X),n=!0;break}}return e}function X(e,t){let n=e[0],r=t[0];return(n?.startTokenIndex??0)-(r?.startTokenIndex??0)||(n?.endTokenIndex??0)-(r?.endTokenIndex??0)}function Z(e,t,n){let r=e.filter(e=>!e.sharedWithMergedGroup),i=t.filter(e=>!e.sharedWithMergedGroup),a=[],o=0,s=-1;for(let e of i){for(;o<r.length;){let t=r[o];if(t&&t.endTokenIndex+n<e.startTokenIndex)o+=1;else break}let t=r[o];t&&t.endTokenIndex<=e.startTokenIndex&&t.startTokenIndex>=s&&(a.push([t,e]),s=e.endTokenIndex,o+=1)}let c=a.length===e.length,l=a.length===t.length;if(!(a.length<2||!c&&!l))return{merged:a.map(([e,t])=>({...e,sharedWithMergedGroup:void 0,segments:[...e.segments,...t.segments],tokenCount:e.tokenCount+t.tokenCount,endTokenIndex:t.endTokenIndex,endIndex:t.endIndex,endLine:t.endLine})),firstConsumed:c,secondConsumed:l,pairedRetained:c===l?[]:a.map(([e,t])=>c?t:e)}}function Q(e){let t=0,n=0,r=!1;for(let i of e){if(i.sharedWithMergedGroup){r=!0;continue}t+=i.segments.length,n=Math.max(n,i.segments.length)}return r?t:t-n}function ie(e,t,n){let r=0,i=0,a=[],o=new Set;for(let s of e){r+=Q(s);for(let e of s){i=Math.max(i,e.tokenCount);for(let r of e.segments)$(r,n,t,o)}a.push(s.map(({startLine:e,endLine:t})=>({startLine:e,endLine:t})).toSorted((e,t)=>e.startLine-t.startLine))}return a.sort((e,t)=>(e[0]?.startLine??0)-(t[0]?.startLine??0)),{duplicateBlockCount:r,duplicateBlockGroupCount:e.length,duplicateBlockGroups:a,duplicateLineCount:o.size,duplicateLineNumbers:[...o].toSorted((e,t)=>e-t),duplicationRatio:t.size===0?0:o.size/t.size,maxDuplicateBlockSize:i}}function $(e,t,n,r){for(let i=e.startTokenIndex;i<e.endTokenIndex;i+=1){let e=t[i];for(let t=e?.startRow??0;t<=(e?.endRow??-1);t+=1)(!n||n.has(t+1))&&r.add(t+1)}}exports.buildLiteralCountPrefix=b,exports.collectCrossFileDuplicateCandidates=m,exports.collectSegmentLines=$,exports.collectSequenceWindowCandidates=w,exports.countRedundantFragments=Q,exports.defaultDuplicationOptions=d,exports.measureDuplication=p,exports.mergeAdjacentGroups=Y;
1
+ "use strict";const e=require("./duplicateSelection.cjs"),t=new Set(`statement_block.block.compound_statement.body_statement.constructor_body.do_block.if_statement.for_statement.for_in_statement.enhanced_for_statement.for_range_loop.while_statement.do_statement.try_statement.try_with_resources_statement.with_statement.switch_statement.switch_expression.switch_case.switch_block_statement_group.switch_rule.case_clause.case_statement.match_statement.match_arm.except_clause.catch_clause.finally_clause.elif_clause.ensure.expression_statement.return_statement.return_expression.if_expression.for_expression.while_expression.loop_expression.match_expression.jsx_element.jsx_self_closing_element.if.unless.case.case_match.while.until.for.begin.when`.split(`.`)),n=new Set([`program`,`source_file`,`translation_unit`,`module`,`statement_block`,`block`,`compound_statement`,`body_statement`,`constructor_body`,`class_body`,`block_body`,`do_block`,`do`,`ensure`,`then`,`else`,`case_statement`,`switch_block_statement_group`,`switch_rule`,`expression_case`,`type_case`,`communication_case`,`default_case`]),r=new Set([`identifier`,`constant`,`instance_variable`,`class_variable`,`global_variable`]),i=new Set([`shorthand_property_identifier`,`shorthand_property_identifier_pattern`]),a=new Map([[`number`,`#num`],[`number_literal`,`#num`],[`integer`,`#num`],[`float`,`#num`],[`integer_literal`,`#num`],[`float_literal`,`#num`],[`int_literal`,`#num`],[`rune_literal`,`#char`],[`imaginary_literal`,`#num`],[`decimal_integer_literal`,`#num`],[`hex_integer_literal`,`#num`],[`octal_integer_literal`,`#num`],[`binary_integer_literal`,`#num`],[`decimal_floating_point_literal`,`#num`],[`hex_floating_point_literal`,`#num`],[`string_fragment`,`#str`],[`multiline_string_fragment`,`#str`],[`string_content`,`#str`],[`raw_string_content`,`#str`],[`heredoc_content`,`#str`],[`heredoc_beginning`,`#heredoc`],[`heredoc_end`,`#heredoc`],[`string`,`#str`],[`template_string`,`#str`],[`string_literal`,`#str`],[`interpreted_string_literal`,`#str`],[`raw_string_literal`,`#str`],[`raw_string`,`#str`],[`escape_sequence`,`#str`],[`char_literal`,`#char`],[`character_literal`,`#char`],[`character`,`#char`],[`regex_pattern`,`#regex`]]),o=new Set([`#num`,`#str`,`#char`,`#regex`]),s=new Set([`comment`,`line_comment`,`block_comment`]),c=new Set([`string_fragment`,`multiline_string_fragment`,`string_content`,`raw_string_content`,`escape_sequence`,`heredoc_content`]),l=new Set([`string_fragment`,`multiline_string_fragment`,`string_content`,`raw_string_content`,`escape_sequence`,`heredoc_content`,`string_start`,`string_end`]),u=new Map([[`call_expression`,`function`],[`method_invocation`,`name`],[`call`,`method`],[`attribute`,`attribute`],[`macro_invocation`,`macro`],[`field_access`,`field`],[`new_expression`,`constructor`],[`keyword_argument`,`name`],[`element_value_pair`,`key`],[`generic_function`,`function`],[`template_function`,`name`]]),d={minTokens:40,maxGapTokens:30,minSimilarityPercent:70};function f(e,t){return e*5>=t}function p(t,n,r){let i=r?.minTokens??d.minTokens,a=r?.maxGapTokens??d.maxGapTokens,o=r?.minSimilarityPercent??d.minSimilarityPercent,s=[],c=[],l=[];h(t,s,c,l);let u=b(s),f=[...S(s,u,c,i),...C(s,u,l,i)],p=Y(re(e.selectMaximalGroups(f,e=>e.length>=2)),a),m=D(s,u,c,i,o,p);return ie([...p.filter(e=>e.length>0),...m],n,s)}function m(t,n){let r=n?.minTokens??d.minTokens,i=[],a=[],o=[];h(t,i,a,o);let s=b(i),c=S(i,s,a,r);for(let e of o){let t=e[0],n=e.at(-1);!t||!n||n.endTokenIndex-t.startTokenIndex<r||c.push(z(`s:${W(i,s,t.startTokenIndex,n.endTokenIndex)}`,t.startTokenIndex,n.endTokenIndex,t,n))}return{candidates:e.dedupeByRegion(c),tokens:i,containerStatements:o}}function h(e,r,i,a){function o(e){let c=r.length,l=e.childCount===0?void 0:g(e);if(e.childCount===0)ee(e,r);else if(l!==void 0)r.push(_(l,v(e,l),e.startPosition.row,e.endPosition.row));else if(!s.has(e.type)){let t=[],r=e.isNamed&&n.has(e.type);for(let n of e.children){let e=o(n);r&&n.isNamed&&!s.has(n.type)&&t.push(e)}r&&t.length>0&&a.push(t)}let u={startTokenIndex:c,endTokenIndex:r.length,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1};return e.isNamed&&t.has(e.type)&&i.push(u),u}o(e)}function g(e){let t=e.isNamed?a.get(e.type):void 0;if(t!==void 0)return e.namedChildren.every(e=>l.has(e.type))?t:void 0}function ee(e,t){if(s.has(e.type))return;let n=e.startPosition.row,o=e.endPosition.row;if(e.isNamed&&i.has(e.type)){t.push(_(e.text,void 0,n,o,!0),_(`:`,void 0,n,o),{kind:`id`,text:e.text,textHash:0,textHash2:0,startRow:n,endRow:o});return}if(e.isNamed&&r.has(e.type)&&!x(e)){t.push({kind:`id`,text:e.text,textHash:0,textHash2:0,startRow:n,endRow:o});return}let c=e.isNamed?a.get(e.type):void 0;c===void 0?t.push(_(e.text,void 0,n,o,e.isNamed)):t.push(_(c,v(e,c),n,o))}function _(e,t,n,r,i=!1){let a={kind:`text`,text:e,textHash:K(e),textHash2:q(e),startRow:n,endRow:r};return t!==void 0&&o.has(e)&&(a.literalHash=K(t),a.literalHash2=q(t)),i&&(a.isName=!0),a}function v(e,t){if(t!==`#str`&&t!==`#char`||c.has(e.type))return e.text;let n=e.namedChildren.filter(e=>c.has(e.type));return n.length>0?n.map(e=>e.text).join(``):te(e.text)}const y=new Set([`"`,`'`,"`"]);function te(e){let t=e[0];return e.length>=2&&t!==void 0&&y.has(t)&&e.endsWith(t)?e.slice(1,-1):e}function b(e){let t=new Int32Array(e.length+1);for(let[n,r]of e.entries())t[n+1]=(t[n]??0)+(r.literalHash===void 0?0:1);return t}function x(e){let t=e.parent;if(!t)return!1;if(t.type===`method_reference`||t.type===`call`&&t.childForFieldName(`function`)?.id===e.id||e.type===`constant`&&t.type===`call`&&t.childForFieldName(`receiver`)?.id===e.id||t.type===`method_invocation`&&t.childForFieldName(`object`)?.id===e.id&&/^\p{Lu}/u.test(e.text))return!0;if((t.type===`scoped_identifier`||t.type===`qualified_identifier`)&&(t.childForFieldName(`name`)?.id===e.id||t.childForFieldName(`path`)?.id===e.id)){let e=t;for(;e.parent&&(e.parent.type===`scoped_identifier`||e.parent.type===`qualified_identifier`||e.parent.type===`generic_function`||e.parent.type===`template_function`);)e=e.parent;if(e.parent?.type===`call_expression`&&e.parent.childForFieldName(`function`)?.id===e.id)return!0}if(t.type===`literal_element`&&t.parent?.type===`keyed_element`&&t.parent.namedChild(0)?.id===t.id)return!0;let n=u.get(t.type);return n!==void 0&&t.childForFieldName(n)?.id===e.id}function S(e,t,n,r){let i=[];for(let a of n)a.endTokenIndex-a.startTokenIndex<r||i.push(z(`b:${W(e,t,a.startTokenIndex,a.endTokenIndex)}`,a.startTokenIndex,a.endTokenIndex,a,a));return i}function C(e,t,n,r){return w([{tokens:e,literalCountPrefix:t,containers:n}],r,!1).map(({candidate:e})=>e)}function w(e,t,n){let r=[],i=[],a=[];for(let[t,n]of e.entries())for(let e of n.containers)i.push(t),a.push(e);let o=t=>e[i[t]??0],s=new Map,c=a.map((e,n)=>E(o(n)?.tokens??[],e,t));for(let[e,t]of c.entries()){let n=i[e]??0;for(let[r,i]of t.windowKeysByStart.entries())for(let t of i){if(t===void 0)continue;let i=s.get(t);i?(i.count+=1,i.containerIndex!==e&&(i.containerIndex=-1),i.contextIndex!==n&&(i.contextIndex=-1),i.minStart=Math.min(i.minStart,r),i.maxStart=Math.max(i.maxStart,r)):s.set(t,{count:1,containerIndex:e,contextIndex:n,minStart:r,maxStart:r})}}let l=(e,t)=>{if(e===void 0)return!1;let r=s.get(e);return r===void 0||r.count<2?!1:n?r.contextIndex===-1:r.containerIndex===-1||r.maxStart-r.minStart>=t},u=e=>{let t=c[e.containerIndex]?.statementHashes??[],n=t[e.start];for(let r=e.start+1;r<e.start+e.length;r+=1)if(t[r]!==n)return!0;return!1},d=[];for(let[e,t]of c.entries())for(let[n,r]of t.windowKeysByStart.entries())for(let[i,a]of r.entries()){if(!l(a,i)||!u({containerIndex:e,start:n,length:i}))continue;let r=t.windowKeysByStart[n]?.[i+1],o=t.windowKeysByStart[n-1]?.[i+1];l(r,i+1)||l(o,i+1)||d.push({containerIndex:e,start:n,length:i})}let f=new Set(d.map(T)),p=d;for(;p.length>0;){let e=[];for(let t of p){let n=a[t.containerIndex],s=n?.[t.start],c=n?.[t.start+t.length-1],l=o(t.containerIndex);if(!s||!c||!l)continue;let u=`s:${W(l.tokens,l.literalCountPrefix,s.startTokenIndex,c.endTokenIndex)}`;r.push({candidate:z(u,s.startTokenIndex,c.endTokenIndex,s,c),contextIndex:i[t.containerIndex]??0}),e.push(t)}p=[];for(let t of e)for(let e of[t.start,t.start+1]){let n={containerIndex:t.containerIndex,start:e,length:t.length-1},r=c[t.containerIndex]?.windowKeysByStart[e]?.[n.length];f.has(T(n))||!l(r,n.length)||!u(n)||(f.add(T(n)),p.push(n))}}return r}function T(e){return`${e.containerIndex}:${e.start}:${e.length}`}function E(e,t,n){let r=t.map(t=>ne(e,t.startTokenIndex,t.endTokenIndex)),i=[];for(let e=0;e<t.length;e+=1){let a=[],o=5381,s=0,c=Math.min(t.length,e+100);for(let i=e;i<c;i+=1){let c=t[i],l=r[i];if(!c||l===void 0)break;o=J(o,l),s+=c.endTokenIndex-c.startTokenIndex;let u=i-e+1;a[u]=u>=2&&s>=n?J(o,u):void 0}i.push(a)}return{windowKeysByStart:i,statementHashes:r}}function D(e,t,n,r,i,a){if(i>=100)return[];let o=O(n.filter(e=>{let n=e.endTokenIndex-e.startTokenIndex,i=(t[e.endTokenIndex]??0)-(t[e.startTokenIndex]??0);return n>=r&&!f(i,n)}).toSorted((e,t)=>e.startTokenIndex-t.startTokenIndex||t.endTokenIndex-e.endTokenIndex));if(o.length<2)return[];let s=o.map(e=>{let t=[];for(let[n,r]of a.entries())r.some(t=>t.startTokenIndex<e.endTokenIndex&&e.startTokenIndex<t.endTokenIndex)&&t.push(n);return t}),c=new Map,l=o.map(t=>N(e,t,c)),u=l.map(({sequence:e})=>F(e)),d=I(u),p=o.map((e,t)=>t),m=e=>{let t=e;for(;p[t]!==t;)t=p[t]??t;for(;p[e]!==t;){let n=p[e]??t;p[e]=t,e=n}return t};for(let[e,t]of d){let n=Math.floor(e/u.length),r=e%u.length,a=l[n],o=l[r],c=u[n],d=u[r];if(!(!a||!o||!c||!d)&&!((s[n]?.length??0)>0&&(s[r]?.length??0)>0)&&!(t*100<10*Math.min(c.size,d.size))&&!(P(a,o)*100<=50*Math.max(a.contentTotal,o.contentTotal))&&L(a.sequence,o.sequence)*100>=i*Math.max(a.sequence.length,o.sequence.length)){let e=m(n),t=m(r);p[Math.max(e,t)]=Math.min(e,t)}}let h=new Map;for(let e of o.keys()){let t=m(e),n=h.get(t)??[];n.push(e),h.set(t,n)}let g=[];for(let e of h.values()){if(e.length<2)continue;let t=e.filter(e=>(s[e]?.length??0)===0),n=e.filter(e=>(s[e]?.length??0)>0);if(n.length===0){g.push(e.flatMap(e=>o[e]?[M(o[e])]:[]));continue}if(t.length===0)continue;let r=t=>e.some(e=>{let n=o[e];return n!==void 0&&t.startTokenIndex<n.endTokenIndex&&n.startTokenIndex<t.endTokenIndex}),i=[...new Set(n.flatMap(e=>s[e]??[]))].filter(e=>{let t=a[e];return t!==void 0&&t.length>0&&t.every(r)}).toSorted((e,t)=>e-t),[c,...l]=i;if(c!==void 0){let t=new Set,n=[];for(let r of e){let e=o[r];if(!e)continue;let c=[];for(let n of i)for(let r of a[n]??[])!t.has(r)&&r.startTokenIndex<e.endTokenIndex&&e.startTokenIndex<r.endTokenIndex&&(t.add(r),c.push({occurrence:r,groupIndex:n}));c.sort((e,t)=>e.occurrence.startTokenIndex-t.occurrence.startTokenIndex||e.occurrence.endTokenIndex-t.occurrence.endTokenIndex);let l=[],u=new Set;for(let{occurrence:e,groupIndex:t}of c)u.has(t)&&(n.push(A(l)),l=[],u.clear()),l.push(e),u.add(t);l.length>0&&n.push(A(l)),c.length===0&&(s[r]?.length??0)===0&&n.push(M(e))}n.sort((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex);for(let e of n)e.sharedWithMergedGroup=void 0;a[c]=n;for(let e of l)a[e]=[]}else t.length>=2&&g.push(t.flatMap(e=>o[e]?[M(o[e])]:[]))}return g.sort(X),g}function O(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n.at(-1).range.endTokenIndex<=r.startTokenIndex;)n.pop();let e=n.at(-1);if(e&&e.range.startTokenIndex===r.startTokenIndex&&e.range.endTokenIndex===r.endTokenIndex)continue;let i={range:r,children:[]};e?e.children.push(i):t.push(i),n.push(i)}let r=[],i=e=>{if(k(e))for(let t of e.children)i(t);else r.push(e.range)};for(let e of t)i(e);return r}function k(e){let[t]=e.children;return e.children.length>=2||t!==void 0&&k(t)}function A(e){let t=e[0];if(!t||e.length===1)return t??j();let n=[];for(let t of e.flatMap(e=>e.segments).toSorted((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex)){let e=n.at(-1);e&&t.startTokenIndex<e.endTokenIndex?e.endTokenIndex=Math.max(e.endTokenIndex,t.endTokenIndex):n.push({...t})}return{segments:n,tokenCount:n.reduce((e,t)=>e+t.endTokenIndex-t.startTokenIndex,0),startTokenIndex:Math.min(...e.map(e=>e.startTokenIndex)),endTokenIndex:Math.max(...e.map(e=>e.endTokenIndex)),startIndex:Math.min(...e.map(e=>e.startIndex)),endIndex:Math.max(...e.map(e=>e.endIndex)),startLine:Math.min(...e.map(e=>e.startLine)),endLine:Math.max(...e.map(e=>e.endLine))}}function j(){return{segments:[],tokenCount:0,startTokenIndex:0,endTokenIndex:0,startIndex:0,endIndex:0,startLine:0,endLine:0}}function M(e){return{segments:[{startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex}],tokenCount:e.endTokenIndex-e.startTokenIndex,startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startLine,endLine:e.endLine}}function N(e,t,n){let r=new Int32Array(t.endTokenIndex-t.startTokenIndex),i=new Map,a=new Map,o=0;for(let s=t.startTokenIndex;s<t.endTokenIndex;s+=1){let c=e[s];if(!c)continue;let l;if(c.kind===`id`){let e=i.get(c.text);e===void 0&&(e=i.size,i.set(c.text,e)),l=-(e+1)}else{let e=`${c.textHash}:${c.textHash2}:${c.literalHash??0}:${c.literalHash2??0}`,t=n.get(e);t===void 0&&(t=n.size,n.set(e,t)),l=t,(c.isName===!0||c.literalHash!==void 0)&&(a.set(l,(a.get(l)??0)+1),o+=1)}r[s-t.startTokenIndex]=l}return{sequence:r,contentCountBySymbol:a,contentTotal:o}}function P(e,t){let[n,r]=e.contentCountBySymbol.size<=t.contentCountBySymbol.size?[e,t]:[t,e],i=0;for(let[e,t]of n.contentCountBySymbol)i+=Math.min(t,r.contentCountBySymbol.get(e)??0);return i}function F(e){let t=new Set;for(let n=0;n+5<=e.length;n+=1){let r=5381;for(let t=0;t<5;t+=1)r=Math.imul(r,31)+(e[n+t]??0)|0;t.add(r)}return t}function I(e){let t=new Map;for(let[n,r]of e.entries())for(let e of r){let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}let n=new Map;for(let r of t.values())for(let t=0;t<r.length;t+=1){let i=r[t]??0;for(let a=t+1;a<r.length;a+=1){let t=i*e.length+(r[a]??0);n.set(t,(n.get(t)??0)+1)}}return n}function L(e,t){let n=e.length+31>>>5,r=new Map;for(let[t,i]of e.entries()){let e=r.get(i);e||(e=new Uint32Array(n),r.set(i,e));let a=t>>>5;e[a]=(e[a]??0)|1<<(t&31)}let i=new Uint32Array(n);for(let e of t){let t=r.get(e),a=1,o=0;for(let e=0;e<n;e+=1){let n=i[e]??0,r=((t?.[e]??0)|n)>>>0,s=(n<<1|a)>>>0;a=n>>>31;let c=r-s-o;o=+(c<0),i[e]=r&~c}}let a=0;for(let e of i)a+=R(e);return a}function R(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),Math.imul(t+(t>>>4)&252645135,16843009)>>>24&255}function z(e,t,n,r,i){return{fingerprint:e,tokenCount:n-t,startTokenIndex:t,endTokenIndex:n,startIndex:r.startIndex,endIndex:i.endIndex,startLine:r.startLine,endLine:i.endLine}}const B=[],V=[];function H(e){let t=B[e];return t===void 0&&(t=K(`$${e}`),B[e]=t),t}function U(e){let t=V[e];return t===void 0&&(t=q(`$${e}`),V[e]=t),t}function W(e,t,n,r){let[i,a]=G(e,n,r,f((t[r]??0)-(t[n]??0),r-n));return`${i}:${a}:${r-n}`}function ne(e,t,n){let[r,i]=G(e,t,n,!1);return r^Math.imul(i,31)}function G(e,t,n,r){let i=new Map,a=5381,o=52711;for(let s=t;s<n;s+=1){let t=e[s];if(!t)continue;let n,c;if(t.kind===`id`){let e=i.get(t.text);e===void 0&&(e=i.size,i.set(t.text,e)),n=H(e),c=U(e)}else n=t.textHash,c=t.textHash2;a=Math.imul(a,31)+n|0,o=Math.imul(o,37)^c,r&&t.literalHash!==void 0&&t.literalHash2!==void 0&&(a=Math.imul(a,31)+t.literalHash|0,o=Math.imul(o,37)^t.literalHash2)}return[a,o]}function K(e){let t=5381;for(let n=0;n<e.length;n+=1)t=Math.imul(t,33)^e.charCodeAt(n);return t}function q(e){let t=-2128831035;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return t}function J(e,t){return Math.imul(e,31)+t}function re(e){let t=[];for(let n of e.values()){let e=n.map(e=>({segments:[{startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex}],tokenCount:e.tokenCount,startTokenIndex:e.startTokenIndex,endTokenIndex:e.endTokenIndex,startIndex:e.startIndex,endIndex:e.endIndex,startLine:e.startLine,endLine:e.endLine}));e.sort((e,t)=>e.startTokenIndex-t.startTokenIndex||e.endTokenIndex-t.endTokenIndex),t.push(e)}return t}function Y(e,t){if(t<=0||e.length<2)return e;e.sort(X);for(let n=!0;n;){n=!1;for(let r=0;r<e.length&&!n;r+=1)for(let i=r+1;i<e.length;i+=1){let a=e[r],o=e[i];if(!a||!o)continue;let s=Z(a,o,t),c=s??Z(o,a,t);if(!c)continue;let l=s?c.firstConsumed:c.secondConsumed,u=s?c.secondConsumed:c.firstConsumed;l&&u?(e[r]=c.merged,e.splice(i,1)):u?e[i]=c.merged:e[r]=c.merged;for(let e of c.pairedRetained)e.sharedWithMergedGroup=!0;e.sort(X),n=!0;break}}return e}function X(e,t){let n=e[0],r=t[0];return(n?.startTokenIndex??0)-(r?.startTokenIndex??0)||(n?.endTokenIndex??0)-(r?.endTokenIndex??0)}function Z(e,t,n){let r=e.filter(e=>!e.sharedWithMergedGroup),i=t.filter(e=>!e.sharedWithMergedGroup),a=[],o=0,s=-1;for(let e of i){for(;o<r.length;){let t=r[o];if(t&&t.endTokenIndex+n<e.startTokenIndex)o+=1;else break}let t=r[o];t&&t.endTokenIndex<=e.startTokenIndex&&t.startTokenIndex>=s&&(a.push([t,e]),s=e.endTokenIndex,o+=1)}let c=a.length===e.length,l=a.length===t.length;if(!(a.length<2||!c&&!l))return{merged:a.map(([e,t])=>({...e,sharedWithMergedGroup:void 0,segments:[...e.segments,...t.segments],tokenCount:e.tokenCount+t.tokenCount,endTokenIndex:t.endTokenIndex,endIndex:t.endIndex,endLine:t.endLine})),firstConsumed:c,secondConsumed:l,pairedRetained:c===l?[]:a.map(([e,t])=>c?t:e)}}function Q(e){let t=0,n=0,r=!1;for(let i of e){if(i.sharedWithMergedGroup){r=!0;continue}t+=i.segments.length,n=Math.max(n,i.segments.length)}return r?t:t-n}function ie(e,t,n){let r=0,i=0,a=[],o=new Set;for(let s of e){r+=Q(s);for(let e of s){i=Math.max(i,e.tokenCount);for(let r of e.segments)$(r,n,t,o)}a.push(s.map(({startLine:e,endLine:t})=>({startLine:e,endLine:t})).toSorted((e,t)=>e.startLine-t.startLine))}return a.sort((e,t)=>(e[0]?.startLine??0)-(t[0]?.startLine??0)),{duplicateBlockCount:r,duplicateBlockGroupCount:e.length,duplicateBlockGroups:a,duplicateLineCount:o.size,duplicateLineNumbers:[...o].toSorted((e,t)=>e-t),duplicationRatio:t.size===0?0:o.size/t.size,maxDuplicateBlockSize:i}}function $(e,t,n,r){for(let i=e.startTokenIndex;i<e.endTokenIndex;i+=1){let e=t[i];for(let t=e?.startRow??0;t<=(e?.endRow??-1);t+=1)(!n||n.has(t+1))&&r.add(t+1)}}exports.buildLiteralCountPrefix=b,exports.collectCrossFileDuplicateCandidates=m,exports.collectSegmentLines=$,exports.collectSequenceWindowCandidates=w,exports.countRedundantFragments=Q,exports.defaultDuplicationOptions=d,exports.hashText=K,exports.lcsLength=L,exports.measureDuplication=p,exports.mergeAdjacentGroups=Y;
2
2
  //# sourceMappingURL=duplication.cjs.map