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(apex): Apex REST resources and HTTP callouts as workspace contracts (#4407)

Raghav Chamadiya99b04a7a9c54
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index e625c67f5..7c119c057 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -970,6 +970,12 @@ declared names keep their written case. CumulusCI `%%%NAMESPACE%%%` tokens are
blanked byte for byte before parsing. Apex has no import statement, so
cross-file calls resolve only through the repository-wide tiers.
+A `@RestResource` class's `@Http*` methods are HTTP providers at
+`/services/apexrest` plus its `urlMapping`, and are entry points in the graph.
+An `HttpRequest` callout is a consumer when its endpoint and verb are literal
+within one method; `callout:Name` keeps the Named Credential as the base. The
+credential's own endpoint is not read.
+
### QML
Module specs resolve against an index built from the `qmldir` manifests in the
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 021afc7bd..211ac599e 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -144,6 +144,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| C# | ASP.NET (attribute and minimal API) | HttpClient, UnityWebRequest, Best.HTTP |
| Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |
| Rust | Axum, Actix, Rocket | reqwest |
+| Apex | `@RestResource` classes (`/services/apexrest` + `urlMapping`) | `HttpRequest` callouts (literal endpoint and verb) |
| Any | OpenAPI 3.x documents | |
**Database tables:**
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index cc908f099..e7dde83e5 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -23,6 +23,7 @@ from . import (
alembic_runner,
android_manifest,
angular,
+ apex_rest,
aspnet,
aura,
aws_lambda,
@@ -79,6 +80,7 @@ _HANDLERS: list[FrameworkHandler] = [
*laravel.HANDLERS,
*spring.HANDLERS,
*jakarta.HANDLERS,
+ *apex_rest.HANDLERS,
*quarkus.HANDLERS,
*micronaut.HANDLERS,
*android_manifest.HANDLERS,
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/apex_rest.py b/packages/core/src/repowise/core/ingestion/framework_edges/apex_rest.py
new file mode 100644
index 000000000..576044de9
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/apex_rest.py
@@ -0,0 +1,47 @@
+"""Salesforce Apex REST route handlers.
+
+The platform calls a ``@RestResource`` class's ``@Http*`` methods, so each one
+is bound from its file's module symbol, as Spring binds a ``@GetMapping`` method.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from ..framework_routes import apex_rest_routes
+from .base import DetectionContext, FrameworkHandler, add_symbol_edge, source_text
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers import ResolverContext
+
+
+class _ApexRestHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ return any(p.file_info.language == "apex" for p in dctx.parsed_files.values())
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ count = 0
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "apex":
+ continue
+ text = source_text(path, parsed, ctx.source_map or {})
+ methods = [s for s in parsed.symbols if s.kind == "method"]
+ for route in apex_rest_routes(text):
+ line = text.count("\n", 0, route.offset) + 1
+ # An Apex method's span starts at its annotations.
+ holders = [s for s in methods if s.start_line <= line <= s.end_line]
+ if holders:
+ handler = max(holders, key=lambda s: s.start_line)
+ count += add_symbol_edge(graph, f"{path}::__module__", handler.id)
+ return count
+
+
+HANDLERS: list[FrameworkHandler] = [_ApexRestHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index 1d6198cac..0f25c27e0 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -986,6 +986,55 @@ def jaxrs_routes(content: str) -> Iterator[RouteMatch]:
)
+# ---------------------------------------------------------------------------
+# Apex REST (Salesforce)
+# ---------------------------------------------------------------------------
+
+# `@RestResource(urlMapping=...)` names the path and `@HttpGet` and siblings the
+# verbs. Apex annotations are case-insensitive and `'` is its only quote.
+_APEX_REST_RESOURCE_RE = re.compile(r"@RestResource\b", re.IGNORECASE)
+_APEX_URL_MAPPING_RE = re.compile(
+ r"\s*\(\s*urlMapping\s*=\s*'(?P<path>[^'\\\n]*)'\s*\)", re.IGNORECASE
+)
+_APEX_REST_VERB_RE = re.compile(r"@Http(?P<verb>Get|Post|Put|Patch|Delete)\b", re.IGNORECASE)
+
+
+def apex_code(content: str) -> str:
+ """*content* with Apex comments and string literals blanked, offsets and newlines kept."""
+ out = [c if c == "\n" else " " for c in content]
+ for i, c, _depth in scan_code(content, quotes="'"):
+ out[i] = c
+ return "".join(out)
+
+
+def apex_rest_routes(content: str, code: str | None = None) -> Iterator[RouteMatch]:
+ """Verb-annotated methods under the file's ``@RestResource`` class.
+
+ ``path`` is the class's raw ``urlMapping``, or ``None`` when it is not one
+ literal. The platform allows the annotation on one top-level class per
+ file, so there is one mapping. A file whose ``@RestResource`` sits only in
+ a comment or a string serves nothing. *code* is :func:`apex_code` of
+ *content*, for a caller that already has it.
+ """
+ if "restresource" not in content.lower():
+ return
+ code = apex_code(content) if code is None else code
+ resource = _APEX_REST_RESOURCE_RE.search(code)
+ if resource is None:
+ return
+ mapping = _APEX_URL_MAPPING_RE.match(content, resource.end())
+ path = mapping.group("path") if mapping else None
+ for m in _APEX_REST_VERB_RE.finditer(code):
+ yield RouteMatch(
+ verb=m.group("verb").upper(),
+ path=path,
+ receiver=None,
+ handler=None,
+ offset=m.start(),
+ paren_offset=m.start(),
+ )
+
+
# ---------------------------------------------------------------------------
# Next.js App Router
# ---------------------------------------------------------------------------
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 d3f827500..6680f43e4 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -18,6 +18,8 @@ from typing import TYPE_CHECKING
from ..base import ScanContext, select_files
from ..dialect import ContractDialect, union_extensions
from ..langs import PYTHON
+from .apex_callouts import ApexCalloutsDialect
+from .apex_rest import ApexRestDialect
from .aspnet import AspNetDialect
from .csharp_http import CSharpHttpDialect
from .django import DjangoDialect
@@ -69,6 +71,7 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (
MicronautDialect(),
NextAppDialect(),
RemixDialect(),
+ ApexRestDialect(),
)
# HTTP-client call recognisers (one client/language each).
@@ -82,6 +85,7 @@ CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (
JavaClientsDialect(),
KotlinClientsDialect(),
PhpClientsDialect(),
+ ApexCalloutsDialect(),
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py b/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py
new file mode 100644
index 000000000..9b04d0b1f
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py
@@ -0,0 +1,229 @@
+"""Salesforce Apex HTTP callout consumer dialect.
+
+An Apex callout is a ``System.HttpRequest`` configured statement by statement::
+
+ HttpRequest req = new HttpRequest();
+ req.setEndpoint('callout:Weather_Endpoint/weather');
+ req.setMethod('GET');
+ new Http().send(req);
+
+A row needs, inside one method, an ``HttpRequest`` declared there (or taken as
+a parameter), its ``setEndpoint`` and exactly one literal verb; anything else is
+refused rather than guessed. The endpoint must be an absolute URL or
+``callout:Name/path``, whose credential name becomes the call's base token
+(the ``${API_BASE}/users`` shape) for ``service_bases`` to map. A name folds
+only as a ``final`` field or a local the method assigns once, never a parameter.
+
+Ceiling: the Named Credential's own ``.xml`` endpoint is not read; reading it
+would add a host and path prefix to each ``callout:`` row.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import apex_code
+
+from ..base import line_at
+from ..langs import APEX
+from ..strings import (
+ APEX_SYNTAX,
+ NAME_RE,
+ call_arguments,
+ resolve_string,
+ split_top_level,
+ string_constants,
+)
+from .client_calls import method_from_argument
+from .dialect import build_consumer_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+# Apex identifiers and method names are case-insensitive.
+_SET_ENDPOINT_RE = re.compile(
+ r"(?<!\.)\b(?P<recv>[A-Za-z_]\w*)\s*\.\s*setEndpoint\s*\(", re.IGNORECASE
+)
+_TYPE_HEADER_RE = re.compile(r"\b(?:class|interface|enum)\b", re.IGNORECASE)
+# Only a test class holds `@isTest` or `testMethod`; its requests are fixtures.
+_IS_TEST_RE = re.compile(r"@isTest\b|\btestMethod\b", re.IGNORECASE)
+
+# `callout:Name/path`, the name an identifier and the rest a path or query.
+_CALLOUT_RE = re.compile(
+ r"callout:(?P<name>[A-Za-z]\w*)(?P<rest>[/?].*)?", re.IGNORECASE | re.DOTALL
+)
+_ABSOLUTE_RE = re.compile(r"https?://[^/$?]+(?:[/?]|$)", re.IGNORECASE)
+
+_CONFIDENCE = 0.75
+
+
+def _blocks(code: str) -> list[tuple[int, int, bool]]:
+ """``(open, close, is_type_body)`` per brace block of comment- and string-blanked *code*."""
+ out: list[tuple[int, int, bool]] = []
+ stack: list[tuple[int, bool]] = []
+ boundary = 0 # just past the last `;`, `{` or `}`: where the current header starts
+ for i, c in enumerate(code):
+ if c == "{":
+ stack.append((i, _TYPE_HEADER_RE.search(code, boundary, i) is not None))
+ boundary = i + 1
+ elif c == "}":
+ if stack:
+ start, is_type = stack.pop()
+ out.append((start, i, is_type))
+ boundary = i + 1
+ elif c == ";":
+ boundary = i + 1
+ return out
+
+
+def _method_scope(
+ blocks: list[tuple[int, int, bool]], code: str, offset: int
+) -> tuple[int, int] | None:
+ """``(header start, body end)`` of the method around *offset*.
+
+ The method body is the outermost enclosing block that is not a type body.
+ A file with no enclosing block (an anonymous ``.apex`` script) is one scope;
+ a call sitting directly in a type body is not a statement and has none.
+ """
+ enclosing = sorted((b for b in blocks if b[0] < offset < b[1]), key=lambda b: b[0])
+ if not enclosing:
+ return 0, len(code)
+ for start, end, is_type in enclosing:
+ if not is_type:
+ # The header holds the parameter list, where a request can be declared.
+ header = max(
+ code.rfind(";", 0, start), code.rfind("{", 0, start), code.rfind("}", 0, start)
+ )
+ return header + 1, end
+ return None
+
+
+def _verb(content: str, code: str, recv: str, start: int, end: int) -> str | None:
+ """The one literal verb *recv*'s ``setMethod`` calls name in ``[start, end)``, else None."""
+ pattern = re.compile(rf"\b{re.escape(recv)}\s*\.\s*setMethod\s*\(", re.IGNORECASE)
+ verbs: set[str | None] = set()
+ for m in pattern.finditer(code, start, end):
+ args = call_arguments(content, m.end() - 1)
+ verbs.add(method_from_argument(args[0]) if args and len(args) == 1 else None)
+ if len(verbs) != 1:
+ return None
+ return verbs.pop()
+
+
+def _cut_query(expr: str) -> str:
+ """*expr* up to the literal piece that opens the query string.
+
+ What follows fills query values (``'...json?location=' + req.lat``), which
+ never change the path the call reaches but often are expressions the
+ strings layer refuses.
+ """
+ pieces = split_top_level(expr, "+")
+ for i, piece in enumerate(pieces):
+ if piece.strip().startswith("'") and "?" in piece:
+ return "+".join(pieces[: i + 1])
+ return expr
+
+
+def _local_value(content: str, code: str, name: str, start: int, end: int) -> str | None:
+ """The right-hand side of *name*'s one assignment in ``[start, end)``, else None."""
+ pattern = rf"(?<![.\w]){re.escape(name)}\s*(\+?)=(?!=)"
+ assigns = list(re.finditer(pattern, code[start:end], re.IGNORECASE))
+ if len(assigns) != 1 or assigns[0].group(1):
+ return None
+ rhs = start + assigns[0].end()
+ semi = code.find(";", rhs, end)
+ return content[rhs:semi] if semi != -1 else None
+
+
+def _declared_in(code: str, name: str, start: int, end: int) -> bool:
+ """Whether *name* is declared as a local or parameter in ``[start, end)``."""
+ pattern = rf"[\w>]\s+{re.escape(name)}\s*[,)=;:]"
+ return re.search(pattern, code[start:end], re.IGNORECASE) is not None
+
+
+def _final_fields(content: str, code: str) -> dict[str, str]:
+ """The file's single-assignment string names that are declared ``final``."""
+ return {
+ name: rhs
+ for name, rhs in string_constants(content, APEX_SYNTAX).items()
+ if re.search(rf"\bfinal\b[^;={{}}]*\b{re.escape(name)}\s*=", code, re.IGNORECASE)
+ }
+
+
+def _endpoint(url: str) -> str | None:
+ """*url* as the consumer layer reads it, or None when its target is not literal."""
+ callout = _CALLOUT_RE.fullmatch(url)
+ if callout is not None:
+ return "${" + callout.group("name") + "}" + (callout.group("rest") or "")
+ if _ABSOLUTE_RE.match(url):
+ return url
+ return None
+
+
+def _holds_request(code: str, recv: str, start: int, end: int) -> bool:
+ """Whether ``[start, end)`` declares *recv* as an ``HttpRequest`` (local or parameter)."""
+ declared = re.compile(rf"\bHttpRequest\s+{re.escape(recv)}\b", re.IGNORECASE)
+ return declared.search(code, start, end) is not None
+
+
+def _url(
+ content: str, code: str, expr: str, scope: tuple[int, int], constants: dict[str, str]
+) -> str | None:
+ """The text endpoint argument *expr* denotes, or None when it is not settled here."""
+ start, end = scope
+ if NAME_RE.fullmatch(expr) and _declared_in(code, expr, start, end):
+ # A local or parameter shadows any field of the same name.
+ local = _local_value(content, code, expr, start, end)
+ if local is None:
+ return None
+ expr = local
+ return resolve_string(_cut_query(expr), APEX_SYNTAX, constants)
+
+
+class ApexCalloutsDialect:
+ name = "apex-callouts"
+ extensions = APEX
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
+ if "setendpoint" not in content.lower():
+ return []
+ code = apex_code(content)
+ if _IS_TEST_RE.search(code):
+ return []
+ blocks = _blocks(code)
+ constants: dict[str, str] | None = None
+ out: list[Contract] = []
+ for m in _SET_ENDPOINT_RE.finditer(code):
+ recv = m.group("recv")
+ scope = _method_scope(blocks, code, m.start())
+ if scope is None:
+ continue
+ start, end = scope
+ if not _holds_request(code, recv, start, end):
+ continue # not a request this method holds
+ method = _verb(content, code, recv, start, end)
+ args = call_arguments(content, m.end() - 1)
+ if method is None or not args or len(args) != 1:
+ continue
+ if constants is None:
+ constants = _final_fields(content, code)
+ url = _url(content, code, args[0], scope, constants)
+ endpoint = _endpoint(url) if url is not None else None
+ if endpoint is None:
+ continue
+ c = build_consumer_contract(
+ ctx,
+ method=method,
+ url=endpoint,
+ client="apex-callout",
+ line=line_at(content, m.start()),
+ confidence=_CONFIDENCE,
+ )
+ if c is not None:
+ c.symbol_name = f"apex-callout:{method} {url}" # as written, not rewritten
+ out.append(c)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/apex_rest.py b/packages/core/src/repowise/core/workspace/extractors/http/apex_rest.py
new file mode 100644
index 000000000..bbefbca09
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/apex_rest.py
@@ -0,0 +1,53 @@
+"""Salesforce Apex REST provider dialect.
+
+``@RestResource(urlMapping='/accounts/*')`` with ``@HttpGet`` serves
+``GET /services/apexrest/accounts/{param}``: ``*`` is read as one path parameter.
+Recognition lives in ``ingestion.framework_routes``, shared with the graph edges.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import HTTP_METHODS, apex_rest_routes
+
+from ..base import line_at
+from ..langs import APEX
+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
+
+#: Where an org serves every ``@RestResource`` class.
+APEX_REST_BASE = "/services/apexrest"
+
+
+def apex_rest_path(url_mapping: str) -> str:
+ """The request path a ``urlMapping`` serves, ``*`` read as a path parameter."""
+ return compose_prefix(APEX_REST_BASE, url_mapping.replace("*", "{param}"))
+
+
+class ApexRestDialect:
+ name = "apex-rest"
+ extensions = APEX
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
+ out: list[Contract] = []
+ for route in apex_rest_routes(content):
+ # A mapping held in a constant is a path, just not this file's to know.
+ if route.verb not in HTTP_METHODS or route.path is None:
+ continue
+ c = build_provider_contract(
+ ctx,
+ method=route.verb,
+ path_raw=apex_rest_path(route.path),
+ framework="apex-rest",
+ 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/langs.py b/packages/core/src/repowise/core/workspace/extractors/langs.py
index 95482b132..c303edfec 100644
--- a/packages/core/src/repowise/core/workspace/extractors/langs.py
+++ b/packages/core/src/repowise/core/workspace/extractors/langs.py
@@ -22,6 +22,7 @@ CSHARP = _REGISTRY.extensions_for(["csharp"])
VBNET = _REGISTRY.extensions_for(["vbnet"])
RUST = _REGISTRY.extensions_for(["rust"])
PROTO = _REGISTRY.extensions_for(["proto"])
+APEX = _REGISTRY.extensions_for(["apex"])
# A JS / TS module file's extension, which an import specifier leaves off.
JS_EXTENSION_RE = re.compile(r"\.(?:[cm]?[jt]sx?)$")
diff --git a/packages/core/src/repowise/core/workspace/extractors/service_boundary.py b/packages/core/src/repowise/core/workspace/extractors/service_boundary.py
index 89b8dbb52..dc318ac83 100644
--- a/packages/core/src/repowise/core/workspace/extractors/service_boundary.py
+++ b/packages/core/src/repowise/core/workspace/extractors/service_boundary.py
@@ -61,6 +61,7 @@ _SOURCE_EXTENSIONS = _LANG_REGISTRY.extensions_for(
"kotlin",
"scala",
"elixir",
+ "apex",
]
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.py
index 6fb602673..41b79dc06 100644
--- a/packages/core/src/repowise/core/workspace/extractors/strings.py
+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py
@@ -804,6 +804,14 @@ JAVA_SYNTAX = StringSyntax(
),
)
+# Apex: `'` is the only quote and nothing interpolates. Ceiling: a constant is
+# looked up in the case it is written, though Apex names are case-insensitive.
+APEX_SYNTAX = StringSyntax(
+ quotes="'",
+ concat="+",
+ assignment=JAVA_SYNTAX.assignment,
+)
+
KOTLIN_SYNTAX = StringSyntax(
quotes='"',
template_quotes='"',
@@ -847,6 +855,7 @@ def syntax_for_suffix(suffix: str) -> StringSyntax | None:
__all__ = [
+ "APEX_SYNTAX",
"CSHARP_SYNTAX",
"GO_SYNTAX",
"JAVA_SYNTAX",
diff --git a/tests/unit/ingestion/test_apex_rest_framework_edges.py b/tests/unit/ingestion/test_apex_rest_framework_edges.py
new file mode 100644
index 000000000..d13aa8260
--- /dev/null
+++ b/tests/unit/ingestion/test_apex_rest_framework_edges.py
@@ -0,0 +1,74 @@
+"""Apex REST handlers are bound from their file's module symbol, as Spring routes are."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion import GraphBuilder
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _graph(repo: Path, files: dict[str, str]) -> nx.DiGraph:
+ parser = ASTParser()
+ parsed = {}
+ for rel, text in files.items():
+ (repo / rel).write_text(text)
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(repo / rel),
+ language="apex",
+ size_bytes=len(text),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed[rel] = parser.parse_file(fi, text.encode())
+ builder = GraphBuilder(repo)
+ for pf in parsed.values():
+ builder.add_file(pf)
+ graph = builder.build()
+ ctx = ResolverContext(path_set=set(parsed), stem_map={}, graph=nx.DiGraph(), repo_path=repo)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ return graph
+
+
+def _bound(graph: nx.DiGraph) -> set[tuple[str, str]]:
+ return {(s, t) for s, t, d in graph.edges(data=True) if d.get("edge_type") == "framework_binds"}
+
+
+def test_each_verb_method_is_bound_and_a_plain_method_is_not(tmp_path: Path) -> None:
+ graph = _graph(
+ tmp_path,
+ {
+ "AccountApi.cls": (
+ "@RestResource(urlMapping='/accounts/*')\n"
+ "global with sharing class AccountApi {\n"
+ " @HttpGet\n"
+ " global static Account doGet() { return helper(); }\n"
+ " @HttpPost global static void doPost() { }\n"
+ " static Account helper() { return null; }\n"
+ "}\n"
+ )
+ },
+ )
+ assert _bound(graph) == {
+ ("AccountApi.cls::__module__", "AccountApi.cls::AccountApi::doGet"),
+ ("AccountApi.cls::__module__", "AccountApi.cls::AccountApi::doPost"),
+ }
+
+
+def test_a_class_without_a_rest_resource_gains_nothing(tmp_path: Path) -> None:
+ graph = _graph(
+ tmp_path,
+ {"Plain.cls": "public class Plain {\n @HttpGet global static void g() { }\n}\n"},
+ )
+ assert _bound(graph) == set()
diff --git a/tests/unit/workspace/test_apex_http.py b/tests/unit/workspace/test_apex_http.py
new file mode 100644
index 000000000..d28e2048a
--- /dev/null
+++ b/tests/unit/workspace/test_apex_http.py
@@ -0,0 +1,360 @@
+"""The Salesforce Apex REST provider and callout consumer dialects.
+
+A provider is a ``@RestResource`` class's verb-annotated method, served under
+``/services/apexrest``. A consumer is an ``HttpRequest`` whose endpoint and one
+verb are both literal inside one method; anything the file does not settle is
+refused rather than guessed.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.framework_routes import apex_rest_routes
+from repowise.core.workspace.extractors.base import ScanContext
+from repowise.core.workspace.extractors.http import HttpExtractor
+from repowise.core.workspace.extractors.http.apex_callouts import ApexCalloutsDialect
+from repowise.core.workspace.extractors.http.apex_rest import ApexRestDialect
+from repowise.core.workspace.extractors.http.js_clients import JsClientsDialect
+from repowise.core.workspace.matching import match_contracts
+
+REST_RESOURCE = """/**
+ * @RestResource(urlMapping='/commented/*') is documentation.
+ */
+@RestResource(urlMapping='/integration-service/*')
+global with sharing class CustomRestEndpoint {
+ @HttpGet
+ global static String getRecord() { return ''; }
+
+ // @HttpPut is not on any method
+ @HttpDelete
+ global static void deleteRecord() { }
+
+ @httpPost global static void create() { }
+}
+"""
+
+
+def contracts(content: str, rel_path: str = "classes/Svc.cls") -> list:
+ ctx = ScanContext("svc", rel_path, ".cls", content, {}, None)
+ return [*ApexRestDialect().extract(ctx), *ApexCalloutsDialect().extract(ctx)]
+
+
+def ids(content: str) -> set[str]:
+ return {c.contract_id for c in contracts(content)}
+
+
+class TestApexRestProvider:
+ def test_each_verb_method_is_served_under_the_apex_rest_base(self) -> None:
+ assert ids(REST_RESOURCE) == {
+ "http::GET::/services/apexrest/integration-service/{param}",
+ "http::DELETE::/services/apexrest/integration-service/{param}",
+ "http::POST::/services/apexrest/integration-service/{param}",
+ }
+
+ def test_rows_carry_the_annotation_line_and_framework(self) -> None:
+ get = next(c for c in contracts(REST_RESOURCE) if c.meta["method"] == "GET")
+ assert get.role == "provider"
+ assert get.line == 6
+ assert get.meta["framework"] == "apex-rest"
+
+ def test_a_wildcard_mid_path_is_one_parameter_segment(self) -> None:
+ source = (
+ "@RestResource(urlMapping='/Account/*/contacts')\n"
+ "global class Contacts { @HttpGet global static void g() {} }\n"
+ )
+ assert ids(source) == {"http::GET::/services/apexrest/account/{param}/contacts"}
+
+ def test_annotations_read_without_regard_to_case(self) -> None:
+ source = (
+ "@restResource(UrlMapping='/whatsapp')\n"
+ "global class W { @HTTPGET global static void g() {} }\n"
+ )
+ assert ids(source) == {"http::GET::/services/apexrest/whatsapp"}
+
+ def test_a_mapping_that_is_not_a_literal_serves_nothing(self) -> None:
+ source = (
+ "@RestResource(urlMapping=Paths.ACCOUNTS)\n"
+ "global class A { @HttpGet global static void g() {} }\n"
+ )
+ assert ids(source) == set()
+ # The graph side still binds the handler: the platform calls it.
+ assert [r.path for r in apex_rest_routes(source)] == [None]
+
+ def test_verb_annotations_without_a_resource_serve_nothing(self) -> None:
+ source = "global class A { @HttpGet global static void g() {} }\n"
+ assert ids(source) == set()
+
+ def test_a_resource_only_in_a_comment_serves_nothing(self) -> None:
+ source = (
+ "// @RestResource(urlMapping='/x/*')\n"
+ "global class A { @HttpGet global static void g() {} }\n"
+ )
+ assert ids(source) == set()
+
+
+def callout(body: str, members: str = "") -> str:
+ return (
+ "public with sharing class Client {\n"
+ f"{members}"
+ " public static HttpResponse call(String id) {\n"
+ f"{body}"
+ " return new Http().send(req);\n"
+ " }\n"
+ "}\n"
+ )
+
+
+class TestApexCalloutConsumer:
+ def test_a_literal_absolute_endpoint_records_its_host(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(\n"
+ " 'https://www.googleapis.com/books/v1/volumes?q=salesforce'\n"
+ " );\n"
+ " req.setMethod('GET');\n"
+ )
+ [c] = contracts(source)
+ assert c.contract_id == "http::GET::/books/v1/volumes"
+ assert c.role == "consumer"
+ assert c.line == 4
+ assert c.meta["host"] == "www.googleapis.com"
+ assert c.meta["client"] == "apex-callout"
+
+ def test_a_named_credential_becomes_the_base_token(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('callout:Weather_Endpoint/weather?lat=1&date=' + id);\n"
+ " req.setMethod('GET');\n"
+ )
+ [c] = contracts(source)
+ assert c.contract_id == "http::GET::/weather"
+ assert c.meta["base_token"] == "Weather_Endpoint"
+ assert c.symbol_name.startswith("apex-callout:GET callout:Weather_Endpoint/weather")
+
+ def test_the_verb_may_be_set_before_the_endpoint(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setMethod('POST');\n"
+ " req.setEndpoint('callout:Orders/v1/orders/' + id);\n"
+ )
+ assert ids(source) == {"http::POST::/v1/orders/{param}"}
+
+ def test_a_same_file_constant_folds(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(API_URL);\n"
+ " req.setMethod('POST');\n",
+ members=" private static final String API_URL = 'https://api.sendgrid.com/api/mail.send';\n",
+ )
+ assert ids(source) == {"http::POST::/api/mail.send"}
+
+ def test_query_values_built_from_expressions_leave_the_path(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('https://repair.example.com/api/score?id=' + reqs[0].custId);\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == {"http::GET::/api/score"}
+
+ def test_a_local_assigned_once_in_the_method_folds(self) -> None:
+ source = callout(
+ " String url = 'https://maps.example.com/api/tz/json?loc=' + reqs[0].lat;\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(url);\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == {"http::GET::/api/tz/json"}
+
+ def test_a_local_extended_after_assignment_emits_nothing(self) -> None:
+ source = callout(
+ " String url = 'https://maps.example.com/api';\n"
+ " url += suffix;\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(url);\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_parameter_never_reads_another_method_s_local(self) -> None:
+ # `endpoint` is assigned once in the file, but in the caller; the
+ # request is sent to `url`, so folding by name would drop a segment.
+ source = (
+ "public class C {\n"
+ " static void run(String key) {\n"
+ " String endpoint = 'https://api.example.com/messages/';\n"
+ " String url = endpoint + key;\n"
+ " send(url);\n"
+ " }\n"
+ " static void send(String endpoint) {\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(endpoint);\n"
+ " req.setMethod('POST');\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_parameter_shadows_a_final_field_of_the_same_name(self) -> None:
+ source = (
+ "public class C {\n"
+ " static final String URL = 'https://a.example.com/x';\n"
+ " static void send(String URL) {\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(URL);\n"
+ " req.setMethod('GET');\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_legacy_test_method_class_emits_nothing(self) -> None:
+ source = (
+ "public class LegacyTests {\n"
+ " static testMethod void t() {\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('https://a.example.com/x');\n"
+ " req.setMethod('GET');\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_request_held_by_another_object_is_not_the_local(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " wrapper.req.setEndpoint('callout:Svc/items');\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_request_taken_as_a_parameter_counts(self) -> None:
+ source = (
+ "public class C {\n"
+ " static void prepare(HttpRequest req) {\n"
+ " req.setEndpoint('callout:Svc/items');\n"
+ " req.setMethod('GET');\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == {"http::GET::/items"}
+
+ def test_an_anonymous_script_is_one_scope(self) -> None:
+ source = (
+ "HttpRequest req = new HttpRequest();\n"
+ "req.setEndpoint('https://jsonplaceholder.typicode.com/todos/1');\n"
+ "req.setMethod('GET');\n"
+ )
+ ctx = ScanContext("svc", "scripts/sample.apex", ".apex", source, {}, None)
+ assert {c.contract_id for c in ApexCalloutsDialect().extract(ctx)} == {
+ "http::GET::/todos/1"
+ }
+
+ def test_a_variable_endpoint_emits_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint(endpoint);\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_variable_named_credential_emits_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('callout:' + this.credential + '/users/current');\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_variable_host_emits_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('https://' + host + '/v1/users');\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_verb_held_in_a_variable_emits_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('callout:Svc/items');\n"
+ " req.setMethod(method);\n"
+ )
+ assert ids(source) == set()
+
+ def test_two_verbs_for_one_request_emit_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('callout:Svc/items');\n"
+ " if (id == null) { req.setMethod('GET'); } else { req.setMethod('DELETE'); }\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_verb_set_in_another_method_is_not_borrowed(self) -> None:
+ source = (
+ "public class C {\n"
+ " HttpRequest build() {\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setEndpoint('callout:Svc/items');\n"
+ " return req;\n"
+ " }\n"
+ " void other() {\n"
+ " HttpRequest req = new HttpRequest();\n"
+ " req.setMethod('GET');\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_receiver_that_is_not_a_request_emits_nothing(self) -> None:
+ source = callout(
+ " Callable req = new Fake();\n"
+ " req.setEndpoint('callout:Svc/items');\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_commented_out_call_emits_nothing(self) -> None:
+ source = callout(
+ " HttpRequest req = new HttpRequest();\n"
+ " // req.setEndpoint('callout:Svc/items');\n"
+ " req.setMethod('GET');\n"
+ )
+ assert ids(source) == set()
+
+ def test_a_test_class_mock_emits_nothing(self) -> None:
+ source = (
+ "@isTest\n"
+ "global class Mock implements HttpCalloutMock {\n"
+ " global HttpResponse respond(HttpRequest req) {\n"
+ " req.setEndpoint('https://salesforce.com/services/data/v55.0/x');\n"
+ " req.setMethod('GET');\n"
+ " return null;\n"
+ " }\n"
+ "}\n"
+ )
+ assert ids(source) == set()
+
+
+JS_CONSUMER = """export async function load(id) {
+ return fetch(`/services/apexrest/integration-service/${id}`);
+}
+"""
+
+
+class TestApexCrossRepoLink:
+ def test_a_js_consumer_links_to_an_apex_rest_resource(self) -> None:
+ extractor = HttpExtractor()
+ extractor.provider_dialects = (ApexRestDialect(),)
+ extractor.consumer_dialects = (JsClientsDialect(),)
+ providers = extractor.extract(
+ Path("."), "org", files=[("classes/Svc.cls", ".cls", REST_RESOURCE)]
+ )
+ consumers = extractor.extract(
+ Path("."), "portal", files=[("src/load.js", ".js", JS_CONSUMER)]
+ )
+ links = match_contracts(providers + consumers)
+ assert [(link.provider_repo, link.consumer_repo) for link in links] == [("org", "portal")]
+
+ def test_the_registered_extractor_reads_apex_files(self) -> None:
+ assert {".cls", ".trigger", ".apex"} <= HttpExtractor.source_extensions()