Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: resolve tsconfig/jsconfig path aliases in dependency graph (#40) (#71)
Raghav Chamadiya57200dfdd4e4
diff --git a/packages/core/src/repowise/core/ingestion/__init__.py b/packages/core/src/repowise/core/ingestion/__init__.pyindex b6d8f716c..bce70f167 100644--- a/packages/core/src/repowise/core/ingestion/__init__.py+++ b/packages/core/src/repowise/core/ingestion/__init__.py@@ -25,6 +25,7 @@ from .models import ()from .parser import LANGUAGE_CONFIGS, ASTParser, LanguageConfig, parse_filefrom .traverser import FileTraverser, TraversalStats+from .tsconfig_resolver import TsconfigResolver__all__ = [# Models@@ -42,6 +43,7 @@ __all__ = ["TraversalStats",# Graph"GraphBuilder",+ "TsconfigResolver","Import","LanguageConfig","PackageInfo",diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.pyindex b0e9baf3d..f86b259a0 100644--- a/packages/core/src/repowise/core/ingestion/graph.py+++ b/packages/core/src/repowise/core/ingestion/graph.py@@ -120,6 +120,11 @@ class GraphBuilder:self._built = Falseself._repo_path: Path | None = Path(repo_path) if repo_path else Noneself._compile_commands_cache: dict[str, dict] | None = None+ self._tsconfig_resolver: Any | None = None # TsconfigResolver (lazy import)++ def set_tsconfig_resolver(self, resolver: Any) -> None:+ """Attach a :class:`TsconfigResolver` for TS/JS path-alias resolution."""+ self._tsconfig_resolver = resolver# ------------------------------------------------------------------# Building@@ -350,7 +355,9 @@ class GraphBuilder:)return self._compile_commands_cache# No valid entries — try next candidate- log.debug("compile_commands.json had no resolvable entries", path=str(candidate))+ log.debug(+ "compile_commands.json had no resolvable entries", path=str(candidate)+ )except Exception as exc:log.debug("Failed to load compile_commands.json", error=str(exc))return None@@ -510,7 +517,18 @@ class GraphBuilder:)if candidate in path_set:return candidate- # External npm package+ return None++ # Non-relative: try tsconfig path-alias resolution first.+ if self._tsconfig_resolver is not None:+ importer_abs = (+ str(self._repo_path / importer_path) if self._repo_path else importer_path+ )+ alias_resolved = self._tsconfig_resolver.resolve(module_path, importer_abs)+ if alias_resolved is not None:+ return alias_resolved++ # Fallback: external npm package.external_key = f"external:{module_path}"if external_key not in self._graph.nodes:self._graph.add_node(diff --git a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.pynew file mode 100644index 000000000..d45c3f002--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py@@ -0,0 +1,423 @@+"""tsconfig.json / jsconfig.json path-alias resolver for the dependency graph.++Discovers all TypeScript/JavaScript compiler configs in a repository, resolves+``extends`` chains (following TypeScript semantics), and provides per-import+alias resolution that ``GraphBuilder._resolve_import()`` calls before falling+back to the ``external:`` classification.++Design constraints:+ - Stateless after ``__init__``: safe to share across all files and threads.+ - One-time I/O at construction time; per-import resolution is O(k) prefix+ matching + set lookup where k is the number of alias patterns.+ - Fully backwards-compatible: if no tsconfig/jsconfig is found in the repo,+ ``resolve()`` always returns ``None`` and behaviour is identical to before.+ - Pattern matching follows TypeScript's exact semantics:+ 1. Exact matches before wildcard matches.+ 2. Wildcard matches sorted by prefix length descending (most specific wins).+ 3. Candidates tried left-to-right; first hit wins.+ 4. ``baseUrl``-only fallback when no ``paths`` entry matches.+"""++from __future__ import annotations++import json+import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import structlog++log = structlog.get_logger(__name__)++# Extensions probed in TypeScript module resolution order.+_TS_EXTENSIONS = (".ts", ".tsx", ".js", ".jsx")+_INDEX_FILES = ("index.ts", "index.tsx", "index.js", "index.jsx")+++# ---------------------------------------------------------------------------+# Data model+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class ResolvedConfig:+ """Fully-resolved compiler options for one tsconfig/jsconfig file.++ All paths stored as absolute :class:`Path` objects; conversion to+ repo-relative POSIX strings happens at resolution time when the+ ``path_set`` is available.+ """++ config_path: Path+ base_url: Path | None+ path_entries: list[tuple[str, list[str]]] = field(default_factory=list)+ """Ordered ``(alias_pattern, [abs_path_template, ...])`` pairs.++ Exact patterns (no ``*``) come first, then wildcard patterns sorted+ by prefix length descending so the most specific match wins.+ """+++# ---------------------------------------------------------------------------+# Resolver+# ---------------------------------------------------------------------------+++class TsconfigResolver:+ """Discovers and caches tsconfig/jsconfig alias configurations.++ Instantiate once per ``GraphBuilder.build()`` invocation, passing the+ complete ``path_set`` so that extension probing can check membership.++ Args:+ repo_path: Absolute path to the repository root.+ path_set: Set of POSIX-relative file paths known to the graph builder.+ """++ def __init__(self, repo_path: Path, path_set: set[str]) -> None:+ self._repo_path = repo_path.resolve()+ self._path_set = path_set++ # directory (absolute) -> ResolvedConfig+ self._dir_to_config: dict[Path, ResolvedConfig] = {}++ # source-file directory -> applicable ResolvedConfig (or None)+ self._file_config_cache: dict[Path, ResolvedConfig | None] = {}++ self._discover_configs()+ log.info(+ "tsconfig_resolver_ready",+ configs=len(self._dir_to_config),+ )++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ def resolve(+ self,+ module_path: str,+ importer_abs_path: str,+ ) -> str | None:+ """Attempt to resolve a non-relative TS/JS import via path aliases.++ Returns a POSIX-relative-to-repo-root path if resolved, else ``None``.++ Algorithm:+ 1. Find applicable config by walking up from the importer's directory.+ 2. Try alias patterns (exact first, then wildcards by specificity).+ 3. For each match try candidate templates left-to-right.+ 4. For each template try file extensions + index files.+ 5. If no alias matched but ``baseUrl`` is set, try ``baseUrl + specifier``.+ 6. Return the first hit found in ``path_set``, or ``None``.+ """+ config = self._find_config_for_file(Path(importer_abs_path))+ if config is None:+ return None++ # Step 1: try path alias entries.+ for alias_pattern, candidate_templates in config.path_entries:+ captured = self._match_alias(alias_pattern, module_path)+ if captured is None:+ continue+ for template in candidate_templates:+ resolved = self._apply_template(template, captured)+ if resolved is not None:+ return resolved++ # Step 2: baseUrl-only fallback.+ if config.base_url is not None:+ resolved = self._try_extensions(config.base_url / module_path)+ if resolved is not None:+ return resolved++ return None++ # ------------------------------------------------------------------+ # Config discovery+ # ------------------------------------------------------------------++ def _discover_configs(self) -> None:+ """Find all tsconfig/jsconfig files, parse and resolve ``extends``."""+ # Group candidates by directory, assign priority (lower = higher).+ dir_candidates: dict[Path, list[tuple[int, Path]]] = {}++ for config_file in self._repo_path.rglob("*.json"):+ if "node_modules" in config_file.parts:+ continue+ name = config_file.name+ if name == "tsconfig.json":+ priority = 0+ elif name.startswith("tsconfig") and name.endswith(".json"):+ priority = 1+ elif name == "jsconfig.json":+ priority = 2+ else:+ continue+ directory = config_file.parent.resolve()+ dir_candidates.setdefault(directory, []).append((priority, config_file))++ for directory, candidates in dir_candidates.items():+ candidates.sort(key=lambda x: x[0])+ _, config_file = candidates[0]+ resolved = self._load_and_resolve(config_file.resolve(), visited=frozenset())+ if resolved is not None:+ self._dir_to_config[directory] = resolved++ # ------------------------------------------------------------------+ # Config loading & extends resolution+ # ------------------------------------------------------------------++ def _load_and_resolve(+ self,+ config_path: Path,+ visited: frozenset[Path],+ ) -> ResolvedConfig | None:+ """Load one config, follow ``extends``, return :class:`ResolvedConfig`.++ TypeScript semantics:+ - Child ``paths`` completely overrides parent (no merge).+ - Child ``baseUrl`` overrides parent.+ - ``baseUrl`` is resolved relative to the config that defines it.+ """+ config_path = config_path.resolve()+ if config_path in visited:+ log.warning("circular_tsconfig_extends", path=str(config_path))+ return None+ visited = visited | {config_path}++ data = self._parse_json_lenient(config_path)+ if data is None:+ return None++ config_dir = config_path.parent+ compiler_options = data.get("compilerOptions", {})+ if not isinstance(compiler_options, dict):+ compiler_options = {}++ # Resolve parent first.+ parent: ResolvedConfig | None = None+ extends_val = data.get("extends")+ if isinstance(extends_val, str):+ parent = self._resolve_extends(extends_val, config_dir, visited)++ # Own baseUrl.+ own_base_url_str: str | None = compiler_options.get("baseUrl")+ if own_base_url_str is not None:+ effective_base_url: Path | None = (config_dir / own_base_url_str).resolve()+ elif parent is not None:+ effective_base_url = parent.base_url+ else:+ effective_base_url = None++ # Own paths (child completely overrides parent per TS spec).+ own_paths = compiler_options.get("paths")+ if own_paths is not None and isinstance(own_paths, dict):+ path_entries = self._build_path_entries(own_paths, effective_base_url, config_dir)+ elif parent is not None and parent.path_entries:+ path_entries = parent.path_entries+ else:+ path_entries = []++ return ResolvedConfig(+ config_path=config_path,+ base_url=effective_base_url,+ path_entries=path_entries,+ )++ def _resolve_extends(+ self,+ extends_val: str,+ config_dir: Path,+ visited: frozenset[Path],+ ) -> ResolvedConfig | None:+ """Resolve an ``extends`` value to a :class:`ResolvedConfig`.++ Handles relative paths, bare node_modules specifiers, and+ scoped packages.+ """+ if extends_val.startswith("."):+ candidate = (config_dir / extends_val).resolve()+ if not candidate.suffix:+ candidate = candidate.with_suffix(".json")+ if candidate.exists():+ return self._load_and_resolve(candidate, visited)+ return None++ # Bare package / scoped package: look in node_modules.+ for search_dir in (config_dir, self._repo_path):+ node_modules = search_dir / "node_modules"+ if not node_modules.exists():+ continue+ candidate = node_modules / extends_val+ if not candidate.suffix:+ if candidate.is_dir():+ # Check package.json for a tsconfig pointer.+ pkg_json = candidate / "package.json"+ if pkg_json.exists():+ try:+ pkg_data = json.loads(+ pkg_json.read_text(encoding="utf-8", errors="ignore")+ )+ tsconfig_field = pkg_data.get("tsconfig")+ if isinstance(tsconfig_field, str):+ candidate = (candidate / tsconfig_field).resolve()+ else:+ candidate = candidate / "tsconfig.json"+ except Exception:+ candidate = candidate / "tsconfig.json"+ else:+ candidate = candidate / "tsconfig.json"+ else:+ candidate = candidate.with_suffix(".json")+ candidate = candidate.resolve()+ if candidate.exists():+ return self._load_and_resolve(candidate, visited)++ log.debug(+ "tsconfig_extends_not_found",+ extends=extends_val,+ from_dir=str(config_dir),+ )+ return None++ # ------------------------------------------------------------------+ # Path entry building+ # ------------------------------------------------------------------++ def _build_path_entries(+ self,+ paths: dict[str, Any],+ base_url: Path | None,+ config_dir: Path,+ ) -> list[tuple[str, list[str]]]:+ """Convert ``compilerOptions.paths`` to sorted alias entries.++ Ordering:+ 1. Exact patterns (no ``*``) first.+ 2. Wildcard patterns sorted by prefix length descending.+ """+ exact: list[tuple[str, list[str]]] = []+ wildcard: list[tuple[str, list[str]]] = []++ resolution_base = base_url if base_url else config_dir++ for alias_pattern, candidates in paths.items():+ if not isinstance(candidates, list):+ continue+ abs_templates: list[str] = []+ for candidate in candidates:+ if not isinstance(candidate, str):+ continue+ abs_templates.append(str((resolution_base / candidate).resolve()))+ if not abs_templates:+ continue++ if "*" in alias_pattern:+ wildcard.append((alias_pattern, abs_templates))+ else:+ exact.append((alias_pattern, abs_templates))++ # Most-specific wildcard first (longest prefix before *).+ wildcard.sort(key=lambda e: len(e[0].split("*")[0]), reverse=True)+ return exact + wildcard++ # ------------------------------------------------------------------+ # Per-file config lookup (walk-up with cache)+ # ------------------------------------------------------------------++ def _find_config_for_file(self, source_file: Path) -> ResolvedConfig | None:+ """Find the nearest tsconfig for a source file by walking up."""+ directory = source_file.parent.resolve()++ if directory in self._file_config_cache:+ return self._file_config_cache[directory]++ current = directory+ while True:+ if current in self._dir_to_config:+ self._file_config_cache[directory] = self._dir_to_config[current]+ return self._dir_to_config[current]+ parent = current.parent+ if parent == current or not current.is_relative_to(self._repo_path):+ break+ current = parent++ self._file_config_cache[directory] = None+ return None++ # ------------------------------------------------------------------+ # Pattern matching helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _match_alias(alias_pattern: str, module_path: str) -> str | None:+ """Return captured wildcard text if *alias_pattern* matches, else ``None``.++ For exact patterns (no ``*``): returns ``""`` on match.+ For wildcard patterns: returns the text that ``*`` matched.+ """+ if "*" not in alias_pattern:+ return "" if module_path == alias_pattern else None+ prefix, suffix = alias_pattern.split("*", 1)+ if not module_path.startswith(prefix):+ return None+ remainder = module_path[len(prefix) :]+ if suffix and not remainder.endswith(suffix):+ return None+ if suffix:+ return remainder[: len(remainder) - len(suffix)]+ return remainder++ def _apply_template(self, template: str, captured: str) -> str | None:+ """Substitute *captured* into a candidate template and probe extensions."""+ concrete = template.replace("*", captured, 1) if "*" in template else template+ return self._try_extensions(Path(concrete))++ def _try_extensions(self, base: Path) -> str | None:+ """Try common TS/JS extensions and index files, return first ``path_set`` hit."""+ # 1. As-is (if template already has extension).+ rel = self._to_repo_relative(base)+ if rel is not None and rel in self._path_set:+ return rel++ # 2. Direct extensions.+ for ext in _TS_EXTENSIONS:+ rel = self._to_repo_relative(base.with_suffix(ext))+ if rel is not None and rel in self._path_set:+ return rel++ # 3. Index files (base is a directory).+ for index in _INDEX_FILES:+ rel = self._to_repo_relative(base / index)+ if rel is not None and rel in self._path_set:+ return rel++ return None++ def _to_repo_relative(self, path: Path) -> str | None:+ """Convert *path* to a repo-relative POSIX string, or ``None``."""+ try:+ return path.resolve().relative_to(self._repo_path).as_posix()+ except ValueError:+ return None++ # ------------------------------------------------------------------+ # JSON parsing+ # ------------------------------------------------------------------++ @staticmethod+ def _parse_json_lenient(config_path: Path) -> dict[str, Any] | None:+ """Parse JSON with trailing-comma tolerance (common in tsconfig)."""+ try:+ text = config_path.read_text(encoding="utf-8", errors="ignore")+ try:+ data = json.loads(text)+ except json.JSONDecodeError:+ cleaned = re.sub(r",\s*([}\]])", r"\1", text)+ data = json.loads(cleaned)+ return data if isinstance(data, dict) else None+ except Exception as exc:+ log.debug("tsconfig_parse_failed", path=str(config_path), error=str(exc))+ return Nonediff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 084ed8386..1765ba53f 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -469,6 +469,18 @@ async def _run_ingestion(if _use_process_pool and progress:progress.on_item_done("parse")+ # ---- tsconfig path-alias resolver (before graph build) ------------------+ try:+ from repowise.core.ingestion.tsconfig_resolver import TsconfigResolver++ _ts_langs = {"typescript", "javascript"}+ if any(pf.file_info.language in _ts_langs for pf in parsed_files):+ _path_set = set(graph_builder._parsed_files.keys())+ _resolver = TsconfigResolver(repo_path=repo_path, path_set=_path_set)+ graph_builder.set_tsconfig_resolver(_resolver)+ except Exception as _resolver_exc:+ logger.warning("tsconfig_resolver_init_failed", error=str(_resolver_exc))+# ---- Graph build phase -------------------------------------------------if progress:progress.on_phase_start("graph", 1)diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.pyindex 702f62785..985bb4cc3 100644--- a/tests/unit/ingestion/test_graph.py+++ b/tests/unit/ingestion/test_graph.py@@ -206,9 +206,7 @@ class TestStemDisambiguation:b.build()g = b.graph()assert g.has_edge("src/flask/app.py", "src/flask/__init__.py")- assert not g.has_edge(- "src/flask/app.py", "tests/test_apps/cliapp/inner1/inner2/flask.py"- )+ assert not g.has_edge("src/flask/app.py", "tests/test_apps/cliapp/inner1/inner2/flask.py")def test_test_fixture_loses_to_source_file(self) -> None:"""When two files share a stem and one is under tests/, the@@ -327,6 +325,93 @@ class TestTypeScriptImports:external_node = next(n for n in g.nodes if n.startswith("external:"))assert g.has_edge("src/app.ts", external_node)+ def test_tsconfig_alias_resolves_to_file(self, tmp_path: Path) -> None:+ """Non-relative import resolved via TsconfigResolver instead of external:."""+ import json++ from repowise.core.ingestion.tsconfig_resolver import TsconfigResolver++ # Write a tsconfig with @/* -> ./src/*+ tsconfig = tmp_path / "tsconfig.json"+ tsconfig.write_text(+ json.dumps(+ {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ )+ )++ b = GraphBuilder(repo_path=tmp_path)+ b.add_file(_parsed("src/utils.ts", language="typescript"))+ b.add_file(+ _parsed(+ "src/app.ts",+ language="typescript",+ imports=[_imp("@/utils")],+ )+ )+ # Attach resolver before build.+ path_set = set(b._parsed_files.keys())+ resolver = TsconfigResolver(repo_path=tmp_path, path_set=path_set)+ b.set_tsconfig_resolver(resolver)+ b.build()++ g = b.graph()+ assert g.has_edge("src/app.ts", "src/utils.ts")+ assert not any(n.startswith("external:@/") for n in g.nodes)++ def test_tsconfig_alias_fallback_to_external(self, tmp_path: Path) -> None:+ """Unmatched alias still creates external: node."""+ import json++ from repowise.core.ingestion.tsconfig_resolver import TsconfigResolver++ tsconfig = tmp_path / "tsconfig.json"+ tsconfig.write_text(+ json.dumps(+ {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ )+ )++ b = GraphBuilder(repo_path=tmp_path)+ b.add_file(+ _parsed(+ "src/app.ts",+ language="typescript",+ imports=[_imp("react")],+ )+ )+ path_set = set(b._parsed_files.keys())+ resolver = TsconfigResolver(repo_path=tmp_path, path_set=path_set)+ b.set_tsconfig_resolver(resolver)+ b.build()++ g = b.graph()+ assert g.has_edge("src/app.ts", "external:react")++ def test_no_resolver_backwards_compatible(self) -> None:+ """GraphBuilder without resolver behaves identically to before."""+ b = GraphBuilder()+ b.add_file(+ _parsed(+ "src/app.ts",+ language="typescript",+ imports=[_imp("@/utils")],+ )+ )+ b.build()+ g = b.graph()+ # Without resolver, @/utils becomes external:@/utils.+ assert g.has_edge("src/app.ts", "external:@/utils")+# ---------------------------------------------------------------------------# Go import resolution@@ -552,6 +637,7 @@ class TestCppCompileCommandsResolution:}]import json+(tmp_path / "compile_commands.json").write_text(json.dumps(compile_commands))(tmp_path / "src").mkdir()@@ -574,6 +660,7 @@ class TestCppCompileCommandsResolution:}]import json+(tmp_path / "compile_commands.json").write_text(json.dumps(compile_commands))(tmp_path / "src").mkdir()@@ -624,6 +711,7 @@ class TestCppCompileCommandsResolution:}]import json+(build_dir / "compile_commands.json").write_text(json.dumps(compile_commands))(tmp_path / "src").mkdir()diff --git a/tests/unit/ingestion/test_tsconfig_resolver.py b/tests/unit/ingestion/test_tsconfig_resolver.pynew file mode 100644index 000000000..39faa9096--- /dev/null+++ b/tests/unit/ingestion/test_tsconfig_resolver.py@@ -0,0 +1,512 @@+"""Tests for TsconfigResolver — path alias resolution for TS/JS imports."""++from __future__ import annotations++import json+from pathlib import Path++from repowise.core.ingestion.tsconfig_resolver import TsconfigResolver++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _write_json(path: Path, data: dict) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data), encoding="utf-8")+++def _make_resolver(+ tmp_path: Path,+ configs: dict[str, dict],+ path_set: set[str],+) -> TsconfigResolver:+ """Write tsconfig JSON files and return a resolver for the tmp dir."""+ for rel_path, data in configs.items():+ _write_json(tmp_path / rel_path, data)+ return TsconfigResolver(repo_path=tmp_path, path_set=path_set)+++def _importer(tmp_path: Path, rel: str) -> str:+ """Return absolute path string for a repo-relative importer."""+ return str(tmp_path / rel)+++# ---------------------------------------------------------------------------+# Next.js @/* alias+# ---------------------------------------------------------------------------+++class TestBasicAliasResolution:+ def test_nextjs_at_alias(self, tmp_path: Path) -> None:+ """@/* maps to src/* — Next.js default."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set={"src/components/Button.tsx", "src/utils/format.ts"},+ )+ result = resolver.resolve("@/components/Button", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/components/Button.tsx"++ result = resolver.resolve("@/utils/format", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils/format.ts"++ def test_baseurl_without_paths(self, tmp_path: Path) -> None:+ """baseUrl: 'src' resolves bare imports like 'utils/format'."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {"baseUrl": "src"},+ }+ },+ path_set={"src/utils/format.ts", "src/services/api.ts"},+ )+ result = resolver.resolve("utils/format", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils/format.ts"++ result = resolver.resolve("services/api", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/services/api.ts"++ def test_exact_non_wildcard_mapping(self, tmp_path: Path) -> None:+ """paths: {'utils': ['./src/utils/index.ts']} — exact key, no wildcard."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"utils": ["./src/utils/index.ts"]},+ }+ }+ },+ path_set={"src/utils/index.ts"},+ )+ result = resolver.resolve("utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils/index.ts"+++# ---------------------------------------------------------------------------+# Directory index resolution+# ---------------------------------------------------------------------------+++class TestIndexResolution:+ def test_alias_resolves_to_directory_index(self, tmp_path: Path) -> None:+ """@/Button resolves to src/Button/index.ts when src/Button.ts doesn't exist."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set={"src/Button/index.ts"},+ )+ result = resolver.resolve("@/Button", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/Button/index.ts"++ def test_alias_resolves_to_directory_index_tsx(self, tmp_path: Path) -> None:+ """Tries index.tsx when index.ts isn't in path_set."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set={"src/Button/index.tsx"},+ )+ result = resolver.resolve("@/Button", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/Button/index.tsx"+++# ---------------------------------------------------------------------------+# Pattern specificity+# ---------------------------------------------------------------------------+++class TestPatternSpecificity:+ def test_specific_pattern_wins_over_broad(self, tmp_path: Path) -> None:+ """@components/* is tried before @/* for '@components/Button'."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {+ "@/*": ["./src/*"],+ "@components/*": ["./src/ui/components/*"],+ },+ }+ }+ },+ path_set={+ "src/ui/components/Button.tsx",+ "src/components/Button.tsx",+ },+ )+ result = resolver.resolve("@components/Button", _importer(tmp_path, "src/app.tsx"))+ # Should match @components/* (more specific) -> src/ui/components/*+ assert result == "src/ui/components/Button.tsx"+++# ---------------------------------------------------------------------------+# Multiple candidates+# ---------------------------------------------------------------------------+++class TestMultipleCandidates:+ def test_first_matching_candidate_wins(self, tmp_path: Path) -> None:+ """['./src/*', './lib/*'] — first candidate that resolves wins."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*", "./lib/*"]},+ }+ }+ },+ path_set={"src/utils.ts", "lib/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts" # src/* tried first++ def test_second_candidate_when_first_missing(self, tmp_path: Path) -> None:+ """Falls to second candidate when first doesn't exist in path_set."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*", "./lib/*"]},+ }+ }+ },+ path_set={"lib/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "lib/utils.ts"+++# ---------------------------------------------------------------------------+# jsconfig.json support+# ---------------------------------------------------------------------------+++class TestJsconfig:+ def test_jsconfig_fallback(self, tmp_path: Path) -> None:+ """jsconfig.json used when no tsconfig.json present."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "jsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set={"src/utils.js"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.js"))+ assert result == "src/utils.js"++ def test_tsconfig_wins_over_jsconfig(self, tmp_path: Path) -> None:+ """Both in same dir -> tsconfig takes precedence."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ },+ "jsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./other/*"]},+ }+ },+ },+ path_set={"src/utils.ts", "other/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts" # tsconfig's mapping, not jsconfig's+++# ---------------------------------------------------------------------------+# Extends chains+# ---------------------------------------------------------------------------+++class TestExtendsChain:+ def test_child_paths_override_parent(self, tmp_path: Path) -> None:+ """Child has own paths -> parent paths ignored entirely."""+ _write_json(+ tmp_path / "tsconfig.base.json",+ {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./parent-src/*"]},+ }+ },+ )+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "extends": "./tsconfig.base.json",+ "compilerOptions": {+ "paths": {"@/*": ["./src/*"]},+ },+ }+ },+ path_set={"src/utils.ts", "parent-src/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts"++ def test_child_inherits_parent_paths(self, tmp_path: Path) -> None:+ """Child has no paths -> parent's paths are used."""+ _write_json(+ tmp_path / "tsconfig.base.json",+ {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ },+ )+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "extends": "./tsconfig.base.json",+ "compilerOptions": {"strict": True},+ }+ },+ path_set={"src/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts"++ def test_extends_chain_two_levels(self, tmp_path: Path) -> None:+ """Grandparent baseUrl inherited through two-level chain."""+ _write_json(+ tmp_path / "tsconfig.grandparent.json",+ {"compilerOptions": {"baseUrl": "src"}},+ )+ _write_json(+ tmp_path / "tsconfig.parent.json",+ {+ "extends": "./tsconfig.grandparent.json",+ "compilerOptions": {+ "paths": {"@/*": ["./*"]},+ },+ },+ )+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "extends": "./tsconfig.parent.json",+ "compilerOptions": {"strict": True},+ }+ },+ path_set={"src/utils.ts"},+ )+ # Inherits paths from parent and baseUrl from grandparent.+ # paths @/* -> [./*] resolved against baseUrl "src" -> src/*+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts"++ def test_extends_from_node_modules(self, tmp_path: Path) -> None:+ """extends: '@tsconfig/next' resolved from node_modules.++ The parent config in node_modules sets strict options; the child+ project config adds its own baseUrl + paths relative to the project.+ """+ nm_pkg = tmp_path / "node_modules" / "@tsconfig" / "next"+ nm_pkg.mkdir(parents=True)+ _write_json(+ nm_pkg / "tsconfig.json",+ {+ "compilerOptions": {+ "strict": True,+ "esModuleInterop": True,+ }+ },+ )+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "extends": "@tsconfig/next",+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ },+ }+ },+ path_set={"src/utils.ts"},+ )+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts"++ def test_circular_extends(self, tmp_path: Path) -> None:+ """Circular extends chain logs warning, no crash, returns None."""+ _write_json(+ tmp_path / "a.json",+ {"extends": "./b.json", "compilerOptions": {}},+ )+ _write_json(+ tmp_path / "b.json",+ {"extends": "./a.json", "compilerOptions": {}},+ )+ # Should not hang or crash.+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "extends": "./a.json",+ "compilerOptions": {+ "paths": {"@/*": ["./src/*"]},+ },+ }+ },+ path_set={"src/utils.ts"},+ )+ # Still resolves because tsconfig.json itself has paths.+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result == "src/utils.ts"+++# ---------------------------------------------------------------------------+# Monorepo+# ---------------------------------------------------------------------------+++class TestMonorepo:+ def test_per_package_tsconfig(self, tmp_path: Path) -> None:+ """Files in packages/web use web's tsconfig; packages/api use api's."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "packages/web/tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ },+ "packages/api/tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./lib/*"]},+ }+ },+ },+ path_set={+ "packages/web/src/Button.tsx",+ "packages/api/lib/handler.ts",+ },+ )+ # Web file resolves via web tsconfig.+ result = resolver.resolve("@/Button", _importer(tmp_path, "packages/web/src/app.tsx"))+ assert result == "packages/web/src/Button.tsx"++ # API file resolves via api tsconfig.+ result = resolver.resolve("@/handler", _importer(tmp_path, "packages/api/lib/index.ts"))+ assert result == "packages/api/lib/handler.ts"+++# ---------------------------------------------------------------------------+# Fallback / backwards compat+# ---------------------------------------------------------------------------+++class TestFallback:+ def test_no_tsconfig_at_all(self, tmp_path: Path) -> None:+ """Empty repo -> resolve() always returns None."""+ resolver = TsconfigResolver(repo_path=tmp_path, path_set={"src/utils.ts"})+ result = resolver.resolve("@/utils", _importer(tmp_path, "src/app.tsx"))+ assert result is None++ def test_no_match_returns_none(self, tmp_path: Path) -> None:+ """Unmatched alias -> None (caller creates external: node)."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set={"src/utils.ts"},+ )+ # "react" doesn't match any alias pattern and baseUrl won't find it.+ result = resolver.resolve("react", _importer(tmp_path, "src/app.tsx"))+ assert result is None++ def test_alias_candidate_missing_returns_none(self, tmp_path: Path) -> None:+ """Alias matches but resolved file not in path_set -> None."""+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./src/*"]},+ }+ }+ },+ path_set=set(), # empty path_set+ )+ result = resolver.resolve("@/nonexistent", _importer(tmp_path, "src/app.tsx"))+ assert result is None+++# ---------------------------------------------------------------------------+# _match_alias unit tests+# ---------------------------------------------------------------------------+++class TestMatchAlias:+ def test_exact_match(self) -> None:+ assert TsconfigResolver._match_alias("utils", "utils") == ""++ def test_exact_no_match(self) -> None:+ assert TsconfigResolver._match_alias("utils", "lodash") is None++ def test_wildcard_match(self) -> None:+ assert TsconfigResolver._match_alias("@/*", "@/components/Button") == "components/Button"++ def test_wildcard_no_match(self) -> None:+ assert TsconfigResolver._match_alias("@components/*", "@/Button") is None++ def test_wildcard_with_suffix(self) -> None:+ assert TsconfigResolver._match_alias("@/*.js", "@/utils.js") == "utils"++ def test_wildcard_empty_capture(self) -> None:+ assert TsconfigResolver._match_alias("@/*", "@/") == ""