codegraphcontext-rust 0.9.24__cp314-cp314-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codegraphcontext/__init__.py +2 -0
- codegraphcontext/__main__.py +5 -0
- codegraphcontext/_cgc_rust.cp314-win_amd64.pyd +4 -0
- codegraphcontext/cli/__init__.py +1 -0
- codegraphcontext/cli/cli_helpers.py +774 -0
- codegraphcontext/cli/config_manager.py +1051 -0
- codegraphcontext/cli/entry.py +21 -0
- codegraphcontext/cli/main.py +2386 -0
- codegraphcontext/cli/registry_commands.py +404 -0
- codegraphcontext/cli/setup_macos.py +93 -0
- codegraphcontext/cli/setup_wizard.py +991 -0
- codegraphcontext/cli/visualizer.py +50 -0
- codegraphcontext/core/__init__.py +165 -0
- codegraphcontext/core/bundle_registry.py +181 -0
- codegraphcontext/core/cgc_bundle.py +858 -0
- codegraphcontext/core/cgcignore.py +118 -0
- codegraphcontext/core/database.py +273 -0
- codegraphcontext/core/database_falkordb.py +480 -0
- codegraphcontext/core/database_falkordb_remote.py +199 -0
- codegraphcontext/core/database_kuzu.py +636 -0
- codegraphcontext/core/falkor_worker.py +132 -0
- codegraphcontext/core/jobs.py +132 -0
- codegraphcontext/core/watcher.py +260 -0
- codegraphcontext/prompts.py +125 -0
- codegraphcontext/server.py +471 -0
- codegraphcontext/tool_definitions.py +220 -0
- codegraphcontext/tools/__init__.py +0 -0
- codegraphcontext/tools/advanced_language_query_tool.py +103 -0
- codegraphcontext/tools/code_finder.py +1160 -0
- codegraphcontext/tools/graph_builder.py +337 -0
- codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
- codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
- codegraphcontext/tools/handlers/management_handlers.py +339 -0
- codegraphcontext/tools/handlers/query_handlers.py +83 -0
- codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
- codegraphcontext/tools/indexing/__init__.py +1 -0
- codegraphcontext/tools/indexing/angular_routes.py +396 -0
- codegraphcontext/tools/indexing/cgc_wiki_cli.py +1334 -0
- codegraphcontext/tools/indexing/constants.py +70 -0
- codegraphcontext/tools/indexing/context_generator.py +461 -0
- codegraphcontext/tools/indexing/discovery.py +64 -0
- codegraphcontext/tools/indexing/engine.py +114 -0
- codegraphcontext/tools/indexing/execution_flows.py +355 -0
- codegraphcontext/tools/indexing/module_grouping.py +551 -0
- codegraphcontext/tools/indexing/noise_filter.py +131 -0
- codegraphcontext/tools/indexing/op_param_extraction.py +287 -0
- codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
- codegraphcontext/tools/indexing/persistence/duckdb_writer.py +1116 -0
- codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
- codegraphcontext/tools/indexing/persistence/writer.py +1562 -0
- codegraphcontext/tools/indexing/pipeline.py +171 -0
- codegraphcontext/tools/indexing/pre_scan.py +105 -0
- codegraphcontext/tools/indexing/rationale_extraction.py +154 -0
- codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
- codegraphcontext/tools/indexing/resolution/calls.py +253 -0
- codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
- codegraphcontext/tools/indexing/route_extraction.py +659 -0
- codegraphcontext/tools/indexing/sanitize.py +41 -0
- codegraphcontext/tools/indexing/schema.py +79 -0
- codegraphcontext/tools/indexing/schema_contract.py +44 -0
- codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
- codegraphcontext/tools/languages/c.py +563 -0
- codegraphcontext/tools/languages/cpp.py +616 -0
- codegraphcontext/tools/languages/csharp.py +551 -0
- codegraphcontext/tools/languages/dart.py +378 -0
- codegraphcontext/tools/languages/elixir.py +460 -0
- codegraphcontext/tools/languages/go.py +499 -0
- codegraphcontext/tools/languages/haskell.py +426 -0
- codegraphcontext/tools/languages/java.py +500 -0
- codegraphcontext/tools/languages/javascript.py +589 -0
- codegraphcontext/tools/languages/kotlin.py +640 -0
- codegraphcontext/tools/languages/perl.py +260 -0
- codegraphcontext/tools/languages/php.py +519 -0
- codegraphcontext/tools/languages/python.py +578 -0
- codegraphcontext/tools/languages/ruby.py +537 -0
- codegraphcontext/tools/languages/rust.py +295 -0
- codegraphcontext/tools/languages/scala.py +519 -0
- codegraphcontext/tools/languages/swift.py +491 -0
- codegraphcontext/tools/languages/typescript.py +606 -0
- codegraphcontext/tools/languages/typescriptjsx.py +151 -0
- codegraphcontext/tools/package_resolver.py +472 -0
- codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
- codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
- codegraphcontext/tools/scip_indexer.py +467 -0
- codegraphcontext/tools/scip_pb2.py +2455 -0
- codegraphcontext/tools/system.py +133 -0
- codegraphcontext/tools/tree_sitter_parser.py +103 -0
- codegraphcontext/utils/debug_log.py +90 -0
- codegraphcontext/utils/path_ignore.py +55 -0
- codegraphcontext/utils/repo_path.py +27 -0
- codegraphcontext/utils/tree_sitter_manager.py +285 -0
- codegraphcontext/utils/visualize_graph.py +0 -0
- codegraphcontext/viz/server.py +282 -0
- codegraphcontext_rust-0.9.24.dist-info/METADATA +543 -0
- codegraphcontext_rust-0.9.24.dist-info/RECORD +112 -0
- codegraphcontext_rust-0.9.24.dist-info/WHEEL +4 -0
- codegraphcontext_rust-0.9.24.dist-info/entry_points.txt +4 -0
- codegraphcontext_rust-0.9.24.dist-info/licenses/LICENSE +21 -0
- codegraphcontext_rust-0.9.24.dist-info/sboms/cgc-python.cyclonedx.json +2302 -0
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
"""Detect API routes/endpoints from parsed source code.
|
|
2
|
+
|
|
3
|
+
Supports:
|
|
4
|
+
- Express.js/Hono: app.get("/path", handler), router.post(...)
|
|
5
|
+
- FastAPI/Flask: @app.get("/path"), @app.route("/path")
|
|
6
|
+
- Spring Boot: @GetMapping("/path"), @PostMapping, @RequestMapping
|
|
7
|
+
- Next.js: file-based routing (page.tsx → route)
|
|
8
|
+
- Django: path("url/", view), urlpatterns
|
|
9
|
+
- NestJS: @Get(), @Post(), @Controller("/prefix")
|
|
10
|
+
- Laravel: Route::get("/path", [Controller, "method"])
|
|
11
|
+
- Go: http.HandleFunc("/path", handler), r.GET("/path", handler)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Dict, List, Optional
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
# ── Route patterns per framework ────────────────────────────────────
|
|
25
|
+
|
|
26
|
+
# Decorator-based routes (Python, Java, NestJS)
|
|
27
|
+
_DECORATOR_ROUTE_PATTERNS = [
|
|
28
|
+
# FastAPI / Flask
|
|
29
|
+
re.compile(r'@(?:app|router|api)\.(get|post|put|delete|patch|options|head)\s*\(\s*["\']([^"\']+)["\']'),
|
|
30
|
+
re.compile(r'@(?:app|router|api)\.route\s*\(\s*["\']([^"\']+)["\']'),
|
|
31
|
+
# Spring Boot
|
|
32
|
+
re.compile(r'@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']'),
|
|
33
|
+
re.compile(r'@RequestMapping\s*\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']'),
|
|
34
|
+
# NestJS
|
|
35
|
+
re.compile(r'@(Get|Post|Put|Delete|Patch)\s*\(\s*["\']([^"\']+)["\']'),
|
|
36
|
+
re.compile(r'@Controller\s*\(\s*["\']([^"\']+)["\']'),
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
# Function call-based routes (Express, Hono, Go Fiber/Gin/Echo/Chi, ...)
|
|
40
|
+
# Generic pattern: <any identifier>.<Verb>("<path starting with />", ...)
|
|
41
|
+
# Works for: app.get / router.Post / translationGroup.Get / r.GET / api.use / etc.
|
|
42
|
+
# Case-insensitive to cover JS (get) + Go (Get/GET) + mixed conventions.
|
|
43
|
+
# Require path arg to start with "/" — reduces false positives like res.get("header").
|
|
44
|
+
_CALL_ROUTE_PATTERNS = [
|
|
45
|
+
re.compile(
|
|
46
|
+
r'\b[\w.]+\.(get|post|put|delete|patch|head|options|use|all)\s*\(\s*["\'](\/[^"\']*)["\']',
|
|
47
|
+
re.IGNORECASE,
|
|
48
|
+
),
|
|
49
|
+
# Go net/http
|
|
50
|
+
re.compile(r'(?:http\.)?HandleFunc\s*\(\s*["\'](\/[^"\']*)["\']'),
|
|
51
|
+
# Laravel
|
|
52
|
+
re.compile(r'Route::(get|post|put|delete|patch)\s*\(\s*["\'](\/[^"\']*)["\']', re.IGNORECASE),
|
|
53
|
+
# Django
|
|
54
|
+
re.compile(r'\bpath\s*\(\s*["\']([^"\']+)["\']'),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
# Next.js / Nuxt file-based routing patterns
|
|
58
|
+
_NEXTJS_ROUTE_FILES = {"page.tsx", "page.ts", "page.jsx", "page.js", "route.tsx", "route.ts"}
|
|
59
|
+
_NEXTJS_ROUTE_GROUPS = re.compile(r'\(([^)]+)\)') # strip (group) from path
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ── Spring (Java/Kotlin) annotation scanning ───────────────────────
|
|
63
|
+
|
|
64
|
+
_SPRING_MAPPING_RE = re.compile(r'@(Get|Post|Put|Delete|Patch|Request)Mapping\b')
|
|
65
|
+
_STRING_LITERAL_RE = re.compile(r'"((?:[^"\\]|\\.)*)"')
|
|
66
|
+
_NAMED_PATH_ARG_RE = re.compile(r'\b(?:value|path)\s*=\s*')
|
|
67
|
+
_REQUEST_METHOD_RE = re.compile(r'RequestMethod\.(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b')
|
|
68
|
+
_TYPE_DECL_RE = re.compile(r'\b(?:class|interface|object)\s+[A-Z]\w*')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _strip_jvm_comments(src: str) -> str:
|
|
72
|
+
"""Blank out // and /* */ comments, keeping string literals and newlines.
|
|
73
|
+
|
|
74
|
+
Line numbers are preserved so offsets still map to source lines. String
|
|
75
|
+
literals are honoured, so `"/api/**"` or `// see /api/*` cannot open a
|
|
76
|
+
phantom block comment.
|
|
77
|
+
"""
|
|
78
|
+
out = []
|
|
79
|
+
i, n = 0, len(src)
|
|
80
|
+
while i < n:
|
|
81
|
+
ch = src[i]
|
|
82
|
+
two = src[i:i + 2]
|
|
83
|
+
if src.startswith('"""', i): # Java text block / Kotlin raw string
|
|
84
|
+
j = src.find('"""', i + 3)
|
|
85
|
+
j = n if j == -1 else j + 3
|
|
86
|
+
out.append(src[i:j]); i = j
|
|
87
|
+
elif ch == '"' or ch == "'":
|
|
88
|
+
j = i + 1
|
|
89
|
+
while j < n and src[j] != ch and src[j] != "\n":
|
|
90
|
+
j += 2 if src[j] == "\\" else 1
|
|
91
|
+
j = min(j + 1, n)
|
|
92
|
+
out.append(src[i:j]); i = j
|
|
93
|
+
elif two == "//":
|
|
94
|
+
j = src.find("\n", i)
|
|
95
|
+
j = n if j == -1 else j
|
|
96
|
+
out.append(" " * (j - i)); i = j
|
|
97
|
+
elif two == "/*":
|
|
98
|
+
j = src.find("*/", i + 2)
|
|
99
|
+
j = n if j == -1 else j + 2
|
|
100
|
+
out.append(re.sub(r"[^\n]", " ", src[i:j])); i = j
|
|
101
|
+
else:
|
|
102
|
+
out.append(ch); i += 1
|
|
103
|
+
return "".join(out)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _balanced_args(code: str, pos: int) -> Optional[str]:
|
|
107
|
+
"""Return the text inside the parenthesis group starting at/after ``pos``.
|
|
108
|
+
|
|
109
|
+
None when the annotation has no argument list (bare ``@GetMapping``).
|
|
110
|
+
"""
|
|
111
|
+
j = pos
|
|
112
|
+
while j < len(code) and code[j] in " \t\r\n":
|
|
113
|
+
j += 1
|
|
114
|
+
if j >= len(code) or code[j] != "(":
|
|
115
|
+
return None
|
|
116
|
+
depth, k = 0, j
|
|
117
|
+
while k < len(code):
|
|
118
|
+
c = code[k]
|
|
119
|
+
if c == '"':
|
|
120
|
+
k += 1
|
|
121
|
+
while k < len(code) and code[k] != '"':
|
|
122
|
+
k += 2 if code[k] == "\\" else 1
|
|
123
|
+
elif c in "([{":
|
|
124
|
+
depth += 1
|
|
125
|
+
elif c in ")]}":
|
|
126
|
+
depth -= 1
|
|
127
|
+
if depth == 0:
|
|
128
|
+
return code[j + 1:k]
|
|
129
|
+
k += 1
|
|
130
|
+
return code[j + 1:]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _leading_value(args: str) -> str:
|
|
134
|
+
"""The first argument expression (a string, or an array of strings)."""
|
|
135
|
+
a = args.lstrip()
|
|
136
|
+
for opener, closer in (("{", "}"), ("[", "]"), ("arrayOf(", ")")):
|
|
137
|
+
if a.startswith(opener):
|
|
138
|
+
end = a.find(closer, len(opener))
|
|
139
|
+
return a[: end + 1] if end != -1 else a
|
|
140
|
+
m = _STRING_LITERAL_RE.match(a)
|
|
141
|
+
return m.group(0) if m else ""
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _mapping_paths(args: Optional[str]) -> List[str]:
|
|
145
|
+
"""Paths declared by a mapping annotation; [""] when it declares none."""
|
|
146
|
+
if args is None:
|
|
147
|
+
return [""]
|
|
148
|
+
value = _leading_value(args)
|
|
149
|
+
if not value:
|
|
150
|
+
m = _NAMED_PATH_ARG_RE.search(args)
|
|
151
|
+
if m:
|
|
152
|
+
value = _leading_value(args[m.end():])
|
|
153
|
+
paths = [p for p in _STRING_LITERAL_RE.findall(value)]
|
|
154
|
+
return paths or [""]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _join_route(prefix: str, path: str) -> str:
|
|
158
|
+
prefix = prefix.rstrip("/")
|
|
159
|
+
if path and not path.startswith("/"):
|
|
160
|
+
path = "/" + path
|
|
161
|
+
joined = prefix + path
|
|
162
|
+
return joined if joined.startswith("/") else "/" + joined
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _extract_spring_mappings(code: str) -> List[tuple]:
|
|
166
|
+
"""Return ``(METHOD, path, line)`` for each Spring handler mapping.
|
|
167
|
+
|
|
168
|
+
Handles bare annotations (``@GetMapping``), ``value=``/``path=``, array
|
|
169
|
+
forms (``@GetMapping({"", "/search"})``), multi-line argument lists and
|
|
170
|
+
method-level ``@RequestMapping(method = RequestMethod.X)``. A
|
|
171
|
+
``@RequestMapping`` placed before the first type declaration is treated
|
|
172
|
+
as the class-level prefix.
|
|
173
|
+
"""
|
|
174
|
+
first_type = _TYPE_DECL_RE.search(code)
|
|
175
|
+
type_pos = first_type.start() if first_type else -1
|
|
176
|
+
|
|
177
|
+
prefixes = [""]
|
|
178
|
+
mappings = []
|
|
179
|
+
for m in _SPRING_MAPPING_RE.finditer(code):
|
|
180
|
+
kind = m.group(1)
|
|
181
|
+
args = _balanced_args(code, m.end())
|
|
182
|
+
if kind == "Request" and 0 <= m.start() < type_pos:
|
|
183
|
+
prefixes = _mapping_paths(args)
|
|
184
|
+
continue
|
|
185
|
+
if kind == "Request":
|
|
186
|
+
methods = _REQUEST_METHOD_RE.findall(args or "") or ["ANY"]
|
|
187
|
+
else:
|
|
188
|
+
methods = [kind.upper()]
|
|
189
|
+
line = code.count("\n", 0, m.start()) + 1
|
|
190
|
+
mappings.append((methods, _mapping_paths(args), line))
|
|
191
|
+
|
|
192
|
+
results = []
|
|
193
|
+
for methods, paths, line in mappings:
|
|
194
|
+
for prefix in prefixes:
|
|
195
|
+
for path in paths:
|
|
196
|
+
for method in methods:
|
|
197
|
+
results.append((method, _join_route(prefix, path), line))
|
|
198
|
+
return results
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _extract_nextjs_route(file_path: str, repo_path: str) -> Optional[str]:
|
|
202
|
+
"""Convert Next.js file path to route path."""
|
|
203
|
+
try:
|
|
204
|
+
rel = os.path.relpath(file_path, repo_path)
|
|
205
|
+
except ValueError:
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
parts = Path(rel).parts
|
|
209
|
+
# Find "app" directory
|
|
210
|
+
try:
|
|
211
|
+
app_idx = list(parts).index("app")
|
|
212
|
+
except ValueError:
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
route_parts = []
|
|
216
|
+
for part in parts[app_idx + 1:-1]: # skip "app" and filename
|
|
217
|
+
# Strip route groups like (dashboard), (auth)
|
|
218
|
+
if part.startswith("(") and part.endswith(")"):
|
|
219
|
+
continue
|
|
220
|
+
# Convert [param] to :param
|
|
221
|
+
if part.startswith("[") and part.endswith("]"):
|
|
222
|
+
param = part[1:-1]
|
|
223
|
+
if param.startswith("..."):
|
|
224
|
+
route_parts.append(f"*{param[3:]}")
|
|
225
|
+
else:
|
|
226
|
+
route_parts.append(f":{param}")
|
|
227
|
+
else:
|
|
228
|
+
route_parts.append(part)
|
|
229
|
+
|
|
230
|
+
return "/" + "/".join(route_parts) if route_parts else "/"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def extract_routes(
|
|
234
|
+
parsed_results: List[Dict[str, Any]],
|
|
235
|
+
repo_path: str,
|
|
236
|
+
) -> List[Dict[str, Any]]:
|
|
237
|
+
"""Extract API routes from parsed source files.
|
|
238
|
+
|
|
239
|
+
Returns list of:
|
|
240
|
+
{
|
|
241
|
+
method: str (GET, POST, etc.),
|
|
242
|
+
path: str ("/api/users/:id"),
|
|
243
|
+
handler: str (function name),
|
|
244
|
+
file: str (relative path),
|
|
245
|
+
line: int,
|
|
246
|
+
framework: str ("express", "fastapi", "spring", "nextjs", etc.),
|
|
247
|
+
}
|
|
248
|
+
"""
|
|
249
|
+
routes: List[Dict[str, Any]] = []
|
|
250
|
+
seen: set = set()
|
|
251
|
+
|
|
252
|
+
for file_data in parsed_results:
|
|
253
|
+
if "error" in file_data:
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
file_path = file_data.get("path", "")
|
|
257
|
+
file_name = Path(file_path).name
|
|
258
|
+
lang = file_data.get("lang", "")
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
rel_path = os.path.relpath(file_path, repo_path)
|
|
262
|
+
except ValueError:
|
|
263
|
+
rel_path = file_name
|
|
264
|
+
|
|
265
|
+
# ── Next.js file-based routing ──
|
|
266
|
+
if file_name in _NEXTJS_ROUTE_FILES:
|
|
267
|
+
route = _extract_nextjs_route(file_path, repo_path)
|
|
268
|
+
if route is not None:
|
|
269
|
+
is_route_file = file_name.startswith("route.")
|
|
270
|
+
|
|
271
|
+
if is_route_file and os.path.exists(file_path):
|
|
272
|
+
# App Router `route.ts` exports one function per HTTP method:
|
|
273
|
+
# export async function GET(req) { ... }
|
|
274
|
+
# export async function POST(req) { ... }
|
|
275
|
+
# Emit one route per exported method.
|
|
276
|
+
try:
|
|
277
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
278
|
+
src = fh.read()
|
|
279
|
+
except OSError:
|
|
280
|
+
src = ""
|
|
281
|
+
method_re = re.compile(
|
|
282
|
+
r'export\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b',
|
|
283
|
+
)
|
|
284
|
+
found_methods = set()
|
|
285
|
+
for m in method_re.finditer(src):
|
|
286
|
+
method = m.group(1).upper()
|
|
287
|
+
if method in found_methods:
|
|
288
|
+
continue
|
|
289
|
+
found_methods.add(method)
|
|
290
|
+
key = f"{method}|{route}"
|
|
291
|
+
if key in seen:
|
|
292
|
+
continue
|
|
293
|
+
seen.add(key)
|
|
294
|
+
routes.append({
|
|
295
|
+
"method": method,
|
|
296
|
+
"path": route,
|
|
297
|
+
"handler": method, # route.ts handler IS the method
|
|
298
|
+
"file": rel_path,
|
|
299
|
+
"line": 0,
|
|
300
|
+
"framework": "nextjs",
|
|
301
|
+
})
|
|
302
|
+
if not found_methods:
|
|
303
|
+
# Fallback: emit a GET route with file name
|
|
304
|
+
key = f"GET|{route}"
|
|
305
|
+
if key not in seen:
|
|
306
|
+
seen.add(key)
|
|
307
|
+
routes.append({
|
|
308
|
+
"method": "GET", "path": route,
|
|
309
|
+
"handler": "", "file": rel_path,
|
|
310
|
+
"line": 0, "framework": "nextjs",
|
|
311
|
+
})
|
|
312
|
+
else:
|
|
313
|
+
# page.tsx: single GET route. Handler = `export default function ...`
|
|
314
|
+
handler = ""
|
|
315
|
+
if os.path.exists(file_path):
|
|
316
|
+
try:
|
|
317
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
318
|
+
src = fh.read()
|
|
319
|
+
# export default function Name(...)
|
|
320
|
+
m = re.search(r'export\s+default\s+(?:async\s+)?function\s+([A-Z]\w*)', src)
|
|
321
|
+
if m:
|
|
322
|
+
handler = m.group(1)
|
|
323
|
+
else:
|
|
324
|
+
# export default Name | export default const Name = ...
|
|
325
|
+
m = re.search(r'export\s+default\s+([A-Z]\w*)\b', src)
|
|
326
|
+
if m:
|
|
327
|
+
handler = m.group(1)
|
|
328
|
+
except OSError:
|
|
329
|
+
pass
|
|
330
|
+
|
|
331
|
+
if not handler:
|
|
332
|
+
for fn in file_data.get("functions", []):
|
|
333
|
+
name = fn.get("name", "")
|
|
334
|
+
if name and name[0].isupper():
|
|
335
|
+
handler = name
|
|
336
|
+
break
|
|
337
|
+
if not handler:
|
|
338
|
+
fns = file_data.get("functions", [])
|
|
339
|
+
handler = fns[0]["name"] if fns else file_name
|
|
340
|
+
|
|
341
|
+
key = f"GET|{route}"
|
|
342
|
+
if key not in seen:
|
|
343
|
+
seen.add(key)
|
|
344
|
+
routes.append({
|
|
345
|
+
"method": "GET",
|
|
346
|
+
"path": route,
|
|
347
|
+
"handler": handler,
|
|
348
|
+
"file": rel_path,
|
|
349
|
+
"line": 0,
|
|
350
|
+
"framework": "nextjs",
|
|
351
|
+
})
|
|
352
|
+
|
|
353
|
+
# ── Decorator-based routes (read from decorators on functions) ──
|
|
354
|
+
# Java/Kotlin annotations also land in `decorators`, but Spring routes
|
|
355
|
+
# need the class-level @RequestMapping prefix: the source scan below
|
|
356
|
+
# handles them, so skip them here to avoid duplicate/unprefixed routes.
|
|
357
|
+
decorated_fns = [] if lang in ("java", "kotlin") else file_data.get("functions", [])
|
|
358
|
+
for fn in decorated_fns:
|
|
359
|
+
decorators = fn.get("decorators", []) or []
|
|
360
|
+
for dec in decorators:
|
|
361
|
+
dec_str = str(dec)
|
|
362
|
+
for pattern in _DECORATOR_ROUTE_PATTERNS:
|
|
363
|
+
m = pattern.search(dec_str)
|
|
364
|
+
if m:
|
|
365
|
+
groups = m.groups()
|
|
366
|
+
if len(groups) == 2:
|
|
367
|
+
method = groups[0].upper()
|
|
368
|
+
path = groups[1]
|
|
369
|
+
else:
|
|
370
|
+
method = "ANY"
|
|
371
|
+
path = groups[0]
|
|
372
|
+
|
|
373
|
+
# Normalize method
|
|
374
|
+
method_map = {"GET": "GET", "POST": "POST", "PUT": "PUT",
|
|
375
|
+
"DELETE": "DELETE", "PATCH": "PATCH",
|
|
376
|
+
"GETMAPPING": "GET", "POSTMAPPING": "POST",
|
|
377
|
+
"PUTMAPPING": "PUT", "DELETEMAPPING": "DELETE",
|
|
378
|
+
"PATCHMAPPING": "PATCH"}
|
|
379
|
+
method = method_map.get(method.upper().replace("MAPPING", "MAPPING"), method)
|
|
380
|
+
|
|
381
|
+
framework = "spring" if "Mapping" in dec_str else \
|
|
382
|
+
"fastapi" if lang == "python" else \
|
|
383
|
+
"nestjs" if lang in ("typescript", "javascript") else "unknown"
|
|
384
|
+
|
|
385
|
+
key = f"{method}|{path}"
|
|
386
|
+
if key not in seen:
|
|
387
|
+
seen.add(key)
|
|
388
|
+
routes.append({
|
|
389
|
+
"method": method,
|
|
390
|
+
"path": path,
|
|
391
|
+
"handler": fn.get("name", ""),
|
|
392
|
+
"file": rel_path,
|
|
393
|
+
"line": fn.get("line_number", 0),
|
|
394
|
+
"framework": framework,
|
|
395
|
+
})
|
|
396
|
+
break
|
|
397
|
+
|
|
398
|
+
# ── Java/Kotlin annotation-based routes (source scan fallback) ──
|
|
399
|
+
# Rust parser doesn't extract Java annotations as decorators,
|
|
400
|
+
# so scan the (comment-stripped) source for Spring mappings.
|
|
401
|
+
if lang in ("java", "kotlin") and os.path.exists(file_path):
|
|
402
|
+
try:
|
|
403
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
404
|
+
code = _strip_jvm_comments(fh.read())
|
|
405
|
+
except OSError:
|
|
406
|
+
code = ""
|
|
407
|
+
functions = file_data.get("functions", [])
|
|
408
|
+
for method, path, line in _extract_spring_mappings(code):
|
|
409
|
+
# Handler: closest function within a few lines of the annotation.
|
|
410
|
+
# Rust parser sometimes reports function line as FIRST annotation
|
|
411
|
+
# (e.g. @Scheduled above @GetMapping), so we look both directions.
|
|
412
|
+
handler = ""
|
|
413
|
+
best_dist = 999
|
|
414
|
+
for fn in functions:
|
|
415
|
+
dist = abs(fn.get("line_number", 0) - line)
|
|
416
|
+
if dist < best_dist:
|
|
417
|
+
best_dist = dist
|
|
418
|
+
handler = fn.get("name", "")
|
|
419
|
+
if best_dist > 8:
|
|
420
|
+
handler = ""
|
|
421
|
+
|
|
422
|
+
# Keyed per file: in a multi-service repo a gateway and a
|
|
423
|
+
# downstream service legitimately expose the same path.
|
|
424
|
+
key = f"{method}|{path}|{rel_path}"
|
|
425
|
+
if key not in seen:
|
|
426
|
+
seen.add(key)
|
|
427
|
+
routes.append({
|
|
428
|
+
"method": method,
|
|
429
|
+
"path": path,
|
|
430
|
+
"handler": handler,
|
|
431
|
+
"file": rel_path,
|
|
432
|
+
"line": line,
|
|
433
|
+
"framework": "spring",
|
|
434
|
+
})
|
|
435
|
+
|
|
436
|
+
# ── NestJS decorator-based routes (source scan) ──
|
|
437
|
+
if lang in ("typescript", "javascript") and os.path.exists(file_path):
|
|
438
|
+
try:
|
|
439
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
440
|
+
source_lines = fh.readlines()
|
|
441
|
+
|
|
442
|
+
# Check if this is a NestJS controller
|
|
443
|
+
is_nestjs = any("@Controller" in line for line in source_lines)
|
|
444
|
+
if is_nestjs:
|
|
445
|
+
# Find controller prefix
|
|
446
|
+
ctrl_prefix = ""
|
|
447
|
+
for line in source_lines:
|
|
448
|
+
cm = re.search(r"@Controller\s*\(\s*['\"]([^'\"]+)['\"]", line)
|
|
449
|
+
if cm:
|
|
450
|
+
ctrl_prefix = "/" + cm.group(1).strip("/")
|
|
451
|
+
break
|
|
452
|
+
|
|
453
|
+
# Find route decorators
|
|
454
|
+
nestjs_re = re.compile(
|
|
455
|
+
r"@(Get|Post|Put|Delete|Patch)\s*\(\s*(?:['\"]([^'\"]*)['\"])?\s*\)"
|
|
456
|
+
)
|
|
457
|
+
for i, line in enumerate(source_lines):
|
|
458
|
+
stripped = line.lstrip()
|
|
459
|
+
if stripped.startswith("//") or stripped.startswith("*"):
|
|
460
|
+
continue
|
|
461
|
+
nm = nestjs_re.search(line)
|
|
462
|
+
if nm:
|
|
463
|
+
method = nm.group(1).upper()
|
|
464
|
+
path_suffix = nm.group(2) or ""
|
|
465
|
+
path = ctrl_prefix
|
|
466
|
+
if path_suffix:
|
|
467
|
+
path = ctrl_prefix + "/" + path_suffix.strip("/")
|
|
468
|
+
if not path:
|
|
469
|
+
path = "/"
|
|
470
|
+
|
|
471
|
+
# Find handler: closest function after annotation (within 5 lines)
|
|
472
|
+
handler = ""
|
|
473
|
+
ann_line = i + 1
|
|
474
|
+
best_fn = None
|
|
475
|
+
best_dist = 999
|
|
476
|
+
for fn in file_data.get("functions", []):
|
|
477
|
+
fn_line = fn.get("line_number", 0)
|
|
478
|
+
if fn_line >= ann_line and (fn_line - ann_line) < best_dist:
|
|
479
|
+
best_dist = fn_line - ann_line
|
|
480
|
+
best_fn = fn
|
|
481
|
+
if best_fn and best_dist <= 5:
|
|
482
|
+
handler = best_fn.get("name", "")
|
|
483
|
+
|
|
484
|
+
key = f"{method}|{path}"
|
|
485
|
+
if key not in seen:
|
|
486
|
+
seen.add(key)
|
|
487
|
+
routes.append({
|
|
488
|
+
"method": method,
|
|
489
|
+
"path": path,
|
|
490
|
+
"handler": handler,
|
|
491
|
+
"file": rel_path,
|
|
492
|
+
"line": i + 1,
|
|
493
|
+
"framework": "nestjs",
|
|
494
|
+
})
|
|
495
|
+
except OSError:
|
|
496
|
+
pass
|
|
497
|
+
|
|
498
|
+
# ── Go source scan (Fiber, Gin, Echo, Chi) ─────────────
|
|
499
|
+
# Rust parser doesn't populate function_call args for Go, so scan source.
|
|
500
|
+
if lang == "go" and os.path.exists(file_path):
|
|
501
|
+
try:
|
|
502
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
503
|
+
src_lines = fh.readlines()
|
|
504
|
+
go_route_re = re.compile(
|
|
505
|
+
r'\b(\w+)\.(Get|Post|Put|Delete|Patch|Head|Options|Use|All|GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|USE|ALL)'
|
|
506
|
+
r'\s*\(\s*["\'](\/[^"\']*)["\']\s*,\s*([\w.]+)'
|
|
507
|
+
)
|
|
508
|
+
# Skip common non-route method calls
|
|
509
|
+
_SKIP_GO_RECV = {"ctx", "c", "req", "request", "res", "response",
|
|
510
|
+
"header", "headers", "url", "w", "writer"}
|
|
511
|
+
for i, line in enumerate(src_lines):
|
|
512
|
+
stripped = line.lstrip()
|
|
513
|
+
if stripped.startswith("//") or stripped.startswith("*"):
|
|
514
|
+
continue
|
|
515
|
+
m = go_route_re.search(line)
|
|
516
|
+
if not m:
|
|
517
|
+
continue
|
|
518
|
+
recv, verb, path, handler = m.groups()
|
|
519
|
+
if recv.lower() in _SKIP_GO_RECV:
|
|
520
|
+
continue
|
|
521
|
+
method = verb.upper()
|
|
522
|
+
if method in ("USE", "ALL"):
|
|
523
|
+
method = "USE"
|
|
524
|
+
key = f"{method}|{path}"
|
|
525
|
+
if key in seen:
|
|
526
|
+
continue
|
|
527
|
+
seen.add(key)
|
|
528
|
+
routes.append({
|
|
529
|
+
"method": method,
|
|
530
|
+
"path": path,
|
|
531
|
+
"handler": handler,
|
|
532
|
+
"file": rel_path,
|
|
533
|
+
"line": i + 1,
|
|
534
|
+
"framework": "go",
|
|
535
|
+
})
|
|
536
|
+
except OSError:
|
|
537
|
+
pass
|
|
538
|
+
|
|
539
|
+
# ── Call-based routes (scan function calls) ──
|
|
540
|
+
for call in file_data.get("function_calls", []):
|
|
541
|
+
call_name = call.get("full_name", "") or call.get("name", "")
|
|
542
|
+
|
|
543
|
+
# Skip false positive patterns (db.get, request.get, etc.)
|
|
544
|
+
if any(call_name.startswith(prefix) for prefix in (
|
|
545
|
+
"db.", "session.", "request.", "response.", "res.", "req.",
|
|
546
|
+
"self.", "this.", "super.", "cls.", "console.", "logger.",
|
|
547
|
+
"Math.", "JSON.", "Object.", "Array.", "String.",
|
|
548
|
+
"os.", "sys.", "path.", "fs.",
|
|
549
|
+
)):
|
|
550
|
+
continue
|
|
551
|
+
|
|
552
|
+
for pattern in _CALL_ROUTE_PATTERNS:
|
|
553
|
+
m = pattern.search(call_name)
|
|
554
|
+
if not m:
|
|
555
|
+
# Also check args for path string
|
|
556
|
+
args = call.get("args", [])
|
|
557
|
+
if args:
|
|
558
|
+
first_arg = str(args[0]).strip('"\'')
|
|
559
|
+
# Only match if first arg looks like a URL path
|
|
560
|
+
if first_arg.startswith("/") or first_arg.startswith("api/"):
|
|
561
|
+
combined = " ".join(str(a) for a in args[:2])
|
|
562
|
+
m = pattern.search(f'{call_name}({combined})')
|
|
563
|
+
if m:
|
|
564
|
+
groups = m.groups()
|
|
565
|
+
if len(groups) == 2:
|
|
566
|
+
method = groups[0].upper()
|
|
567
|
+
path = groups[1]
|
|
568
|
+
else:
|
|
569
|
+
method = "ANY"
|
|
570
|
+
path = groups[0]
|
|
571
|
+
|
|
572
|
+
# Validate path looks like URL (not variable name)
|
|
573
|
+
if not path.startswith("/") and not path.startswith("api"):
|
|
574
|
+
continue
|
|
575
|
+
|
|
576
|
+
# Determine framework by language
|
|
577
|
+
if "HandleFunc" in call_name or lang == "go":
|
|
578
|
+
framework = "go"
|
|
579
|
+
elif "Route::" in call_name:
|
|
580
|
+
framework = "laravel"
|
|
581
|
+
elif "path(" in call_name:
|
|
582
|
+
framework = "django"
|
|
583
|
+
elif lang == "python":
|
|
584
|
+
framework = "fastapi"
|
|
585
|
+
elif lang in ("typescript", "javascript", "tsx"):
|
|
586
|
+
framework = "express"
|
|
587
|
+
elif lang == "java":
|
|
588
|
+
framework = "spring"
|
|
589
|
+
elif lang == "php":
|
|
590
|
+
framework = "laravel"
|
|
591
|
+
elif lang == "ruby":
|
|
592
|
+
framework = "rails"
|
|
593
|
+
else:
|
|
594
|
+
framework = "unknown"
|
|
595
|
+
|
|
596
|
+
handler = call.get("context", ("",))[0] if isinstance(call.get("context"), tuple) else ""
|
|
597
|
+
if not handler:
|
|
598
|
+
handler = call.get("name", "")
|
|
599
|
+
|
|
600
|
+
# For decorator-style calls (@router.get, @app.post) the parsed call
|
|
601
|
+
# name is an HTTP verb — not a real handler. Replace with the function
|
|
602
|
+
# declared immediately AFTER the decorator line (FastAPI/Flask pattern).
|
|
603
|
+
# Exception: Express/Hono/Fiber inline arrow handlers — the handler is
|
|
604
|
+
# an anonymous arrow on the same line, NOT a named function below.
|
|
605
|
+
_HTTP_VERBS = {"get", "post", "put", "delete", "patch", "use", "all",
|
|
606
|
+
"options", "head"}
|
|
607
|
+
if not handler or handler.lower() in _HTTP_VERBS:
|
|
608
|
+
call_line = call.get("line_number", 0) or 0
|
|
609
|
+
# Detect inline arrow/function on the call line itself
|
|
610
|
+
is_inline = False
|
|
611
|
+
if call_line > 0 and os.path.exists(file_path) and lang in (
|
|
612
|
+
"javascript", "typescript", "tsx"
|
|
613
|
+
):
|
|
614
|
+
try:
|
|
615
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
616
|
+
src_lines = fh.readlines()
|
|
617
|
+
# Look at call_line through call_line+3 (multi-line calls)
|
|
618
|
+
window = "".join(src_lines[call_line - 1: call_line + 3])
|
|
619
|
+
if re.search(r'=>\s*[{(]|\bfunction\s*\(', window):
|
|
620
|
+
is_inline = True
|
|
621
|
+
except OSError:
|
|
622
|
+
pass
|
|
623
|
+
if is_inline:
|
|
624
|
+
handler = "<anonymous>"
|
|
625
|
+
else:
|
|
626
|
+
best_fn = None
|
|
627
|
+
best_dist = 999
|
|
628
|
+
for fn in file_data.get("functions", []):
|
|
629
|
+
fn_line = fn.get("line_number", 0) or 0
|
|
630
|
+
if fn_line > call_line and (fn_line - call_line) < best_dist:
|
|
631
|
+
best_dist = fn_line - call_line
|
|
632
|
+
best_fn = fn
|
|
633
|
+
if best_fn and best_dist <= 5:
|
|
634
|
+
handler = best_fn.get("name", "") or handler
|
|
635
|
+
|
|
636
|
+
key = f"{method}|{path}"
|
|
637
|
+
if key not in seen:
|
|
638
|
+
seen.add(key)
|
|
639
|
+
routes.append({
|
|
640
|
+
"method": method,
|
|
641
|
+
"path": path,
|
|
642
|
+
"handler": handler or "",
|
|
643
|
+
"file": rel_path,
|
|
644
|
+
"line": call.get("line_number", 0),
|
|
645
|
+
"framework": framework,
|
|
646
|
+
})
|
|
647
|
+
break
|
|
648
|
+
|
|
649
|
+
# Sort by path
|
|
650
|
+
routes.sort(key=lambda r: (r["path"], r["method"]))
|
|
651
|
+
logger.info("Detected %d API routes", len(routes))
|
|
652
|
+
|
|
653
|
+
# Angular Router (route tables + lazy-loaded modules), full paths
|
|
654
|
+
try:
|
|
655
|
+
from .angular_routes import extract_angular_routes
|
|
656
|
+
routes.extend(extract_angular_routes(parsed_results, repo_path))
|
|
657
|
+
except Exception as exc: # never let one framework break route extraction
|
|
658
|
+
logger.debug("Angular route extraction failed: %s", exc)
|
|
659
|
+
return routes
|