UNPKG

code-complexity

Version:

Measure the churn/complexity score. Higher values mean hotspots where refactorings should happen.

45 lines (44 loc) 1.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculate = void 0; const node_path_1 = require("node:path"); const node_fs_1 = require("node:fs"); const utils_1 = require("../../../utils"); const core_1 = require("@babel/core"); // eslint-disable-next-line @typescript-eslint/no-var-requires const escomplex = require("escomplex"); const internal = { debug: (0, utils_1.buildDebugger)("cyclomatic") }; function calculate(path) { switch ((0, node_path_1.extname)(path)) { case ".ts": return fromTypeScript(path); case ".mjs": case ".js": return fromJavaScript(path); default: internal.debug("Unsupported file extension. Falling back on default complexity (1)"); return new utils_1.UnsupportedExtension(); } } exports.calculate = calculate; function fromJavaScript(path) { const content = (0, node_fs_1.readFileSync)(path, { encoding: "utf8" }); const babelResult = (0, core_1.transformSync)(content, { presets: ["@babel/preset-env"], }); if (!babelResult) throw new Error(`Error while parsing file ${path}`); const result = escomplex.analyse(babelResult.code, {}); return result.aggregate.cyclomatic; } function fromTypeScript(path) { const content = (0, node_fs_1.readFileSync)(path, { encoding: "utf8" }); const babelResult = (0, core_1.transformSync)(content, { plugins: ["@babel/plugin-transform-typescript"], presets: ["@babel/preset-env"], }); if (!babelResult) throw new Error(`Error while parsing file ${path}`); const result = escomplex.analyse(babelResult.code); return result.aggregate.cyclomatic; }