@interlace/eslint-devkit 1.3.2 → 1.4.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.
- package/CHANGELOG.md +107 -0
- package/README.md +10 -8
- package/package.json +13 -11
- package/src/index.d.ts +1 -0
- package/src/index.js +4 -0
- package/src/messaging/formatters-ai.d.ts +22 -3
- package/src/messaging/formatters-v2.d.ts +84 -0
- package/src/messaging/formatters-v2.js +363 -0
- package/src/messaging/types-v2.d.ts +112 -0
- package/src/messaging/types-v2.js +7 -0
- package/src/resolver/dependency-analysis.d.ts +53 -11
- package/src/resolver/dependency-analysis.js +235 -71
- package/src/resolver/resolver-adapter.js +1 -0
- package/src/resolver/resolver-detection.js +16 -11
- package/src/resolver/resolver.d.ts +6 -26
- package/src/resolver/resolver.js +162 -185
- package/src/security/security-utils.js +3 -3
- package/src/types/index.d.ts +1 -0
- package/src/types/index.js +4 -0
- package/src/types/meta-augmentation.d.ts +44 -0
- package/src/types/meta-augmentation.js +7 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* V2 Message Formatter Types
|
|
8
|
+
*
|
|
9
|
+
* Category-specific message option interfaces for security, code quality,
|
|
10
|
+
* and performance rules. Each type exposes purpose-specific fields
|
|
11
|
+
* (e.g., `vulnerable`/`safe` for security, `cycle` for code quality).
|
|
12
|
+
*/
|
|
13
|
+
import type { Severity, OWASPCategory, ComplianceFramework } from './types';
|
|
14
|
+
/**
|
|
15
|
+
* Base fields shared by all v2 message categories.
|
|
16
|
+
*
|
|
17
|
+
* Key additions over v1 `LLMMessageOptions`:
|
|
18
|
+
* - `why` — architectural rationale (industry best practice for LLM teaching)
|
|
19
|
+
* - `vulnerable` / `safe` — before/after code examples for reliable auto-fix
|
|
20
|
+
*/
|
|
21
|
+
export interface BaseMessageOptionsV2 {
|
|
22
|
+
/** Severity level */
|
|
23
|
+
severity: Severity;
|
|
24
|
+
/** Concise description of the issue */
|
|
25
|
+
description: string;
|
|
26
|
+
/**
|
|
27
|
+
* Architectural rationale explaining *why* this pattern is dangerous.
|
|
28
|
+
* Transforms the message from "detection" into a "teaching prompt".
|
|
29
|
+
*/
|
|
30
|
+
why?: string;
|
|
31
|
+
/** Specific, actionable fix instruction */
|
|
32
|
+
fix: string;
|
|
33
|
+
/** Documentation link */
|
|
34
|
+
docs?: string;
|
|
35
|
+
/** Estimated remediation effort */
|
|
36
|
+
effort?: 'trivial' | 'low' | 'medium' | 'high';
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Options for security-focused rules (CWE-mapped).
|
|
40
|
+
*
|
|
41
|
+
* Evolution of v1 `LLMMessageOptions` with:
|
|
42
|
+
* - `vulnerable` / `safe` code examples for before/after comparison
|
|
43
|
+
* - `why` rationale for LLM teaching
|
|
44
|
+
* - Auto-enrichment from CWE (OWASP, CVSS, compliance)
|
|
45
|
+
*/
|
|
46
|
+
export interface SecurityMessageOptions extends BaseMessageOptionsV2 {
|
|
47
|
+
/** CWE reference (e.g., 'CWE-89') — triggers auto-enrichment */
|
|
48
|
+
cwe?: string;
|
|
49
|
+
/** OWASP Top 10 category (auto-detected from CWE if omitted) */
|
|
50
|
+
owasp?: OWASPCategory;
|
|
51
|
+
/** CVSS 3.1 score 0.0–10.0 (auto-calculated from severity if omitted) */
|
|
52
|
+
cvss?: number;
|
|
53
|
+
/** Affected compliance frameworks (auto-detected from CWE if omitted) */
|
|
54
|
+
compliance?: ComplianceFramework[];
|
|
55
|
+
/**
|
|
56
|
+
* Vulnerable code example (the "before").
|
|
57
|
+
* Shown as `✗` in human mode, `bad` in agent JSON.
|
|
58
|
+
*/
|
|
59
|
+
vulnerable?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Safe code example (the "after").
|
|
62
|
+
* Shown as `✓` in human mode, `good` in agent JSON.
|
|
63
|
+
*/
|
|
64
|
+
safe?: string;
|
|
65
|
+
}
|
|
66
|
+
/** Well-known code quality categories */
|
|
67
|
+
export type CodeQualityCategory = 'circular-dependency' | 'unused-import' | 'barrel-file' | 'dependency-boundary' | 'import-order' | 'naming-convention' | 'dead-code';
|
|
68
|
+
/**
|
|
69
|
+
* Options for code quality / structural rules.
|
|
70
|
+
* No CWE/OWASP/CVSS — these are architecture concerns, not vulnerabilities.
|
|
71
|
+
*/
|
|
72
|
+
export interface CodeQualityMessageOptions extends BaseMessageOptionsV2 {
|
|
73
|
+
/** Well-known category for grouping and routing */
|
|
74
|
+
category: CodeQualityCategory | string;
|
|
75
|
+
/**
|
|
76
|
+
* Import cycle path (for circular dependency rules).
|
|
77
|
+
* Rendered as `A → B → C → A` in human mode.
|
|
78
|
+
*/
|
|
79
|
+
cycle?: string[];
|
|
80
|
+
/**
|
|
81
|
+
* Vulnerable code example (the "before").
|
|
82
|
+
*/
|
|
83
|
+
vulnerable?: string;
|
|
84
|
+
/**
|
|
85
|
+
* Safe code example (the "after").
|
|
86
|
+
*/
|
|
87
|
+
safe?: string;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Options for performance-focused rules.
|
|
91
|
+
* Uses complexity metrics instead of security metadata.
|
|
92
|
+
*/
|
|
93
|
+
export interface PerformanceMessageOptions extends BaseMessageOptionsV2 {
|
|
94
|
+
/**
|
|
95
|
+
* Vulnerable code example (the "before").
|
|
96
|
+
*/
|
|
97
|
+
vulnerable?: string;
|
|
98
|
+
/**
|
|
99
|
+
* Safe code example (the "after").
|
|
100
|
+
*/
|
|
101
|
+
safe?: string;
|
|
102
|
+
/**
|
|
103
|
+
* Performance impact metrics.
|
|
104
|
+
* Displayed as "Impact: O(n) queries → O(1) query" in human mode.
|
|
105
|
+
*/
|
|
106
|
+
impact?: {
|
|
107
|
+
/** Current (bad) complexity or behavior */
|
|
108
|
+
current: string;
|
|
109
|
+
/** Optimized (good) complexity or behavior */
|
|
110
|
+
optimized: string;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -90,13 +90,31 @@ export interface FileSystemCache {
|
|
|
90
90
|
* Resolved import paths cache (LRU)
|
|
91
91
|
* Key: `${fromFile}::${importPath}`, Value: resolved path or null
|
|
92
92
|
* This avoids re-resolving the same import from the same file
|
|
93
|
+
*
|
|
94
|
+
* PERFORMANCE: Uses plain Map instead of LRU cache. The LRU's
|
|
95
|
+
* delete+re-insert on every get() was 3x overhead at 40K+ calls.
|
|
96
|
+
* Within a lint run, memory is bounded by codebase size (~50K entries ≈ 2MB).
|
|
93
97
|
*/
|
|
94
|
-
resolvedPaths:
|
|
98
|
+
resolvedPaths: Map<string, string | null>;
|
|
95
99
|
/**
|
|
96
100
|
* Files known to not be in any cycle (optimization)
|
|
97
101
|
* Once a file is confirmed to not be in a cycle, we can skip SCC check for it
|
|
98
102
|
*/
|
|
99
103
|
nonCyclicFiles: Set<string>;
|
|
104
|
+
/**
|
|
105
|
+
* Pending cycle reports keyed by *member* file path. Populated when ANY
|
|
106
|
+
* file's DFS discovers a cycle: every member of the discovered cycle gets
|
|
107
|
+
* a pending entry. When ESLint later lints that member, the rule flushes
|
|
108
|
+
* the entry as a diagnostic at `Program:exit`.
|
|
109
|
+
*
|
|
110
|
+
* This is what closes the with-router.tsx gap — without it, only the file
|
|
111
|
+
* whose DFS discovered the cycle gets the diagnostic, and ordering
|
|
112
|
+
* sometimes leaves other members silent.
|
|
113
|
+
*/
|
|
114
|
+
pendingCycleReports: Map<string, Array<{
|
|
115
|
+
minimalCycle: string[];
|
|
116
|
+
cycleHash: string;
|
|
117
|
+
}>>;
|
|
100
118
|
}
|
|
101
119
|
/**
|
|
102
120
|
* Create a new empty cache
|
|
@@ -268,23 +286,47 @@ export interface CycleDetectionOptions {
|
|
|
268
286
|
resolverSettings?: ResolverSetting;
|
|
269
287
|
}
|
|
270
288
|
/**
|
|
271
|
-
*
|
|
289
|
+
* Lightweight per-import cycle detector (Phase 3 optimization)
|
|
290
|
+
*
|
|
291
|
+
* Instead of building the full graph upfront via BFS + Tarjan SCC,
|
|
292
|
+
* this function does a simple bounded DFS from a target file, looking
|
|
293
|
+
* for any path back to the source file. This is architecturally similar
|
|
294
|
+
* to eslint-plugin-import's no-cycle approach and is dramatically faster
|
|
295
|
+
* because it only reads files along the actual traversal path.
|
|
296
|
+
*
|
|
297
|
+
* Performance characteristics:
|
|
298
|
+
* - O(depth) file reads per call (not O(|V|) like BFS)
|
|
299
|
+
* - nonCyclicFiles cache provides O(1) rejection across the lint run
|
|
300
|
+
* - getFileImports cache reuses parsed results across files
|
|
301
|
+
* - Bounded by maxDepth to prevent runaway traversal
|
|
302
|
+
*
|
|
303
|
+
* @param sourceFile - The file containing the import (looking for path back to here)
|
|
304
|
+
* @param targetFile - The file being imported (starting point for DFS)
|
|
305
|
+
* @param options - Detection options
|
|
306
|
+
* @returns Array of cycle paths found (each is an array of file paths ending at sourceFile)
|
|
307
|
+
*/
|
|
308
|
+
export declare function detectCycleFromImport(sourceFile: string, targetFile: string, options: CycleDetectionOptions): string[][];
|
|
309
|
+
/**
|
|
310
|
+
* Find all circular dependencies using SCC + DFS hybrid approach
|
|
272
311
|
*
|
|
273
|
-
* Performance Strategy:
|
|
274
|
-
* 1.
|
|
275
|
-
*
|
|
276
|
-
*
|
|
312
|
+
* Performance Strategy (v2 — optimized based on benchmark data):
|
|
313
|
+
* 1. Compute SCCs via Tarjan's algorithm on first call (cached for lint run)
|
|
314
|
+
* — now significantly faster thanks to resolver fast path + getTsconfig cache
|
|
315
|
+
* 2. Use O(1) SCC membership for instant non-cyclic file rejection
|
|
316
|
+
* 3. Only run DFS for files known to be in a cycle (to extract paths)
|
|
317
|
+
* 4. Build graph lazily via getFileImports() with caching
|
|
277
318
|
*
|
|
278
|
-
*
|
|
279
|
-
* -
|
|
280
|
-
* -
|
|
281
|
-
* -
|
|
319
|
+
* Key optimizations vs v1:
|
|
320
|
+
* - Resolver fast path: existsSync for relative imports (10-50x per call)
|
|
321
|
+
* - Global getTsconfig cache: eliminates per-file directory traversal
|
|
322
|
+
* - visited Set: prevents DFS re-traversal of explored subtrees
|
|
323
|
+
* - nonCyclicFiles cache: O(1) rejection across entire lint run
|
|
282
324
|
*
|
|
283
325
|
* @param file - Starting file for cycle detection
|
|
284
326
|
* @param options - Detection options
|
|
285
327
|
* @param currentPath - Current path in DFS (internal use)
|
|
286
328
|
* @param depth - Current depth (internal use)
|
|
287
|
-
* @param visited - Set of
|
|
329
|
+
* @param visited - Set of fully explored files (internal use, persistent)
|
|
288
330
|
* @returns Array of cycles found (each cycle is an array of file paths)
|
|
289
331
|
*/
|
|
290
332
|
export declare function findAllCircularDependencies(file: string, options: CycleDetectionOptions, currentPath?: string[], depth?: number, visited?: Set<string>): string[][];
|
|
@@ -22,6 +22,7 @@ exports.hasOnlyTypeImports = hasOnlyTypeImports;
|
|
|
22
22
|
exports.computeSCCsFromFile = computeSCCsFromFile;
|
|
23
23
|
exports.isFileInCycle = isFileInCycle;
|
|
24
24
|
exports.getCycleForFile = getCycleForFile;
|
|
25
|
+
exports.detectCycleFromImport = detectCycleFromImport;
|
|
25
26
|
exports.findAllCircularDependencies = findAllCircularDependencies;
|
|
26
27
|
exports.getMinimalCycle = getMinimalCycle;
|
|
27
28
|
exports.getCycleHash = getCycleHash;
|
|
@@ -40,6 +41,7 @@ exports.isIncrementalAvailable = isIncrementalAvailable;
|
|
|
40
41
|
* It relies on node-utils for low-level system operations.
|
|
41
42
|
*/
|
|
42
43
|
const resolver_1 = require("./resolver");
|
|
44
|
+
const node_fs_1 = require("node:fs");
|
|
43
45
|
const fs_1 = require("../node/fs");
|
|
44
46
|
const path_1 = require("../node/path");
|
|
45
47
|
// =============================================================================
|
|
@@ -49,8 +51,13 @@ const path_1 = require("../node/path");
|
|
|
49
51
|
/**
|
|
50
52
|
* Maximum entries in LRU cache before eviction
|
|
51
53
|
* eslint-plugin-import uses similar approach for their ExportMap cache
|
|
54
|
+
*
|
|
55
|
+
* PERFORMANCE: Sized for large codebases (5K+ files × ~10 imports = ~50K entries).
|
|
56
|
+
* A too-small cache causes thrashing: every evicted entry requires a full
|
|
57
|
+
* re-resolution through the resolver pipeline (enhanced-resolve, getTsconfig,
|
|
58
|
+
* extension fan-out). Memory cost is ~2KB per entry, so 50K ≈ 100MB max.
|
|
52
59
|
*/
|
|
53
|
-
const LRU_MAX_SIZE =
|
|
60
|
+
const LRU_MAX_SIZE = 50_000;
|
|
54
61
|
/**
|
|
55
62
|
* Quick check patterns for skipping external modules early
|
|
56
63
|
* This is a key optimization - skip node_modules paths without full resolution
|
|
@@ -121,6 +128,23 @@ const DYNAMIC_IMPORT_REGEX = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
|
121
128
|
* Matches: import type { x } from 'y'
|
|
122
129
|
*/
|
|
123
130
|
const TYPE_IMPORT_REGEX = /import\s+type\s/;
|
|
131
|
+
/**
|
|
132
|
+
* Pre-compiled regex for re-exports (export … from '…').
|
|
133
|
+
*
|
|
134
|
+
* Re-exports establish runtime import edges. The cycle in next.js's
|
|
135
|
+
* `client/router.ts` ↔ `client/with-router.tsx` propagates ENTIRELY through
|
|
136
|
+
* re-exports — without this regex our DFS doesn't see the edge and misses
|
|
137
|
+
* the cycle (verified against oxlint native, which catches it).
|
|
138
|
+
*
|
|
139
|
+
* Negative lookahead `(?!type[\s{])` excludes `export type ... from` —
|
|
140
|
+
* those are erased at compile time and don't cause runtime cycles.
|
|
141
|
+
*/
|
|
142
|
+
const EXPORT_FROM_REGEX = /(?:^|[\s;])export\s+(?!type[\s{])[\w*{}\s,]+from\s+['"]([^'"]+)['"]/gm;
|
|
143
|
+
/**
|
|
144
|
+
* Default extensions for import resolution.
|
|
145
|
+
* Module-level constant to avoid allocating a new array per resolve call.
|
|
146
|
+
*/
|
|
147
|
+
const DEFAULT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
|
|
124
148
|
// =============================================================================
|
|
125
149
|
// LRU Cache Implementation (inspired by eslint-plugin-import's caching)
|
|
126
150
|
// =============================================================================
|
|
@@ -204,8 +228,9 @@ function createFileSystemCache() {
|
|
|
204
228
|
sccs: [],
|
|
205
229
|
sccComputed: false,
|
|
206
230
|
graphHash: '',
|
|
207
|
-
resolvedPaths: new
|
|
231
|
+
resolvedPaths: new Map(),
|
|
208
232
|
nonCyclicFiles: new Set(),
|
|
233
|
+
pendingCycleReports: new Map(),
|
|
209
234
|
};
|
|
210
235
|
}
|
|
211
236
|
/**
|
|
@@ -221,8 +246,9 @@ function clearCache(cache) {
|
|
|
221
246
|
cache.sccs = [];
|
|
222
247
|
cache.sccComputed = false;
|
|
223
248
|
cache.graphHash = '';
|
|
224
|
-
cache.resolvedPaths
|
|
249
|
+
cache.resolvedPaths = new Map();
|
|
225
250
|
cache.nonCyclicFiles.clear();
|
|
251
|
+
cache.pendingCycleReports.clear();
|
|
226
252
|
}
|
|
227
253
|
/**
|
|
228
254
|
* Invalidate SCC cache (call when graph changes)
|
|
@@ -308,23 +334,41 @@ function shouldIgnoreFileWithCache(file, patterns, cache) {
|
|
|
308
334
|
* @returns Absolute file path or null for external packages
|
|
309
335
|
*/
|
|
310
336
|
function resolveImportPath(importPath, options) {
|
|
311
|
-
const
|
|
337
|
+
const fromFile = options.fromFile;
|
|
338
|
+
const extensions = options.extensions || DEFAULT_EXTENSIONS;
|
|
339
|
+
const cache = options.cache;
|
|
340
|
+
const resolverSettings = options.resolverSettings;
|
|
312
341
|
// OPTIMIZATION 1: Quick external check (no fs access needed)
|
|
313
342
|
// This avoids unnecessary file system calls for packages like 'lodash', 'react', etc.
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
343
|
+
if (isDefinitelyExternal(importPath)) {
|
|
344
|
+
// For @-scoped imports, we can't use isDefinitelyExternal alone
|
|
345
|
+
// because @app/foo (internal alias) looks like @testing-library/react (external).
|
|
346
|
+
// We still skip the external check for these and let the resolver handle them.
|
|
347
|
+
if (!importPath.startsWith('@')) {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// OPTIMIZATION 2a: For non-relative imports, use a global cache keyed by
|
|
352
|
+
// just the import specifier. Non-relative imports (like @app/utils, react)
|
|
353
|
+
// resolve to the same path regardless of which file imports them in a
|
|
354
|
+
// single-tsconfig project. This turns ~14K resolution calls into ~400.
|
|
355
|
+
const isRelative = importPath.startsWith('.');
|
|
356
|
+
if (!isRelative) {
|
|
357
|
+
const globalCached = cache.resolvedPaths.get(importPath);
|
|
358
|
+
if (globalCached !== undefined) {
|
|
359
|
+
return globalCached;
|
|
360
|
+
}
|
|
317
361
|
}
|
|
318
|
-
// OPTIMIZATION
|
|
319
|
-
const cacheKey = `${fromFile}::${importPath}
|
|
362
|
+
// OPTIMIZATION 2b: Per-file cache for relative imports (./foo varies by dir)
|
|
363
|
+
const cacheKey = isRelative ? `${fromFile}::${importPath}` : importPath;
|
|
320
364
|
const cached = cache.resolvedPaths.get(cacheKey);
|
|
321
365
|
if (cached !== undefined) {
|
|
322
366
|
return cached;
|
|
323
367
|
}
|
|
324
|
-
// Use the
|
|
368
|
+
// Use the robust resolver
|
|
325
369
|
// This supports:
|
|
326
370
|
// 1. TypeScript paths (tsconfig.json)
|
|
327
|
-
// 2. Webpack aliases (via
|
|
371
|
+
// 2. Webpack aliases (via oxc-resolver/tsconfig)
|
|
328
372
|
// 3. Package.json exports
|
|
329
373
|
// 4. Monorepo resolution
|
|
330
374
|
let result = (0, resolver_1.resolveModule)(importPath, fromFile, {
|
|
@@ -334,8 +378,30 @@ function resolveImportPath(importPath, options) {
|
|
|
334
378
|
mainFields: ['module', 'main'],
|
|
335
379
|
resolverSettings,
|
|
336
380
|
});
|
|
381
|
+
// OPTIMIZATION 3: If non-relative import resolved to node_modules, treat as external.
|
|
382
|
+
// This prevents the DFS from traversing into external packages.
|
|
383
|
+
//
|
|
384
|
+
// CAVEAT: In monorepos, workspace packages are often symlinked into
|
|
385
|
+
// node_modules (e.g., pnpm/npm workspaces). We use realpathSync to check
|
|
386
|
+
// if the file truly lives in node_modules vs being a symlinked local package.
|
|
387
|
+
if (result && !isRelative && result.includes('node_modules')) {
|
|
388
|
+
try {
|
|
389
|
+
const realPath = (0, node_fs_1.realpathSync)(result);
|
|
390
|
+
if (realPath.includes('node_modules')) {
|
|
391
|
+
cache.resolvedPaths.set(cacheKey, null);
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
// Symlinked workspace package — use the real path for DFS traversal
|
|
395
|
+
result = realPath;
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
// realpathSync failed (broken symlink, etc.) — treat as external
|
|
399
|
+
cache.resolvedPaths.set(cacheKey, null);
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
337
403
|
// Fallback for relative imports that don't exist (useful for error reporting)
|
|
338
|
-
if (!result &&
|
|
404
|
+
if (!result && isRelative) {
|
|
339
405
|
// We can't know the extension, but we can return the absolute path base
|
|
340
406
|
// This matches what tests expect for non-existent files
|
|
341
407
|
result = (0, path_1.resolvePath)((0, path_1.getDirname)(fromFile), importPath);
|
|
@@ -359,12 +425,14 @@ function resolveImportPath(importPath, options) {
|
|
|
359
425
|
*/
|
|
360
426
|
function getFileImports(file, options) {
|
|
361
427
|
const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
|
|
362
|
-
//
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
428
|
+
// PHASE 6 OPTIMIZATION: Within a single lint run, files don't change.
|
|
429
|
+
// Skip the expensive isCacheValid (which calls statSync per file) and
|
|
430
|
+
// just check if we already have cached dependencies. The hash-based
|
|
431
|
+
// invalidation still runs after parsing (line ~635) to support watch
|
|
432
|
+
// mode and cross-run ESLint cache.
|
|
433
|
+
const cached = cache.dependencies.get(file);
|
|
434
|
+
if (cached) {
|
|
435
|
+
return cached;
|
|
368
436
|
}
|
|
369
437
|
const imports = [];
|
|
370
438
|
try {
|
|
@@ -375,40 +443,45 @@ function getFileImports(file, options) {
|
|
|
375
443
|
if (content === null) {
|
|
376
444
|
return imports;
|
|
377
445
|
}
|
|
446
|
+
// PHASE 6 OPTIMIZATION: Pre-allocate the resolve options object ONCE per file.
|
|
447
|
+
// Previously, a new options object was created for every regex match (~25K
|
|
448
|
+
// allocations per lint run on snappy-client-dashboard). The `importPath`
|
|
449
|
+
// field is set to a placeholder and will never be used because
|
|
450
|
+
// resolveImportPath takes it as a separate argument.
|
|
451
|
+
const resolveOpts = {
|
|
452
|
+
fromFile: file,
|
|
453
|
+
workspaceRoot,
|
|
454
|
+
barrelExports,
|
|
455
|
+
cache,
|
|
456
|
+
extensions: DEFAULT_EXTENSIONS,
|
|
457
|
+
resolverSettings,
|
|
458
|
+
};
|
|
378
459
|
// Use pre-compiled regex - reset lastIndex for reuse
|
|
379
460
|
IMPORT_REGEX.lastIndex = 0;
|
|
380
461
|
DYNAMIC_IMPORT_REGEX.lastIndex = 0;
|
|
462
|
+
EXPORT_FROM_REGEX.lastIndex = 0;
|
|
381
463
|
let match;
|
|
382
|
-
//
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
extensions: ['.ts', '.tsx', '.js', '.jsx'],
|
|
391
|
-
resolverSettings,
|
|
392
|
-
});
|
|
393
|
-
if (resolved && fileExists(resolved, cache)) {
|
|
394
|
-
imports.push({ path: resolved, source: importPath });
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
// Match dynamic imports using pre-compiled regex
|
|
398
|
-
while ((match = DYNAMIC_IMPORT_REGEX.exec(content)) !== null) {
|
|
399
|
-
const importPath = match[1];
|
|
400
|
-
const resolved = resolveImportPath(importPath, {
|
|
401
|
-
fromFile: file,
|
|
402
|
-
workspaceRoot,
|
|
403
|
-
barrelExports,
|
|
404
|
-
cache,
|
|
405
|
-
extensions: ['.ts', '.tsx', '.js', '.jsx'],
|
|
406
|
-
resolverSettings,
|
|
407
|
-
});
|
|
408
|
-
if (resolved && fileExists(resolved, cache)) {
|
|
409
|
-
imports.push({ path: resolved, source: importPath, dynamic: true });
|
|
464
|
+
// Track resolved paths to dedupe across the three regexes (a single file
|
|
465
|
+
// may have both `import X from 'y'` and `export { X } from 'y'`).
|
|
466
|
+
const seen = new Set();
|
|
467
|
+
const pushImport = (importPath, dynamic = false) => {
|
|
468
|
+
const resolved = resolveImportPath(importPath, resolveOpts);
|
|
469
|
+
if (resolved && fileExists(resolved, cache) && !seen.has(resolved)) {
|
|
470
|
+
seen.add(resolved);
|
|
471
|
+
imports.push(dynamic ? { path: resolved, source: importPath, dynamic } : { path: resolved, source: importPath });
|
|
410
472
|
}
|
|
411
|
-
}
|
|
473
|
+
};
|
|
474
|
+
// Match ES6 static imports using pre-compiled regex
|
|
475
|
+
while ((match = IMPORT_REGEX.exec(content)) !== null)
|
|
476
|
+
pushImport(match[1]);
|
|
477
|
+
// Match re-exports (`export … from '…'`). Without this, cycles routed
|
|
478
|
+
// through re-export-only files (a common pattern in barrel-heavy
|
|
479
|
+
// codebases) are invisible.
|
|
480
|
+
while ((match = EXPORT_FROM_REGEX.exec(content)) !== null)
|
|
481
|
+
pushImport(match[1]);
|
|
482
|
+
// Match dynamic imports
|
|
483
|
+
while ((match = DYNAMIC_IMPORT_REGEX.exec(content)) !== null)
|
|
484
|
+
pushImport(match[1], true);
|
|
412
485
|
// Store file hash for cache invalidation + invalidate SCC if graph changed
|
|
413
486
|
const hash = getFileHash(file);
|
|
414
487
|
if (hash) {
|
|
@@ -615,35 +688,127 @@ function getCycleForFile(file, cache) {
|
|
|
615
688
|
return scc.files;
|
|
616
689
|
}
|
|
617
690
|
/**
|
|
618
|
-
*
|
|
691
|
+
* Lightweight per-import cycle detector (Phase 3 optimization)
|
|
692
|
+
*
|
|
693
|
+
* Instead of building the full graph upfront via BFS + Tarjan SCC,
|
|
694
|
+
* this function does a simple bounded DFS from a target file, looking
|
|
695
|
+
* for any path back to the source file. This is architecturally similar
|
|
696
|
+
* to eslint-plugin-import's no-cycle approach and is dramatically faster
|
|
697
|
+
* because it only reads files along the actual traversal path.
|
|
698
|
+
*
|
|
699
|
+
* Performance characteristics:
|
|
700
|
+
* - O(depth) file reads per call (not O(|V|) like BFS)
|
|
701
|
+
* - nonCyclicFiles cache provides O(1) rejection across the lint run
|
|
702
|
+
* - getFileImports cache reuses parsed results across files
|
|
703
|
+
* - Bounded by maxDepth to prevent runaway traversal
|
|
704
|
+
*
|
|
705
|
+
* @param sourceFile - The file containing the import (looking for path back to here)
|
|
706
|
+
* @param targetFile - The file being imported (starting point for DFS)
|
|
707
|
+
* @param options - Detection options
|
|
708
|
+
* @returns Array of cycle paths found (each is an array of file paths ending at sourceFile)
|
|
709
|
+
*/
|
|
710
|
+
function detectCycleFromImport(sourceFile, targetFile, options) {
|
|
711
|
+
const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
|
|
712
|
+
// Fast path: target is known to not be in any cycle
|
|
713
|
+
if (cache.nonCyclicFiles.has(targetFile)) {
|
|
714
|
+
return [];
|
|
715
|
+
}
|
|
716
|
+
const allCycles = [];
|
|
717
|
+
// PERFORMANCE: Use mutable stack instead of [...currentPath, file]
|
|
718
|
+
// to avoid O(depth) array allocations per DFS branch. The path is
|
|
719
|
+
// only copied when a cycle is actually found (rare).
|
|
720
|
+
const pathStack = [sourceFile];
|
|
721
|
+
// Track whether the DFS was truncated by the depth limit. If it was, we
|
|
722
|
+
// CANNOT cache the target as `nonCyclic` — depth-limit truncation isn't
|
|
723
|
+
// proof of acyclicity, and a poisoned cache cascades into every later
|
|
724
|
+
// lint pass that touches a file in the same subtree (verified on next.js:
|
|
725
|
+
// wide scope reported 0 cycles vs. 17 in oxlint, narrow scope reported 5+).
|
|
726
|
+
let depthLimitHit = false;
|
|
727
|
+
function dfs(file, depth, visited) {
|
|
728
|
+
// Found the cycle — we've reached back to the source file
|
|
729
|
+
if (file === sourceFile) {
|
|
730
|
+
allCycles.push([...pathStack, file]);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
// Depth limit
|
|
734
|
+
if (depth >= maxDepth) {
|
|
735
|
+
depthLimitHit = true;
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
// Already visited in this search tree
|
|
739
|
+
if (visited.has(file))
|
|
740
|
+
return;
|
|
741
|
+
// Known non-cyclic from previous lint file visits
|
|
742
|
+
if (cache.nonCyclicFiles.has(file))
|
|
743
|
+
return;
|
|
744
|
+
// Early exit when only first cycle needed
|
|
745
|
+
if (!reportAllCycles && allCycles.length > 0)
|
|
746
|
+
return;
|
|
747
|
+
visited.add(file);
|
|
748
|
+
pathStack.push(file);
|
|
749
|
+
const imports = getFileImports(file, {
|
|
750
|
+
workspaceRoot,
|
|
751
|
+
barrelExports,
|
|
752
|
+
cache,
|
|
753
|
+
resolverSettings,
|
|
754
|
+
});
|
|
755
|
+
for (const imp of imports) {
|
|
756
|
+
if (imp.dynamic)
|
|
757
|
+
continue;
|
|
758
|
+
if (!reportAllCycles && allCycles.length > 0)
|
|
759
|
+
break;
|
|
760
|
+
dfs(imp.path, depth + 1, visited);
|
|
761
|
+
}
|
|
762
|
+
pathStack.pop();
|
|
763
|
+
}
|
|
764
|
+
const visited = new Set();
|
|
765
|
+
dfs(targetFile, 1, visited);
|
|
766
|
+
// Only cache as non-cyclic when the DFS was complete AND found no cycles.
|
|
767
|
+
// A depth-truncated DFS cannot prove acyclicity (the cycle may exist past
|
|
768
|
+
// the depth limit), and caching it poisons every future lint pass that
|
|
769
|
+
// traverses the same subtree.
|
|
770
|
+
if (allCycles.length === 0 && !depthLimitHit) {
|
|
771
|
+
cache.nonCyclicFiles.add(targetFile);
|
|
772
|
+
}
|
|
773
|
+
return allCycles;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Find all circular dependencies using SCC + DFS hybrid approach
|
|
619
777
|
*
|
|
620
|
-
* Performance Strategy:
|
|
621
|
-
* 1.
|
|
622
|
-
*
|
|
623
|
-
*
|
|
778
|
+
* Performance Strategy (v2 — optimized based on benchmark data):
|
|
779
|
+
* 1. Compute SCCs via Tarjan's algorithm on first call (cached for lint run)
|
|
780
|
+
* — now significantly faster thanks to resolver fast path + getTsconfig cache
|
|
781
|
+
* 2. Use O(1) SCC membership for instant non-cyclic file rejection
|
|
782
|
+
* 3. Only run DFS for files known to be in a cycle (to extract paths)
|
|
783
|
+
* 4. Build graph lazily via getFileImports() with caching
|
|
624
784
|
*
|
|
625
|
-
*
|
|
626
|
-
* -
|
|
627
|
-
* -
|
|
628
|
-
* -
|
|
785
|
+
* Key optimizations vs v1:
|
|
786
|
+
* - Resolver fast path: existsSync for relative imports (10-50x per call)
|
|
787
|
+
* - Global getTsconfig cache: eliminates per-file directory traversal
|
|
788
|
+
* - visited Set: prevents DFS re-traversal of explored subtrees
|
|
789
|
+
* - nonCyclicFiles cache: O(1) rejection across entire lint run
|
|
629
790
|
*
|
|
630
791
|
* @param file - Starting file for cycle detection
|
|
631
792
|
* @param options - Detection options
|
|
632
793
|
* @param currentPath - Current path in DFS (internal use)
|
|
633
794
|
* @param depth - Current depth (internal use)
|
|
634
|
-
* @param visited - Set of
|
|
795
|
+
* @param visited - Set of fully explored files (internal use, persistent)
|
|
635
796
|
* @returns Array of cycles found (each cycle is an array of file paths)
|
|
636
797
|
*/
|
|
637
798
|
function findAllCircularDependencies(file, options, currentPath = [], depth = 0, visited = new Set()) {
|
|
638
799
|
const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
|
|
639
800
|
// OPTIMIZATION 1: Check if file is known to not be in any cycle
|
|
640
|
-
// This
|
|
801
|
+
// This is populated across the lint run — once a file is confirmed
|
|
802
|
+
// non-cyclic, all future calls skip it in O(1).
|
|
641
803
|
if (cache.nonCyclicFiles.has(file)) {
|
|
642
804
|
return [];
|
|
643
805
|
}
|
|
644
|
-
// OPTIMIZATION 2:
|
|
806
|
+
// OPTIMIZATION 2: At the root call, compute or use cached SCC data.
|
|
807
|
+
// SCC computation uses Tarjan's O(V+E) algorithm and is now much faster
|
|
808
|
+
// thanks to the resolver fast path (existsSync for relative imports) and
|
|
809
|
+
// global getTsconfig caching. The one-time cost is amortized across all
|
|
810
|
+
// file visits in the lint run via O(1) cycle membership lookups.
|
|
645
811
|
if (depth === 0) {
|
|
646
|
-
// Compute SCCs (cached - only computed once per lint run)
|
|
647
812
|
computeSCCsFromFile(file, {
|
|
648
813
|
maxDepth,
|
|
649
814
|
workspaceRoot,
|
|
@@ -651,28 +816,24 @@ function findAllCircularDependencies(file, options, currentPath = [], depth = 0,
|
|
|
651
816
|
cache,
|
|
652
817
|
resolverSettings,
|
|
653
818
|
});
|
|
654
|
-
// Fast path:
|
|
819
|
+
// Fast path: O(1) SCC lookup — if file is not in any cycle, skip
|
|
655
820
|
if (!isFileInCycle(file, cache)) {
|
|
656
|
-
// Mark this file as non-cyclic for future fast lookups
|
|
657
821
|
cache.nonCyclicFiles.add(file);
|
|
658
|
-
return [];
|
|
822
|
+
return [];
|
|
659
823
|
}
|
|
660
|
-
// File is in a cycle - now use DFS to get the actual cycle path for error messages
|
|
661
824
|
}
|
|
662
|
-
//
|
|
825
|
+
// Depth limit for performance
|
|
663
826
|
if (depth > maxDepth) {
|
|
664
827
|
return [];
|
|
665
828
|
}
|
|
666
|
-
// Found a cycle
|
|
829
|
+
// Found a cycle — the current file is already on the current DFS path
|
|
667
830
|
if (currentPath.includes(file)) {
|
|
668
831
|
return [[...currentPath, file]];
|
|
669
832
|
}
|
|
670
|
-
// OPTIMIZATION 3: Skip if already
|
|
671
|
-
/* v8 ignore start -- perf optimization: prevents re-traversal in complex graphs */
|
|
833
|
+
// OPTIMIZATION 3: Skip if already fully explored in this DFS tree
|
|
672
834
|
if (visited.has(file)) {
|
|
673
835
|
return [];
|
|
674
836
|
}
|
|
675
|
-
/* v8 ignore stop */
|
|
676
837
|
visited.add(file);
|
|
677
838
|
const imports = getFileImports(file, {
|
|
678
839
|
workspaceRoot,
|
|
@@ -687,14 +848,17 @@ function findAllCircularDependencies(file, options, currentPath = [], depth = 0,
|
|
|
687
848
|
if (imp.dynamic) {
|
|
688
849
|
continue;
|
|
689
850
|
}
|
|
690
|
-
// OPTIMIZATION 4:
|
|
691
|
-
// If reportAllCycles is false and we already found one, skip remaining imports
|
|
851
|
+
// OPTIMIZATION 4: Early exit when only first cycle is needed
|
|
692
852
|
if (!reportAllCycles && allCycles.length > 0) {
|
|
693
853
|
break;
|
|
694
854
|
}
|
|
695
855
|
const cycles = findAllCircularDependencies(imp.path, options, newPath, depth + 1, visited);
|
|
696
856
|
allCycles.push(...cycles);
|
|
697
857
|
}
|
|
858
|
+
// If no cycles found for this file in this search, mark as non-cyclic
|
|
859
|
+
if (depth === 0 && allCycles.length === 0) {
|
|
860
|
+
cache.nonCyclicFiles.add(file);
|
|
861
|
+
}
|
|
698
862
|
return allCycles;
|
|
699
863
|
}
|
|
700
864
|
/**
|