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.

feat(workspace): give Django, JAX-RS, Next.js and the Hono router DSL contracts (#1888)

Raghav Chamadiyaa3dd72031e58
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/django.py b/packages/core/src/repowise/core/ingestion/framework_edges/django.py
index db9668781..9e4deaa1d 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/django.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/django.py
@@ -1,6 +1,9 @@
"""Django convention edges.
-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.
+The same-directory ``urls``->``views`` guess is kept for the file pairs it was
+written for, and a URLconf that names its view module explicitly now also gets
+an edge to that module, read from ``ingestion.framework_routes`` — the same
+declaration the contract extractor reads for the route's path.
"""
from __future__ import annotations
@@ -8,11 +11,13 @@ from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from ..framework_routes import django_includes, django_routes
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
FrameworkHandler,
_add_edge_if_new,
+ read_text,
)
if TYPE_CHECKING:
@@ -56,6 +61,50 @@ def _add_django_edges(graph: nx.DiGraph, path_set: set[str]) -> int:
return count
+def _module_index(path_set: set[str]) -> dict[str, str]:
+ """Dotted module -> file, for every suffix a Django import could name.
+
+ A name claimed by two files is dropped rather than bound to whichever the
+ walk reached first.
+ """
+ seen: dict[str, str | None] = {}
+ for path in path_set:
+ if not path.endswith(".py"):
+ continue
+ parts = path.removesuffix("/__init__.py").removesuffix(".py").split("/")
+ for i in range(len(parts)):
+ module = ".".join(parts[i:])
+ seen[module] = None if module in seen and seen[module] != path else path
+ return {m: p for m, p in seen.items() if p is not None}
+
+
+def _add_urlconf_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], path_set: set[str]
+) -> int:
+ """``urls.py`` -> the view module and the sub-URLconf each entry names."""
+ count = 0
+ by_module = _module_index(path_set)
+ for path, parsed in parsed_files.items():
+ if not path.endswith("urls.py") or parsed.file_info.language != "python":
+ continue
+ text = read_text(parsed)
+ if not text:
+ continue
+ # The head of `views.detail` is a module path, not a declaring type:
+ # the module resolves to a file, the trailing segment is the view.
+ modules = [
+ route.handler.rpartition(".")[0]
+ for route in django_routes(text)
+ if route.handler and "." in route.handler
+ ]
+ modules += [module for _prefix, module in django_includes(text)]
+ for module in modules:
+ target = by_module.get(module)
+ if target and _add_edge_if_new(graph, path, target):
+ count += 1
+ return count
+
+
class _DjangoHandler:
def detect(self, dctx: DetectionContext) -> bool:
return "django" in dctx.stack_lower
@@ -67,7 +116,9 @@ class _DjangoHandler:
ctx: ResolverContext,
path_set: set[str],
) -> int:
- return _add_django_edges(graph, path_set)
+ return _add_django_edges(graph, path_set) + _add_urlconf_edges(
+ graph, parsed_files, path_set
+ )
HANDLERS: list[FrameworkHandler] = [_DjangoHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/express.py b/packages/core/src/repowise/core/ingestion/framework_edges/express.py
index 9fa69f9b5..546da17a5 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/express.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/express.py
@@ -8,7 +8,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
-from ..framework_routes import express_routes, match_paren
+from ..framework_routes import express_routes, js_router_bindings, match_paren
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -29,9 +29,6 @@ _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*\()"
-)
_STRING_LITERAL_RE = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`")
_ARG_IDENT_RE = re.compile(r"[A-Za-z_$][\w$]*")
@@ -78,7 +75,9 @@ def _add_express_edges(
for sym in parsed.symbols
if sym.kind in ("function", "method")
}
- receivers = {m.group(1) for m in _EXPRESS_RECEIVER_RE.finditer(text)}
+ receivers = {
+ var for var, fw in js_router_bindings(text).items() if fw == "express"
+ }
if local_funcs and receivers:
module_sym = f"{path}::__module__"
for route in express_routes(text):
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py b/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py
index d39a63b48..462711bc0 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py
@@ -18,9 +18,9 @@ subgraph the static parser can't see on its own.
from __future__ import annotations
-import re
from typing import TYPE_CHECKING, Any
+from ..framework_routes import next_app_router_file as _is_app_router_file
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -33,26 +33,6 @@ if TYPE_CHECKING:
import networkx as nx
-_APP_ROUTER_BASENAMES: frozenset[str] = frozenset({
- "page", "layout", "route", "middleware", "template", "default",
- "error", "loading", "not-found", "global-error", "forbidden",
- "unauthorized", "instrumentation",
-})
-_APP_ROUTER_EXTS: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", ".mjs")
-_APP_DIR_RE = re.compile(r"(?:^|/)app/")
-
-
-def _is_app_router_file(path: str) -> bool:
- if not _APP_DIR_RE.search(path):
- return False
- for ext in _APP_ROUTER_EXTS:
- if path.endswith(ext):
- stem = path.rsplit("/", 1)[-1][: -len(ext)]
- if stem in _APP_ROUTER_BASENAMES:
- return True
- return False
-
-
class _NextAppRouterHandler:
def detect(self, dctx: DetectionContext) -> bool:
if any("next" in tok for tok in dctx.stack_lower):
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index b3974c4b5..69ef208d2 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -145,6 +145,46 @@ _EXPRESS_ROUTE_RE = re.compile(
)
+# What binds a variable to a router object, per framework. Hono, Fastify, Koa
+# and Elysia all serve routes through Express's ``<var>.get('/path', handler)``
+# DSL, so ``express_routes`` already matches their call sites; only the binding
+# ever told them apart, and each consumer spelled that out for Express alone
+# (``_EXPRESS_RECEIVER_RE`` graph-side, ``_ROUTER_BIND_RE`` contract-side, with
+# different reach). One table, so a route is attributed to the framework that
+# serves it rather than to whichever recogniser claimed the variable first.
+_JS_ROUTER_CTORS: tuple[tuple[str, str], ...] = (
+ # express(), express.Router(), require('express').Router(), bare Router().
+ # The dotted prefix is `[\w$.]*` so a router built off a nested namespace
+ # (`services.http.Router()`) still binds, as it did before this table.
+ ("express", r"(?:[\w$.]*\s*\.\s*)?Router\s*\(|express\s*\("),
+ ("hono", r"new\s+Hono\s*[(<]"),
+ ("fastify", r"[Ff]astify\s*\("),
+ ("koa", r"new\s+[Kk]oa\s*\("),
+ ("elysia", r"new\s+Elysia\s*[(<]"),
+)
+
+_JS_ROUTER_BIND_RE = re.compile(
+ r"(?<![\w$])(?P<var>[\w$]+)\s*(?::[^=;\n]+)?=\s*(?:"
+ + "|".join(f"(?P<{name}>{alt})" for name, alt in _JS_ROUTER_CTORS)
+ + r")"
+)
+
+#: Names conventionally holding a router where no binding is in scope, because
+#: the framework instance is created in another file.
+JS_DEFAULT_ROUTER_NAMES = frozenset({"app", "router"})
+
+
+def js_router_bindings(content: str) -> dict[str, str]:
+ """Every variable bound to a router in *content*, mapped to its framework."""
+ out: dict[str, str] = {}
+ for m in _JS_ROUTER_BIND_RE.finditer(content):
+ for name, _alt in _JS_ROUTER_CTORS:
+ if m.group(name) is not None:
+ out[m.group("var")] = name
+ break
+ return out
+
+
def express_routes(content: str) -> Iterator[RouteMatch]:
"""Router/app route registrations in *content*.
@@ -169,7 +209,12 @@ def express_routes(content: str) -> Iterator[RouteMatch]:
def scan_code(
- text: str, start: int = 0, *, quotes: str = "\"'`", hash_comments: bool = False
+ text: str,
+ start: int = 0,
+ *,
+ quotes: str = "\"'`",
+ hash_comments: bool = False,
+ text_blocks: bool = False,
) -> Iterator[tuple[int, str, int]]:
"""``(index, char, paren_depth)`` over *text*, skipping strings and comments.
@@ -179,12 +224,18 @@ def scan_code(
*quotes* is what opens a string literal — Rust must pass ``'"'``, because its
``'`` is a lifetime. *hash_comments* adds PHP's ``#``, excluding the ``#[``
- of an attribute.
+ of an attribute. *text_blocks* adds Java's ``\"\"\"``, which pairwise quote
+ matching otherwise reads as an empty string followed by an unterminated one,
+ swallowing the rest of the file at the first quote inside the block.
"""
depth = 0
i, n = start, len(text)
while i < n:
c = text[i]
+ if text_blocks and text[i : i + 3] == '"""':
+ end = text.find('"""', i + 3)
+ i = n if end == -1 else end + 3
+ continue
if c in quotes:
i += 1
while i < n and text[i] != c:
@@ -378,3 +429,209 @@ def axum_routes(content: str) -> Iterator[RouteMatch]:
offset=head.start(),
paren_offset=head.start("paren"),
)
+
+
+# ---------------------------------------------------------------------------
+# Django — urls.py
+# ---------------------------------------------------------------------------
+
+# path("users/<int:pk>/", views.detail) / re_path(r"^users/$", View.as_view()) /
+# path("api/", include("api.urls")) — one call shape, split by the handler below.
+# A URLconf entry names no verb (the view chooses), so every match is `*`.
+_DJANGO_ENTRY_RE = re.compile(
+ r"(?<![\w.])(?P<verb>re_path|path|url)\s*(?P<paren>\()"
+ r"""\s*(?:r|rb|b)?(?P<q>['"])(?P<path>[^'"]*)(?P=q)\s*,\s*"""
+ r"(?P<handler>[\w.]+)\s*(?P<after>[,)(])"
+)
+
+_DJANGO_INCLUDE_ARG_RE = re.compile(
+ r"""\s*(?:(?P<q>['"])(?P<mod>[^'"]+)(?P=q)|(?P<expr>[\w.]+))"""
+)
+
+
+def _django_path(raw: str, verb: str) -> str:
+ """A URLconf pattern as a path.
+
+ Both spellings of a capture become ``{name}``: ``path()``'s
+ ``<converter:name>`` and ``re_path()``'s ``(?P<name>...)``, whose anchors go
+ with it. ``normalize_http_path`` reads neither, so a path left as written
+ would carry the converter into the contract id.
+ """
+ if verb == "path":
+ return re.sub(r"<(?:\w+:)?(\w+)>", r"{\1}", raw)
+ raw = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"{\1}", raw)
+ return raw.strip("^$")
+
+
+def django_routes(content: str) -> Iterator[RouteMatch]:
+ """URLconf entries in *content* that name a view.
+
+ ``verb`` is always ``*``; ``handler`` is the view expression as written. An
+ ``include(...)`` entry is not a route — see :func:`django_includes`.
+ """
+ for m in _DJANGO_ENTRY_RE.finditer(content):
+ handler = m.group("handler")
+ if handler == "include":
+ continue
+ yield RouteMatch(
+ verb="*",
+ path=_django_path(m.group("path"), m.group("verb")),
+ receiver=None,
+ handler=handler,
+ offset=m.start(),
+ paren_offset=m.start("paren"),
+ # `path("x/", login_required(view))` names a decorator, not the view.
+ handler_call=m.group("after") == "(",
+ )
+
+
+def django_includes(content: str) -> Iterator[tuple[str, str]]:
+ """``(prefix, module)`` per ``include(...)`` entry — dotted as written."""
+ for m in _DJANGO_ENTRY_RE.finditer(content):
+ if m.group("handler") != "include":
+ continue
+ arg = _DJANGO_INCLUDE_ARG_RE.match(content, m.end("after"))
+ module = (arg.group("mod") or arg.group("expr")) if arg else None
+ if module:
+ yield _django_path(m.group("path"), m.group("verb")), module
+
+
+# ---------------------------------------------------------------------------
+# JAX-RS — Jakarta EE, Quarkus, Jersey, RESTEasy, Dropwizard
+# ---------------------------------------------------------------------------
+
+# A JAX-RS route is two annotations: @GET names the verb, an optional @Path
+# names the sub-path, and the class's own @Path is the prefix. The graph side
+# recognised these as substrings only, to stamp a role; nothing read the paths.
+_JAXRS_VERBS = "GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS"
+
+# `@PathParam` is not a match: the `(` is required.
+_JAXRS_PATH_RE = re.compile(r"""@Path\s*\(\s*(?:value\s*=\s*)?["'](?P<path>[^"']*)["']""")
+
+_JAXRS_VERB_RE = re.compile(rf"@(?P<verb>{_JAXRS_VERBS})\b")
+
+_JAXRS_TYPE_RE = re.compile(
+ r"^[^\S\n]*(?:public|final|abstract|open|internal|sealed|data|\s)*"
+ r"(?:class|interface)\s+\w+",
+ re.MULTILINE,
+)
+
+
+def _jaxrs_decl_end(content: str, start: int) -> int:
+ """End of the declaration annotated at *start* — its ``{`` or ``;``.
+
+ Scanned rather than matched: an annotation run carries parens of its own
+ (``@Produces(MediaType.APPLICATION_JSON)``) and swagger nests them several
+ deep, so anything that stops at the first paren stops inside the run.
+ """
+ for i, c, depth in scan_code(content, start, quotes='"', text_blocks=True):
+ if depth == 0 and c in ";{":
+ return i
+ return len(content)
+
+
+def jaxrs_class_paths(content: str) -> list[tuple[int, str]]:
+ """``(offset, prefix)`` per type-level ``@Path``, ascending.
+
+ A class and its methods share the annotation, so the only thing separating a
+ prefix from a sub-path is which declaration the annotation run reaches.
+ """
+ types = [m.start() for m in _JAXRS_TYPE_RE.finditer(content)]
+ out: list[tuple[int, str]] = []
+ for m in _JAXRS_PATH_RE.finditer(content):
+ end = _jaxrs_decl_end(content, m.start())
+ if any(m.start() < t < end for t in types):
+ out.append((m.start(), m.group("path").rstrip("/")))
+ return out
+
+
+def jaxrs_routes(content: str) -> Iterator[RouteMatch]:
+ """Verb-annotated resource methods in *content*.
+
+ ``path`` is the method's own ``@Path`` or ``""``; the class prefix is
+ stitched on by the consumer, the only side that knows how to compose one.
+ """
+ for m in _JAXRS_VERB_RE.finditer(content):
+ end = _jaxrs_decl_end(content, m.start())
+ sub = _JAXRS_PATH_RE.search(content, m.end(), end)
+ yield RouteMatch(
+ verb=m.group("verb").upper(),
+ path=sub.group("path") if sub else "",
+ receiver=None,
+ handler=None,
+ offset=m.start(),
+ paren_offset=m.start(),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Next.js App Router
+# ---------------------------------------------------------------------------
+
+#: App Router files loaded by filesystem convention rather than by import.
+NEXT_APP_ROUTER_BASENAMES: frozenset[str] = frozenset({
+ "page", "layout", "route", "middleware", "template", "default",
+ "error", "loading", "not-found", "global-error", "forbidden",
+ "unauthorized", "instrumentation",
+})
+NEXT_APP_ROUTER_EXTS: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", ".mjs")
+
+_NEXT_APP_DIR_RE = re.compile(r"(?:^|/)app/")
+
+# Segments naming no URL segment: route group `(marketing)`, parallel route
+# `@modal`, private folder `_lib`.
+_NEXT_INERT_SEG_RE = re.compile(r"\(.*\)|@.*|_.*")
+
+# `[id]`, `[...slug]`, `[[...slug]]` -> `{id}` / `{slug}`.
+_NEXT_DYNAMIC_SEG_RE = re.compile(r"^\[+\.{0,3}(?P<name>[^\]]+)\]+$")
+
+# The App Router takes the verb from the exported name and the path from the
+# file's location, so a route handler's text holds no path literal at all.
+_NEXT_HANDLER_RE = re.compile(
+ r"export\s+(?:async\s+)?(?:function\s+|const\s+|let\s+|var\s+)"
+ r"(?P<verb>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b"
+)
+
+
+def next_app_router_file(rel_path: str) -> bool:
+ """True when *rel_path* is loaded by App Router filesystem convention."""
+ if not _NEXT_APP_DIR_RE.search(rel_path):
+ return False
+ name = rel_path.rsplit("/", 1)[-1]
+ for ext in NEXT_APP_ROUTER_EXTS:
+ if name.endswith(ext) and name[: -len(ext)] in NEXT_APP_ROUTER_BASENAMES:
+ return True
+ return False
+
+
+def next_route_path(rel_path: str) -> str | None:
+ """The URL an ``app/**/route.ts`` handler serves, else None.
+
+ Only ``route.*`` is an endpoint; ``page``/``layout`` and the rest render UI
+ and publish no API surface.
+ """
+ if not next_app_router_file(rel_path):
+ return None
+ parts = rel_path.split("/")
+ if parts[-1].rsplit(".", 1)[0] != "route":
+ return None
+ app_at = len(parts) - 2 - parts[-2::-1].index("app") # the nearest `app/`
+ segments: list[str] = []
+ for seg in parts[app_at + 1 : -1]:
+ if _NEXT_INERT_SEG_RE.fullmatch(seg):
+ continue
+ dyn = _NEXT_DYNAMIC_SEG_RE.match(seg)
+ segments.append("{" + dyn.group("name") + "}" if dyn else seg)
+ return "/" + "/".join(segments)
+
+
+def next_route_verbs(content: str) -> list[tuple[str, int]]:
+ """``(verb, offset)`` per exported handler, in declaration order."""
+ out: list[tuple[str, int]] = []
+ seen: set[str] = set()
+ for m in _NEXT_HANDLER_RE.finditer(content):
+ verb = m.group("verb")
+ if verb not in seen:
+ seen.add(verb)
+ out.append((verb, m.start("verb")))
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
index 111c812b2..49515ba92 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -17,12 +17,15 @@ from ..langs import PYTHON
from .aspnet import AspNetDialect
from .csharp_http import CSharpHttpDialect
from .dialect import HttpDialect
+from .django import DjangoDialect
from .express import ExpressDialect
from .fastapi import FastApiDialect
from .go import GoDialect
+from .jaxrs import JaxRsDialect
from .js_clients import JsClientsDialect
from .laravel import LaravelDialect
from .mounts import merge_mount_maps
+from .next_app import NextAppDialect
from .paths import normalize_http_path
from .python_clients import PythonClientsDialect
from .rust_axum import RustAxumDialect
@@ -47,6 +50,9 @@ PROVIDER_DIALECTS: tuple[HttpDialect, ...] = (
GoDialect(),
AspNetDialect(),
RustAxumDialect(),
+ DjangoDialect(),
+ JaxRsDialect(),
+ NextAppDialect(),
)
# HTTP-client call recognisers (one client/language each).
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/django.py b/packages/core/src/repowise/core/workspace/extractors/http/django.py
new file mode 100644
index 000000000..4085dde62
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/django.py
@@ -0,0 +1,82 @@
+"""Django HTTP provider dialect — ``urls.py`` URLconf entries.
+
+The entry is recognised by ``ingestion.framework_routes``, shared with the
+graph-edge builder that reads the same entry for its view expression.
+
+A URLconf names no method, so every route is recorded as ``*`` (as the Go
+dialect does for ``HandleFunc``). Prefixes come from ``include(...)`` in another
+URLconf, resolved through the orchestrator's repo-wide mount map.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import django_includes, django_routes
+
+from ..base import line_at
+from ..langs import PYTHON
+from .dialect import build_provider_contract
+from .mounts import compose_prefix
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+# Namespaced so a dotted module cannot collide with another dialect's router
+# variable in the one mount map they share.
+_MOUNT_PREFIX = "django:"
+
+# `path`/`url`/`re_path` are ordinary names, so the file has to prove they are
+# Django's before its calls become endpoints. Not a `urls.py` filename gate:
+# `ModelAdmin.get_urls` builds a real URLconf from `options.py`, and Django's
+# own admin publishes most of its surface that way.
+_DJANGO_URLS_IMPORT = ("django.urls", "django.conf.urls")
+
+
+def _module_suffixes(rel_path: str) -> list[str]:
+ """Dotted modules ``rel_path`` could be imported as, longest first.
+
+ ``include()`` names a module relative to whichever directory is on the path,
+ which is not always the repo root, so the match is by suffix.
+ """
+ parts = rel_path.removesuffix(".py").split("/")
+ return [".".join(parts[i:]) for i in range(len(parts))]
+
+
+class DjangoDialect:
+ name = "django"
+ extensions = PYTHON
+
+ def collect_mounts(self, content: str) -> dict[str, str]:
+ """``include("api.urls")`` mounts declared in *content*, keyed by module."""
+ if not any(mod in content for mod in _DJANGO_URLS_IMPORT):
+ return {}
+ return {_MOUNT_PREFIX + module: prefix for prefix, module in django_includes(content)}
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ if not any(mod in ctx.content for mod in _DJANGO_URLS_IMPORT):
+ return []
+ mount = next(
+ (
+ p
+ for m in _module_suffixes(ctx.rel_path)
+ if (p := ctx.mounts.get(_MOUNT_PREFIX + m)) is not None
+ ),
+ "",
+ )
+ out: list[Contract] = []
+ for route in django_routes(ctx.content):
+ c = build_provider_contract(
+ ctx,
+ method="*",
+ path_raw=compose_prefix(mount, route.path or ""),
+ framework="django",
+ line=line_at(ctx.content, route.offset),
+ # `login_required(view)` names the decorator, not the view.
+ handler=None if route.handler_call else route.handler,
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/express.py b/packages/core/src/repowise/core/workspace/extractors/http/express.py
index 1db964ea3..04e26c8ba 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/express.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/express.py
@@ -1,11 +1,15 @@
-"""Express / Node.js HTTP provider dialect — ``router.get('/path', ...)``.
+"""Node router-DSL HTTP provider dialect — ``router.get('/path', ...)``.
-Express routers carry no in-file prefix; the mount lives in a separate
+Express, Hono, Fastify, Koa and Elysia all serve routes through this one call
+shape, and only the variable's binding says which is which. The contract is
+labelled from that binding rather than assumed to be Express.
+
+Routers carry no in-file prefix; the mount lives in a separate
``app.use('/prefix', router)`` call, so the real path is recovered by stitching
the cross-file mount prefix (collected by the orchestrator) onto the route.
-The route call itself is recognised by ``ingestion.framework_routes``, shared
-with the graph-edge builder that scans the same call's argument list.
+The route call and the bindings both come from ``ingestion.framework_routes``,
+shared with the graph-edge builders that scan the same call's argument list.
"""
from __future__ import annotations
@@ -13,7 +17,12 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
-from repowise.core.ingestion.framework_routes import HTTP_METHODS, express_routes
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ JS_DEFAULT_ROUTER_NAMES,
+ express_routes,
+ js_router_bindings,
+)
from ..base import line_at
from ..langs import JS_TS
@@ -25,15 +34,9 @@ if TYPE_CHECKING:
from ..base import ScanContext
-# Variables bound to an Express app / router: ``r = express.Router()``,
-# ``app = express()``, ``router = require('express').Router()``.
-_ROUTER_BIND_RE = re.compile(r"""(\w+)\s*=\s*(?:[\w.]*\.Router\s*\(|express\s*\(|Router\s*\()""")
-
# app.use('/prefix', router) — a cross-file (or in-file) router mount.
_APP_USE_RE = re.compile(r"""\.use\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\w.]+)""")
-_DEFAULT_ROUTER_NAMES = frozenset({"app", "router"})
-
class ExpressDialect:
name = "express"
@@ -47,8 +50,12 @@ class ExpressDialect:
return out
def extract(self, ctx: ScanContext) -> list[Contract]:
- known = {m.group(1) for m in _ROUTER_BIND_RE.finditer(ctx.content)}
- known |= _DEFAULT_ROUTER_NAMES
+ bindings = js_router_bindings(ctx.content)
+ # `app`/`router` are routers whose constructor is in another file, so
+ # they take the file's framework when it binds exactly one, and Express
+ # otherwise — which is what they were always labelled.
+ served = set(bindings.values())
+ default = served.pop() if len(served) == 1 else "express"
out: list[Contract] = []
for route in express_routes(ctx.content):
@@ -56,13 +63,17 @@ class ExpressDialect:
# scans for handlers but which name no HTTP method here.
if route.verb not in HTTP_METHODS or not route.path:
continue
- if route.receiver not in known:
+ if route.receiver in bindings:
+ framework = bindings[route.receiver]
+ elif route.receiver in JS_DEFAULT_ROUTER_NAMES:
+ framework = default
+ else:
continue
c = build_provider_contract(
ctx,
method=route.verb,
path_raw=compose_prefix(ctx.mounts.get(route.receiver, ""), route.path),
- framework="express",
+ framework=framework,
line=line_at(ctx.content, route.offset),
)
if c is not None:
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/jaxrs.py b/packages/core/src/repowise/core/workspace/extractors/http/jaxrs.py
new file mode 100644
index 000000000..090cb7407
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/jaxrs.py
@@ -0,0 +1,55 @@
+"""JAX-RS HTTP provider dialect — Jakarta EE, Quarkus, Jersey, RESTEasy.
+
+``@GET`` names the verb, the method's own ``@Path`` names the sub-path, and the
+nearest type-level ``@Path`` above it is the prefix — the same two-level shape
+the Spring dialect stitches, with the annotations split apart.
+
+The annotations are recognised by ``ingestion.framework_routes``, shared with
+the graph-edge builder that reads them to stamp a ``jax_rs_resource`` role.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ jaxrs_class_paths,
+ jaxrs_routes,
+)
+
+from ..base import line_at
+from ..langs import JAVA, KOTLIN
+from .dialect import build_provider_contract, nearest_prefix
+from .mounts import compose_prefix
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+
+class JaxRsDialect:
+ name = "jaxrs"
+ extensions = JAVA | KOTLIN
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
+ if "@Path" not in content:
+ return []
+ class_paths = jaxrs_class_paths(content)
+ out: list[Contract] = []
+ for route in jaxrs_routes(content):
+ if route.verb not in HTTP_METHODS:
+ continue
+ path = compose_prefix(nearest_prefix(class_paths, route.offset), route.path or "")
+ c = build_provider_contract(
+ ctx,
+ method=route.verb,
+ path_raw=path,
+ framework="jaxrs",
+ line=line_at(content, route.offset),
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/next_app.py b/packages/core/src/repowise/core/workspace/extractors/http/next_app.py
new file mode 100644
index 000000000..9f3c2cabe
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/next_app.py
@@ -0,0 +1,54 @@
+"""Next.js App Router HTTP provider dialect — ``app/**/route.ts``.
+
+Unique among the dialects here in reading no route call at all: the App Router
+takes the path from the file's own location and the verb from the name of each
+exported handler, so both halves come from outside the source text. Both are
+derived by ``ingestion.framework_routes``, shared with the graph-edge builder
+that uses the same convention test to find files loaded without an import.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ next_route_path,
+ next_route_verbs,
+)
+
+from ..base import line_at
+from ..langs import JS_TS
+from .dialect import build_provider_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+
+class NextAppDialect:
+ name = "next-app"
+ extensions = JS_TS
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ path = next_route_path(ctx.rel_path)
+ if path is None:
+ return []
+ out: list[Contract] = []
+ for verb, offset in next_route_verbs(ctx.content):
+ if verb not in HTTP_METHODS:
+ continue
+ # Bound by line, not by `handler=verb`: every route handler in the
+ # repo exports the same few names, so a repo-wide lookup by name
+ # would bind to whichever one it reached first.
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=path,
+ framework="next-app",
+ line=line_at(ctx.content, offset),
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.py
index 18e92ce6e..34bb0b4a1 100644
--- a/tests/unit/test_no_bare_type_name_copies.py
+++ b/tests/unit/test_no_bare_type_name_copies.py
@@ -86,6 +86,10 @@ _KNOWN: dict[str, int] = {
_PREFIX + "dynamic_hints/swift.py": 1,
# Splits an import statement's package path, not a type reference.
_PREFIX + "languages/jvm_same_package.py": 1,
+ # Takes the head of a URLconf's `views.detail` to reach the Python module
+ # declaring the view. The trailing segment is the view function and the
+ # head is a module path, so neither end is a type.
+ _PREFIX + "framework_edges/django.py": 1,
# Split a route handler's path to reach a function name, and keep the
# prefix to resolve the package it came from. Neither wants a type.
_PREFIX + "framework_edges/rust.py": 1,
diff --git a/tests/unit/workspace/test_framework_dialects.py b/tests/unit/workspace/test_framework_dialects.py
new file mode 100644
index 000000000..8d805c223
--- /dev/null
+++ b/tests/unit/workspace/test_framework_dialects.py
@@ -0,0 +1,459 @@
+"""Provider dialects for the frameworks the graph layer already recognised.
+
+Django, JAX-RS, the Next.js App Router and the Hono/Fastify/Koa router DSL had
+graph edges and no contract, so cross-repo links, breaking-change detection and
+schema recovery had nothing to attach to on a repo built with any of them. The
+claims under test are that each now produces a contract with the path its
+framework actually serves, that the two consumers read one declaration, and that
+the shapes only a real repo carries -- an ``include()`` prefix, a class-level
+``@Path`` under a dotted annotation, a route group, a Hono app -- are handled.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.framework_routes import (
+ django_includes,
+ django_routes,
+ jaxrs_class_paths,
+ jaxrs_routes,
+ js_router_bindings,
+ next_route_path,
+ next_route_verbs,
+)
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.workspace.contracts import bind_symbol_ids
+from repowise.core.workspace.extractors.http_extractor import HttpExtractor
+
+from ._repo_index import make_repo_index
+
+ROOT_URLS_PY = """\
+from django.urls import include, path, re_path
+from . import views
+from myapp.views import DetailView
+
+urlpatterns = [
+ path("healthz/", views.healthz),
+ path("orders/<int:pk>/", DetailView.as_view()),
+ re_path(r"^legacy/(?P<slug>[\\w-]+)/$", views.legacy),
+ path("api/", include("myapp.urls")),
+]
+"""
+
+APP_URLS_PY = """\
+from django.urls import path
+from . import views
+
+urlpatterns = [
+ path("items/", views.items),
+]
+"""
+
+VIEWS_PY = """\
+def healthz(request):
+ return None
+
+
+def items(request):
+ return None
+
+
+def legacy(request, slug):
+ return None
+"""
+
+ACCOUNT_RESOURCE_JAVA = """\
+package com.acme;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+
+@Path("/v2/accounts")
[email protected](name = "Account")
+public class AccountResource {
+
+ @GET
+ @Path("/data_report")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Report getReport() {
+ return null;
+ }
+
+ @PUT
+ @Path("/{id}/number")
+ public Response changeNumber(@PathParam("id") String id) {
+ return null;
+ }
+
+ @GET
+ public Response list() {
+ return null;
+ }
+}
+"""
+
+HONO_APP_TS = """\
+import { Hono } from 'hono';
+import { listUsers } from './handlers';
+
+const api = new Hono();
+api.get('/users', listUsers);
+api.post('/users', listUsers);
+
+const legacy = express.Router();
+legacy.get('/ping', listUsers);
+"""
+
+NEXT_ROUTE_TS = """\
+export async function GET(request: Request) {
+ return Response.json({});
+}
+
+export async function POST(request: Request) {
+ return Response.json({});
+}
+"""
+
+
+def _providers(repo: Path, alias: str = "api") -> dict[str, Any]:
+ return {
+ c.contract_id: c
+ for c in HttpExtractor().extract(repo, alias)
+ if c.role == "provider"
+ }
+
+
+# ---------------------------------------------------------------------------
+# Django
+# ---------------------------------------------------------------------------
+
+
+class TestDjangoRecognition:
+ def test_every_urlconf_shape_is_read(self) -> None:
+ routes = [(r.verb, r.path, r.handler) for r in django_routes(ROOT_URLS_PY)]
+ assert routes == [
+ ("*", "healthz/", "views.healthz"),
+ ("*", "orders/{pk}/", "DetailView.as_view"),
+ ("*", "legacy/{slug}/", "views.legacy"),
+ ]
+
+ def test_an_include_is_not_a_route(self) -> None:
+ assert list(django_includes(ROOT_URLS_PY)) == [("api/", "myapp.urls")]
+
+ def test_a_wrapped_view_is_marked_as_a_call(self) -> None:
+ # `DetailView.as_view()` is invoked, so the contract must not bind to it.
+ (wrapped,) = [r for r in django_routes(ROOT_URLS_PY) if r.path.startswith("orders")]
+ assert wrapped.handler_call is True
+
+ def test_a_dotted_attribute_is_not_a_urlconf_entry(self) -> None:
+ assert not list(django_routes('shutil.path("x", y)'))
+
+
+class TestDjangoContracts:
+ def _extract(self, tmp_path: Path) -> dict[str, Any]:
+ (tmp_path / "urls.py").write_text(ROOT_URLS_PY, encoding="utf-8")
+ (tmp_path / "myapp").mkdir()
+ (tmp_path / "myapp" / "urls.py").write_text(APP_URLS_PY, encoding="utf-8")
+ (tmp_path / "myapp" / "views.py").write_text(VIEWS_PY, encoding="utf-8")
+ return _providers(tmp_path)
+
+ def test_a_urlconf_entry_becomes_a_verbless_contract(self, tmp_path: Path) -> None:
+ ids = self._extract(tmp_path)
+ assert "http::*::/healthz" in ids
+ assert ids["http::*::/healthz"].meta["framework"] == "django"
+
+ def test_a_converter_and_a_named_group_normalize_alike(self, tmp_path: Path) -> None:
+ ids = set(self._extract(tmp_path))
+ assert "http::*::/orders/{param}" in ids
+ assert "http::*::/legacy/{param}" in ids
+
+ def test_an_include_prefix_reaches_the_included_urlconf(self, tmp_path: Path) -> None:
+ # Without the mount this was "/items", which matches nothing a client calls.
+ assert "http::*::/api/items" in self._extract(tmp_path)
+
+ def test_a_path_call_outside_django_is_not_an_endpoint(self, tmp_path: Path) -> None:
+ # `path` is an ordinary name, and the dialect reads every .py file, so
+ # without the import gate any repo with a helper of that shape gained
+ # fabricated endpoints.
+ (tmp_path / "router.py").write_text(
+ 'def path(p, h): ...\n\nroutes = [path("admin/", handlers.admin)]\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_urlconf_away_from_urls_py_is_still_read(self, tmp_path: Path) -> None:
+ # Django's own admin publishes most of its surface from `get_urls()` in
+ # options.py, so the gate is the import and not the filename.
+ (tmp_path / "options.py").write_text(
+ "from django.urls import path\n\n"
+ "def get_urls():\n return [path('add/', self.add_view)]\n",
+ encoding="utf-8",
+ )
+ assert "http::*::/add" in _providers(tmp_path)
+
+ def test_a_wrapped_view_records_no_handler(self, tmp_path: Path) -> None:
+ contracts = self._extract(tmp_path)
+ assert contracts["http::*::/healthz"].meta["handler"] == "views.healthz"
+ assert "handler" not in contracts["http::*::/orders/{param}"].meta
+
+
+class TestDjangoGraphConsumer:
+ def test_a_urlconf_links_to_the_module_it_names(self, tmp_path: Path) -> None:
+ (tmp_path / "urls.py").write_text(ROOT_URLS_PY, encoding="utf-8")
+ (tmp_path / "myapp").mkdir()
+ (tmp_path / "myapp" / "urls.py").write_text(APP_URLS_PY, encoding="utf-8")
+ (tmp_path / "myapp" / "views.py").write_text(VIEWS_PY, encoding="utf-8")
+ graph = _graph(tmp_path, "*.py", "python", ["django"])
+ # The same declaration the contracts above came from: the include's
+ # module and the view module the entries name.
+ assert graph.has_edge("urls.py", "myapp/urls.py")
+ assert graph.has_edge("myapp/urls.py", "myapp/views.py")
+
+
+# ---------------------------------------------------------------------------
+# JAX-RS
+# ---------------------------------------------------------------------------
+
+
+class TestJaxRsRecognition:
+ def test_the_class_path_is_told_from_the_method_paths(self) -> None:
+ # A dotted annotation sits between the two, and every @Path here uses the
+ # same syntax, so only the declaration each one reaches separates them.
+ assert [p for _off, p in jaxrs_class_paths(ACCOUNT_RESOURCE_JAVA)] == ["/v2/accounts"]
+
+ def test_each_verb_carries_its_own_sub_path(self) -> None:
+ assert [(r.verb, r.path) for r in jaxrs_routes(ACCOUNT_RESOURCE_JAVA)] == [
+ ("GET", "/data_report"),
+ ("PUT", "/{id}/number"),
+ ("GET", ""),
+ ]
+
+ def test_an_annotation_carrying_braces_does_not_end_the_run(self) -> None:
+ # `@Produces({...})` puts a brace between @GET and its @Path. Only the
+ # paren-depth check keeps the run open across it; a scan for the next
+ # bare `{` stops here and reads no path at all.
+ source = (
+ "@Path(\"/v1\")\npublic class R {\n"
+ ' @GET\n @Produces({"application/json", "text/plain"})\n'
+ ' @Path("/report")\n public Report r() { return null; }\n}\n'
+ )
+ assert [(r.verb, r.path) for r in jaxrs_routes(source)] == [("GET", "/report")]
+
+ def test_a_text_block_does_not_swallow_the_rest_of_the_file(self) -> None:
+ # A Java text block holding an odd number of quotes: pairwise quote
+ # matching reads the opening `\"\"\"` as an empty string plus an
+ # unterminated one, and every later route is lost inside it.
+ source = (
+ "@Path(\"/v1\")\npublic class R {\n"
+ ' @GET\n @Operation(description = """\n'
+ 'He said "gotcha then { boom } ; done\n""")\n'
+ ' @Path("/first")\n public R a() { return null; }\n'
+ ' @POST\n @Path("/second")\n public R b() { return null; }\n}\n'
+ )
+ assert [(r.verb, r.path) for r in jaxrs_routes(source)] == [
+ ("GET", "/first"),
+ ("POST", "/second"),
+ ]
+ assert [p for _off, p in jaxrs_class_paths(source)] == ["/v1"]
+
+ def test_a_method_path_is_not_read_as_the_class_prefix(self) -> None:
+ # Both are spelled `@Path`; only the declaration each one reaches apart.
+ source = (
+ "@Path(\"/v1\")\npublic class R {\n"
+ ' @GET\n @Path("/inner")\n public R a() { return null; }\n}\n'
+ )
+ assert [p for _off, p in jaxrs_class_paths(source)] == ["/v1"]
+
+
+class TestJaxRsContracts:
+ def _extract(self, tmp_path: Path) -> dict[str, Any]:
+ (tmp_path / "AccountResource.java").write_text(
+ ACCOUNT_RESOURCE_JAVA, encoding="utf-8"
+ )
+ return _providers(tmp_path)
+
+ def test_the_class_prefix_is_stitched_onto_each_method(self, tmp_path: Path) -> None:
+ ids = self._extract(tmp_path)
+ assert "http::GET::/v2/accounts/data_report" in ids
+ assert "http::PUT::/v2/accounts/{param}/number" in ids
+ assert ids["http::GET::/v2/accounts/data_report"].meta["framework"] == "jaxrs"
+
+ def test_a_verb_with_no_sub_path_serves_the_class_path(self, tmp_path: Path) -> None:
+ assert "http::GET::/v2/accounts" in self._extract(tmp_path)
+
+
+# ---------------------------------------------------------------------------
+# Next.js App Router
+# ---------------------------------------------------------------------------
+
+
+class TestNextAppRecognition:
+ def test_the_path_comes_from_the_file_location(self) -> None:
+ assert next_route_path("app/api/posts/route.ts") == "/api/posts"
+ assert next_route_path("src/app/api/users/[id]/route.tsx") == "/api/users/{id}"
+
+ def test_inert_segments_name_no_url_segment(self) -> None:
+ assert (
+ next_route_path("app/(marketing)/api/@modal/_lib/v1/[...slug]/route.ts")
+ == "/api/v1/{slug}"
+ )
+
+ def test_only_route_files_are_endpoints(self) -> None:
+ # `page`/`layout` are App Router files but publish no API surface.
+ assert next_route_path("app/api/posts/page.tsx") is None
+ assert next_route_path("pages/api/posts.ts") is None
+
+ def test_the_verb_comes_from_the_exported_name(self) -> None:
+ verbs = [v for v, _off in next_route_verbs(NEXT_ROUTE_TS)]
+ assert verbs == ["GET", "POST"]
+
+
+class TestNextAppContracts:
+ def test_one_file_yields_one_contract_per_exported_verb(self, tmp_path: Path) -> None:
+ route = tmp_path / "app" / "api" / "posts"
+ route.mkdir(parents=True)
+ (route / "route.ts").write_text(NEXT_ROUTE_TS, encoding="utf-8")
+ ids = _providers(tmp_path)
+ assert set(ids) == {"http::GET::/api/posts", "http::POST::/api/posts"}
+ assert ids["http::GET::/api/posts"].meta["framework"] == "next-app"
+
+ async def test_each_verb_binds_to_its_own_export(self, tmp_path: Path) -> None:
+ # Every route handler in a Next repo exports the same few names, so the
+ # binding has to be by line rather than by a repo-wide lookup on "GET".
+ route = tmp_path / "app" / "api" / "posts"
+ route.mkdir(parents=True)
+ (route / "route.ts").write_text(NEXT_ROUTE_TS, encoding="utf-8")
+ contracts = [c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"]
+ index = await _index_of(tmp_path, "*.ts", "typescript")
+ try:
+ expected = {
+ s.name: s.symbol_id
+ for s in index.symbols_for_file("app/api/posts/route.ts")
+ }
+ bind_symbol_ids(contracts, index)
+ finally:
+ await index.close()
+ bound = {c.contract_id: c.symbol_id for c in contracts}
+ assert bound["http::GET::/api/posts"] == expected["GET"]
+ assert bound["http::POST::/api/posts"] == expected["POST"]
+
+
+# ---------------------------------------------------------------------------
+# Hono / Fastify / Koa — the router DSL Express shares
+# ---------------------------------------------------------------------------
+
+
+class TestRouterBindings:
+ def test_each_constructor_names_its_framework(self) -> None:
+ assert js_router_bindings(HONO_APP_TS) == {"api": "hono", "legacy": "express"}
+
+ def test_every_supported_constructor_is_recognised(self) -> None:
+ source = (
+ "const a = new Hono();\n"
+ "const b = Fastify({ logger: true });\n"
+ "const c = new Koa();\n"
+ "const d = new Elysia();\n"
+ "const e = express();\n"
+ "const f: Router = express.Router();\n"
+ )
+ assert js_router_bindings(source) == {
+ "a": "hono", "b": "fastify", "c": "koa",
+ "d": "elysia", "e": "express", "f": "express",
+ }
+
+
+class TestRouterDslContracts:
+ def test_a_hono_route_is_labelled_hono_not_express(self, tmp_path: Path) -> None:
+ # `const api = new Hono()` was invisible: the contract layer only knew
+ # Express bindings, so a route on any name but `app`/`router` was dropped.
+ (tmp_path / "server.ts").write_text(HONO_APP_TS, encoding="utf-8")
+ ids = _providers(tmp_path)
+ assert ids["http::GET::/users"].meta["framework"] == "hono"
+ assert ids["http::GET::/ping"].meta["framework"] == "express"
+
+ def test_a_conventional_name_takes_the_file_s_framework(self, tmp_path: Path) -> None:
+ (tmp_path / "server.ts").write_text(
+ "import { Hono } from 'hono';\n"
+ "const other = new Hono();\n"
+ "app.get('/health', h);\n",
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path)["http::GET::/health"].meta["framework"] == "hono"
+
+ def test_an_express_repo_is_unchanged(self, tmp_path: Path) -> None:
+ (tmp_path / "server.js").write_text(
+ "const router = express.Router();\nrouter.get('/api/users', auth, list);\n",
+ encoding="utf-8",
+ )
+ ids = _providers(tmp_path)
+ assert ids["http::GET::/api/users"].meta["framework"] == "express"
+
+ def test_a_nested_namespace_constructor_still_binds(self, tmp_path: Path) -> None:
+ # The regex this table replaced took any dotted prefix; a one-segment
+ # prefix would have dropped these routes outright.
+ (tmp_path / "server.js").write_text(
+ "const r = services.http.Router();\nr.get('/deep', h);\n", encoding="utf-8"
+ )
+ assert _providers(tmp_path)["http::GET::/deep"].meta["framework"] == "express"
+
+
+# ---------------------------------------------------------------------------
+# Fixtures built from real parser output, never hand-written ids
+# ---------------------------------------------------------------------------
+
+
+def _parse_repo(repo: Path, glob: str, language: str) -> dict[str, Any]:
+ parser = ASTParser()
+ out: dict[str, Any] = {}
+ for src in repo.rglob(glob):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(src.resolve()),
+ language=language,
+ size_bytes=src.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _graph(repo: Path, glob: str, language: str, stack: list[str]) -> nx.DiGraph:
+ parsed = _parse_repo(repo, glob, language)
+ graph = nx.DiGraph()
+ for path in parsed:
+ graph.add_node(path)
+ ctx = ResolverContext(
+ path_set=set(parsed),
+ stem_map={Path(p).stem.lower(): [p] for p in parsed},
+ graph=graph,
+ repo_path=repo,
+ )
+ add_framework_edges(graph, parsed, ctx, stack)
+ return graph
+
+
+async def _index_of(repo: Path, glob: str, language: str) -> Any:
+ """An index over the rows real ingestion produces, so no id is guessed."""
+ parsed = _parse_repo(repo, glob, language)
+ by_file: dict[str, list[Any]] = {}
+ for rel, pf in parsed.items():
+ for sym in pf.symbols:
+ sym.file_path = rel
+ by_file[rel] = list(pf.symbols)
+ return await make_repo_index(repo, by_file, alias="api")