@swayamkothari/codepulse 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.
Files changed (38) hide show
  1. package/README.md +240 -2
  2. package/bin/codepulse.js +6 -0
  3. package/package.json +60 -4
  4. package/src/analyzers/complexity/cognitive.js +170 -0
  5. package/src/analyzers/complexity/cyclomatic.js +96 -0
  6. package/src/analyzers/complexity/index.js +232 -0
  7. package/src/analyzers/dependencies/cycle-detector.js +107 -0
  8. package/src/analyzers/dependencies/graph-builder.js +118 -0
  9. package/src/analyzers/dependencies/import-extractor.js +85 -0
  10. package/src/analyzers/dependencies/index.js +152 -0
  11. package/src/analyzers/duplication/index.js +366 -0
  12. package/src/analyzers/duplication/normalizer.js +238 -0
  13. package/src/analyzers/index.js +9 -0
  14. package/src/analyzers/smells/index.js +213 -0
  15. package/src/cli/argument-parser.js +45 -0
  16. package/src/cli/commands/analyze.js +146 -0
  17. package/src/cli/commands/compare.js +121 -0
  18. package/src/cli/commands/history.js +91 -0
  19. package/src/cli/commands/init.js +51 -0
  20. package/src/cli/commands/rules.js +110 -0
  21. package/src/config/loader.js +142 -0
  22. package/src/config/validator.js +130 -0
  23. package/src/core/analyzer.js +198 -0
  24. package/src/core/file-filter.js +95 -0
  25. package/src/core/project-scanner.js +119 -0
  26. package/src/history/comparison-engine.js +86 -0
  27. package/src/history/snapshot-manager.js +190 -0
  28. package/src/index.js +16 -0
  29. package/src/reporters/html.js +313 -0
  30. package/src/reporters/json.js +45 -0
  31. package/src/reporters/terminal.js +197 -0
  32. package/src/rules/defaults.js +145 -0
  33. package/src/rules/registry.js +75 -0
  34. package/src/scoring/score-calculator.js +299 -0
  35. package/src/scoring/weights.js +53 -0
  36. package/src/utils/ast-utils.js +173 -0
  37. package/src/utils/file-utils.js +64 -0
  38. package/src/utils/logger.js +54 -0
package/README.md CHANGED
@@ -1,3 +1,241 @@
1
- # Temporary Holding Version
1
+ # CodePulse
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A static analysis tool for JavaScript codebases. It measures complexity, finds duplicate code, detects circular dependencies, and surfaces hygiene issues — then rolls everything into a single health score so you can track how a project changes over time.
4
+
5
+ It works on plain JavaScript: `.js`, `.mjs`, `.cjs`, and `.jsx`. No TypeScript, no build step required.
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install -g @swayamkothari/codepulse
13
+ ```
14
+
15
+ Once installed, the `codepulse` command is available everywhere.
16
+
17
+ Requires Node 18 or later.
18
+
19
+ ---
20
+
21
+ ## Usage
22
+
23
+ ### Analyze a project
24
+
25
+ ```bash
26
+ codepulse analyze .
27
+ codepulse analyze ./src
28
+ codepulse analyze . --severity high # only show high and critical issues
29
+ codepulse analyze . --format json # machine-readable output
30
+ codepulse analyze . --format html -o report.html # self-contained HTML report
31
+ ```
32
+
33
+ The terminal report shows an overall health score (0–100), a breakdown across five dimensions, and a prioritised list of findings.
34
+
35
+ ### Save a snapshot for tracking
36
+
37
+ ```bash
38
+ codepulse analyze . --save
39
+ codepulse analyze . --save --label "before refactor"
40
+ ```
41
+
42
+ Snapshots are stored in `.codepulse/snapshots/` inside your project. They are lightweight — only the scores, metrics, and issue counts are persisted, not the full AST.
43
+
44
+ ### Compare two snapshots
45
+
46
+ ```bash
47
+ codepulse compare . # latest vs previous
48
+ codepulse compare . <idA> <idB> # specific snapshots
49
+ codepulse compare . --json # diff as JSON
50
+ ```
51
+
52
+ ### View history
53
+
54
+ ```bash
55
+ codepulse history .
56
+ codepulse history . --limit 20
57
+ codepulse history . --json
58
+ codepulse history . --delete <snapshot-id>
59
+ ```
60
+
61
+ ### List rules
62
+
63
+ ```bash
64
+ codepulse rules
65
+ codepulse rules --category complexity
66
+ codepulse rules --detail complexity/cyclomatic
67
+ ```
68
+
69
+ ### Generate a config file
70
+
71
+ ```bash
72
+ codepulse init
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Health score
78
+
79
+ Each analysis produces one overall score (0–100) and five sub-scores:
80
+
81
+ | Dimension | What it measures | Default weight |
82
+ |-----------------|-----------------------------------------------------------|---------------|
83
+ | Complexity | Cyclomatic and cognitive complexity, nesting depth | 30% |
84
+ | Duplication | Percentage of lines appearing in duplicate blocks | 20% |
85
+ | Maintainability | File size, function length, parameter count | 25% |
86
+ | Dependencies | Circular imports, files with excessive coupling | 15% |
87
+ | Hygiene | Unused variables, empty catch blocks, magic numbers, console.log | 10% |
88
+
89
+ Scores follow the same scale as letter grades:
90
+
91
+ | Score | Label |
92
+ |---------|-----------------|
93
+ | 90–100 | Excellent |
94
+ | 80–89 | Good |
95
+ | 70–79 | Fair |
96
+ | 60–69 | Needs Attention |
97
+ | 50–59 | Poor |
98
+ | 0–49 | Critical |
99
+
100
+ ---
101
+
102
+ ## Rules
103
+
104
+ Thirteen rules are enabled by default:
105
+
106
+ **Complexity**
107
+ - `complexity/cyclomatic` — functions with cyclomatic complexity above threshold (default: 10)
108
+ - `complexity/cognitive` — functions hard to read due to nesting (default: 15)
109
+ - `complexity/nesting-depth` — deeply nested control structures (default: 4)
110
+ - `complexity/parameters` — functions with too many parameters (default: 5)
111
+ - `complexity/function-length` — functions exceeding a line limit (default: 50)
112
+
113
+ **Code smells**
114
+ - `smell/large-file` — files exceeding a line limit (default: 500)
115
+ - `smell/magic-numbers` — numeric literals embedded in logic
116
+ - `smell/empty-catch` — catch blocks that swallow errors silently
117
+ - `smell/unused-vars` — declared variables that are never read
118
+
119
+ **Dependencies**
120
+ - `dependency/circular` — circular import chains
121
+ - `dependency/too-many-imports` — files importing an excessive number of local modules
122
+
123
+ **Duplication**
124
+ - `duplication/block` — identical or structurally similar code blocks
125
+
126
+ **Hygiene**
127
+ - `hygiene/console-log` — console.log statements left in production code
128
+
129
+ ---
130
+
131
+ ## Configuration
132
+
133
+ Create a `codepulse.config.js` in your project root (or run `codepulse init`):
134
+
135
+ ```js
136
+ export default {
137
+ // Extra paths to ignore (supports gitignore-style globs)
138
+ ignore: ['vendor', 'generated/**'],
139
+
140
+ // Extensions to analyze
141
+ extensions: ['.js', '.mjs', '.cjs', '.jsx'],
142
+
143
+ // Turn rules off or change their severity / options
144
+ rules: {
145
+ 'smell/magic-numbers': 'off',
146
+ 'complexity/cyclomatic': { severity: 'critical', options: { threshold: 15 } },
147
+ 'smell/unused-vars': { options: { ignorePattern: '^_' } },
148
+ },
149
+
150
+ // Scoring weights — will be normalised to sum to 1.0
151
+ scoring: {
152
+ weights: {
153
+ complexity: 0.35,
154
+ duplication: 0.20,
155
+ maintainability: 0.20,
156
+ dependencies: 0.15,
157
+ hygiene: 0.10,
158
+ },
159
+ },
160
+ };
161
+ ```
162
+
163
+ You can also use a plain JSON file named `.codepulserc.json` if you prefer not to use ES modules.
164
+
165
+ ### Environment variable overrides
166
+
167
+ Useful for CI pipelines where you want to control behaviour without touching the config file:
168
+
169
+ | Variable | Effect |
170
+ |----------------------------|---------------------------------------------|
171
+ | `CODEPULSE_FAIL_ON` | Exit 1 if any issue at this severity or above exists |
172
+ | `CODEPULSE_MAX_WARNINGS` | Exit 1 if total issue count exceeds this number |
173
+ | `CODEPULSE_SEVERITY` | Minimum severity shown in terminal output |
174
+ | `CODEPULSE_FORMAT` | Output format: `terminal`, `json`, or `html` |
175
+
176
+ ---
177
+
178
+ ## CI/CD integration
179
+
180
+ ```bash
181
+ # Fail the build on any critical or high severity issue
182
+ codepulse analyze . --fail-on high --quiet
183
+
184
+ # Fail if there are more than 50 total issues
185
+ codepulse analyze . --max-warnings 50 --quiet
186
+
187
+ # Save a snapshot on every CI run to track trends
188
+ codepulse analyze . --save --label "$GIT_COMMIT_SHA" --quiet
189
+ ```
190
+
191
+ `--quiet` suppresses all output except error messages, which keeps CI logs clean.
192
+
193
+ **Exit codes:**
194
+ - `0` — analysis completed, no failures triggered
195
+ - `1` — `--fail-on` or `--max-warnings` threshold breached
196
+ - `2` — config validation error
197
+
198
+ ---
199
+
200
+ ## Programmatic API
201
+
202
+ ```js
203
+ import { Analyzer, ProjectScanner, loadConfig } from 'codepulse';
204
+ import { complexityAnalyzer, smellsAnalyzer } from 'codepulse/analyzers';
205
+
206
+ const config = await loadConfig();
207
+ const scanner = new ProjectScanner({ rootDir: './src' });
208
+ const { files } = await scanner.scan();
209
+
210
+ const analyzer = new Analyzer({ config, files, rootDir: './src' });
211
+ analyzer.registerAnalyzer(complexityAnalyzer);
212
+ analyzer.registerAnalyzer(smellsAnalyzer);
213
+
214
+ const result = await analyzer.analyze();
215
+ console.log(result.scores.overall); // 0–100
216
+ console.log(result.issues); // array of findings
217
+ ```
218
+
219
+ ---
220
+
221
+ ## Development
222
+
223
+ ```bash
224
+ git clone https://github.com/swayamkothari345/codepulse.git
225
+ cd codepulse
226
+ npm install
227
+
228
+ npm test # run all 325 tests
229
+ npm run test:watch # watch mode
230
+ npm run test:coverage # coverage report
231
+ npm run lint
232
+
233
+ # Analyze the project itself
234
+ npm run analyze:self
235
+ ```
236
+
237
+ ---
238
+
239
+ ## License
240
+
241
+ MIT
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createCLI } from '../src/cli/argument-parser.js';
4
+
5
+ const program = createCLI();
6
+ program.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@swayamkothari/codepulse",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Intelligent JavaScript code health analyzer — find complexity, duplication, and code smells",
5
+ "type": "module",
6
+ "bin": {
7
+ "codepulse": "bin/codepulse.js"
8
+ },
9
+ "exports": {
10
+ ".": "./src/index.js"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "src",
15
+ "README.md",
16
+ "LICENSE",
17
+ "CHANGELOG.md"
18
+ ],
19
+ "scripts": {
20
+ "test": "vitest run",
21
+ "test:watch": "vitest",
22
+ "test:coverage": "vitest run --coverage",
23
+ "lint": "eslint src tests bin",
24
+ "lint:fix": "eslint src tests bin --fix",
25
+ "analyze:self": "node bin/codepulse.js analyze ."
26
+ },
27
+ "keywords": [
28
+ "static-analysis",
29
+ "code-quality",
30
+ "complexity",
31
+ "duplication",
32
+ "javascript",
33
+ "cli",
34
+ "linter",
35
+ "code-health",
36
+ "maintainability"
37
+ ],
38
+ "author": "",
39
+ "license": "MIT",
40
+ "publishConfig": {
41
+ "registry": "https://npm.pkg.github.com"
42
+ },
43
+ "engines": {
44
+ "node": ">=18.0.0"
45
+ },
46
+ "dependencies": {
47
+ "@babel/parser": "^7.23.0",
48
+ "@babel/traverse": "^7.23.0",
49
+ "@babel/types": "^7.23.0",
50
+ "chalk": "^5.3.0",
51
+ "cli-table3": "^0.6.3",
52
+ "commander": "^11.1.0",
53
+ "fast-glob": "^3.3.2",
54
+ "ignore": "^5.3.0",
55
+ "ora": "^7.0.1"
56
+ },
57
+ "devDependencies": {
58
+ "@vitest/coverage-v8": "^1.0.0",
59
+ "eslint": "^8.56.0",
60
+ "vitest": "^1.0.0"
61
+ }
62
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Cognitive complexity — measures how hard a function is to read and understand.
3
+ *
4
+ * Rules (loosely following the SonarSource white paper):
5
+ * • Structural elements (if / loops / switch / catch) add (1 + nesting level).
6
+ * • else-if and else clauses add 1 flat (no nesting increment).
7
+ * • Each logical operator (&&, ||, ??) adds 1 flat.
8
+ * • Nesting level increases for: if-body, loop-body, switch-body, catch-body.
9
+ * • Nested function bodies are excluded — each function is measured independently.
10
+ */
11
+
12
+ import { isFunctionNode } from '../../utils/ast-utils.js';
13
+
14
+ const SKIP_KEYS = new Set([
15
+ 'type', 'loc', 'start', 'end', 'extra',
16
+ 'innerComments', 'leadingComments', 'trailingComments',
17
+ ]);
18
+
19
+ /**
20
+ * Compute the cognitive complexity of a single function AST node.
21
+ * @param {object} funcNode
22
+ * @returns {number}
23
+ */
24
+ export function computeCognitive(funcNode) {
25
+ let score = 0;
26
+
27
+ /**
28
+ * Walk a node.
29
+ * @param {object} node
30
+ * @param {number} nesting — current nesting depth (0 = top of function)
31
+ * @param {boolean} isElseIf — true when this IfStatement is in an else-if chain
32
+ */
33
+ function walk(node, nesting, isElseIf = false) {
34
+ if (!node || typeof node !== 'object') return;
35
+ if (!node.type) return;
36
+
37
+ // Skip nested function definitions entirely
38
+ if (isFunctionNode(node)) return;
39
+
40
+ switch (node.type) {
41
+ case 'IfStatement': {
42
+ if (isElseIf) {
43
+ score += 1; // else-if: flat increment, no nesting penalty
44
+ } else {
45
+ score += 1 + nesting; // top-level if or nested if
46
+ }
47
+ // Walk the condition at the same nesting (no structural increase there)
48
+ walkGeneric(node.test, nesting);
49
+ // Body of the if runs at nesting + 1
50
+ walkBlock(node.consequent, nesting + 1);
51
+
52
+ if (node.alternate) {
53
+ if (node.alternate.type === 'IfStatement') {
54
+ // else-if: pass isElseIf=true so it adds +1 flat
55
+ walk(node.alternate, nesting, true);
56
+ } else {
57
+ // plain else: +1 flat, body at nesting + 1
58
+ score += 1;
59
+ walkBlock(node.alternate, nesting + 1);
60
+ }
61
+ }
62
+ return;
63
+ }
64
+
65
+ case 'ForStatement':
66
+ case 'ForInStatement':
67
+ case 'ForOfStatement':
68
+ case 'WhileStatement':
69
+ case 'DoWhileStatement': {
70
+ score += 1 + nesting;
71
+ walkLoopChildren(node, nesting + 1);
72
+ return;
73
+ }
74
+
75
+ case 'SwitchStatement': {
76
+ score += 1 + nesting;
77
+ for (const c of node.cases) {
78
+ walkBlock(c, nesting + 1);
79
+ }
80
+ return;
81
+ }
82
+
83
+ case 'CatchClause': {
84
+ score += 1 + nesting;
85
+ walkBlock(node.body, nesting + 1);
86
+ return;
87
+ }
88
+
89
+ case 'LogicalExpression': {
90
+ // Each && / || / ?? adds 1 flat
91
+ score += 1;
92
+ walk(node.left, nesting);
93
+ walk(node.right, nesting);
94
+ return;
95
+ }
96
+
97
+ case 'ConditionalExpression': {
98
+ score += 1 + nesting;
99
+ walk(node.test, nesting);
100
+ walk(node.consequent, nesting + 1);
101
+ walk(node.alternate, nesting + 1);
102
+ return;
103
+ }
104
+
105
+ default:
106
+ walkGeneric(node, nesting);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Walk all direct children of a node at the given nesting level.
112
+ * Used for generic nodes where we just need to descend.
113
+ */
114
+ function walkGeneric(node, nesting) {
115
+ if (!node || typeof node !== 'object') return;
116
+ if (Array.isArray(node)) {
117
+ for (const item of node) if (item?.type) walk(item, nesting);
118
+ return;
119
+ }
120
+ for (const key of Object.keys(node)) {
121
+ if (SKIP_KEYS.has(key)) continue;
122
+ const child = node[key];
123
+ if (Array.isArray(child)) {
124
+ for (const item of child) if (item?.type) walk(item, nesting);
125
+ } else if (child?.type) {
126
+ walk(child, nesting);
127
+ }
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Walk a BlockStatement's statements, or a single statement/expression.
133
+ */
134
+ function walkBlock(node, nesting) {
135
+ if (!node) return;
136
+ if (node.type === 'BlockStatement') {
137
+ for (const stmt of node.body) walk(stmt, nesting);
138
+ } else {
139
+ walk(node, nesting);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Walk the structural parts of a loop (init, test, update are not nesting-structural).
145
+ */
146
+ function walkLoopChildren(node, nesting) {
147
+ // Walk the loop body at the increased nesting; walk other parts at base nesting
148
+ for (const key of Object.keys(node)) {
149
+ if (SKIP_KEYS.has(key)) continue;
150
+ const child = node[key];
151
+ if (!child) continue;
152
+ const isBody = key === 'body';
153
+ if (Array.isArray(child)) {
154
+ for (const item of child) if (item?.type) walk(item, isBody ? nesting : nesting - 1);
155
+ } else if (child?.type) {
156
+ walk(child, isBody ? nesting : nesting - 1);
157
+ }
158
+ }
159
+ }
160
+
161
+ // Start walking from the function body
162
+ if (funcNode.body?.type === 'BlockStatement') {
163
+ for (const stmt of funcNode.body.body) walk(stmt, 0);
164
+ } else if (funcNode.body) {
165
+ // Arrow function with expression body: const f = x => x * 2
166
+ walk(funcNode.body, 0);
167
+ }
168
+
169
+ return score;
170
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Cyclomatic complexity — counts the number of linearly independent paths
3
+ * through a function.
4
+ *
5
+ * Base = 1. Each of the following adds 1:
6
+ * if / else-if / for / for-in / for-of / while / do-while / catch
7
+ * switch case (non-default)
8
+ * ternary (?:)
9
+ * logical operators (&& / || / ??)
10
+ * logical assignments (&&= / ||= / ??=)
11
+ *
12
+ * Nested function bodies are NOT counted — each function is measured
13
+ * independently.
14
+ */
15
+
16
+ import { isFunctionNode } from '../../utils/ast-utils.js';
17
+
18
+ const SKIP_KEYS = new Set([
19
+ 'type', 'loc', 'start', 'end', 'extra',
20
+ 'innerComments', 'leadingComments', 'trailingComments',
21
+ ]);
22
+
23
+ /**
24
+ * Walk every node reachable from `node`, calling `onNode` for each,
25
+ * but never descending into nested function definitions.
26
+ */
27
+ function walkSkipFunctions(node, onNode) {
28
+ if (!node || typeof node !== 'object') return;
29
+
30
+ if (Array.isArray(node)) {
31
+ for (const item of node) walkSkipFunctions(item, onNode);
32
+ return;
33
+ }
34
+
35
+ if (!node.type) return;
36
+
37
+ // Never descend into a nested function's body
38
+ if (isFunctionNode(node)) return;
39
+
40
+ onNode(node);
41
+
42
+ for (const key of Object.keys(node)) {
43
+ if (SKIP_KEYS.has(key)) continue;
44
+ walkSkipFunctions(node[key], onNode);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Compute the cyclomatic complexity of a single function AST node.
50
+ * @param {object} funcNode — Babel FunctionDeclaration / FunctionExpression /
51
+ * ArrowFunctionExpression / ClassMethod / ObjectMethod
52
+ * @returns {number}
53
+ */
54
+ export function computeCyclomatic(funcNode) {
55
+ let complexity = 1; // base path
56
+
57
+ // funcNode.body is the BlockStatement (or an expression for arrow fns).
58
+ // We walk the body, not the params, so parameter defaults don't add branches.
59
+ const body = funcNode.body ?? funcNode;
60
+
61
+ walkSkipFunctions(body, (node) => {
62
+ switch (node.type) {
63
+ case 'IfStatement':
64
+ case 'ForStatement':
65
+ case 'ForInStatement':
66
+ case 'ForOfStatement':
67
+ case 'WhileStatement':
68
+ case 'DoWhileStatement':
69
+ case 'CatchClause':
70
+ case 'ConditionalExpression':
71
+ complexity++;
72
+ break;
73
+
74
+ case 'SwitchCase':
75
+ // Count only non-default cases
76
+ if (node.test !== null) complexity++;
77
+ break;
78
+
79
+ case 'LogicalExpression':
80
+ // && || ?? each represent a branch
81
+ complexity++;
82
+ break;
83
+
84
+ case 'AssignmentExpression':
85
+ if (node.operator === '&&=' || node.operator === '||=' || node.operator === '??=') {
86
+ complexity++;
87
+ }
88
+ break;
89
+
90
+ default:
91
+ break;
92
+ }
93
+ });
94
+
95
+ return complexity;
96
+ }