@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
@@ -0,0 +1,110 @@
1
+ import { getAllRules, getRule } from '../../rules/registry.js';
2
+ import { registerDefaultRules } from '../../rules/defaults.js';
3
+
4
+ export function registerRulesCommand(program) {
5
+ program
6
+ .command('rules')
7
+ .description('List or inspect available analysis rules')
8
+ .option('--category <cat>', 'Filter by category: complexity|smell|duplication|dependency|hygiene')
9
+ .option('--detail <id>', 'Show full details for a specific rule ID')
10
+ .option('--json', 'Output as JSON')
11
+ .action(async (options) => {
12
+ registerDefaultRules();
13
+ const { default: chalk } = await import('chalk');
14
+
15
+ // ── Detail mode ───────────────────────────────────────────────────────
16
+ if (options.detail) {
17
+ const rule = getRule(options.detail);
18
+ if (!rule) {
19
+ console.error(chalk.red(`Rule not found: "${options.detail}"`));
20
+ process.exit(1);
21
+ }
22
+ if (options.json) {
23
+ console.log(JSON.stringify(rule, null, 2));
24
+ return;
25
+ }
26
+ _renderDetail(chalk, rule);
27
+ return;
28
+ }
29
+
30
+ // ── List mode ─────────────────────────────────────────────────────────
31
+ let rules = getAllRules();
32
+ if (options.category) {
33
+ rules = rules.filter(r => r.category === options.category);
34
+ }
35
+
36
+ if (options.json) {
37
+ const output = rules.map(({ id, name, description, category, severity, enabled, defaultOptions }) => ({
38
+ id, name, description, category, severity, enabled, defaultOptions,
39
+ }));
40
+ console.log(JSON.stringify(output, null, 2));
41
+ return;
42
+ }
43
+
44
+ const { default: Table } = await import('cli-table3');
45
+
46
+ const SEVERITY_COLOR = {
47
+ critical: chalk.red.bold,
48
+ high: chalk.yellow,
49
+ medium: chalk.cyan,
50
+ low: chalk.gray,
51
+ };
52
+
53
+ const table = new Table({
54
+ head: ['ID', 'Name', 'Category', 'Severity', 'Status'].map(h => chalk.bold.white(h)),
55
+ style: { head: [], border: ['dim'] },
56
+ colWidths: [32, 28, 14, 10, 10],
57
+ wordWrap: true,
58
+ });
59
+
60
+ for (const rule of rules) {
61
+ const colorFn = SEVERITY_COLOR[rule.severity] ?? (x => x);
62
+ table.push([
63
+ chalk.dim(rule.id),
64
+ rule.name,
65
+ rule.category,
66
+ colorFn(rule.severity),
67
+ rule.enabled !== false ? chalk.green('enabled') : chalk.gray('disabled'),
68
+ ]);
69
+ }
70
+
71
+ console.log('\n' + chalk.bold.cyan('CodePulse') + ' — Available Rules\n');
72
+ console.log(table.toString());
73
+ console.log(chalk.dim(`\n ${rules.length} rule${rules.length !== 1 ? 's' : ''} listed.`));
74
+ console.log(chalk.dim(' Use --detail <id> for full rule info, or `codepulse init` to customise.\n'));
75
+ });
76
+ }
77
+
78
+ function _renderDetail(chalk, rule) {
79
+ const W = 70;
80
+ const div = chalk.dim('─'.repeat(W));
81
+ const SEV = {
82
+ critical: chalk.red.bold, high: chalk.yellow,
83
+ medium: chalk.cyan, low: chalk.gray,
84
+ };
85
+ const sevFn = SEV[rule.severity] ?? (x => x);
86
+
87
+ console.log('\n' + div);
88
+ console.log(` ${chalk.bold.cyan(rule.id)}`);
89
+ console.log(div);
90
+ console.log(` ${chalk.dim('Name:')} ${chalk.white(rule.name)}`);
91
+ console.log(` ${chalk.dim('Category:')} ${rule.category}`);
92
+ console.log(` ${chalk.dim('Severity:')} ${sevFn(rule.severity)}`);
93
+ console.log(` ${chalk.dim('Status:')} ${rule.enabled !== false ? chalk.green('enabled') : chalk.gray('disabled')}`);
94
+ console.log('');
95
+ console.log(` ${chalk.bold('Description:')}`);
96
+ console.log(` ${chalk.white(rule.description)}`);
97
+
98
+ if (rule.defaultOptions && Object.keys(rule.defaultOptions).length > 0) {
99
+ console.log('');
100
+ console.log(` ${chalk.bold('Default options:')}`);
101
+ for (const [k, v] of Object.entries(rule.defaultOptions)) {
102
+ console.log(` ${chalk.dim(k + ':')} ${JSON.stringify(v)}`);
103
+ }
104
+ console.log('');
105
+ console.log(` ${chalk.dim('Override in codepulse.config.js:')}`);
106
+ console.log(chalk.dim(` rules: { '${rule.id}': { severity: '${rule.severity}', options: ${JSON.stringify(rule.defaultOptions)} } }`));
107
+ }
108
+
109
+ console.log('\n' + div + '\n');
110
+ }
@@ -0,0 +1,142 @@
1
+ import path from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { readFileSync, existsSync } from 'node:fs';
4
+
5
+ export const DEFAULT_CONFIG = {
6
+ // Glob patterns to ignore (on top of built-in defaults)
7
+ ignore: [],
8
+
9
+ // File extensions to analyze
10
+ extensions: ['.js', '.mjs', '.cjs', '.jsx'],
11
+
12
+ // Rule-level overrides: { 'rule/id': { severity, options } | 'off' }
13
+ rules: {},
14
+
15
+ // Per-rule threshold overrides (shorthand)
16
+ thresholds: {},
17
+
18
+ // Scoring weights — must conceptually sum to 1.0
19
+ scoring: {
20
+ weights: {
21
+ complexity: 0.30,
22
+ duplication: 0.20,
23
+ maintainability: 0.25,
24
+ dependencies: 0.15,
25
+ hygiene: 0.10,
26
+ },
27
+ },
28
+
29
+ // Output defaults
30
+ output: {
31
+ format: 'terminal',
32
+ },
33
+ };
34
+
35
+ /**
36
+ * Load configuration from an explicit path or by searching the cwd.
37
+ * Falls back to DEFAULT_CONFIG if nothing is found.
38
+ *
39
+ * Supported file formats (searched in order):
40
+ * codepulse.config.js — ES module exporting a default object
41
+ * .codepulserc.js — same
42
+ * .codepulserc.json — plain JSON object
43
+ *
44
+ * After file config is resolved, environment variable overrides are applied:
45
+ * CODEPULSE_FAIL_ON — equivalent to --fail-on <severity>
46
+ * CODEPULSE_MAX_WARNINGS — equivalent to --max-warnings <n>
47
+ * CODEPULSE_SEVERITY — minimum severity for terminal output
48
+ * CODEPULSE_FORMAT — output format: terminal|json|html
49
+ */
50
+ export async function loadConfig(configPath) {
51
+ let fileConfig = null;
52
+
53
+ if (configPath) {
54
+ fileConfig = await _loadFile(path.resolve(configPath));
55
+ if (!fileConfig) throw new Error(`Config file not found: ${configPath}`);
56
+ } else {
57
+ const candidates = [
58
+ path.join(process.cwd(), 'codepulse.config.js'),
59
+ path.join(process.cwd(), '.codepulserc.js'),
60
+ path.join(process.cwd(), '.codepulserc.json'),
61
+ ];
62
+ for (const candidate of candidates) {
63
+ fileConfig = await _loadFile(candidate);
64
+ if (fileConfig) break;
65
+ }
66
+ }
67
+
68
+ const merged = mergeConfig(DEFAULT_CONFIG, fileConfig ?? {});
69
+ return applyEnvOverrides(merged);
70
+ }
71
+
72
+ async function _loadFile(filePath) {
73
+ if (!existsSync(filePath)) return null;
74
+
75
+ // JSON config
76
+ if (filePath.endsWith('.json')) {
77
+ try {
78
+ return JSON.parse(readFileSync(filePath, 'utf8'));
79
+ } catch (e) {
80
+ throw new Error(`Failed to parse JSON config at ${filePath}: ${e.message}`);
81
+ }
82
+ }
83
+
84
+ // JS module config
85
+ try {
86
+ const url = pathToFileURL(filePath).href;
87
+ const mod = await import(url);
88
+ return mod.default ?? mod;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Apply CODEPULSE_* environment variable overrides onto a merged config.
96
+ * Env vars set at the CI/CD level take precedence over file config.
97
+ *
98
+ * @param {object} config
99
+ * @returns {object}
100
+ */
101
+ export function applyEnvOverrides(config) {
102
+ const result = { ...config, output: { ...(config.output ?? {}) } };
103
+
104
+ if (process.env.CODEPULSE_FORMAT) {
105
+ result.output.format = process.env.CODEPULSE_FORMAT;
106
+ }
107
+ if (process.env.CODEPULSE_SEVERITY) {
108
+ result.output.severity = process.env.CODEPULSE_SEVERITY;
109
+ }
110
+ if (process.env.CODEPULSE_FAIL_ON) {
111
+ result.failOn = process.env.CODEPULSE_FAIL_ON;
112
+ }
113
+ if (process.env.CODEPULSE_MAX_WARNINGS) {
114
+ const n = parseInt(process.env.CODEPULSE_MAX_WARNINGS, 10);
115
+ if (!isNaN(n)) result.maxWarnings = n;
116
+ }
117
+
118
+ return result;
119
+ }
120
+
121
+ /**
122
+ * Deep-merge user config over base defaults.
123
+ */
124
+ export function mergeConfig(base, overrides) {
125
+ if (!overrides || typeof overrides !== 'object') return { ...base };
126
+ return {
127
+ ...base,
128
+ ...overrides,
129
+ scoring: {
130
+ ...base.scoring,
131
+ ...(overrides.scoring ?? {}),
132
+ weights: {
133
+ ...base.scoring.weights,
134
+ ...(overrides.scoring?.weights ?? {}),
135
+ },
136
+ },
137
+ rules: {
138
+ ...base.rules,
139
+ ...(overrides.rules ?? {}),
140
+ },
141
+ };
142
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Config Validator
3
+ *
4
+ * Validates a merged config object and returns a structured report so the CLI
5
+ * can surface problems early — before analysis starts — with clear messages.
6
+ *
7
+ * Usage:
8
+ * const { valid, errors, warnings } = validateConfig(config);
9
+ * if (!valid) { errors.forEach(e => logger.error(e)); process.exit(1); }
10
+ * warnings.forEach(w => logger.warn(w));
11
+ */
12
+
13
+ const VALID_SEVERITIES = new Set(['critical', 'high', 'medium', 'low']);
14
+ const VALID_FORMATS = new Set(['terminal', 'json', 'html']);
15
+ const KNOWN_RULE_PREFIXES = ['complexity/', 'smell/', 'duplication/', 'dependency/', 'hygiene/'];
16
+ const WEIGHT_KEYS = ['complexity', 'duplication', 'maintainability', 'dependencies', 'hygiene'];
17
+
18
+ /**
19
+ * @param {object} config — a merged codepulse config object
20
+ * @returns {{ valid: boolean, errors: string[], warnings: string[] }}
21
+ */
22
+ export function validateConfig(config) {
23
+ const errors = [];
24
+ const warnings = [];
25
+
26
+ if (!config || typeof config !== 'object') {
27
+ return { valid: false, errors: ['Config must be a plain object.'], warnings };
28
+ }
29
+
30
+ // ── ignore ────────────────────────────────────────────────────────────────
31
+ if (config.ignore !== undefined) {
32
+ if (!Array.isArray(config.ignore)) {
33
+ errors.push('"ignore" must be an array of glob strings.');
34
+ } else {
35
+ config.ignore.forEach((p, i) => {
36
+ if (typeof p !== 'string') errors.push(`"ignore[${i}]" must be a string.`);
37
+ });
38
+ }
39
+ }
40
+
41
+ // ── extensions ────────────────────────────────────────────────────────────
42
+ if (config.extensions !== undefined) {
43
+ if (!Array.isArray(config.extensions)) {
44
+ errors.push('"extensions" must be an array of strings like [".js", ".mjs"].');
45
+ } else {
46
+ config.extensions.forEach((e, i) => {
47
+ if (typeof e !== 'string') {
48
+ errors.push(`"extensions[${i}]" must be a string.`);
49
+ } else if (!e.startsWith('.')) {
50
+ warnings.push(`"extensions[${i}]" ("${e}") should start with "." — did you mean ".${e}"?`);
51
+ }
52
+ });
53
+ }
54
+ }
55
+
56
+ // ── rules ─────────────────────────────────────────────────────────────────
57
+ if (config.rules !== undefined) {
58
+ if (typeof config.rules !== 'object' || Array.isArray(config.rules)) {
59
+ errors.push('"rules" must be a plain object mapping rule IDs to config.');
60
+ } else {
61
+ for (const [id, val] of Object.entries(config.rules)) {
62
+ const knownPrefix = KNOWN_RULE_PREFIXES.some(p => id.startsWith(p));
63
+ if (!knownPrefix) {
64
+ warnings.push(`Unknown rule ID "${id}". Known prefixes: ${KNOWN_RULE_PREFIXES.join(', ')}`);
65
+ }
66
+ if (val === 'off' || val === false) continue;
67
+ if (typeof val === 'object' && val !== null) {
68
+ if (val.severity !== undefined && !VALID_SEVERITIES.has(val.severity)) {
69
+ errors.push(`Rule "${id}": severity must be one of ${[...VALID_SEVERITIES].join('|')}, got "${val.severity}".`);
70
+ }
71
+ if (val.options !== undefined && (typeof val.options !== 'object' || Array.isArray(val.options))) {
72
+ errors.push(`Rule "${id}": "options" must be a plain object.`);
73
+ }
74
+ } else {
75
+ errors.push(`Rule "${id}": value must be "off", false, or { severity, options }.`);
76
+ }
77
+ }
78
+ }
79
+ }
80
+
81
+ // ── thresholds ────────────────────────────────────────────────────────────
82
+ if (config.thresholds !== undefined) {
83
+ if (typeof config.thresholds !== 'object' || Array.isArray(config.thresholds)) {
84
+ errors.push('"thresholds" must be a plain object.');
85
+ } else {
86
+ for (const [key, val] of Object.entries(config.thresholds)) {
87
+ if (typeof val !== 'number' || val <= 0 || !isFinite(val)) {
88
+ errors.push(`"thresholds.${key}" must be a positive finite number, got ${JSON.stringify(val)}.`);
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ // ── scoring.weights ───────────────────────────────────────────────────────
95
+ if (config.scoring !== undefined) {
96
+ if (typeof config.scoring !== 'object' || Array.isArray(config.scoring)) {
97
+ errors.push('"scoring" must be a plain object.');
98
+ } else if (config.scoring.weights !== undefined) {
99
+ const w = config.scoring.weights;
100
+ if (typeof w !== 'object' || Array.isArray(w)) {
101
+ errors.push('"scoring.weights" must be a plain object.');
102
+ } else {
103
+ for (const key of Object.keys(w)) {
104
+ if (!WEIGHT_KEYS.includes(key)) {
105
+ warnings.push(`Unknown scoring weight key "${key}". Known keys: ${WEIGHT_KEYS.join(', ')}.`);
106
+ }
107
+ }
108
+ for (const key of WEIGHT_KEYS) {
109
+ const v = w[key];
110
+ if (v !== undefined) {
111
+ if (typeof v !== 'number' || v < 0 || !isFinite(v)) {
112
+ errors.push(`"scoring.weights.${key}" must be a non-negative finite number, got ${JSON.stringify(v)}.`);
113
+ }
114
+ }
115
+ }
116
+ const total = WEIGHT_KEYS.reduce((s, k) => s + (w[k] ?? 0), 0);
117
+ if (total > 0 && Math.abs(total - 1) > 0.01) {
118
+ warnings.push(`Scoring weights sum to ${total.toFixed(3)} — they will be auto-normalised to 1.0.`);
119
+ }
120
+ }
121
+ }
122
+ }
123
+
124
+ // ── output.format ─────────────────────────────────────────────────────────
125
+ if (config.output?.format !== undefined && !VALID_FORMATS.has(config.output.format)) {
126
+ errors.push(`"output.format" must be one of ${[...VALID_FORMATS].join('|')}, got "${config.output.format}".`);
127
+ }
128
+
129
+ return { valid: errors.length === 0, errors, warnings };
130
+ }
@@ -0,0 +1,198 @@
1
+ import path from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { parse } from '@babel/parser';
4
+ import * as logger from '../utils/logger.js';
5
+ import { calculateScores } from '../scoring/score-calculator.js';
6
+
7
+ // Babel parser options (mirrors ast-utils.js)
8
+ const PARSE_PLUGINS = [
9
+ 'jsx', 'asyncGenerators', 'bigInt', 'classProperties',
10
+ 'classPrivateProperties', 'classPrivateMethods', 'classStaticBlock',
11
+ 'dynamicImport', 'exportDefaultFrom', 'nullishCoalescingOperator',
12
+ 'numericSeparator', 'objectRestSpread', 'optionalCatchBinding',
13
+ 'optionalChaining', 'privateIn', 'topLevelAwait', 'logicalAssignment',
14
+ 'decorators-legacy',
15
+ ];
16
+
17
+ // Maximum files parsed in parallel (limits peak memory + open-fd count)
18
+ const PARSE_CONCURRENCY = 20;
19
+
20
+ /**
21
+ * Main analysis orchestrator.
22
+ *
23
+ * Phase 1: parses every file and collects basic metadata.
24
+ * Subsequent phases will attach real analyzers (complexity, smells,
25
+ * duplication, dependencies, scoring) through the _runAnalyzers hook.
26
+ */
27
+ export class Analyzer {
28
+ /**
29
+ * @param {object} options
30
+ * @param {object} options.config - Merged codepulse config.
31
+ * @param {string[]} options.files - Absolute paths to analyze.
32
+ * @param {string} options.rootDir - Project root.
33
+ */
34
+ constructor({ config, files, rootDir }) {
35
+ this.config = config;
36
+ this.files = files;
37
+ this.rootDir = rootDir;
38
+
39
+ // Registered analyzer modules (added by later phases)
40
+ this._analyzers = [];
41
+ }
42
+
43
+ /**
44
+ * Register an analyzer module.
45
+ * Each module must export { name, analyze(fileResults, config) → issues[] }
46
+ */
47
+ registerAnalyzer(analyzerModule) {
48
+ this._analyzers.push(analyzerModule);
49
+ }
50
+
51
+ /**
52
+ * Run the full analysis pipeline and return a result object.
53
+ */
54
+ async analyze() {
55
+ const startTime = Date.now();
56
+
57
+ // ── Phase 1: Parse all files (concurrent async I/O + sync Babel parse) ─
58
+ const parsed = await _pooled(this.files, PARSE_CONCURRENCY, (filePath) =>
59
+ _parseAsync(filePath, this.rootDir)
60
+ );
61
+
62
+ const fileResults = [];
63
+ let parseErrors = 0;
64
+ const fileMap = new Map(); // filePath → fileResult (O(1) finding attachment)
65
+
66
+ for (const result of parsed) {
67
+ if (result.error) {
68
+ parseErrors++;
69
+ logger.warn(`Parse error in ${result.relativePath}: ${result.error}`);
70
+ }
71
+ fileResults.push(result);
72
+ fileMap.set(result.path, result);
73
+ }
74
+
75
+ // ── Phase 2+: Run registered analyzers ───────────────────────────────
76
+ for (const analyzer of this._analyzers) {
77
+ try {
78
+ logger.verbose(`Running analyzer: ${analyzer.name}`);
79
+ const findings = await analyzer.analyze(fileResults, this.config);
80
+ for (const finding of findings) {
81
+ const fileResult = fileMap.get(finding.filePath);
82
+ if (fileResult) {
83
+ fileResult.issues.push(finding);
84
+ }
85
+ }
86
+ } catch (err) {
87
+ logger.warn(`Analyzer "${analyzer.name}" failed: ${err.message}`);
88
+ }
89
+ }
90
+
91
+ // ── Flatten all issues ────────────────────────────────────────────────
92
+ const allIssues = fileResults.flatMap(f => f.issues ?? []);
93
+
94
+ // Strip AST from final result (keep memory footprint reasonable)
95
+ const cleanFileResults = fileResults.map(({ ast: _ast, code: _code, ...rest }) => rest);
96
+
97
+ const duration = Date.now() - startTime;
98
+
99
+ const result = {
100
+ version: '0.1.0',
101
+ rootDir: this.rootDir,
102
+ filesAnalyzed: fileResults.filter(f => !f.error).length,
103
+ filesWithErrors: parseErrors,
104
+ totalFiles: this.files.length,
105
+ files: cleanFileResults,
106
+ issues: allIssues,
107
+ metrics: this._aggregateMetrics(fileResults),
108
+ scores: null,
109
+ duration,
110
+ timestamp: new Date().toISOString(),
111
+ };
112
+
113
+ result.scores = calculateScores(result, this.config);
114
+ return result;
115
+ }
116
+
117
+ _aggregateMetrics(fileResults) {
118
+ const analyzed = fileResults.filter(f => !f.error);
119
+ const totalLines = analyzed.reduce((sum, f) => sum + (f.lines ?? 0), 0);
120
+ return {
121
+ totalFiles: analyzed.length,
122
+ totalLines,
123
+ avgLinesPerFile: analyzed.length > 0 ? Math.round(totalLines / analyzed.length) : 0,
124
+ };
125
+ }
126
+ }
127
+
128
+ // ── Module-level helpers ──────────────────────────────────────────────────────
129
+
130
+ /**
131
+ * Read a file asynchronously, then parse it synchronously with Babel.
132
+ * Binary files (null bytes) are reported as errors rather than crashing.
133
+ */
134
+ async function _parseAsync(filePath, rootDir) {
135
+ const relativePath = path.relative(rootDir, filePath);
136
+ let code;
137
+
138
+ try {
139
+ code = await readFile(filePath, 'utf8');
140
+ } catch (e) {
141
+ return { path: filePath, relativePath, error: `Cannot read file: ${e.message}`, lines: 0, issues: [], metrics: {} };
142
+ }
143
+
144
+ // Binary file detection — null bytes indicate non-text content
145
+ if (code.includes('\0')) {
146
+ return { path: filePath, relativePath, error: 'Binary file skipped', lines: 0, issues: [], metrics: {} };
147
+ }
148
+
149
+ // Synchronous Babel parse (try module then script)
150
+ for (const sourceType of ['module', 'script']) {
151
+ try {
152
+ const ast = parse(code, {
153
+ sourceType,
154
+ allowImportExportEverywhere: true,
155
+ allowReturnOutsideFunction: true,
156
+ allowSuperOutsideMethod: true,
157
+ errorRecovery: true,
158
+ plugins: PARSE_PLUGINS,
159
+ });
160
+ return {
161
+ path: filePath,
162
+ relativePath,
163
+ sourceType,
164
+ lines: code.split('\n').length,
165
+ parseErrors: ast.errors ?? [],
166
+ ast,
167
+ code,
168
+ issues: [],
169
+ metrics: {},
170
+ };
171
+ } catch {
172
+ // try next sourceType
173
+ }
174
+ }
175
+
176
+ return { path: filePath, relativePath, error: `Parse failed: ${filePath}`, lines: 0, issues: [], metrics: {} };
177
+ }
178
+
179
+ /**
180
+ * Run `fn` over `items` with at most `concurrency` items in-flight at a time.
181
+ * Preserves input order in the returned array.
182
+ */
183
+ async function _pooled(items, concurrency, fn) {
184
+ const results = new Array(items.length);
185
+ let next = 0;
186
+
187
+ async function worker() {
188
+ while (next < items.length) {
189
+ const idx = next++;
190
+ results[idx] = await fn(items[idx]);
191
+ }
192
+ }
193
+
194
+ await Promise.all(
195
+ Array.from({ length: Math.min(concurrency, items.length) }, worker)
196
+ );
197
+ return results;
198
+ }
@@ -0,0 +1,95 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import ignore from 'ignore';
4
+
5
+ /**
6
+ * Patterns excluded by default regardless of user config.
7
+ * These follow gitignore glob syntax as implemented by the `ignore` package.
8
+ */
9
+ const DEFAULT_IGNORE_PATTERNS = [
10
+ 'node_modules',
11
+ 'node_modules/**',
12
+ '.git',
13
+ '.git/**',
14
+ 'dist',
15
+ 'dist/**',
16
+ 'build',
17
+ 'build/**',
18
+ 'coverage',
19
+ 'coverage/**',
20
+ '.nyc_output',
21
+ '.nyc_output/**',
22
+ '.codepulse',
23
+ '.codepulse/**',
24
+ '**/*.min.js',
25
+ '**/*.bundle.js',
26
+ '**/*.min.mjs',
27
+ '**/*.map',
28
+ '**/vendor/**',
29
+ '**/generated/**',
30
+ ];
31
+
32
+ const DEFAULT_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.jsx']);
33
+
34
+ export class FileFilter {
35
+ /**
36
+ * @param {object} options
37
+ * @param {string} [options.rootDir] - Project root (used to load .gitignore).
38
+ * @param {string[]} [options.ignore] - Additional ignore patterns.
39
+ * @param {string[]} [options.extensions]- Supported file extensions.
40
+ */
41
+ constructor(options = {}) {
42
+ this._ig = ignore();
43
+ this._ig.add(DEFAULT_IGNORE_PATTERNS);
44
+
45
+ if (Array.isArray(options.ignore) && options.ignore.length > 0) {
46
+ this._ig.add(options.ignore);
47
+ }
48
+
49
+ if (options.rootDir) {
50
+ this._loadGitignore(options.rootDir);
51
+ }
52
+
53
+ this.extensions = options.extensions
54
+ ? new Set(options.extensions)
55
+ : DEFAULT_EXTENSIONS;
56
+ }
57
+
58
+ _loadGitignore(rootDir) {
59
+ const gitignorePath = path.join(rootDir, '.gitignore');
60
+ try {
61
+ const content = fs.readFileSync(gitignorePath, 'utf8');
62
+ this._ig.add(content);
63
+ } catch {
64
+ // No .gitignore present — perfectly fine.
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Returns true if the file at absolutePath should be analyzed.
70
+ */
71
+ shouldInclude(absolutePath, rootDir) {
72
+ return this.exclusionReason(absolutePath, rootDir) === null;
73
+ }
74
+
75
+ /**
76
+ * Returns a human-readable string explaining why the file is excluded,
77
+ * or null if the file should be included.
78
+ */
79
+ exclusionReason(absolutePath, rootDir) {
80
+ const ext = path.extname(absolutePath);
81
+ if (!this.extensions.has(ext)) {
82
+ return `unsupported extension: ${ext || '(none)'}`;
83
+ }
84
+
85
+ const relative = path.relative(rootDir, absolutePath);
86
+ // Normalise to forward-slash for the `ignore` library on Windows/macOS.
87
+ const normalized = relative.split(path.sep).join('/');
88
+
89
+ if (this._ig.ignores(normalized)) {
90
+ return 'matched ignore pattern';
91
+ }
92
+
93
+ return null;
94
+ }
95
+ }