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(dead-code): resolve CommonJS require() so property-access calls aren't dead (#299)
joptimus5e39aa63c5dc
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.pyindex 2a19ebf66..497b29e85 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@@ -8,6 +8,65 @@ from ...models import NamedBindingfrom ..helpers import node_text+def _extract_require_bindings(+ stmt_node: Node, src: str+) -> tuple[list[str], list[NamedBinding]] | None:+ """Bindings for a ``variable_declarator`` initialized by ``require(...)``.++ Handles ``const svc = require('./svc')`` (whole-module alias) and+ ``const { a, b: c } = require('./svc')`` (destructured). Returns None when+ the node is not a require() declarator so the caller falls through to the+ existing import/export handling.+ """+ if stmt_node.type != "variable_declarator":+ return None+ value = stmt_node.child_by_field_name("value")+ if value is None or value.type != "call_expression":+ return None+ fn = value.child_by_field_name("function")+ if fn is None or node_text(fn, src) != "require":+ return None++ name_node = stmt_node.child_by_field_name("name")+ if name_node is None:+ return [], []++ names: list[str] = []+ bindings: list[NamedBinding] = []++ if name_node.type == "identifier":+ local = node_text(name_node, src)+ names.append(local)+ bindings.append(+ NamedBinding(+ local_name=local,+ exported_name=None,+ source_file=None,+ is_module_alias=True,+ )+ )+ elif name_node.type == "object_pattern":+ for el in name_node.children:+ if el.type == "shorthand_property_identifier_pattern":+ local = node_text(el, src)+ names.append(local)+ bindings.append(+ NamedBinding(local_name=local, exported_name=local, source_file=None)+ )+ elif el.type == "pair_pattern":+ key = el.child_by_field_name("key")+ val = el.child_by_field_name("value")+ if key is not None and val is not None:+ exported = node_text(key, src)+ local = node_text(val, src)+ names.append(local)+ bindings.append(+ NamedBinding(local_name=local, exported_name=exported, source_file=None)+ )++ return names, bindings++def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:"""Extract bindings from TypeScript/JavaScript import and re-export statements.@@ -19,6 +78,10 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[Nanalyzer can match it to the re-exported symbol and an ``index.ts`` barrelno longer hides every component it forwards."""+ require_result = _extract_require_bindings(stmt_node, src)+ if require_result is not None:+ return require_result+names: list[str] = []bindings: list[NamedBinding] = []diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scmindex a323d66a0..edda78495 100644--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm@@ -44,6 +44,15 @@source: (string) @import.module) @import.statement+; CommonJS: const svc = require('./svc') / const { a, b } = require('./svc')+; Tag the individual declarator so multi-declarator statements aren't deduped.+(variable_declarator+ value: (call_expression+ function: (identifier) @_require+ arguments: (arguments (string) @import.module))+ (#eq? @_require "require")+) @import.statement+; ---------------------------------------------------------------------------; Calls; ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex 093a55403..496626abd 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -89,6 +89,15 @@source: (string) @import.module) @import.statement+; CommonJS: const svc = require('./svc') / const { a, b } = require('./svc')+; Tag the individual declarator so multi-declarator statements aren't deduped.+(variable_declarator+ value: (call_expression+ function: (identifier) @_require+ arguments: (arguments (string) @import.module))+ (#eq? @_require "require")+) @import.statement+; ---------------------------------------------------------------------------; Calls; ---------------------------------------------------------------------------diff --git a/tests/integration/test_commonjs_dead_code.py b/tests/integration/test_commonjs_dead_code.pynew file mode 100644index 000000000..96942b048--- /dev/null+++ b/tests/integration/test_commonjs_dead_code.py@@ -0,0 +1,80 @@+"""End-to-end guard for CommonJS property-access resolution (#295).++A whole-module ``require`` followed by ``svc.used()`` must register as a use of+``used`` (so it is not a dead-code false positive), and the resolution must be+*targeted* — it must not phantom-mark every export of the required module as+used.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ENTRY_JS = """const svc = require('./svc');++function main() {+ return svc.used();+}++module.exports = { main };+"""++SVC_JS = """function used() {+ return 1;+}++function reallyDead() {+ return 2;+}++module.exports = { used, reallyDead };+"""++[email protected](scope="module")+def graph_and_report(tmp_path_factory):+ repo = tmp_path_factory.mktemp("cjs_sample")+ (repo / "entry.js").write_text(ENTRY_JS, encoding="utf-8")+ (repo / "svc.js").write_text(SVC_JS, encoding="utf-8")++ traverser = FileTraverser(repo)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in traverser.traverse():+ source = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, source))+ graph = builder.build()+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze({"min_confidence": 0.0})+ return graph, report+++def _calls_to(graph, target: str) -> bool:+ return any(+ graph[u][target].get("edge_type") == "calls" for u in graph.predecessors(target)+ )+++def test_property_access_call_resolves_to_required_export(graph_and_report):+ """svc.used() must create a `calls` edge to svc.js::used (the fix)."""+ graph, _ = graph_and_report+ assert "svc.js::used" in graph+ assert _calls_to(graph, "svc.js::used")+++def test_used_function_is_not_flagged_dead(graph_and_report):+ """The actively-used export must not appear as a dead-code finding."""+ _, report = graph_and_report+ assert "used" not in {f.symbol_name for f in report.findings}+++def test_resolution_is_targeted_not_whole_module(graph_and_report):+ """Only the accessed member resolves — `reallyDead` must NOT get a phantom+ `calls` edge just because the whole module was required."""+ graph, _ = graph_and_report+ assert "svc.js::reallyDead" in graph+ assert not _calls_to(graph, "svc.js::reallyDead")diff --git a/tests/unit/ingestion/parser/test_commonjs_require.py b/tests/unit/ingestion/parser/test_commonjs_require.pynew file mode 100644index 000000000..d93e64328--- /dev/null+++ b/tests/unit/ingestion/parser/test_commonjs_require.py@@ -0,0 +1,45 @@+"""CommonJS ``require()`` import-extraction tests (issue #295)."""++from __future__ import annotations++from repowise.core.ingestion.parser import ASTParser+from tests.unit.ingestion.parser._helpers import _make_file_info+++def _parse(parser: ASTParser, source: str, language: str = "javascript"):+ fi = _make_file_info(f"a.{('ts' if language == 'typescript' else 'js')}", language)+ return parser.parse_file(fi, source.encode("utf-8"))+++def test_whole_module_require_is_extracted_as_import(parser: ASTParser) -> None:+ result = _parse(parser, "const svc = require('./svc');\nsvc.bar();\n")+ reqs = [i for i in result.imports if i.module_path == "./svc"]+ assert reqs, "require('./svc') was not extracted as an import"+ aliases = [b for b in reqs[0].bindings if b.is_module_alias]+ assert [b.local_name for b in aliases] == ["svc"]+++def test_destructured_require_is_extracted_as_named_imports(parser: ASTParser) -> None:+ result = _parse(parser, "const { bar, baz } = require('./svc');\n")+ imp = next(i for i in result.imports if i.module_path == "./svc")+ assert sorted(b.local_name for b in imp.bindings) == ["bar", "baz"]+ assert all(not b.is_module_alias for b in imp.bindings)+ assert sorted(b.exported_name for b in imp.bindings) == ["bar", "baz"]+++def test_renamed_destructure_records_exported_and_local(parser: ASTParser) -> None:+ result = _parse(parser, "const { x: y } = require('./z');\n")+ imp = next(i for i in result.imports if i.module_path == "./z")+ binding = next(b for b in imp.bindings if b.local_name == "y")+ assert binding.exported_name == "x"+++def test_multi_declarator_require_keeps_both(parser: ASTParser) -> None:+ result = _parse(parser, "const a = require('./a'), b = require('./b');\n")+ modules = sorted(i.module_path for i in result.imports if i.module_path in ("./a", "./b"))+ assert modules == ["./a", "./b"]+++def test_var_require_is_extracted(parser: ASTParser) -> None:+ result = _parse(parser, "var svc = require('./svc');\n")+ assert any(i.module_path == "./svc" for i in result.imports)