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
fix(ingestion): rescue local Express route middleware from unused-export detection (#386)
joptimusa75555e8b07c
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/express.py b/packages/core/src/repowise/core/ingestion/framework_edges/express.pyindex daf5ee714..e857f1ff4 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/express.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/express.py@@ -27,6 +27,44 @@ _NEST_MODULE_RE = re.compile(r"@Module\s*\(\s*\{([^}]*)\}\s*\)", re.DOTALL)_NEST_ARRAY_FIELD_RE = re.compile(r"\b(?:controllers|providers|imports|exports)\s*:\s*\[([^\]]*)\]")_IDENT_RE = re.compile(r"\b([A-Z]\w*)\b")+_EXPRESS_RECEIVER_RE = re.compile(+ r"\b(\w+)\s*(?::[^=;\n]+)?=\s*(?:express\s*\(\s*\)|(?:express\s*\.\s*)?Router\s*\()"+)+_ROUTE_CALL_START_RE = re.compile(+ r"\b(\w+)\s*\.\s*(?:get|post|put|delete|patch|options|head|all|use)\s*\("+)+_STRING_LITERAL_RE = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`")+_ARG_IDENT_RE = re.compile(r"[A-Za-z_$][\w$]*")+++def _match_paren(text: str, open_idx: int) -> int:+ depth = 0+ i = open_idx+ n = len(text)+ while i < n:+ c = text[i]+ if c in "\"'`":+ i += 1+ while i < n and text[i] != c:+ i += 2 if text[i] == "\\" else 1+ elif c == "(":+ depth += 1+ elif c == ")":+ depth -= 1+ if depth == 0:+ return i+ i += 1+ return -1+++def _add_reads_edge(graph: nx.DiGraph, source: str, target: str) -> bool:+ if source == target or not graph.has_node(source) or not graph.has_node(target):+ return False+ if graph.has_edge(source, target):+ return False+ graph.add_edge(source, target, edge_type="reads", imported_names=[])+ return True+def _has_express_imports(parsed_files: dict[str, Any]) -> bool:for parsed in parsed_files.values():@@ -65,6 +103,26 @@ def _add_express_edges(if target and target in path_set and _add_edge_if_new(graph, path, target):count += 1+ local_funcs = {+ sym.name: sym.id+ for sym in parsed.symbols+ if sym.kind in ("function", "method")+ }+ receivers = {m.group(1) for m in _EXPRESS_RECEIVER_RE.finditer(text)}+ if local_funcs and receivers:+ module_sym = f"{path}::__module__"+ for m in _ROUTE_CALL_START_RE.finditer(text):+ if m.group(1) not in receivers:+ continue+ close = _match_paren(text, m.end() - 1)+ if close == -1:+ continue+ arg_blob = _STRING_LITERAL_RE.sub("", text[m.end() : close])+ for ident in _ARG_IDENT_RE.finditer(arg_blob):+ sym_id = local_funcs.get(ident.group(0))+ if sym_id and _add_reads_edge(graph, module_sym, sym_id):+ count += 1+# ---- NestJS: @Module({ controllers: [...], providers: [...], imports: [...] }) ----for mod_match in _NEST_MODULE_RE.finditer(text):body = mod_match.group(1)diff --git a/tests/unit/ingestion/test_express_framework_edges.py b/tests/unit/ingestion/test_express_framework_edges.pyindex af15e032a..82c140ab7 100644--- a/tests/unit/ingestion/test_express_framework_edges.py+++ b/tests/unit/ingestion/test_express_framework_edges.py@@ -7,17 +7,19 @@ from pathlib import Pathimport networkx as nx+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion import GraphBuilderfrom repowise.core.ingestion.framework_edges import add_framework_edgesfrom repowise.core.ingestion.models import FileInfo, ParsedFilefrom repowise.core.ingestion.parser import ASTParserfrom repowise.core.ingestion.resolvers.context import ResolverContext-def _file_info(rel: str, abs_path: str) -> FileInfo:+def _file_info(rel: str, abs_path: str, language: str = "typescript") -> FileInfo:return FileInfo(path=rel,abs_path=abs_path,- language="typescript",+ language=language,size_bytes=100,git_hash="",last_modified=datetime.now(),@@ -107,3 +109,142 @@ class TestExpressGate:ctx = _ctx(tmp_path, parsed)count = add_framework_edges(graph, parsed, ctx, tech_stack=[])assert count == 0+++def _build_graph_with_framework_edges(repo: Path) -> nx.DiGraph:+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for src in sorted([*repo.rglob("*.ts"), *repo.rglob("*.js")]):+ rel = src.resolve().relative_to(repo.resolve()).as_posix()+ language = "javascript" if src.suffix == ".js" else "typescript"+ fi = _file_info(rel, str(src.resolve()), language)+ builder.add_file(parser.parse_file(fi, src.read_bytes()))+ graph = builder.build()+ builder.add_framework_edges(["express"])+ return graph+++class TestExpressLocalMiddlewareReads:+ def test_route_post_middleware_get_reads_edges(self, tmp_path: Path) -> None:+ (tmp_path / "routes.ts").write_text(+ "import { Router } from 'express';\n"+ "export function logRequest(req, res, next) { next(); }\n"+ "export function validateRequest(req, res, next) { next(); }\n"+ "export function handler(req, res) { res.send('ok'); }\n"+ "const router = Router();\n"+ "router.post('/example', logRequest, validateRequest, handler);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ module_sym = "routes.ts::__module__"+ for name in ("logRequest", "validateRequest", "handler"):+ sym_id = f"routes.ts::{name}"+ assert graph.has_edge(module_sym, sym_id), f"missing reads edge to {name}"+ assert graph[module_sym][sym_id]["edge_type"] == "reads"++ def test_app_use_middleware_gets_reads_edge(self, tmp_path: Path) -> None:+ (tmp_path / "mw.ts").write_text(+ "import express from 'express';\n"+ "export function authGuard(req, res, next) { next(); }\n"+ "const app = express();\n"+ "app.use(authGuard);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ assert graph.has_edge("mw.ts::__module__", "mw.ts::authGuard")+ assert graph["mw.ts::__module__"]["mw.ts::authGuard"]["edge_type"] == "reads"++ def test_defines_edge_preserved(self, tmp_path: Path) -> None:+ (tmp_path / "routes.ts").write_text(+ "import { Router } from 'express';\n"+ "export function handler(req, res) { res.send('ok'); }\n"+ "const router = Router();\n"+ "router.get('/x', handler);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ assert graph["routes.ts"]["routes.ts::handler"]["edge_type"] == "defines"++ def test_nested_middleware_call_before_handler(self, tmp_path: Path) -> None:+ (tmp_path / "routes.ts").write_text(+ "import { Router } from 'express';\n"+ "export function requireRole(role) { return (req, res, next) => next(); }\n"+ "export function handler(req, res) { res.send('ok'); }\n"+ "const router = Router();\n"+ "router.get('/x', requireRole('admin'), handler);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ handler = "routes.ts::handler"+ assert graph.has_edge("routes.ts::__module__", handler)+ assert graph["routes.ts::__module__"][handler]["edge_type"] == "reads"+ assert graph.has_edge("routes.ts::__module__", "routes.ts::requireRole")++ def test_commonjs_multiline_route_reads_edges(self, tmp_path: Path) -> None:+ (tmp_path / "routes.js").write_text(+ 'const express = require("express");\n'+ "const router = express.Router();\n"+ "\n"+ "function logRequest(req, res, next) { next(); }\n"+ "function validateRequest(req, res, next) { next(); }\n"+ "\n"+ 'router.post("/x",\n'+ " logRequest,\n"+ " validateRequest,\n"+ " async (req, res) => { res.send('ok'); }\n"+ ");\n"+ "\n"+ "module.exports = router;\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ module_sym = "routes.js::__module__"+ for name in ("logRequest", "validateRequest"):+ sym_id = f"routes.js::{name}"+ assert graph.has_edge(module_sym, sym_id), f"missing reads edge to {name}"+ assert graph[module_sym][sym_id]["edge_type"] == "reads"++ def test_non_route_receiver_in_express_file_no_reads_edge(self, tmp_path: Path) -> None:+ (tmp_path / "svc.ts").write_text(+ "import express from 'express';\n"+ "export function cleanup() {}\n"+ "const cache = new Map();\n"+ "cache.get(cleanup);\n"+ "const app = express();\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ assert not graph.has_edge("svc.ts::__module__", "svc.ts::cleanup")++ def test_non_express_file_no_reads_edge(self, tmp_path: Path) -> None:+ (tmp_path / "app.ts").write_text(+ "import express from 'express';\nconst app = express();\n"+ )+ (tmp_path / "cache.ts").write_text(+ "export function helper() { return 1; }\n"+ "const store = new Map();\n"+ "store.get(helper);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ assert not graph.has_edge("cache.ts::__module__", "cache.ts::helper")+++class TestExpressDeadCodeRegression:+ def test_local_route_middleware_not_flagged_unused(self, tmp_path: Path) -> None:+ (tmp_path / "routes.ts").write_text(+ "import { Router } from 'express';\n"+ "export function logRequest(req, res, next) { next(); }\n"+ "export function handler(req, res) { res.send('ok'); }\n"+ "const router = Router();\n"+ "router.get('/x', logRequest, handler);\n"+ "export default router;\n"+ )+ (tmp_path / "app.ts").write_text(+ "import express from 'express';\n"+ "import router from './routes';\n"+ "const app = express();\n"+ "app.use('/', router);\n"+ )+ graph = _build_graph_with_framework_edges(tmp_path)+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze({"min_confidence": 0.0})+ unused = {+ f.symbol_name+ for f in report.findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "logRequest" not in unused+ assert "handler" not in unused