I need a very thorough exploration of how the TypeScript dependency graph and import parsing works in the desloppify codebase. Focus on:
desloppify/lang/typescript/detectors/deps.py — the full file. How does build_ts_dep_graph work? What file extensions does it process? How does it parse imports? How does it resolve import paths?
How the dep graph is used downstream — search for all usages of _dep_graph, dep_graph, build_ts_dep_graph across the codebase. Which detectors consume it?
The orphaned file detector — find it and understand how it determines a file is orphaned. Does it rely on the dep graph?
The dead-export detector — find it and understand how it determines an export is dead. Does it rely on the dep graph?
How .svelte files are currently handled (or not) — search for "svelte" across the codebase.
How tsconfig path aliases like @/* are currently handled (or not) — search for "tsconfig", "paths", "alias", "baseUrl" across the codebase.
Please read the full contents of all relevant files, not just snippets. I need to understand the complete flow.
Assistant
I'll conduct a thorough exploration of the TypeScript dependency graph and import parsing system. Let me start with systematic searches.
Assistant
Let me continue the exploration by searching for usages and related files.
Assistant
Now let me search for orphaned files and continue understanding the ecosystem:
User
I need a thorough exploration of the fixer infrastructure and file scanning in the desloppify codebase. Focus on:
The dead-exports fixer — search for files related to fixing dead exports. How does it work? What does it actually do to files?
desloppify/fixers/ directory — read all files there. Understand the fixer architecture.
The file scanning/discovery mechanism — how does desloppify discover which files to analyze? Search for how file extensions are determined, how files are collected for scanning. Look in desloppify/lang/typescript/ for how TS files are discovered.
desloppify/lang/typescript/__init__.py or any config file that defines what extensions are processed.
The plan.py file — how does the scan pipeline work? How is the dep graph built and attached?
Any existing support for non-TS/TSX files in the TS language plugin (e.g., .js, .jsx, .svelte, .vue, .astro).
The zone classification system in zones.py — how are TS zones defined? Would .svelte files get a zone?
Please read full file contents for all relevant files.
Assistant
I'll conduct a thorough exploration of the fixer infrastructure and file scanning in the desloppify codebase. Let me start by examining the key files systematically.
Assistant
Now let me search for more details on specific issues - graph.py, base.py, and more on how dep graphs are used:
Assistant
Let me continue reading the key files related to fixers and file scanning:
Assistant
Let me get the full find_ts_files function and more utilities:
Assistant
Now let me continue exploring the remaining fixer files and file scanning:
User
I need to understand the Python language plugin's dependency graph as a comparison point, and also understand how the test coverage detector handles cross-file imports. Focus on:
desloppify/lang/python/detectors/deps.py — how does the Python dep graph work? How does it parse imports?
desloppify/detectors/test_coverage.py — this detector already does cross-language import parsing. How does it work? Does it parse tsconfig paths?
desloppify/lang/python/__init__.py — what extensions does Python handle?
desloppify/lang/typescript/__init__.py — what extensions does TS handle? What's in the LangConfig?
Search for how _find_external_test_files works — does it scan non-standard extensions?
Any existing tsconfig.json parsing anywhere in the codebase.
The scan.py or plan.py command flow — how does the scan orchestrate everything?
Read full file contents for all key files.
Assistant
Now let me check tests to understand expected behavior better:
Assistant
I'll systematically explore the dependency graph handling, test coverage detection, and the language plugins to understand how imports and cross-file relationships are managed.
Assistant
Now let me continue reading the file discovery utilities and look at the language base configuration:
Assistant
Let me check more about how the unused detector works:
Assistant
Now let me search for how _find_external_test_files works and check for tsconfig.json parsing:
Assistant
Let me check the Python dep graph for comparison and look at plan.py:
Assistant
Now let me read the test coverage detector and check the Python language config:
Assistant
Now let me look at how scan command uses these:
Assistant
Now let me check the plan and scan commands to understand the orchestration:
Assistant
Perfect! Now let me gather the remaining pieces about scanning and file discovery. Let me check a couple more key files:
Assistant
Perfect. Now let me do a final check on how _dep_graph is cached and used in the scan phases:
Assistant
Let me get the rest of the scan command and check plan.py:
Assistant
Perfect! Now let me check one more thing about detection flow and check if there's any .svelte handling:
Assistant
Let me find the plan.py file:
Assistant
Excellent! Now let me compile a comprehensive summary. Let me do one final check on how imports are resolved - looking at the actual import statement detection patterns:
Assistant
Now let me check for any tsconfig parsing or additional imports handling in the detectors:
Assistant
Perfect. Now let me create a comprehensive summary based on all the code I've reviewed. Let me also check the zones.py to understand file classification:
Assistant
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the relevant files to understand the current architecture before designing the plan.
Assistant
Now let me explore the TS lang plugin configuration, tsconfig handling, and how the scan pipeline wires things together.
Assistant
Now let me look at the plan.py (where zone_map and dep_graph are set up), the CLI entry point, and how the scan pipeline works.
Assistant
Now let me look at the existing fixer infrastructure, the base lang config, and the test coverage detector (which also uses the dep graph).
Assistant
Now let me look at the existing tests to understand patterns and the unused/dynamic import detectors.
Assistant
Now let me check the existing test files and how imports are tested.
Assistant
Let me look at the test file for deps, and the move command's TS specifier code (which also handles aliases).
Assistant
Now let me check the test for exports and how grep_files_containing works for the reference index.
Assistant
Now let me examine how finalize_graph works in graph.py, and the coupling detector since it also uses the dep graph.
Assistant
I have now explored enough of the codebase. Let me now check the graph.py finalize_graph completely and look at the narrative file for the DETECTOR_TOOLS mapping to see if we need to update it.
Assistant
Good. No existing framework file handling at all. Now I have a thorough understanding of the codebase. Let me design the implementation plan.
Assistant
Assistant
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/deps.py - Core dep graph builder: add tsconfig alias resolution, framework file scanning, and extract _resolve_module helper
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/exports.py - Dead export detector: expand _build_reference_index to search framework files
/Users/user_c042661f/Documents/desloppify/desloppify/utils.py - find_source_files() will be reused by the new find_framework_files() function with different extension list
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/__init__.py - TypeScript config: where _phase_coupling wires up dep graph, orphan detection, and ts_alias_resolver
/Users/user_c042661f/Documents/desloppify/tests/test_ts_deps.py - Primary test file: pattern to follow for new dep graph tests with _set_project_root fixture and _write helper
Perfect! Now let me create a comprehensive report with all the findings from my exploration:
Comprehensive Exploration Report: Fixer Infrastructure & File Scanning in Desloppify
Based on my thorough exploration of the desloppify codebase, here are the detailed findings:
generate_findings(path, lang, zone_overrides)
↓
_generate_findings_from_lang(path, lang)
↓
1. Build zone map (FileZoneMap from lang.file_finder)
2. Run all phases (lang.phases) in order
3. Stamp language + zone on each finding
4. Apply zone policy confidence downgrades
↓
Returns: (findings, potentials)
Dep graph attachment:
Built during _phase_coupling (not at start)
Stored in lang._dep_graph for reuse
Built via lang.build_dep_graph(path) → TypeScript: build_dep_graph() in detectors/deps.py
Fixer infrastructure is modular but file-mutation focused: Each fixer is a pure function + file I/O wrapper. No undo capability.
File discovery is lightweight: Uses os.walk with in-place pruning. Extension-based, not content-based.
Zone classification is deterministic and early: Applied before any detection, affects scoring and detector policies.
TypeScript plugin is strictly .ts/.tsx: Would need significant refactoring to support .js/.jsx or framework files like .svelte.
Dep graph is built during coupling phase, not at the start. This means earlier phases (logs, unused, exports, deprecated) don't benefit from graph info.
No support for non-TS/TSX currently: The zone system would classify them as PRODUCTION, but they wouldn't be scanned because they're not in the extension list.
Perfect. Now I have all the information needed. Let me compile a comprehensive report.
Comprehensive Analysis Report
Based on my thorough exploration of the desloppify codebase, here's the complete picture of how dependency graphs, cross-file imports, and test coverage detection work:
def _find_external_test_files(path: Path, lang_name: str) -> set[str]:
for test_dir in ("tests", "test"):
d = PROJECT_ROOT / test_dir
if not d.is_dir(): continue
# Skip if test_dir is inside scanned path (already in zone_map)
try:
d.resolve().relative_to(path.resolve())
continue # inside scanned path
except ValueError:
pass # outside scanned path — include it
ext = ".py"
# Walk and collect all .py files
/Users/user_c042661f/Documents/desloppify/desloppify/commands/scan.py — Scan command entry point
This architecture enables cross-file analysis (cycles, orphaned files, test coverage) through a unified graph abstraction while keeping language-specific parsing logic isolated. The test coverage detector is particularly clever — it chains three strategies (import-based, naming, transitive) to maximize coverage detection accuracy.
Perfect! Now I have enough information. Let me create a comprehensive summary report.
Import Parsing: Single regex per line: r"""from\s+['"]([^'"]+)['"]""" (line 22)
Only processes the first match per line
Does NOT support multiple imports per line in a single pass
Does NOT parse destructuring syntax
File Extension Resolution (lines 37-43):
When resolving relative imports like ./utils, the system tries these extensions in order:
python
for ext in ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]:
candidate = Path(str(target) + ext)
if candidate.is_file():
# Found it — adds to graph and breaks
Critical: First match wins. If utils.ts and utils/ both exist, utils.ts is preferred
Returns a set of import specifiers (strings like "./lazy" or "@/config"), NOT resolved file paths. Used by orphaned file detector to check if a zero-importer file is actually dynamically loaded.
Import-Based Test Mapping (detectors/test_coverage.py)
Uses graph to find which test files import which production files:
Parse test file imports
Resolve imports via graph
Walk transitive dependencies (BFS through dep graph)
Mark as "tested" if any test transitively imports it
Quality Metrics:
Assertion density: lines with expect(, assert., .should.
Mock ratio: lines with mock/spy/stub calls
Snapshot ratio: snapshot test usage
This concludes the exploration. The TypeScript dependency system is regex + path-resolution based, with support for relative imports and a hardcoded @/ alias, but lacking dynamic tsconfig parsing and non-TypeScript file support.
I need a concrete implementation plan for fixing GitHub issue #38 in the desloppify codebase — false positives caused by invisible imports from framework files (.svelte, .vue, .astro) and unresolved tsconfig path aliases.
Problem Analysis
There are TWO distinct root causes producing false positives:
Root Cause 1: Framework files (.svelte, .vue, .astro) invisible to import graph
build_dep_graph() in desloppify/lang/typescript/detectors/deps.py only scans .ts/.tsx files via find_ts_files(path)
.svelte files that import { X } from "./foo" create invisible import edges
find_source_files() uses _find_source_files_cached() with LRU cache keyed on (path, extensions, exclusions)
Extension-based filtering via fname.endswith(ext)
Key Insight: NOT new detectors
These should NOT be Svelte-specific detectors. The existing detectors work fine — they just need a more complete picture of what's importing what. The fix belongs at the import graph / reference search layer, and should be framework-agnostic (handle .svelte, .vue, .astro, etc.).
Design Questions to Address
Where to extract imports from framework files: .svelte has <script> blocks, .vue has <script> blocks, .astro has frontmatter fences ---. All use standard ES import syntax inside these blocks.
How to integrate with dep graph: Framework files should contribute import EDGES to the graph (as importers) but shouldn't themselves be analyzed for code smells, complexity, etc. They're "import sources" not "scan targets."
How to handle tsconfig paths: Need to parse tsconfig.json (and handle extends from tsconfig.app.json etc.), extract paths and baseUrl, and use them during import resolution.
Scope of changes:
deps.py: dep graph builder needs to see framework file imports AND resolve tsconfig aliases
exports.py: reference index needs to also search framework files
deps.py: ts_alias_resolver() needs to use tsconfig paths instead of hardcoded @/
Possibly utils.py: a new file finder for framework files, or extend find_source_files
Fixer safety: The original issue mentions the fixer removed live exports causing 247 errors. Should we add a post-check safety net? Or is fixing the detection sufficient?
Please design a concrete, minimal implementation plan that:
Considers edge cases (tsconfig extends, multiple aliases, no tsconfig)
Addresses the fixer safety concern
Here is the complete implementation plan.
Implementation Plan: Fix False Positives from Framework Files and tsconfig Path Aliases (Issue #38)
Problem Summary
Two independent root causes produce false positives in the TypeScript analysis pipeline:
Framework files invisible to import graph: .svelte, .vue, .astro files import from .ts/.tsx files but are never scanned. This makes imported files appear orphaned with dead exports.
tsconfig path aliases unresolved: Only @/ is hardcoded to src/. Projects with @components/*, @utils/*, ~/*, $lib/*, etc. have imports that silently fail to resolve. Files imported only through custom aliases appear orphaned with dead exports.
Architecture Observations
After reading the full codebase, here are the key architectural facts:
Dep graph (deps.py lines 12-56): build_dep_graph() calls find_ts_files(path) which discovers only .ts/.tsx files. It then greps for from\s+['"] and resolves modules. The alias handling is a simple elif module_path.startswith("@/") that maps to SRC_PATH / relative. All downstream consumers -- orphaned, coupling, single_use, cycles, facade, test_coverage -- use this graph.
Dead exports (exports.py lines 21-29): _build_reference_index() independently calls find_ts_files(search_path) and uses grep_files_containing() for word-boundary symbol matching. It does NOT use the dep graph. So even with a perfect dep graph, dead exports will still have false positives unless the reference index also searches framework files.
Dynamic imports (deps.py lines 136-156): build_dynamic_import_targets() calls find_source_files(path, extensions) where extensions come from the caller (in _phase_coupling, line 328: extensions=lang.extensions which is [".ts", ".tsx"]). This also misses framework files.
ts_alias_resolver() (deps.py lines 159-161): Used by orphaned detection for dynamic import matching. Currently returns target.replace("@/", "src/"). This is the only alias resolution outside the dep graph builder.
Move command (_move_ts.py): _compute_ts_specifiers() also hardcodes @/ alias. This is lower priority but should be noted.
Design Decisions
Decision 1: Framework files contribute import edges but are NOT scan targets.
Framework files should appear in the dep graph as importers (they import from .ts/.tsx files) but should NOT themselves be analyzed for code smells, complexity, naming, etc. They are "import sources" not "scan targets." This means:
They get added to the dep graph as nodes with import edges.
They do NOT need to be added to lang.extensions (which would make all detectors scan them).
They need separate discovery and import extraction.
Decision 2: tsconfig parsing is a one-time operation per scan.
Parse tsconfig.json once at the start of build_dep_graph(), extract paths and baseUrl, and pass the resolver down. Cache it on the LangConfig object (like _zone_map and _dep_graph).
Decision 3: Framework-agnostic script block extraction.
All three frameworks (.svelte, .vue, .astro) put JS/TS imports inside delimited blocks:
.svelte: <script>...</script> or <script lang="ts">...</script>
.vue: <script>...</script> or <script setup>...</script>
.astro: ---\n...\n--- (frontmatter fence)
A single regex-based extractor can handle all three by extracting the script region and then applying the same from\s+['"] grep.
Decision 4: No changes to find_ts_files() or find_source_files().
These are performance-sensitive, LRU-cached functions used everywhere. Adding .svelte/.vue/.astro to find_ts_files() would cause all detectors (smells, complexity, etc.) to analyze framework files, producing errors and noise. Instead, we create a separate find_framework_files() function.
Decision 5: Fixer safety via dry-run-first behavior.
The dead exports fixer (fixers/exports.py) uses apply_fixer() with a dry_run flag. Rather than adding a post-check safety net, the correct fix is ensuring the detection is accurate. Once detection no longer flags live exports, the fixer becomes safe. The user already has --dry-run. No additional safety mechanism needed.
Implementation Steps
Step 1: Create desloppify/lang/typescript/detectors/tsconfig.py (NEW FILE)
Purpose: Parse tsconfig.json, resolve extends, extract paths and baseUrl, provide an alias resolver function.
python
"""tsconfig.json paths resolution for import alias mapping."""
import json
from pathlib import Path
from functools import lru_cache
def load_tsconfig_paths(project_root: Path) -> tuple[str, dict[str, list[str]]]:
"""Load paths and baseUrl from tsconfig.json, following extends.
Returns (baseUrl, paths) where:
baseUrl: str like "." or "src" (relative to project_root)
paths: dict like {"@/*": ["src/*"], "@components/*": ["src/components/*"]}
Returns (".", {}) if no tsconfig.json or no paths configured.
"""
...
Key behaviors:
Start from project_root / "tsconfig.json".
If it has "extends", load the parent tsconfig first (handle "./tsconfig.app.json", "./tsconfig.base.json", etc.). Limit depth to 5 to avoid infinite recursion.
Merge compilerOptions.paths from child over parent (child wins).
Extract compilerOptions.baseUrl (defaults to ".").
Use json.loads() with comment stripping (tsconfig supports // comments -- strip them with a simple regex before parsing).
Return (".", {}) on any error (missing file, parse error, etc.) so the system degrades gracefully.
python
def build_alias_resolver(
project_root: Path, base_url: str, paths: dict[str, list[str]]
) -> callable:
"""Build a function that resolves a module specifier to an absolute path.
The resolver tries each matching pattern from paths config.
Returns None if no alias matches, the resolved absolute path if matched.
Handles patterns like:
"@/*" -> ["src/*"] → "@/utils/foo" -> PROJECT_ROOT/src/utils/foo
"@components/*" -> [...] → "@components/Button" -> ...
"~/*" -> ["src/*"] → "~/hooks/useAuth" -> ...
"""
...
Key behaviors:
Pre-compile the patterns: convert "@/*" to prefix "@/" and mapping target "src/".
Sort patterns longest-prefix-first to match the most specific alias.
Resolution: for a module like @components/Button, try each mapping target path with extensions ["", ".ts", ".tsx", "/index.ts", "/index.tsx"].
The base_url_abs = (project_root / base_url).resolve() is the root for resolving mapping targets.
Return None for non-alias imports (relative, bare package names).
This replaces the hardcoded @/ logic in build_dep_graph() and ts_alias_resolver().
Step 2: Create desloppify/lang/typescript/detectors/framework.py (NEW FILE)
Purpose: Discover framework files and extract import specifiers from their script blocks.
python
"""Framework file (.svelte, .vue, .astro) import extraction."""
import re
from pathlib import Path
FRAMEWORK_EXTENSIONS = (".svelte", ".vue", ".astro")
# Script block extraction patterns
_SCRIPT_BLOCK_RE = re.compile(
r"<script[^>]*>(.*?)</script>",
re.DOTALL | re.IGNORECASE,
)
_ASTRO_FRONTMATTER_RE = re.compile(
r"^---\s*\n(.*?)\n---",
re.DOTALL,
)
_IMPORT_RE = re.compile(r"""from\s+['"]([^'"]+)['"]""")
def find_framework_files(path: Path) -> list[str]:
"""Find all .svelte, .vue, .astro files under path."""
from ....utils import find_source_files
return find_source_files(path, list(FRAMEWORK_EXTENSIONS))
def extract_framework_imports(filepath: str) -> list[str]:
"""Extract import module specifiers from a framework file.
Returns list of module specifier strings (e.g., ["./utils", "@/hooks/useAuth", "svelte"]).
"""
...
Key behaviors:
find_framework_files() reuses the existing find_source_files() with different extensions. This automatically gets exclusion handling for free.
extract_framework_imports() reads the file, extracts script blocks based on extension, then applies the same from\s+['"] regex used in build_dep_graph().
For .svelte and .vue: use _SCRIPT_BLOCK_RE to extract <script> block content.
For .astro: use _ASTRO_FRONTMATTER_RE to extract frontmatter between --- fences.
Returns raw module specifiers (resolution is handled by the caller in build_dep_graph()).
3b. Modify build_dep_graph() to use tsconfig alias resolution.
Current code (lines 44-54):
python
elif module_path.startswith("@/"):
relative = module_path[2:]
target = SRC_PATH / relative
for ext in ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]:
...
New code replaces the entire elif module_path.startswith("@/") block with a generic alias resolver call:
python
else:
# Try alias resolution (tsconfig paths, including @/ -> src/)
resolved = alias_resolve(module_path)
if resolved is not None:
graph[source_resolved]["imports"].add(resolved)
graph[resolved]["importers"].add(source_resolved)
Where alias_resolve is the function built by build_alias_resolver() from Step 1.
The full modified build_dep_graph() signature stays the same but internally:
Calls load_tsconfig_paths(PROJECT_ROOT) once at the top.
If no tsconfig paths found, the alias resolver still handles the default @/ -> src/ mapping (built-in fallback).
After processing all .ts/.tsx files, also processes framework files.
3c. Add framework file import scanning after the main TS file loop.
After the existing for filepath, _lineno, content in hits: loop, add:
python
# Also scan framework files for import edges (they import TS files)
from .framework import find_framework_files, extract_framework_imports
fw_files = find_framework_files(path)
for fw_file in fw_files:
fw_resolved = resolve_path(fw_file)
graph[fw_resolved] # ensure node exists
for module_path in extract_framework_imports(fw_file):
# Same resolution logic as above (relative, alias)
resolved_target = _resolve_module(module_path, fw_file, alias_resolve)
if resolved_target:
graph[fw_resolved]["imports"].add(resolved_target)
graph[resolved_target]["importers"].add(fw_resolved)
To avoid duplicating the resolution logic, extract it into a helper _resolve_module(module_path, source_file, alias_resolve) -> str | None:
python
def _resolve_module(module_path: str, source_file: str, alias_resolve) -> str | None:
"""Resolve a module specifier to an absolute file path, or None."""
if module_path.startswith("."):
source_dir = Path(source_file).parent if Path(source_file).is_absolute() else (PROJECT_ROOT / source_file).parent
target = (source_dir / module_path).resolve()
for ext in ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]:
candidate = Path(str(target) + ext)
if candidate.is_file():
return str(candidate)
else:
return alias_resolve(module_path)
return None
3d. Update ts_alias_resolver() to use tsconfig paths.
Currently:
python
def ts_alias_resolver(target: str) -> str:
"""Resolve TS/Vite @/ alias to src/."""
return target.replace("@/", "src/") if target.startswith("@/") else target
Change to use the tsconfig paths. Since this is called from _phase_coupling (line 329) and needs to be fast, load the paths once and cache:
python
_cached_alias_map: dict[str, str] | None = None
def ts_alias_resolver(target: str) -> str:
"""Resolve TS path aliases to src-relative paths for dynamic import matching."""
global _cached_alias_map
if _cached_alias_map is None:
from .tsconfig import load_tsconfig_paths
_, paths = load_tsconfig_paths(PROJECT_ROOT)
_cached_alias_map = {}
for pattern, targets in paths.items():
if pattern.endswith("/*") and targets:
prefix = pattern[:-2]
target_prefix = targets[0][:-2] if targets[0].endswith("/*") else targets[0]
_cached_alias_map[prefix + "/"] = target_prefix + "/"
if "@/" not in _cached_alias_map:
_cached_alias_map["@/"] = "src/" # fallback default
for alias_prefix, target_prefix in sorted(_cached_alias_map.items(), key=lambda x: -len(x[0])):
if target.startswith(alias_prefix):
return target_prefix + target[len(alias_prefix):]
return target
3e. Update build_dynamic_import_targets() to also scan framework files.
Currently (line 140): files = find_source_files(path, extensions)
Add after:
python
from .framework import find_framework_files, extract_framework_imports
# Also check framework files for dynamic/side-effect imports
for fw_file in find_framework_files(path):
for spec in extract_framework_imports(fw_file):
targets.add(spec)
Note: This is a minor addition. Framework files rarely use dynamic imports, but for completeness and to handle import './global.css' side-effect patterns.
4a. Modify _build_reference_index() to also search framework files.
Current code (lines 21-29):
python
def _build_reference_index(search_path: Path, names: set[str]) -> dict[str, set[str]]:
from ....utils import find_ts_files
ts_files = find_ts_files(search_path)
raw = grep_files_containing(names, ts_files, word_boundary=True)
return {name: {resolve_path(f) for f in files} for name, files in raw.items()}
Modified:
python
def _build_reference_index(search_path: Path, names: set[str]) -> dict[str, set[str]]:
from ....utils import find_ts_files
ts_files = find_ts_files(search_path)
# Also search framework files for symbol references
from .framework import find_framework_files
fw_files = find_framework_files(search_path)
all_files = ts_files + fw_files
raw = grep_files_containing(names, all_files, word_boundary=True)
return {name: {resolve_path(f) for f in files} for name, files in raw.items()}
This is a minimal, targeted change. grep_files_containing() already handles arbitrary file lists -- it reads any file and searches for word-boundary matches. The framework files contain <script> blocks with valid JS/TS that includes the symbol names. False positive risk from matching in non-script regions (HTML template) is minimal because we use word-boundary matching and export names tend to be unique identifiers.
In _phase_coupling() (which runs before test_coverage and needs the dep graph), the tsconfig is already loaded by build_dep_graph(). For efficiency, cache the loaded tsconfig on the lang config:
No change needed here. The tsconfig loading happens inside build_dep_graph() and is cached via module-level caching in tsconfig.py.
6b. No changes to zone rules or entry_patterns needed.
Framework files enter the dep graph as importers but are not part of find_ts_files(). Zone classification only runs on files found by lang.file_finder (which is find_ts_files). So framework files won't pollute zone classification, structural analysis, or any other detector.
Step 7: Handle the tsconfig @/ default fallback
If no tsconfig.json exists or it has no paths, the build_alias_resolver() function should include a default mapping of @/* -> src/*. This preserves backward compatibility with the current hardcoded behavior.
python
def build_alias_resolver(project_root, base_url, paths):
# If no paths configured, use sensible defaults
if not paths:
paths = {"@/*": ["src/*"]}
...
Step 8: Reset module-level cache in ts_alias_resolver() on exclusion changes
The _cached_alias_map in ts_alias_resolver() should be reset when set_exclusions() clears caches. Add it to the _find_source_files_cached.cache_clear() call chain, or more simply, make it a function-level variable cleared per scan. Since set_exclusions() is called once at startup, and ts_alias_resolver() is called during the scan, the simplest approach is to not cache globally but compute once per build_dep_graph() call and pass it through.
Better design: remove the module-level _cached_alias_map and instead accept the alias map as a closure:
python
def make_ts_alias_resolver(project_root: Path) -> callable:
"""Build a ts_alias_resolver using tsconfig paths."""
from .tsconfig import load_tsconfig_paths
_, paths = load_tsconfig_paths(project_root)
alias_map = {}
for pattern, targets in paths.items():
if pattern.endswith("/*") and targets:
prefix = pattern[:-2]
target_prefix = targets[0][:-2] if targets[0].endswith("/*") else targets[0]
alias_map[prefix + "/"] = target_prefix + "/"
if "@/" not in alias_map:
alias_map["@/"] = "src/"
sorted_prefixes = sorted(alias_map.items(), key=lambda x: -len(x[0]))
def resolver(target: str) -> str:
for alias_prefix, target_prefix in sorted_prefixes:
if target.startswith(alias_prefix):
return target_prefix + target[len(alias_prefix):]
return target
return resolver
Then in _phase_coupling(), pass the resolver:
python
alias_resolver = make_ts_alias_resolver(PROJECT_ROOT)
# ... pass to detect_orphaned_files
Step 9: Write tests
New test file: tests/test_tsconfig.py
test_load_empty_project -- no tsconfig, returns defaults
test_load_simple_paths -- tsconfig with "@/*": ["src/*"]
Add tests for alias resolution and framework imports
tests/test_ts_exports.py
MODIFY
Add test for svelte/alias references
Edge Cases and Risks
tsconfig with no paths: Fallback to {"@/*": ["src/*"]} preserves existing behavior.
tsconfig extends chain: Limit recursion depth to 5. Handle both relative ("./tsconfig.base.json") and bare ("@tsconfig/svelte") extends. For bare extends (npm packages), skip -- these rarely have paths that matter.
Multiple mapping targets: tsconfig allows "@/*": ["src/*", "lib/*"]. Try each target in order, return the first that resolves to an existing file.
baseUrl interaction: When baseUrl is set, bare imports like components/Button can resolve relative to baseUrl. This is a separate feature from paths -- implement paths resolution first, baseUrl bare-import resolution can be a follow-up if needed.
Framework file false positives in reference index: grep_files_containing() with word-boundary matching on framework files could match symbol names in HTML template text. This is low risk because: (a) export names are typically camelCase or PascalCase identifiers unlikely to appear as English words in templates, and (b) false negatives (missing real references) are far worse than false positives (extra references that prevent flagging).
Performance: find_framework_files() adds one os.walk per path (cached by find_source_files). extract_framework_imports() reads each framework file once. For a project with 100 .svelte files, this adds ~100 file reads. Acceptable -- the TS file scanning already reads thousands of files.
_move_ts.py alias handling: The move command hardcodes @/ -> src/ alias in _compute_ts_specifiers(). This is out of scope for this issue but should be tracked as a follow-up. The move command is rarely used and the alias resolution there is about generating new import specifiers, not detecting false positives.
tsconfig comment stripping: tsconfig.json officially supports // and /* */ comments. A simple regex re.sub(r'//[^\n]*', '', content) and re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL) before json.loads() handles this.
Implementation Order
tsconfig.py (no dependencies, fully self-contained)
framework.py (depends only on utils.find_source_files)
deps.py modifications (depends on 1 and 2)
exports.py modifications (depends on 2)
deprecated.py modifications (depends on 2)
base.py minor field addition (optional, can be deferred)
All tests (in parallel with each step)
This ordering minimizes risk: each step can be tested independently, and the system degrades gracefully at each stage (if tsconfig parsing fails, the @/ default still works; if framework discovery finds no files, the behavior is unchanged).
Dataset releases
Not yet included in a published release.
snapshot_heavy
smoke
adequate
thorough
Fixer safety: No explicit post-check needed. Once detection is accurate, the fix dead-exports fixer only removes the export keyword from truly-dead declarations. The user can verify with --dry-run first. The original 247-error incident was caused by the detector falsely flagging live exports, not a fixer bug.