Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(ingestion): capture TS/JS re-export barrels so forwarded symbols aren't dead (#245)

Raghav Chamadiya6506dfdf267f
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 43145c4b7..801fd9155 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -36,7 +36,7 @@ call resolution, named bindings, heritage extraction, and docstrings.
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
| **Python** | `.py` `.pyi` | `main.py` `app.py` `__main__.py` `manage.py` `wsgi.py` `asgi.py` | `import x` / `from x import y` |
-| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |
+| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `export { x } from 'y'` & `export * from 'y'` re-export barrels / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |
| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` |
| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` |
| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match) |
@@ -146,7 +146,8 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
Python: dotted module paths via a source-root-aware module index
(src/ + monorepo packages/*/src + PEP 420 namespace
packages), __init__.py re-export barrels, stem fallback
- TS/JS: relative paths, tsconfig aliases, node_modules
+ TS/JS: relative paths, tsconfig aliases, workspace exports,
+ `export ... from` re-export barrels, node_modules
Go: go.mod module path stripping
Rust: crate::/self::/super::, mod.rs probing
C/C++: compile_commands.json include directories
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index c1f0b0717..9128b37a9 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -149,6 +149,24 @@ from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
logger = structlog.get_logger(__name__)
+# Re-export barrel filenames. Skipped in the *unreachable-file* pass only:
+# a barrel aggregates other modules' symbols and is reached by importing
+# those names (or, for a package's public entry, via package.json
+# ``exports``/``main``), so a barrel with no inbound graph edge is not dead.
+# They are NOT skipped in the unused-export pass — a genuine symbol defined
+# in a barrel that nobody imports should still be flagged.
+_BARREL_FILENAMES: frozenset[str] = frozenset({
+ "__init__.py",
+ "index.ts",
+ "index.tsx",
+ "index.js",
+ "index.jsx",
+ "index.mts",
+ "index.cts",
+ "index.mjs",
+ "index.cjs",
+})
+
def _is_synthetic_node(node: str) -> bool:
"""True for non-file graph nodes that should be skipped in 'is this dead?' passes.
@@ -316,6 +334,11 @@ class DeadCodeAnalyzer:
continue
if self._should_never_flag(str(node), whitelist):
continue
+ # Re-export barrels (index.* / __init__.py) are reached by the
+ # names they forward or via package ``exports``/``main`` — a barrel
+ # with no inbound graph edge is not dead code.
+ if Path(str(node)).name in _BARREL_FILENAMES:
+ continue
if self._is_api_contract(node_data):
continue
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
index 20e73d0f5..2a19ebf66 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
@@ -9,11 +9,49 @@ from ..helpers import node_text
def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from TypeScript/JavaScript import statements."""
+ """Extract bindings from TypeScript/JavaScript import and re-export statements.
+
+ Handles both ``import ... from`` and barrel ``export ... from`` (re-export)
+ statements — the query tags re-exports carrying a ``source`` as
+ ``@import.statement`` so they flow through the same pipeline. For a
+ re-export, ``imported_names`` carries the name as it exists in the *source*
+ module (``export { A as B } from`` records ``A``), so the dead-code
+ analyzer can match it to the re-exported symbol and an ``index.ts`` barrel
+ no longer hides every component it forwards.
+ """
names: list[str] = []
bindings: list[NamedBinding] = []
+ is_reexport = stmt_node.type == "export_statement"
+
for child in stmt_node.children:
+ # --- Re-export (barrel) clauses: ``export { X } from`` / ``export *`` ---
+ if is_reexport:
+ if child.type == "export_clause":
+ for spec in child.children:
+ if spec.type != "export_specifier":
+ continue
+ name_node = spec.child_by_field_name("name") or (
+ spec.children[0] if spec.children else None
+ )
+ alias_node = spec.child_by_field_name("alias")
+ if name_node:
+ exported = node_text(name_node, src)
+ local = node_text(alias_node, src) if alias_node else exported
+ names.append(exported)
+ bindings.append(
+ NamedBinding(
+ local_name=local, exported_name=exported, source_file=None
+ )
+ )
+ elif child.type == "namespace_export":
+ # ``export * as ns from "x"`` — forwards the whole module.
+ names.append("*")
+ bindings.append(
+ NamedBinding(local_name="*", exported_name=None, source_file=None)
+ )
+ continue
+
if child.type != "import_clause":
continue
for sub in child.children:
@@ -61,4 +99,11 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[N
NamedBinding(local_name="*", exported_name=None, source_file=None)
)
+ # ``export * from "x"`` carries neither an export_clause nor a
+ # namespace_export — just the source. Treat it as a wildcard so every
+ # symbol the barrel forwards is reachable.
+ if is_reexport and not names:
+ names.append("*")
+ bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
+
return names, bindings
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
index b8916e8c9..6c8695b15 100644
--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
@@ -77,6 +77,18 @@
source: (string) @import.module
) @import.statement
+; Re-export (barrel) statements — only those with a `source` are imports of
+; another module's symbols. Captured as @import.statement so the existing
+; import pipeline resolves the edge and carries the re-exported names:
+; export { A, B } from "./module"
+; export { A as B } from "./module"
+; export * from "./module"
+; export * as ns from "./module"
+; export type { T } from "./types"
+(export_statement
+ source: (string) @import.module
+) @import.statement
+
; ---------------------------------------------------------------------------
; Calls
; ---------------------------------------------------------------------------
diff --git a/tests/unit/ingestion/test_ts_reexport_dead_code.py b/tests/unit/ingestion/test_ts_reexport_dead_code.py
new file mode 100644
index 000000000..bcac04b2a
--- /dev/null
+++ b/tests/unit/ingestion/test_ts_reexport_dead_code.py
@@ -0,0 +1,120 @@
+"""Regression tests: TS/JS barrel re-exports keep forwarded symbols live.
+
+A symbol reached only through an ``index.ts`` re-export chain (the standard
+component-library barrel pattern) used to be flagged as an unused export
+because ``export { X } from "./x"`` / ``export * from "./y"`` produced no
+graph edge — only ``import ... from`` was captured. These tests drive the
+real parser → GraphBuilder → DeadCodeAnalyzer over a barrel chain and assert
+the forwarded symbol is no longer flagged.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _file_info(path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="typescript",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _graph_from_sources(sources: dict[str, str]) -> nx.DiGraph:
+ builder = GraphBuilder()
+ for path, src in sources.items():
+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))
+ builder.add_file(parsed)
+ return builder.build()
+
+
+def _unused_export_names(graph: nx.DiGraph) -> set[str]:
+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ return {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+
+
+def _unreachable_paths(graph: nx.DiGraph) -> set[str]:
+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+ return {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+
+
+def _imported_names(src: str) -> list[str]:
+ """Parse a single-statement TS source and return the edge's imported names."""
+ parsed = _PARSER.parse_file(_file_info("pkg/m.ts"), src.encode("utf-8"))
+ assert parsed.imports, f"no import/re-export captured for: {src!r}"
+ return parsed.imports[0].imported_names
+
+
+# ---------------------------------------------------------------------------
+# Binding extraction — re-export statements
+# ---------------------------------------------------------------------------
+
+
+class TestReExportBindings:
+ def test_named_reexport_records_source_name(self) -> None:
+ assert _imported_names('export { SearchBar } from "./SearchBar";') == ["SearchBar"]
+
+ def test_aliased_reexport_records_source_name(self) -> None:
+ # `A as B` re-exports the source module's `A`; reachability is about A.
+ assert _imported_names('export { A as B } from "./m";') == ["A"]
+
+ def test_wildcard_reexport_is_star(self) -> None:
+ assert _imported_names('export * from "./panels";') == ["*"]
+
+ def test_namespace_reexport_is_star(self) -> None:
+ assert _imported_names('export * as ns from "./m";') == ["*"]
+
+ def test_local_export_is_not_an_import(self) -> None:
+ # `export const x` has no `source` — it must not be captured as an import.
+ parsed = _PARSER.parse_file(_file_info("pkg/m.ts"), b"export const x = 1;\n")
+ assert parsed.imports == []
+
+
+# ---------------------------------------------------------------------------
+# End-to-end — barrel chain keeps the leaf symbol live
+# ---------------------------------------------------------------------------
+
+
+def test_symbol_reexported_through_barrel_chain_not_flagged() -> None:
+ sources = {
+ "pkg/src/comp/search-bar.tsx": "export function SearchBar() {\n return null;\n}\n",
+ "pkg/src/comp/index.ts": 'export { SearchBar } from "./search-bar";\n',
+ "pkg/src/index.ts": 'export * from "./comp";\n',
+ "pkg/src/app.tsx": (
+ 'import { SearchBar } from "./index";\n\n'
+ "export function App() {\n return SearchBar();\n}\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ assert "SearchBar" not in _unused_export_names(graph)
+ # Every barrel + leaf is reachable through the re-export edges.
+ assert "pkg/src/comp/search-bar.tsx" not in _unreachable_paths(graph)
+
+
+def test_barrel_files_never_flagged_unreachable() -> None:
+ """An `index.ts` barrel with no inbound import is still not flagged."""
+ sources = {
+ "pkg/src/widget.tsx": "export function Widget() {\n return null;\n}\n",
+ "pkg/src/index.ts": 'export { Widget } from "./widget";\n',
+ }
+ graph = _graph_from_sources(sources)
+ assert "pkg/src/index.ts" not in _unreachable_paths(graph)