ouch4ts 0.0.0-stage → 0.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.
@@ -0,0 +1,60 @@
1
+ export interface AnalysisOptions {
2
+ sources: readonly {
3
+ path: string;
4
+ text: string;
5
+ }[];
6
+ lcov: string;
7
+ projectRoot?: string;
8
+ }
9
+ /** Analyze original JavaScript and TypeScript sources against LCOV mapped to those sources. */
10
+ export declare function analyze({ sources, lcov, projectRoot }: AnalysisOptions): ({
11
+ coverage: null;
12
+ crap: null;
13
+ ouch: null;
14
+ name: string;
15
+ file: string;
16
+ line: number;
17
+ endLine: number;
18
+ complexity: number;
19
+ cognitive: number;
20
+ } | {
21
+ coverage: number;
22
+ crap: number;
23
+ ouch: number;
24
+ name: string;
25
+ file: string;
26
+ line: number;
27
+ endLine: number;
28
+ complexity: number;
29
+ cognitive: number;
30
+ })[];
31
+ /** Return function and file scores from the same parsed sources. */
32
+ export declare function analyzeReport({ sources, lcov, projectRoot }: AnalysisOptions): {
33
+ entries: ({
34
+ coverage: null;
35
+ crap: null;
36
+ ouch: null;
37
+ name: string;
38
+ file: string;
39
+ line: number;
40
+ endLine: number;
41
+ complexity: number;
42
+ cognitive: number;
43
+ } | {
44
+ coverage: number;
45
+ crap: number;
46
+ ouch: number;
47
+ name: string;
48
+ file: string;
49
+ line: number;
50
+ endLine: number;
51
+ complexity: number;
52
+ cognitive: number;
53
+ })[];
54
+ files: {
55
+ complexity: number;
56
+ cognitive: number;
57
+ functions: number;
58
+ file: string;
59
+ }[];
60
+ };
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ import { dirname, relative, resolve, sep } from "node:path";
2
+ import ts from "typescript";
3
+ import { cognitiveComplexity, fileComplexity } from "./cognitive.js";
4
+ import { recursiveFunctions } from "./recursion.js";
5
+ import { readLcov } from "./lcov.js";
6
+ import { hasImplementation } from "./syntax.js";
7
+ /** Analyze original JavaScript and TypeScript sources against LCOV mapped to those sources. */
8
+ export function analyze({ sources, lcov, projectRoot = process.cwd() }) {
9
+ return analyzeReport({ sources, lcov, projectRoot }).entries;
10
+ }
11
+ /** Return function and file scores from the same parsed sources. */
12
+ export function analyzeReport({ sources, lcov, projectRoot = process.cwd() }) {
13
+ const coverage = readLcov(lcov, projectRoot);
14
+ const { program, parsed } = parseSources(sources, projectRoot);
15
+ const recursive = recursiveFunctions(parsed.map(entry => entry.source), program.getTypeChecker());
16
+ const files = parsed.map(({ path, source }) => ({
17
+ file: relative(projectRoot, resolve(projectRoot, path)).split(sep).join("/"), ...fileComplexity(source, recursive),
18
+ }));
19
+ const entries = parsed.flatMap(({ path, source }) => {
20
+ const analyzer = new SourceAnalyzer(source, coverage.get(resolve(projectRoot, path)), projectRoot, recursive);
21
+ analyzer.visit(source);
22
+ return analyzer.entries;
23
+ }).sort(compareFunctionScores);
24
+ files.sort((a, b) => b.cognitive - a.cognitive || a.file.localeCompare(b.file));
25
+ return { entries, files };
26
+ }
27
+ function compareFunctionScores(a, b) {
28
+ return (b.ouch ?? -1) - (a.ouch ?? -1) || a.file.localeCompare(b.file) || a.line - b.line;
29
+ }
30
+ class SourceAnalyzer {
31
+ source;
32
+ lines;
33
+ root;
34
+ recursive;
35
+ entries = [];
36
+ constructor(source, lines, root, recursive) {
37
+ this.source = source;
38
+ this.lines = lines;
39
+ this.root = root;
40
+ this.recursive = recursive;
41
+ }
42
+ visit(node, scope = "") {
43
+ if (hasImplementation(node)) {
44
+ const name = scope + functionName(node, this.source);
45
+ this.entries.push(scoreFunction(node, this.source, this.lines, name, this.root, this.recursive));
46
+ ts.forEachChild(node, child => this.visit(child, name + "."));
47
+ return;
48
+ }
49
+ const container = className(node);
50
+ const nestedScope = container ? scope + container + "." : scope;
51
+ ts.forEachChild(node, child => this.visit(child, nestedScope));
52
+ }
53
+ }
54
+ function parseSources(sources, root) {
55
+ const parsed = sources.map(({ path, text }) => ({
56
+ path, source: ts.createSourceFile(resolve(root, path), text, ts.ScriptTarget.Latest, true),
57
+ }));
58
+ const byPath = new Map(parsed.map(({ source }) => [source.fileName, source]));
59
+ const directories = sourceDirectories(byPath.keys());
60
+ const options = {
61
+ noLib: true, allowJs: true, types: [],
62
+ module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext,
63
+ };
64
+ const program = ts.createProgram([...byPath.keys()], options, {
65
+ ...ts.createCompilerHost(options),
66
+ getCurrentDirectory: () => resolve(root),
67
+ getSourceFile: file => byPath.get(resolve(root, file)),
68
+ fileExists: file => byPath.has(resolve(root, file)),
69
+ readFile: file => byPath.get(resolve(root, file))?.text,
70
+ directoryExists: directory => directories.has(resolve(root, directory)),
71
+ getDirectories: () => [],
72
+ realpath: file => resolve(root, file),
73
+ });
74
+ for (const { path, source } of parsed)
75
+ validateSourceSyntax(program, path, source);
76
+ return { program, parsed };
77
+ }
78
+ function sourceDirectories(paths) {
79
+ const directories = new Set();
80
+ for (const path of paths) {
81
+ for (let directory = dirname(path); !directories.has(directory); directory = dirname(directory))
82
+ directories.add(directory);
83
+ }
84
+ return directories;
85
+ }
86
+ function validateSourceSyntax(program, path, source) {
87
+ const [error] = program.getSyntacticDiagnostics(source);
88
+ if (error)
89
+ throw new Error(`${path}: syntax error: ${ts.flattenDiagnosticMessageText(error.messageText, " ")}`);
90
+ }
91
+ function className(node) {
92
+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node))
93
+ return node.name?.text;
94
+ }
95
+ function accessorPrefix(node) {
96
+ if (ts.isGetAccessorDeclaration(node))
97
+ return "get ";
98
+ if (ts.isSetAccessorDeclaration(node))
99
+ return "set ";
100
+ return "";
101
+ }
102
+ function functionName(node, source) {
103
+ if (ts.isConstructorDeclaration(node))
104
+ return "constructor";
105
+ if (node.name)
106
+ return accessorPrefix(node) + node.name.getText(source);
107
+ return assignedFunctionName(node, source) ?? unassignedFunctionName(node, source);
108
+ }
109
+ function unassignedFunctionName(node, source) {
110
+ if (ts.isFunctionDeclaration(node))
111
+ return "default";
112
+ const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));
113
+ return `<anonymous@${line + 1}:${character + 1}>`;
114
+ }
115
+ function assignedFunctionName(node, source) {
116
+ const parent = node.parent;
117
+ if (ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isPropertyDeclaration(parent)) {
118
+ return parent.name.getText(source);
119
+ }
120
+ }
121
+ function scoreFunction(node, source, lines, name, root, recursive) {
122
+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
123
+ const endLine = source.getLineAndCharacterOfPosition(node.end - 1).line + 1;
124
+ const { complexity, range, nestedRanges } = functionStructure(node, source);
125
+ const fraction = functionCoverage(lines, range, nestedRanges);
126
+ const cognitive = cognitiveComplexity(node, recursive);
127
+ return {
128
+ name, file: relative(root, resolve(root, source.fileName)).split(sep).join("/"), line, endLine, complexity, cognitive,
129
+ ...functionScores(complexity, cognitive, fraction),
130
+ };
131
+ }
132
+ function functionScores(complexity, cognitive, fraction) {
133
+ if (fraction === null)
134
+ return { coverage: null, crap: null, ouch: null };
135
+ const crap = complexity ** 2 * (1 - fraction) ** 3 + complexity;
136
+ return { coverage: fraction * 100, crap, ouch: crap + cognitive };
137
+ }
138
+ function functionStructure(node, source) {
139
+ const range = bodyRange(node, source);
140
+ const counter = new FunctionSyntaxCounter(source);
141
+ ts.forEachChild(node, child => counter.count(child));
142
+ return { complexity: counter.complexity, range, nestedRanges: counter.nestedRanges };
143
+ }
144
+ class FunctionSyntaxCounter {
145
+ source;
146
+ nestedRanges = [];
147
+ complexity = 1;
148
+ constructor(source) {
149
+ this.source = source;
150
+ }
151
+ count(child) {
152
+ if (hasImplementation(child)) {
153
+ this.recordNestedRange(child);
154
+ return;
155
+ }
156
+ if (isDecision(child))
157
+ this.complexity++;
158
+ ts.forEachChild(child, node => this.count(node));
159
+ }
160
+ recordNestedRange(node) {
161
+ const nested = bodyRange(node, this.source);
162
+ if (nested)
163
+ this.nestedRanges.push(nested);
164
+ }
165
+ }
166
+ function functionCoverage(lines, range, nestedRanges) {
167
+ const executable = [...(lines ?? [])].filter(([number]) => range && number >= range[0] && number <= range[1] &&
168
+ !nestedRanges.some(([start, end]) => number >= start && number <= end));
169
+ return executable.length === 0 ? null
170
+ : executable.filter(([, hits]) => hits > 0).length / executable.length;
171
+ }
172
+ const decisionKinds = new Set([
173
+ ts.SyntaxKind.IfStatement, ts.SyntaxKind.ConditionalExpression, ts.SyntaxKind.ForStatement,
174
+ ts.SyntaxKind.ForInStatement, ts.SyntaxKind.ForOfStatement, ts.SyntaxKind.WhileStatement,
175
+ ts.SyntaxKind.DoStatement, ts.SyntaxKind.CatchClause, ts.SyntaxKind.CaseClause,
176
+ ]);
177
+ const shortCircuitOperators = new Set([
178
+ ts.SyntaxKind.BarBarToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.QuestionQuestionToken,
179
+ ts.SyntaxKind.BarBarEqualsToken, ts.SyntaxKind.AmpersandAmpersandEqualsToken,
180
+ ts.SyntaxKind.QuestionQuestionEqualsToken,
181
+ ]);
182
+ function isDecision(node) {
183
+ return decisionKinds.has(node.kind) || hasDefaultValue(node) || isOptionalChainStep(node) ||
184
+ isShortCircuitExpression(node);
185
+ }
186
+ function isShortCircuitExpression(node) {
187
+ return ts.isBinaryExpression(node) && shortCircuitOperators.has(node.operatorToken.kind);
188
+ }
189
+ function hasDefaultValue(node) {
190
+ return (ts.isParameter(node) || ts.isBindingElement(node)) && node.initializer !== undefined;
191
+ }
192
+ function isOptionalChainStep(node) {
193
+ return (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) || ts.isCallExpression(node)) &&
194
+ node.questionDotToken !== undefined;
195
+ }
196
+ function bodyRange(node, source) {
197
+ const statements = bodyStatements(node.body);
198
+ const first = statements[0];
199
+ const last = statements.at(-1);
200
+ if (!first || !last)
201
+ return null;
202
+ return [source.getLineAndCharacterOfPosition(first.getStart(source)).line + 1,
203
+ source.getLineAndCharacterOfPosition(last.end - 1).line + 1];
204
+ }
205
+ function bodyStatements(body) {
206
+ return ts.isBlock(body) ? body.statements : [body];
207
+ }
package/dist/lcov.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function readLcov(text: string, root: string): Map<string, Map<number, number>>;
package/dist/lcov.js ADDED
@@ -0,0 +1,49 @@
1
+ import { resolve } from "node:path";
2
+ export function readLcov(text, root) {
3
+ const files = new Map();
4
+ let lines;
5
+ for (const record of text.split(/\r?\n/)) {
6
+ lines = readCoverageRecord(record, root, files, lines);
7
+ }
8
+ validateLcovComplete(files, lines);
9
+ return files;
10
+ }
11
+ function readCoverageRecord(record, root, files, lines) {
12
+ if (record === "end_of_record")
13
+ return undefined;
14
+ switch (record.slice(0, 3)) {
15
+ case "SF:": return sourceCoverage(record, root, files, lines);
16
+ case "DA:": recordLineCoverage(record, lines);
17
+ }
18
+ return lines;
19
+ }
20
+ function sourceCoverage(record, root, files, current) {
21
+ if (current || record.length === 3)
22
+ throw new Error("Invalid LCOV source record");
23
+ const path = resolve(root, record.slice(3));
24
+ const lines = files.get(path) ?? new Map();
25
+ files.set(path, lines);
26
+ return lines;
27
+ }
28
+ function recordLineCoverage(record, lines) {
29
+ if (!lines)
30
+ throw new Error(`Invalid LCOV line record: ${record}`);
31
+ const { line, hits } = parseLineCoverage(record);
32
+ lines.set(line, (lines.get(line) ?? 0) + hits);
33
+ }
34
+ function parseLineCoverage(record) {
35
+ const [line, hits] = record.slice(3).split(",").map(Number);
36
+ if (!isSafeCount(line, 1) || !isSafeCount(hits, 0) || !/^\d+,\d+(?:,.*)?$/.test(record.slice(3))) {
37
+ throw new Error(`Invalid LCOV line record: ${record}`);
38
+ }
39
+ return { line, hits };
40
+ }
41
+ function isSafeCount(value, minimum) {
42
+ return value !== undefined && Number.isSafeInteger(value) && value >= minimum;
43
+ }
44
+ function validateLcovComplete(files, current) {
45
+ if (current)
46
+ throw new Error("Incomplete LCOV report: missing end_of_record");
47
+ if (files.size === 0)
48
+ throw new Error("LCOV report contains no source records");
49
+ }
@@ -0,0 +1,3 @@
1
+ export declare function readManifest(cwd: string): Promise<Record<string, unknown>>;
2
+ export declare function isManifestObject(value: unknown): value is Record<string, unknown>;
3
+ export declare function readOptionalFile(path: string): Promise<string | null>;
@@ -0,0 +1,19 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { missingFileOrThrow } from "./files.js";
4
+ export async function readManifest(cwd) {
5
+ const text = await readOptionalFile(resolve(cwd, "package.json"));
6
+ if (text === null)
7
+ return {};
8
+ const manifest = JSON.parse(text);
9
+ if (!isManifestObject(manifest)) {
10
+ throw new Error(`Expected an object in ${resolve(cwd, "package.json")}`);
11
+ }
12
+ return manifest;
13
+ }
14
+ export function isManifestObject(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ export async function readOptionalFile(path) {
18
+ return readFile(path, "utf8").catch(missingFileOrThrow);
19
+ }
@@ -0,0 +1,2 @@
1
+ export declare function defaultCoverageCommand(cwd: string): Promise<string>;
2
+ export declare function defaultSetupCommand(cwd: string): Promise<string>;
@@ -0,0 +1,121 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readdir } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { isManifestObject, readManifest, readOptionalFile } from "./manifest.js";
5
+ export async function defaultCoverageCommand(cwd) {
6
+ const manifest = await readManifest(cwd);
7
+ if (!coverageScript(manifest.scripts)) {
8
+ throw new Error('No "test:coverage" script in package.json. Pass --coverage-command \'<command>\' '
9
+ + "to generate LCOV, or --use-existing-coverage to read an existing report.");
10
+ }
11
+ const manager = await detectPackageManager(cwd, "--coverage-command");
12
+ return `${manager.name} run test:coverage`;
13
+ }
14
+ function coverageScript(scripts) {
15
+ if (!isManifestObject(scripts))
16
+ return;
17
+ const command = scripts["test:coverage"];
18
+ if (typeof command !== "string")
19
+ return;
20
+ return command.trim();
21
+ }
22
+ export async function defaultSetupCommand(cwd) {
23
+ const manager = await detectPackageManager(cwd, "--setup-command");
24
+ if (manager.name === "npm")
25
+ return "npm ci --ignore-scripts";
26
+ if (manager.name === "yarn")
27
+ return yarnSetupCommand(manager);
28
+ return `${manager.name} install --frozen-lockfile --ignore-scripts`;
29
+ }
30
+ async function yarnSetupCommand(manager) {
31
+ const lockfile = await yarnLockfile(manager.directory);
32
+ if (lockfile === null)
33
+ throw new Error("Default Yarn setup requires yarn.lock. Pass --setup-command '<command>'.");
34
+ return yarnInstallCommand(manager.major ?? yarnMajor(manager.directory, lockfile));
35
+ }
36
+ function yarnInstallCommand(major) {
37
+ if (major === 2)
38
+ return "yarn install --immutable --skip-builds";
39
+ if (major >= 3)
40
+ return "yarn install --immutable --mode=skip-build";
41
+ return "yarn install --frozen-lockfile --ignore-scripts";
42
+ }
43
+ function yarnMajor(cwd, lockfile) {
44
+ if (!/^__metadata:/m.test(lockfile))
45
+ return 1;
46
+ return installedYarnMajor(cwd);
47
+ }
48
+ function installedYarnMajor(cwd) {
49
+ const result = spawnSync("yarn", ["--version"], { cwd, encoding: "utf8" });
50
+ const major = Number.parseInt(String(result.stdout), 10);
51
+ if (!succeeded(result) || !isModernYarnMajor(major)) {
52
+ throw new Error("Cannot determine modern Yarn's version with yarn --version. Pass --setup-command '<command>'.");
53
+ }
54
+ return major;
55
+ }
56
+ function succeeded(result) {
57
+ return !result.error && result.status === 0;
58
+ }
59
+ function isModernYarnMajor(major) {
60
+ return Number.isFinite(major) && major >= 2;
61
+ }
62
+ async function yarnLockfile(cwd) {
63
+ const text = await readOptionalFile(resolve(cwd, "yarn.lock"));
64
+ if (text !== null)
65
+ return text;
66
+ return parentYarnLockfile(cwd);
67
+ }
68
+ async function parentYarnLockfile(cwd) {
69
+ if (await stopsYarnSearch(cwd))
70
+ return null;
71
+ return yarnLockfile(dirname(cwd));
72
+ }
73
+ async function stopsYarnSearch(cwd) {
74
+ if (dirname(cwd) === cwd)
75
+ return true;
76
+ return (await readdir(cwd)).includes(".git");
77
+ }
78
+ const lockfiles = [
79
+ { name: "npm", files: ["package-lock.json", "npm-shrinkwrap.json"] },
80
+ { name: "yarn", files: ["yarn.lock"] },
81
+ { name: "pnpm", files: ["pnpm-lock.yaml"] },
82
+ { name: "bun", files: ["bun.lock", "bun.lockb"] },
83
+ ];
84
+ async function detectPackageManager(cwd, flag) {
85
+ const manifest = await readManifest(cwd);
86
+ if (manifest.packageManager !== undefined) {
87
+ return { ...declaredPackageManager(manifest.packageManager, flag), directory: cwd };
88
+ }
89
+ return detectUndeclaredManager(cwd, flag);
90
+ }
91
+ async function detectUndeclaredManager(cwd, flag) {
92
+ const files = new Set(await readdir(cwd));
93
+ const manager = lockfileManager(files, flag);
94
+ if (manager)
95
+ return { name: manager.name, major: undefined, directory: cwd };
96
+ if (isSearchRoot(cwd, files))
97
+ return { name: "npm", major: undefined, directory: cwd };
98
+ return detectPackageManager(dirname(cwd), flag);
99
+ }
100
+ function isSearchRoot(cwd, files) {
101
+ return dirname(cwd) === cwd || files.has(".git");
102
+ }
103
+ function lockfileManager(files, flag) {
104
+ const matches = lockfiles.filter(manager => manager.files.some(file => files.has(file)));
105
+ if (matches.length > 1) {
106
+ throw new Error(`Multiple package-manager lockfiles found. Set packageManager in package.json or pass ${flag} '<command>'.`);
107
+ }
108
+ return matches[0];
109
+ }
110
+ function declaredPackageManager(value, flag) {
111
+ const [name, version = ""] = packageManagerParts(value);
112
+ const major = Number.parseInt(version, 10);
113
+ const manager = lockfiles.find(manager => manager.name === name);
114
+ if (!manager || !Number.isFinite(major)) {
115
+ throw new Error(`Unsupported packageManager in package.json. Pass ${flag} '<command>'.`);
116
+ }
117
+ return { name: manager.name, major };
118
+ }
119
+ function packageManagerParts(value) {
120
+ return typeof value === "string" ? value.split("@") : [];
121
+ }
@@ -0,0 +1 @@
1
+ export declare function runCommand(command: string, cwd: string, label: "Setup" | "Coverage"): void;
@@ -0,0 +1,9 @@
1
+ import { spawnSync } from "node:child_process";
2
+ export function runCommand(command, cwd, label) {
3
+ const result = spawnSync(command, { cwd, shell: true, stdio: ["ignore", 2, 2] });
4
+ const hint = `Check the command and project dependencies in ${cwd}. Pass --${label.toLowerCase()}-command to override it.`;
5
+ if (result.error)
6
+ throw new Error(`${label} command could not start: ${result.error.message}. ${hint}`);
7
+ if (result.status !== 0)
8
+ throw new Error(`${label} command failed: ${result.signal ?? result.status}. ${hint}`);
9
+ }
@@ -0,0 +1,39 @@
1
+ export interface ProjectOptions {
2
+ cwd: string;
3
+ sourceRoots: readonly string[];
4
+ exclude: readonly string[];
5
+ lcov: string;
6
+ coverageCommand: string | undefined;
7
+ useExistingCoverage: boolean;
8
+ repositoryRoot?: string;
9
+ }
10
+ export declare function warnUnknownCoverage(entries: Awaited<ReturnType<typeof analyzeProject>>["entries"], context?: string): void;
11
+ export declare function analyzeProject(options: ProjectOptions): Promise<{
12
+ entries: ({
13
+ coverage: null;
14
+ crap: null;
15
+ ouch: null;
16
+ name: string;
17
+ file: string;
18
+ line: number;
19
+ endLine: number;
20
+ complexity: number;
21
+ cognitive: number;
22
+ } | {
23
+ coverage: number;
24
+ crap: number;
25
+ ouch: number;
26
+ name: string;
27
+ file: string;
28
+ line: number;
29
+ endLine: number;
30
+ complexity: number;
31
+ cognitive: number;
32
+ })[];
33
+ files: {
34
+ complexity: number;
35
+ cognitive: number;
36
+ functions: number;
37
+ file: string;
38
+ }[];
39
+ }>;
@@ -0,0 +1,54 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { relative, resolve, sep } from "node:path";
3
+ import picomatch from "picomatch";
4
+ import { analyzeReport } from "./index.js";
5
+ import { canonicalRepositoryPath, reportStamp } from "./files.js";
6
+ import { discoverSources } from "./discovery.js";
7
+ import { runCommand } from "./process.js";
8
+ import { defaultCoverageCommand } from "./package-manager.js";
9
+ export function warnUnknownCoverage(entries, context = "") {
10
+ const unknown = entries.filter(entry => entry.coverage === null).length;
11
+ if (unknown)
12
+ console.error(`Warning: ${unknown} functions have N/A coverage${context}. Check LCOV source paths and source maps.`);
13
+ }
14
+ export async function analyzeProject(options) {
15
+ const reportPath = resolve(options.cwd, options.lcov);
16
+ await validateRepositoryInputs(options);
17
+ if (!options.useExistingCoverage)
18
+ await updateCoverage(options, reportPath);
19
+ await validateRepositoryInputs(options);
20
+ const paths = await projectSourcePaths(options);
21
+ const sources = await Promise.all(paths.map(async (path) => ({ path, text: await readFile(path, "utf8") })));
22
+ return analyzeReport({ sources, lcov: await readCoverage(reportPath), projectRoot: options.cwd });
23
+ }
24
+ async function validateRepositoryInputs({ cwd, sourceRoots, lcov, repositoryRoot }) {
25
+ if (repositoryRoot === undefined)
26
+ return;
27
+ await Promise.all([".", ...sourceRoots, lcov].map(path => canonicalRepositoryPath(resolve(cwd, path), repositoryRoot)));
28
+ }
29
+ async function readCoverage(path) {
30
+ try {
31
+ return await readFile(path, "utf8");
32
+ }
33
+ catch (error) {
34
+ const message = error instanceof Error ? error.message : String(error);
35
+ throw new Error(`Cannot read LCOV: ${message}. Generate original-source LCOV or select its path with --lcov.`);
36
+ }
37
+ }
38
+ async function projectSourcePaths(options) {
39
+ const { cwd, sourceRoots } = options;
40
+ const matchesExclude = picomatch([...options.exclude], { dot: true, nonegate: true });
41
+ const isExcluded = (path) => matchesExclude(relative(cwd, path).split(sep).join("/"));
42
+ const paths = [...new Set((await Promise.all(sourceRoots.map(root => discoverSources(resolve(cwd, root), isExcluded)))).flat())];
43
+ if (paths.length === 0)
44
+ throw new Error(`No JavaScript or TypeScript sources found under ${sourceRoots.join(", ")}`);
45
+ return paths;
46
+ }
47
+ async function updateCoverage({ cwd, lcov, coverageCommand }, reportPath) {
48
+ const before = await reportStamp(reportPath);
49
+ runCommand(coverageCommand ?? await defaultCoverageCommand(cwd), cwd, "Coverage");
50
+ const after = await reportStamp(reportPath);
51
+ if (after === null || before === after) {
52
+ throw new Error(`Coverage command did not update ${lcov}. Generate original-source LCOV or select the updated report with --lcov.`);
53
+ }
54
+ }
@@ -0,0 +1,3 @@
1
+ import ts from "typescript";
2
+ /** Identify functions in direct or indirect cycles of statically resolved calls. */
3
+ export declare function recursiveFunctions(sources: readonly ts.SourceFile[], checker: ts.TypeChecker): Set<ts.SignatureDeclaration>;