Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): HTTP consumer contracts for Go, Ruby, Java, Kotlin and PHP (#2114)
Raghav Chamadiyafe6b4192aac9
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 8ac60a965..02624e01a 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -46,10 +46,11 @@ CONTRACTS_FILENAME = "contracts.json"#: package surface became a ``code`` contract, and to 5 when ASP.NET minimal#: APIs gained ``MapGroup`` prefixes and a handler-bound ``symbol_id``, and to 6#: when a multi-line axum route became readable and go/axum providers gained a-#: handler-bound ``symbol_id``.+#: handler-bound ``symbol_id``, and to 7 when HTTP consumers gained Go, Ruby,+#: Java, Kotlin and PHP client calls resolved from URL expressions.#: A store written under an older version is readable but not reusable: its#: rows carry no identity, and nothing short of re-extraction can give them one.-CONTRACTS_VERSION = 6+CONTRACTS_VERSION = 7# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex dda0bfcf0..bb54df44f 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -21,13 +21,18 @@ from .django import DjangoDialectfrom .express import ExpressDialectfrom .fastapi import FastApiDialectfrom .go import GoDialect+from .go_clients import GoClientsDialect+from .java_clients import JavaClientsDialectfrom .jaxrs import JaxRsDialectfrom .js_clients import JsClientsDialect+from .kotlin_clients import KotlinClientsDialectfrom .laravel import LaravelDialectfrom .mounts import merge_mount_mapsfrom .next_app import NextAppDialectfrom .paths import normalize_http_path+from .php_clients import PhpClientsDialectfrom .python_clients import PythonClientsDialect+from .ruby_clients import RubyClientsDialectfrom .rust_axum import RustAxumDialectfrom .rust_clients import RustClientsDialectfrom .spring import SpringDialect@@ -61,6 +66,11 @@ CONSUMER_DIALECTS: tuple[HttpDialect, ...] = (PythonClientsDialect(),CSharpHttpDialect(),RustClientsDialect(),+ GoClientsDialect(),+ RubyClientsDialect(),+ JavaClientsDialect(),+ KotlinClientsDialect(),+ PhpClientsDialect(),)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/client_calls.py b/packages/core/src/repowise/core/workspace/extractors/http/client_calls.pynew file mode 100644index 000000000..a90e8f8e7--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/client_calls.py@@ -0,0 +1,759 @@+"""Shared recognition layer for HTTP client calls.++The provider side splits recognition from output: ``framework_routes`` finds a+route registration once and each consumer of that match builds its own row.+This module is the consumer-side counterpart. A client library's call shape is+recognised in one function yielding :class:`ClientCallMatch` rows, and+:func:`consumer_contracts` turns those rows into contracts through one URL+resolver, one method inference and one path guard, so a dialect module is a+table of recognisers and nothing else.++**The URL is an expression, not a literal.** Real call sites spell it as a+literal, an interpolated string, a format call (``format!``, ``fmt.Sprintf``,+``String.format``), a concatenation, a name bound to one of those earlier in+the file, or a wrapper such as ``URI.create(...)``. :func:`resolve_url` reads+each of these into the ``${expr}`` template text :mod:`.paths` already+understands, per language through a :class:`UrlSyntax` table, and refuses when+the expression cannot be settled inside the file. A refused site is a missing+edge; a guessed one is a wrong edge.++**What folds and what is refused.** A name folds only when the file assigns it+exactly once, to a single string literal. Assigned twice, or assigned anything+else anywhere in the file, it is left unresolved. File scope, not lexical+scope: a single static assignment means the same thing wherever it is read.+An interpolated expression that is itself such a name is inlined; any other+expression becomes ``${expr}`` and is stripped as a base or collapsed to a+parameter downstream. An escaped brace (``{{``) is refused rather than+corrupted, because no later step can tell it from a parameter.++Placed under ``workspace`` because no graph-edge builder reads client calls;+it moves under ``ingestion`` the day one does.+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Iterator+from dataclasses import dataclass+from functools import cache+from typing import TYPE_CHECKING++from ..base import line_at+from .dialect import build_consumer_contract, method_from_callee++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# Every verb a call shape may name. Wider than ``dialect.METHODS``, which is+# the alternation the *callee-name* inference reads and is left as it is.+VERBS = frozenset({"get", "post", "put", "delete", "patch", "head", "options"})+++@dataclass(frozen=True)+class ClientCallMatch:+ """One HTTP client call a recogniser found in a file's text.++ ``url`` is the URL argument's source text, unparsed; :func:`resolve_url`+ reads it. ``method`` is the verb when the call shape settles it (a verb+ argument, a builder terminal, an explicit option) and ``None`` when only+ the callee's name carries it, in which case :func:`method_from_callee`+ reads ``callee``. ``offset`` is where the call starts, for its line.+ """++ client: str+ url: str+ offset: int+ callee: str = ""+ method: str | None = None+ confidence: float = 0.75+++@dataclass(frozen=True)+class UrlSyntax:+ """How one language spells a URL expression.++ ``template_quotes`` are quotes whose literal always interpolates (a JS+ backtick); ``template_prefixes`` are prefixes that switch interpolation on+ (Python ``f``, C# ``$``). ``interpolation`` matches one interpolated+ expression inside such a body; its first non-empty group is the expression.+ ``None`` means the body is already in ``${expr}`` form.++ ``format_heads`` name calls whose first argument is a template with+ ``placeholder`` holes. ``unwrap_heads`` name calls whose single argument+ *is* the URL. ``concat`` is the string-concatenation operator, empty when+ the language's dialects do not fold concatenation. ``assignment`` locates+ ``name = rhs`` statements for constant folding; ``assignment_strip`` drops a+ trailing decoration from the right-hand side (Ruby's ``.freeze``).+ """++ quotes: str = "\"'"+ prefixes: str = ""+ template_quotes: str = ""+ template_prefixes: str = ""+ interpolation: re.Pattern[str] | None = None+ refuse: re.Pattern[str] | None = None+ refuse_prefixes: str = ""+ format_heads: tuple[str, ...] = ()+ placeholder: re.Pattern[str] | None = None+ unwrap_heads: tuple[str, ...] = ()+ concat: str = ""+ assignment: re.Pattern[str] | None = None+ assignment_strip: re.Pattern[str] | None = None+++# ---------------------------------------------------------------------------+# Argument scanning+# ---------------------------------------------------------------------------++_QUOTES = "'\"`"++# How far a scan may run past its opening bracket. A stray quote in a comment+# desynchronises the scan, and without a bound every candidate after it would+# read to the end of the file.+SCAN_LIMIT = 50_000+++def match_paren(content: str, open_idx: int, limit: int = SCAN_LIMIT, closer: str = ")") -> int:+ """Index of the bracket closing the one at *open_idx*, or -1.++ Quote- and template-aware so a parenthesis inside a string literal does not+ unbalance the scan. Nested ``${...}`` inside a template literal is tracked+ as ordinary depth, which is what makes ``` `/a/${f(x)}/b` ``` parse. A+ call that does not close within *limit* characters is -1 as well.+ *closer* is ``}`` for a trailing lambda block.+ """+ depth = 0+ i = open_idx+ n = min(len(content), open_idx + limit)+ # Open template literals, innermost last. A backtick inside a ``${...}``+ # opens a *nested* literal rather than closing the outer one, so the state+ # has to be a stack: ``fetch(`/a/${c ? `x` : `y`}/b`)`` otherwise reads the+ # inner backtick as the end of the string and desynchronises everything+ # after it.+ tmpl: list[int] = []+ quote: str | None = None+ while i < n:+ ch = content[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and content[i + 1] == "{":+ tmpl.append(depth)+ depth += 1+ quote = None+ i += 2+ continue+ if ch == quote:+ quote = None+ i += 1+ continue+ if ch in _QUOTES:+ quote = ch+ elif ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if tmpl and ch == "}" and depth == tmpl[-1]:+ tmpl.pop()+ quote = "`" # back inside the template literal that opened it+ elif depth == 0 and ch == closer:+ return i+ i += 1+ return -1+++def _split_top_level(text: str, sep: str) -> list[str]:+ """Split *text* at each top-level *sep* character, outside quotes and brackets."""+ out: list[str] = []+ depth = 0+ tmpl: list[int] = [] # see :func:`match_paren`: nested templates need a stack+ quote: str | None = None+ start = 0+ i = 0+ n = len(text)+ while i < n:+ ch = text[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and text[i + 1] == "{":+ tmpl.append(depth)+ depth += 1+ quote = None+ i += 2+ continue+ if ch == quote:+ quote = None+ i += 1+ continue+ if ch in _QUOTES:+ quote = ch+ elif ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if tmpl and ch == "}" and depth == tmpl[-1]:+ tmpl.pop()+ quote = "`"+ elif ch == sep and depth == 0:+ out.append(text[start:i])+ start = i + 1+ i += 1+ out.append(text[start:])+ return out+++def split_first_arg(args: str) -> tuple[str, str]:+ """Split an argument list into ``(first_arg, rest)`` at the top-level comma.++ Stops at that comma: the rest is returned unscanned, so a call whose second+ argument is a large options literal costs only its first argument.+ """+ depth = 0+ tmpl: list[int] = [] # see :func:`match_paren`: nested templates need a stack+ quote: str | None = None+ i = 0+ n = len(args)+ while i < n:+ ch = args[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and args[i + 1] == "{":+ tmpl.append(depth)+ depth += 1+ quote = None+ i += 2+ continue+ if ch == quote:+ quote = None+ i += 1+ continue+ if ch in _QUOTES:+ quote = ch+ elif ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if tmpl and ch == "}" and depth == tmpl[-1]:+ tmpl.pop()+ quote = "`"+ elif ch == "," and depth == 0:+ return args[:i].strip(), args[i + 1 :]+ i += 1+ return args.strip(), ""+++def call_arguments(content: str, paren_offset: int, close: int | None = None) -> list[str] | None:+ """The top-level arguments of the call whose ``(`` is at *paren_offset*.++ ``None`` when the argument list does not close, so a recogniser can tell a+ scanner failure from a call with no arguments. *close* is the matching+ ``)`` when the caller has already found it.+ """+ if close is None:+ close = match_paren(content, paren_offset)+ if close < 0:+ return None+ inner = content[paren_offset + 1 : close]+ if not inner.strip():+ return []+ return [a.strip() for a in _split_top_level(inner, ",")]+++# ---------------------------------------------------------------------------+# Method inference from an argument+# ---------------------------------------------------------------------------++_QUOTED_WORD_RE = re.compile(r"""^['"]([A-Za-z]+)['"]$""")+_LAST_SEGMENT_RE = re.compile(r"(?:\.|::|->)")+++def method_from_argument(text: str) -> str | None:+ """The HTTP verb an argument names, else ``None``.++ Reads a quoted verb (``'GET'``), and a verb constant by its last segment+ (``http.MethodGet``, ``HttpMethod.POST``, ``HTTPMethods.Get``,+ ``Net::HTTP::Get``). Anything else, a variable above all, is not a verb+ this layer may claim to know.+ """+ t = text.strip()+ m = _QUOTED_WORD_RE.match(t)+ if m is None:+ # A bare name is a verb only as a constant (`GET`), never as a+ # lower-case variable that happens to be called `get`.+ segments = _LAST_SEGMENT_RE.split(t)+ if len(segments) == 1 and not t.isupper():+ return None+ word = m.group(1) if m else _LAST_SEGMENT_RE.split(t)[-1]+ if not m and word.startswith("Method") and len(word) > len("Method"):+ word = word[len("Method") :]+ return word.upper() if word.lower() in VERBS else None+++# ---------------------------------------------------------------------------+# URL expression resolution+# ---------------------------------------------------------------------------++_NAME_RE = re.compile(r"[A-Za-z_$][\w$]*(?:(?:\.|::|->)[A-Za-z_]\w*)*")++# Already-template text: one ``${expr}`` interpolation, for folding a constant+# inside a body a language wrote in the target form to begin with.+_TEMPLATE_INTERP_RE = re.compile(r"\$\{([^{}]+)\}")++# Dropped from an interpolated expression (``settings.base.rstrip('/')``) so+# :func:`.paths.base_token_identifier` reads the attribute, not ``rstrip``.+_TRAILING_CALL_RE = re.compile(r"\.\s*\w+\s*\([^()]*\)\s*$")+++@cache+def _literal_re(quotes: str, prefixes: str) -> re.Pattern[str]:+ alts = []+ if '"' in quotes:+ alts.append('"""')+ if "'" in quotes:+ alts.append("'''")+ alts.extend(re.escape(q) for q in quotes)+ prefix = f"[{re.escape(prefixes)}]*" if prefixes else ""+ return re.compile(+ rf"^(?P<prefix>{prefix})(?P<q>{'|'.join(alts)})(?P<body>.*)(?P=q)$", re.DOTALL+ )+++@cache+def _head_re(heads: tuple[str, ...]) -> re.Pattern[str]:+ alts = "|".join(re.escape(h).replace(r"\ ", r"\s+") for h in heads)+ return re.compile(rf"^(?:{alts})\s*\(")+++def _parse_literal(text: str, syntax: UrlSyntax) -> tuple[str, str, str] | None:+ """``(lowercased prefix, quote, body)`` when *text* is exactly one string literal."""+ m = _literal_re(syntax.quotes, syntax.prefixes).match(text.strip())+ if m is None:+ return None+ body = m.group("body")+ if m.group("q") in body:+ return None # the literal ended and something else followed it+ return m.group("prefix").lower(), m.group("q"), body+++def _interpolates(prefix: str, quote: str, syntax: UrlSyntax) -> bool:+ # A triple quote interpolates when its single form does (Kotlin raw strings).+ return quote[0] in syntax.template_quotes or any(+ p in syntax.template_prefixes.lower() for p in prefix+ )+++def _lookup(name: str, constants: dict[str, str]) -> str | None:+ const = constants.get(name)+ if const is None and name.startswith("$"):+ const = constants.get(name[1:]) # a PHP variable, keyed without its sigil+ return const+++def _fold(expr: str, syntax: UrlSyntax, constants: dict[str, str]) -> str:+ """One interpolated expression as template text, inlining a plain constant.++ Only a constant whose own text does not interpolate is inlined: nothing in+ the corpus needs a second level, and a half-folded template would be wrong.+ """+ expr = expr.strip()+ const = _lookup(expr, constants)+ if const is not None:+ lit = _parse_literal(const, syntax)+ text = _literal_text(lit, syntax, {}) if lit is not None else None+ if text is not None and "${" not in text:+ return text+ return "${" + _TRAILING_CALL_RE.sub("", expr) + "}"+++def _literal_text(+ parsed: tuple[str, str, str], syntax: UrlSyntax, constants: dict[str, str]+) -> str | None:+ prefix, quote, body = parsed+ if any(p in syntax.refuse_prefixes for p in prefix):+ return None # bytes, not a URL this layer records+ if not _interpolates(prefix, quote, syntax):+ return body+ if syntax.refuse is not None and syntax.refuse.search(body):+ return None+ if syntax.interpolation is None:+ if not constants:+ return body+ return _TEMPLATE_INTERP_RE.sub(lambda m: _fold(m.group(1), syntax, constants), body)++ def sub(m: re.Match[str]) -> str:+ expr = next(g for g in m.groups() if g is not None)+ return _fold(expr, syntax, constants)++ return syntax.interpolation.sub(sub, body)+++def _format_template(text: str, syntax: UrlSyntax, constants: dict[str, str]) -> str | None:+ """A ``format!("...")``-style call as template text, or ``None``."""+ m = _head_re(syntax.format_heads).match(text)+ if m is None or syntax.placeholder is None:+ return None+ args = _whole_call_arguments(text, m.end() - 1)+ if not args:+ return None+ parsed = _parse_literal(args[0], syntax)+ if parsed is None:+ return None+ body = _literal_text(parsed, syntax, constants)+ if body is None:+ return None+ # `%%` is a literal percent sign, not a hole.+ return syntax.placeholder.sub(lambda h: "%" if h.group() == "%%" else "${x}", body)+++def _whole_call_arguments(text: str, paren: int) -> list[str] | None:+ """The arguments of the call at *paren* when the call is all of *text*.++ ``URI.create(BASE).resolve("/x")`` is not ``URI.create(BASE)``: reading the+ head alone would drop the path the request reaches.+ """+ close = match_paren(text, paren)+ if close < 0 or text[close + 1 :].strip():+ return None+ return call_arguments(text, paren, close)+++def _unwrap(text: str, syntax: UrlSyntax) -> str | None:+ """The single argument of a ``URI.create(...)``-style wrapper, or ``None``."""+ m = _head_re(syntax.unwrap_heads).match(text)+ if m is None:+ return None+ args = _whole_call_arguments(text, m.end() - 1)+ return args[0] if args and len(args) == 1 else None+++def _concat(text: str, syntax: UrlSyntax, constants: dict[str, str]) -> str | None:+ """``a + "/x"`` as template text, or ``None`` when a piece is not readable."""+ if syntax.concat not in text:+ return None+ pieces = _split_top_level(text, syntax.concat)+ if len(pieces) < 2:+ return None+ out: list[str] = []+ for piece in pieces:+ piece = piece.strip()+ parsed = _parse_literal(piece, syntax)+ if parsed is not None:+ body = _literal_text(parsed, syntax, constants)+ if body is None:+ return None+ out.append(body)+ elif _NAME_RE.fullmatch(piece):+ out.append(_fold(piece, syntax, constants))+ else:+ return None # a call or an operator: not settled in this file+ return "".join(out)+++def resolve_url(+ expr: str, syntax: UrlSyntax, constants: dict[str, str] | None = None+) -> str | None:+ """The URL text *expr* denotes, or ``None`` when it cannot be resolved here.++ Interpolations come out as ``${expr}``, so :func:`.paths.strip_leading_base_expr`+ strips a base placeholder and :func:`.paths.normalize_http_path` collapses a+ parameter with no per-language branch in either.+ """+ constants = constants or {}+ text = expr.strip()+ parsed = _parse_literal(text, syntax)+ if parsed is not None:+ return _literal_text(parsed, syntax, constants)+ if syntax.format_heads:+ folded = _format_template(text, syntax, constants)+ if folded is not None:+ return folded+ if syntax.unwrap_heads:+ inner = _unwrap(text, syntax)+ if inner is not None:+ return resolve_url(inner, syntax, constants)+ if syntax.concat:+ folded = _concat(text, syntax, constants)+ if folded is not None:+ return folded+ if _NAME_RE.fullmatch(text):+ # A bare name. Its value resolved without constants when it was+ # recorded, so this step cannot reach another bare name.+ const = _lookup(text, constants)+ if const is not None:+ return resolve_url(const, syntax, constants)+ return None+++def string_constants(content: str, syntax: UrlSyntax, code: str | None = None) -> dict[str, str]:+ """Names *content* assigns exactly once, to a URL expression that resolves.++ The value is the right-hand side's raw text, so an interpolating literal,+ a format call or a concatenation keeps its parts for :func:`resolve_url`+ to fold at the call site.++ *code*, when given, is *content* with comments and string bodies blanked at+ the same offsets. Assignments are located in it and their values read from+ *content*, so the example code in a docstring (`` url = "/docs/example"``)+ is not read as a real assignment.+ """+ if syntax.assignment is None:+ return {}+ text = content if code is None else code+ seen: dict[str, str | None] = {}+ for m in syntax.assignment.finditer(text):+ if code is None and _on_comment_line(content, m.start()):+ continue # an example in a doc comment is not a binding+ name = m.group("name")+ rhs = content[m.start("rhs") : m.end("rhs")].strip()+ if syntax.assignment_strip is not None:+ rhs = syntax.assignment_strip.sub("", rhs).strip()+ # A second assignment retires the name whatever it assigns: the reader+ # cannot tell which one reaches the call site.+ seen[name] = None if name in seen or resolve_url(rhs, syntax) is None else rhs+ # `x += "/v1"` and `x, err = f()` rebind a name without the plain form.+ for m in _COMPOUND_ASSIGN_RE.finditer(text):+ seen[m.group(1)] = None+ for m in _MULTI_ASSIGN_RE.finditer(text):+ for name in m.group(1).replace(" ", "").split(","):+ seen[name.lstrip("$")] = None+ return {name: text for name, text in seen.items() if text is not None}+++# ``x += ...`` / ``$x .= ...``; the name is keyed without a PHP sigil.+_COMPOUND_ASSIGN_RE = re.compile(r"(?<![\w.$-])\$?([A-Za-z_]\w*)[ \t]*[+.]=(?!=)")+# ``a, b := f()`` / ``a, b = f()``: every name on the left is rebound.+_MULTI_ASSIGN_RE = re.compile(+ r"^[ \t]*(\$?[A-Za-z_]\w*(?:[ \t]*,[ \t]*\$?[A-Za-z_]\w*)+)[ \t]*:?=(?!=)", re.MULTILINE+)+++def _on_comment_line(content: str, offset: int) -> bool:+ """True when the line holding *offset* starts as a line or block comment."""+ start = max(content.rfind("\n", 0, offset) + 1, offset - 200)+ return content[start:offset].lstrip().startswith(("//", "#", "*", "/*"))+++# ---------------------------------------------------------------------------+# Contracts+# ---------------------------------------------------------------------------++# A URL concrete enough to name a route on its own: a rooted path, a base+# placeholder, or an absolute URL. A relative path composes onto a base this+# layer cannot see.+_ROOTED_URL_RE = re.compile(r"^(?:/|\$\{|https?:|//)")+++def is_rooted_url(url: str) -> bool:+ return _ROOTED_URL_RE.match(url) is not None+++def consumer_contracts(+ ctx: ScanContext,+ matches: Iterable[ClientCallMatch],+ syntax: UrlSyntax,+ *,+ constants: dict[str, str] | None = None,+ path_only: bool = False,+ rooted_only: bool = False,+) -> list[Contract]:+ """Consumer contracts for *matches*, resolving each URL through *syntax*.++ *path_only* drops a URL with no ``/`` in it. It is for recognisers whose+ receiver is ambiguous, so a map's ``.get("key")`` never becomes a route.++ *rooted_only* drops a URL that is neither absolute nor rooted. A client+ with a configured base composes ``"some/path"`` onto it, so the path the+ request reaches has a prefix this layer cannot see.+ """+ out: list[Contract] = []+ for m in matches:+ url = resolve_url(m.url, syntax, constants)+ if url is None or (path_only and "/" not in url):+ continue+ if rooted_only and not is_rooted_url(url):+ continue+ method = m.method or method_from_callee(m.callee)+ c = build_consumer_contract(+ ctx,+ method=method.upper(),+ url=url,+ client=m.client,+ line=line_at(ctx.content, m.offset),+ confidence=m.confidence,+ )+ if c is not None:+ out.append(c)+ return out+++def literal_span(content: str, m: re.Match[str], group: int) -> str:+ """The source text of a quoted literal whose *body* is *group* of *m*.++ For a recogniser whose regex captures the text between the quotes: the+ slice one character wider on each side is the literal as written, which is+ what :func:`resolve_url` reads. A capture that stopped at a different quote+ (one inside a ``${...}`` expression) is closed with its own opening quote,+ so the text read is the prefix the regex saw and the row is kept.+ """+ quote = content[m.start(group) - 1]+ body = content[m.start(group) : m.end(group)]+ return quote + body + quote+++def matches_in(+ content: str,+ pattern: re.Pattern[str],+ *,+ client: str,+ url_group: int,+ method_group: int | None = None,+ callee_group: int | None = None,+ confidence: float = 0.75,+ prefix_group: int | None = None,+) -> Iterator[ClientCallMatch]:+ """Rows for every match of *pattern* whose *url_group* captured a literal body.++ The common recogniser: a regex that reads the callee (or a fixed client+ name), an optional verb group, and the body of a quoted URL literal.+ *prefix_group* is a literal prefix captured before the opening quote (C#'s+ ``$``/``@``), included in the row's ``url`` text.+ """+ for m in pattern.finditer(content):+ url = literal_span(content, m, url_group)+ if prefix_group is not None:+ url = m.group(prefix_group) + url+ yield ClientCallMatch(+ client=client,+ url=url,+ offset=m.start(),+ callee=m.group(callee_group) if callee_group is not None else "",+ method=m.group(method_group).upper() if method_group is not None else None,+ confidence=confidence,+ )+++# ---------------------------------------------------------------------------+# Per-language syntax tables+# ---------------------------------------------------------------------------++_C_FORMAT_PLACEHOLDER_RE = re.compile(r"%%|%[-+ #0]*\d*(?:\.\d+)?[a-zA-Z]")+_BRACE_PLACEHOLDER_RE = re.compile(r"\{[^}]*\}")+_BRACE_INTERP_RE = re.compile(r"(?<!\{)\{([^{}]+)\}(?!\})")+_ESCAPED_BRACE_RE = re.compile(r"\{\{|\}\}")++JS_SYNTAX = UrlSyntax(quotes="\"'`", template_quotes="`")++# ``NAME = <expr>`` at any indentation, RHS to end of line. The whitespace+# around ``=`` is required, which excludes the usual unspaced keyword argument+# on its own line (``url=str(resp.url),``) that otherwise reads as a second+# assignment and retires the very name being folded.+PYTHON_SYNTAX = UrlSyntax(+ prefixes="fFrRbBuU",+ template_prefixes="f",+ interpolation=_BRACE_INTERP_RE,+ refuse=_ESCAPED_BRACE_RE,+ refuse_prefixes="b",+ assignment=re.compile(+ r"^[ \t]*(?P<name>[A-Za-z_]\w*)(?:[ \t]*:[^=\n]+)?[ \t]+=[ \t]+(?P<rhs>.*)$",+ re.MULTILINE,+ ),+)++RUST_SYNTAX = UrlSyntax(+ quotes='"',+ format_heads=("format!",),+ placeholder=_BRACE_PLACEHOLDER_RE,+)++CSHARP_SYNTAX = UrlSyntax(+ quotes='"',+ prefixes="$@",+ template_prefixes="$",+ interpolation=_BRACE_INTERP_RE,+ refuse=_ESCAPED_BRACE_RE,+)++GO_SYNTAX = UrlSyntax(+ quotes='"`',+ format_heads=("fmt.Sprintf",),+ placeholder=_C_FORMAT_PLACEHOLDER_RE,+ concat="+",+ assignment=re.compile(+ r"^[ \t]*(?:(?:const|var)[ \t]+)?(?P<name>[A-Za-z_]\w*)[ \t]*:?=[ \t]*(?P<rhs>[^\n]+)$",+ re.MULTILINE,+ ),+)++RUBY_SYNTAX = UrlSyntax(+ template_quotes='"',+ interpolation=re.compile(r"#\{([^{}]+)\}"),+ unwrap_heads=("URI.parse", "URI"),+ concat="+",+ assignment=re.compile(+ r"^[ \t]*(?P<name>[A-Za-z_]\w*)[ \t]*=[ \t]*(?P<rhs>[^\n]+)$", re.MULTILINE+ ),+ assignment_strip=re.compile(r"\.freeze$"),+)++JAVA_SYNTAX = UrlSyntax(+ quotes='"',+ format_heads=("String.format",),+ placeholder=_C_FORMAT_PLACEHOLDER_RE,+ unwrap_heads=("URI.create", "new URI", "new URL", "URI", "HttpUrl.parse"),+ concat="+",+ assignment=re.compile(+ r"(?<![=!<>.\w])(?P<name>[A-Za-z_]\w*)[ \t]*=(?!=)[ \t]*(?P<rhs>[^;\n]+);"+ ),+)++KOTLIN_SYNTAX = UrlSyntax(+ quotes='"',+ template_quotes='"',+ interpolation=re.compile(r"\$\{([^{}]+)\}|\$([A-Za-z_]\w*)"),+ unwrap_heads=("Url", "URI.create", "URI"),+ concat="+",+ assignment=re.compile(+ r"\b(?:val|var)[ \t]+(?P<name>[A-Za-z_]\w*)(?:[ \t]*:[ \t]*[\w<>?]+)?[ \t]*=[ \t]*(?P<rhs>[^\n]+)$",+ re.MULTILINE,+ ),+)++PHP_SYNTAX = UrlSyntax(+ template_quotes='"',+ interpolation=re.compile(r"\{\$([^{}]+)\}|\$\{([^{}]+)\}|\$([A-Za-z_]\w*(?:->[A-Za-z_]\w*)?)"),+ concat=".",+ assignment=re.compile(+ r"(?:\bconst[ \t]+|\$)(?P<name>[A-Za-z_]\w*)[ \t]*=(?!=)[ \t]*(?P<rhs>[^;\n]+);"+ ),+)++__all__ = [+ "CSHARP_SYNTAX",+ "GO_SYNTAX",+ "JAVA_SYNTAX",+ "JS_SYNTAX",+ "KOTLIN_SYNTAX",+ "PHP_SYNTAX",+ "PYTHON_SYNTAX",+ "RUBY_SYNTAX",+ "RUST_SYNTAX",+ "VERBS",+ "ClientCallMatch",+ "call_arguments",+ "consumer_contracts",+ "is_rooted_url",+ "literal_span",+ "match_paren",+ "matches_in",+ "method_from_argument",+ "resolve_url",+ "split_first_arg",+ "string_constants",+]diff --git a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.pyindex 0dc1e4a8c..a3721b3c4 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py@@ -2,25 +2,24 @@Recognises the call shapes common in C# / Unity service clients:-* ``HttpClient`` and wrapper methods — ``GetAsync`` / ``PostAsync`` /+* ``HttpClient`` and wrapper methods: ``GetAsync`` / ``PostAsync`` /``GetRequest<T>`` / ``PostRequest<T>`` (with or without a generic type arg);* ``UnityWebRequest.Get/Post/Put/Delete`` with a literal or interpolated URL;-* Best.HTTP — ``new HTTPRequest(new Uri("..."), HTTPMethods.Get)``.+* Best.HTTP: ``new HTTPRequest(new Uri("..."), HTTPMethods.Get)``.-C# interpolated strings (``$"{_baseUrl}/path/{id}"``) are normalised by-rewriting ``{expr}`` to the ``${expr}`` template form the shared path helpers-already understand, so the leading base placeholder is stripped and interior-expressions collapse to ``{param}``.+An interpolated string (``$"{_baseUrl}/path/{id}"``) resolves through the+shared C# syntax table, so the leading base placeholder is stripped and+interior expressions collapse to ``{param}``."""from __future__ import annotationsimport re+from collections.abc import Iteratorfrom typing import TYPE_CHECKING-from ..base import line_atfrom ..langs import CSHARP-from .dialect import build_consumer_contract+from .client_calls import CSHARP_SYNTAX, ClientCallMatch, consumer_contracts, matches_inif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -48,15 +47,43 @@ _BESTHTTP_RE = re.compile(re.IGNORECASE,)--def _to_template(prefix: str, text: str) -> str:- """Rewrite a C# interpolated string body into ``${expr}`` template form.-- For a non-interpolated string the text is returned unchanged.- """- if "$" in prefix:- return text.replace("{", "${")- return text+_CONFIDENCE = 0.70+++def httpclient_calls(content: str) -> Iterator[ClientCallMatch]:+ yield from matches_in(+ content,+ _WRAPPER_RE,+ client="httpclient",+ url_group=3,+ prefix_group=2,+ method_group=1,+ confidence=_CONFIDENCE,+ )+++def unitywebrequest_calls(content: str) -> Iterator[ClientCallMatch]:+ yield from matches_in(+ content,+ _UNITY_RE,+ client="unitywebrequest",+ url_group=3,+ prefix_group=2,+ method_group=1,+ confidence=_CONFIDENCE,+ )+++def besthttp_calls(content: str) -> Iterator[ClientCallMatch]:+ yield from matches_in(+ content,+ _BESTHTTP_RE,+ client="besthttp",+ url_group=2,+ prefix_group=1,+ method_group=3,+ confidence=_CONFIDENCE,+ )class CSharpHttpDialect:@@ -65,24 +92,10 @@ class CSharpHttpDialect:def extract(self, ctx: ScanContext) -> list[Contract]:content = ctx.content- out: list[Contract] = []-- def emit(method: str, prefix: str, text: str, client: str, line: int) -> None:- url = _to_template(prefix, text)- if "/" not in url:- return # Not a URL path — skip non-route strings.- c = build_consumer_contract(- ctx, method=method.upper(), url=url, client=client, line=line, confidence=0.70- )- if c is not None:- out.append(c)-- for m in _WRAPPER_RE.finditer(content):- emit(m.group(1), m.group(2), m.group(3), "httpclient", line_at(content, m.start()))- for m in _UNITY_RE.finditer(content):- emit(m.group(1), m.group(2), m.group(3), "unitywebrequest", line_at(content, m.start()))- for m in _BESTHTTP_RE.finditer(content):- # Group order: prefix, text, method (method trails the URL here).- emit(m.group(3), m.group(1), m.group(2), "besthttp", line_at(content, m.start()))-- return out+ matches = [+ *httpclient_calls(content),+ *unitywebrequest_calls(content),+ *besthttp_calls(content),+ ]+ # A slash-free string is a key or a name, not a route.+ return consumer_contracts(ctx, matches, CSHARP_SYNTAX, path_only=True)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/go_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/go_clients.pynew file mode 100644index 000000000..764cfca7a--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/go_clients.py@@ -0,0 +1,120 @@+"""Go HTTP consumer dialect: ``net/http`` calls.++Two shapes carry a verb the file can be read for:++* the package-level helpers ``http.Get`` / ``http.Head`` / ``http.Post`` /+ ``http.PostForm``, whose name is the verb and whose first argument is the+ URL;+* ``http.NewRequest(method, url, body)`` and its+ ``http.NewRequestWithContext(ctx, method, url, body)`` sibling, where the+ verb is an argument (``http.MethodGet``, ``"GET"``).++The URL argument is an expression: a literal, a raw string, a+``fmt.Sprintf`` template, a ``base + "/x"`` concatenation, or a name the file+binds once to a string. Anything the file does not settle is refused, and a+``NewRequest`` whose method argument is a runtime value (``o.Method``) is+refused too rather than given an invented verb.++Method calls on a client value (``client.Get(u)``) are not recognised: the+receiver's type is not visible to a text pass, and ``c.Get(key)`` on a cache or+a config map is far more common in Go than a request.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from typing import TYPE_CHECKING++from ..langs import GO+from .client_calls import (+ GO_SYNTAX,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ method_from_argument,+ string_constants,+)++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++_CLIENT = "net/http"++# http.Get( / http.Head( / http.Post( / http.PostForm(+_PACKAGE_VERB_RE = re.compile(r"\bhttp\.(Get|Head|Post|PostForm)\s*\(")++# http.NewRequest( / http.NewRequestWithContext(+_NEW_REQUEST_RE = re.compile(r"\bhttp\.NewRequest(WithContext)?\s*\(")++# Argument positions of (method, url) in each NewRequest form.+_NEW_REQUEST_ARGS = {False: (0, 1), True: (1, 2)}+++def _commented_out(content: str, offset: int) -> bool:+ """True when a ``//`` comment opens on *offset*'s line before it.++ Go doc comments show usage as indented example code, so without this a+ ``// req, _ := http.NewRequest("GET", "https://host/x", nil)`` in a+ docstring becomes a contract. A ``//`` that follows a colon is a URL's+ scheme separator, not a comment.+ """+ prefix = content[content.rfind("\n", 0, offset) + 1 : offset]+ idx = prefix.find("//")+ while idx != -1:+ if idx == 0 or prefix[idx - 1] != ":":+ return True+ idx = prefix.find("//", idx + 2)+ return False+++def net_http_calls(content: str) -> Iterator[ClientCallMatch]:+ """Every ``net/http`` call site whose verb and URL argument are readable."""+ for m in _PACKAGE_VERB_RE.finditer(content):+ if _commented_out(content, m.start()):+ continue+ paren = m.end() - 1+ args = call_arguments(content, paren)+ if not args:+ continue+ # PostForm posts a form body; the verb it sends is still POST.+ verb = "POST" if m.group(1) == "PostForm" else m.group(1).upper()+ yield ClientCallMatch(+ client=_CLIENT,+ url=args[0],+ offset=m.start(),+ method=verb,+ )++ for m in _NEW_REQUEST_RE.finditer(content):+ if _commented_out(content, m.start()):+ continue+ paren = m.end() - 1+ args = call_arguments(content, paren)+ method_at, url_at = _NEW_REQUEST_ARGS[m.group(1) is not None]+ if args is None or len(args) <= url_at:+ continue+ method = method_from_argument(args[method_at])+ if method is None:+ continue # a runtime method value: this layer does not know the verb+ yield ClientCallMatch(+ client=_CLIENT,+ url=args[url_at],+ offset=m.start(),+ method=method,+ )+++class GoClientsDialect:+ name = "go-clients"+ extensions = GO++ def extract(self, ctx: ScanContext) -> list[Contract]:+ rows = list(net_http_calls(ctx.content))+ if not rows:+ return []+ return consumer_contracts(+ ctx, rows, GO_SYNTAX, constants=string_constants(ctx.content, GO_SYNTAX)+ )diff --git a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.pyindex ad2f20d24..d4644c2c7 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py@@ -32,8 +32,17 @@ from typing import TYPE_CHECKINGfrom ..base import line_atfrom ..langs import PYTHON+from .client_calls import (+ JS_SYNTAX,+ PYTHON_SYNTAX,+ VERBS,+ is_rooted_url,+ match_paren,+ resolve_url,+ split_first_arg,+ string_constants,+)from .dialect import build_consumer_contract-from .python_urls import resolve_url_argument, string_constantsfrom .wrappers import (DEFAULT_HOP_BUDGET,GENERIC_ARGS,@@ -70,133 +79,27 @@ _CLIENT_CALL_RE = re.compile(# ``request`` is absent on purpose: it takes the method as its first argument# and the URL as its second, so this rule would record the verb as the path.-_HTTP_VERBS = frozenset({"get", "post", "put", "patch", "delete", "head", "options"})--# A first argument concrete enough to be a URL: a path, a base placeholder, or-# an absolute URL. Mirrors the concreteness test the regex dialect already-# applies, so both paths agree on what counts as a usable literal.-_CONCRETE_URL_RE = re.compile(r"^(?:/|\$\{|https?:|//)")+_HTTP_VERBS = VERBS# ``method: "POST"`` anywhere in the remaining arguments of the same call._METHOD_OPT_RE = re.compile(r"""method\s*:\s*['"](\w+)['"]""")-_QUOTES = "'\"`"---def _match_paren(content: str, open_idx: int) -> int:- """Index of the ``)`` closing the ``(`` at *open_idx*, or -1.-- Quote- and template-aware so a parenthesis inside a string literal does not- unbalance the scan. Nested ``${...}`` inside a template literal is tracked- as ordinary depth, which is what makes ``` `/a/${f(x)}/b` ``` parse.- """- depth = 0- i = open_idx- n = len(content)- # Open template literals, innermost last. A backtick inside a ``${...}``- # opens a *nested* literal rather than closing the outer one, so the state- # has to be a stack: ``fetch(`/a/${c ? `x` : `y`}/b`)`` otherwise reads the- # inner backtick as the end of the string and desynchronises everything- # after it.- tmpl: list[int] = []- quote: str | None = None- while i < n:- ch = content[i]- if quote is not None:- if ch == "\\":- i += 2- continue- if quote == "`" and ch == "$" and i + 1 < n and content[i + 1] == "{":- tmpl.append(depth)- depth += 1- quote = None- i += 2- continue- if ch == quote:- quote = None- i += 1- continue- if ch in _QUOTES:- quote = ch- elif ch in "([{":- depth += 1- elif ch in ")]}":- depth -= 1- if tmpl and ch == "}" and depth == tmpl[-1]:- tmpl.pop()- quote = "`" # back inside the template literal that opened it- elif depth == 0 and ch == ")":- return i- i += 1- return -1---def _split_first_arg(args: str) -> tuple[str, str]:- """Split an argument list into ``(first_arg, rest)`` at the top-level comma."""- depth = 0- tmpl: list[int] = [] # see :func:`_match_paren` — nested templates need a stack- quote: str | None = None- i = 0- n = len(args)- while i < n:- ch = args[i]- if quote is not None:- if ch == "\\":- i += 2- continue- if quote == "`" and ch == "$" and i + 1 < n and args[i + 1] == "{":- tmpl.append(depth)- depth += 1- quote = None- i += 2- continue- if ch == quote:- quote = None- i += 1- continue- if ch in _QUOTES:- quote = ch- elif ch in "([{":- depth += 1- elif ch in ")]}":- depth -= 1- if tmpl and ch == "}" and depth == tmpl[-1]:- tmpl.pop()- quote = "`"- elif ch == "," and depth == 0:- return args[:i].strip(), args[i + 1 :]- i += 1- return args.strip(), ""---def _literal_url(arg: str) -> str | None:- """The URL text of *arg* when it is a single string/template literal, else None.-- A literal spanning the whole argument is required: ``"/a" + x`` and a bare- identifier both return ``None``, because neither is a path this layer may- claim to know.- """- arg = arg.strip()- if len(arg) < 2 or arg[0] not in _QUOTES or arg[-1] != arg[0]:- return None- inner = arg[1:-1]- # A closing quote in the middle means the literal ended and something else- # followed (concatenation), so the argument is not a single literal.- if arg[0] in inner:- return None- return inner if _CONCRETE_URL_RE.match(inner) else None+# Module-level names so a test can stand in a failing scanner.+_match_paren = match_paren+_split_first_arg = split_first_argdef _first_arg_url(arg: str, is_python: bool, constants: dict[str, str]) -> str | None:"""The URL a call's first argument names, or ``None`` if it is not one.- Python additionally reads an f-string and folds a name bound to a string- literal, then faces the same concreteness test as every other language.+ A literal spanning the whole argument is required: ``"/a" + x`` and a bare+ identifier both return ``None``, because neither is a path this layer may+ claim to know. Python additionally reads an f-string and folds a name bound+ to a string literal, then faces the same concreteness test as every other+ language."""- if not is_python:- return _literal_url(arg)- url = resolve_url_argument(arg, constants)- return url if url is not None and _CONCRETE_URL_RE.match(url) else None+ url = resolve_url(arg, PYTHON_SYNTAX if is_python else JS_SYNTAX, constants)+ return url if url is not None and is_rooted_url(url) else Nonedef _client_library(@@ -281,7 +184,7 @@ def extract_consumers(if not confirmed and not sinks and not clients:return [], 0- constants = string_constants(content, code) if is_python else {}+ constants = string_constants(content, PYTHON_SYNTAX, code) if is_python else {}declarations = _declaration_sites(symbols)# Pass 1: every call site of a confirmed wrapper, split into resolveddiff --git a/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/java_clients.pynew file mode 100644index 000000000..784e88175--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py@@ -0,0 +1,188 @@+"""Java HTTP consumer dialect.++Three call shapes, each with its own source for the verb:++* Feign declarative clients: ``@RequestLine("POST /v1/{entityType}/images")``.+ Verb and path both sit inside one annotation string and the placeholders are+ already ``{param}`` shaped, so this is the cleanest Java shape there is.+* ``java.net.http``: ``HttpRequest.newBuilder(URI.create(url))`` or+ ``HttpRequest.newBuilder().uri(URI.create(url))``, with the verb read from the+ builder terminal (``.GET()``, ``.POST(...)``, ``.method("PATCH", ...)``) found+ by walking the chain up to its ``;`` or its ``.build()``.+* Spring ``RestTemplate``: ``getForObject`` / ``postForEntity`` and friends name+ the verb in the callee, ``exchange(uri, HttpMethod.GET, ...)`` names it in the+ second argument.++A chain with no terminal verb is refused rather than defaulted to GET, and a URL+that is a bare variable is refused unless the file assigns it a string literal+exactly once. OkHttp is left out: the corpus builds its ``Request.Builder`` from+a URL validated upstream, so no site carries a path this layer could read.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from typing import TYPE_CHECKING++from ..langs import JAVA+from .client_calls import (+ JAVA_SYNTAX,+ VERBS,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ match_paren,+ method_from_argument,+ string_constants,+)++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# @RequestLine("POST /v1/{entityType}/images"): verb then path, one literal.+_REQUEST_LINE_RE = re.compile(r"@RequestLine\s*\(\s*\"([A-Za-z]+)[ \t]+([^\"\n]*)\"")++# The head of a java.net.http builder chain.+_NEW_BUILDER_RE = re.compile(r"\bHttpRequest\s*\.\s*newBuilder\s*\(")++# One `.name(` step of a fluent chain.+_CHAIN_STEP_RE = re.compile(r"\.\s*([A-Za-z_]\w*)\s*\(")++# How far past the chain head a terminal may sit. A java.net.http request is+# built in a handful of lines; beyond that the scan is reading unrelated code.+_CHAIN_LIMIT = 2000++# RestTemplate calls. The verb-suffixed names are unmistakable; bare `put` and+# `delete` are not, which is why the file is gated on the class name and the+# rows go through `path_only`.+_REST_TEMPLATE_RE = re.compile(+ r"\b(?:[A-Za-z_]\w*\s*\.\s*"+ r"(getForObject|getForEntity|postForObject|postForEntity|patchForObject|exchange)"+ r"|\w*[Tt]emplate\w*\s*\.\s*(put|delete))"+ r"\s*\("+)++_FEIGN_CONFIDENCE = 0.75+_BUILDER_CONFIDENCE = 0.75+_REST_TEMPLATE_CONFIDENCE = 0.65+++def feign_calls(content: str) -> Iterator[ClientCallMatch]:+ for m in _REQUEST_LINE_RE.finditer(content):+ verb = m.group(1)+ if verb.lower() not in VERBS:+ continue+ yield ClientCallMatch(+ client="feign",+ # The annotation holds the path unquoted; the resolver reads a+ # literal, so hand it one.+ url=f'"{m.group(2).strip()}"',+ offset=m.start(),+ method=verb.upper(),+ confidence=_FEIGN_CONFIDENCE,+ )+++def _chain_steps(content: str, start: int) -> Iterator[tuple[str, int]]:+ """``(step name, its '(' offset)`` for each ``.name(...)`` from *start*.++ Stops at the first character that is not part of the chain (the statement's+ ``;``, a comma, a closing paren) and after ``.build()``, so a verb belonging+ to a neighbouring call is never read as this request's terminal.+ """+ i = start+ limit = min(len(content), start + _CHAIN_LIMIT)+ while i < limit:+ if content[i].isspace():+ i += 1+ continue+ m = _CHAIN_STEP_RE.match(content, i)+ if m is None:+ return+ close = match_paren(content, m.end() - 1)+ if close < 0:+ return+ yield m.group(1), m.end() - 1+ if m.group(1) == "build":+ return+ i = close + 1+++def java_net_http_calls(content: str) -> Iterator[ClientCallMatch]:+ for m in _NEW_BUILDER_RE.finditer(content):+ paren = m.end() - 1+ close = match_paren(content, paren)+ args = call_arguments(content, paren, close) if close >= 0 else None+ if args is None:+ continue+ # newBuilder(uri); the two-argument copy form carries a request, not a URL.+ url = args[0] if len(args) == 1 else None+ method: str | None = None+ for name, step_paren in _chain_steps(content, close + 1):+ if name == "uri" and url is None:+ inner = call_arguments(content, step_paren)+ if inner is not None and len(inner) == 1:+ url = inner[0]+ elif name.isupper() and name.lower() in VERBS:+ method = name+ elif name == "method":+ inner = call_arguments(content, step_paren)+ if inner:+ method = method_from_argument(inner[0])+ if url is None or method is None:+ continue # no URL, or a verb only the caller knows+ yield ClientCallMatch(+ client="java-net-http",+ url=url,+ offset=m.start(),+ method=method,+ confidence=_BUILDER_CONFIDENCE,+ )+++def resttemplate_calls(content: str) -> Iterator[ClientCallMatch]:+ if "RestTemplate" not in content:+ return+ for m in _REST_TEMPLATE_RE.finditer(content):+ callee = m.group(1) or m.group(2)+ paren = m.end() - 1+ args = call_arguments(content, paren)+ if not args:+ continue+ method = None+ if callee == "exchange":+ if len(args) < 2:+ continue+ method = method_from_argument(args[1])+ if method is None:+ continue # a verb held in a variable is not one we know+ yield ClientCallMatch(+ client="resttemplate",+ url=args[0],+ offset=m.start(),+ callee=callee,+ method=method,+ confidence=_REST_TEMPLATE_CONFIDENCE,+ )+++class JavaClientsDialect:+ name = "java-clients"+ extensions = JAVA++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ named = [*feign_calls(content), *java_net_http_calls(content)]+ # `.put`/`.delete` on any receiver could be a collection, so a URL with+ # no slash in it is a key rather than a route.+ ambiguous = list(resttemplate_calls(content))+ if not named and not ambiguous:+ return []+ constants = string_constants(content, JAVA_SYNTAX)+ return [+ *consumer_contracts(ctx, named, JAVA_SYNTAX, constants=constants),+ *consumer_contracts(ctx, ambiguous, JAVA_SYNTAX, constants=constants, path_only=True),+ ]diff --git a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.pyindex 718e4e9c0..ffbcb0083 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py@@ -1,20 +1,21 @@"""JavaScript / TypeScript HTTP consumer dialect.Covers direct ``fetch`` / ``axios`` calls plus wrapper calls whose first-argument is a concrete URL literal — e.g. ``fetchJSON(`${BASE}/path`, { method:+argument is a concrete URL literal, e.g. ``fetchJSON(`${BASE}/path`, { method:"POST" })``. Wrapper detection is signal-gated (the callee name looks HTTP-ish,or the call carries a ``method:`` option) so ordinary `/`-prefixed string-arguments — router navigation, i18n keys — are not mistaken for service calls.+arguments, router navigation and i18n keys, are not mistaken for service calls."""from __future__ import annotationsimport re+from collections.abc import Iteratorfrom typing import TYPE_CHECKING-from ..base import line_atfrom ..langs import JS_TS-from .dialect import METHODS, build_consumer_contract, method_from_callee+from .client_calls import JS_SYNTAX, ClientCallMatch, consumer_contracts, literal_span, matches_in+from .dialect import METHODSif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -52,71 +53,55 @@ _METHOD_OPT_RE = re.compile(r"""method\s*:\s*['"](\w+)['"]""")_WRAPPER_SKIP = frozenset({"fetch", "if", "for", "while", "switch", "catch", "return"})+def fetch_calls(content: str) -> Iterator[ClientCallMatch]:+ """``fetch(url, { method })`` rows first, then plain ``fetch(url)`` as GET.++ A URL that appears with an explicit method anywhere in the file is not+ re-emitted as a GET.+ """+ yield from matches_in(content, _FETCH_METHOD_RE, client="fetch", url_group=1, method_group=2)+ method_urls = {m.group(1) for m in _FETCH_METHOD_RE.finditer(content)}+ for m in _FETCH_RE.finditer(content):+ if m.group(1) in method_urls:+ continue+ yield ClientCallMatch(+ client="fetch", url=literal_span(content, m, 1), offset=m.start(), callee="fetch"+ )+++def axios_calls(content: str) -> Iterator[ClientCallMatch]:+ yield from matches_in(content, _AXIOS_RE, client="axios", url_group=2, method_group=1)+++def wrapper_calls(content: str) -> Iterator[ClientCallMatch]:+ """``fetchJSON(`${BASE}/path`, { method: "POST" })`` and its relatives."""+ for m in _WRAPPER_CALL_RE.finditer(content):+ callee = m.group(1)+ if callee in _WRAPPER_SKIP:+ continue+ nl = content.find("\n", m.end())+ window = content[m.end() :] if nl == -1 else content[m.end() : nl]+ method_opt = _METHOD_OPT_RE.search(window)+ # Require an HTTP signal: an HTTP-ish callee name or a method option.+ if not (_HTTP_NAME_RE.search(callee) or method_opt):+ continue+ # No `method:` option: the callee name is the only verb evidence there+ # is, and `apiPost`/`apiDelete` carry it.+ yield ClientCallMatch(+ client="wrapper",+ url=literal_span(content, m, 2),+ offset=m.start(),+ callee=callee,+ method=method_opt.group(1).upper() if method_opt else None,+ confidence=0.65,+ )++class JsClientsDialect:name = "js-clients"extensions = JS_TSdef extract(self, ctx: ScanContext) -> list[Contract]:content = ctx.content- out: list[Contract] = []-- def emit(- *, method: str, url: str, client: str, line: int, confidence: float = 0.75- ) -> None:- c = build_consumer_contract(- ctx, method=method, url=url, client=client, line=line, confidence=confidence- )- if c is not None:- out.append(c)-- # fetch() with an explicit method.- for m in _FETCH_METHOD_RE.finditer(content):- emit(- method=m.group(2).upper(),- url=m.group(1),- client="fetch",- line=line_at(content, m.start()),- )-- # fetch() without a method → GET, skipping URLs already matched above.- method_urls = {m.group(1) for m in _FETCH_METHOD_RE.finditer(content)}- for m in _FETCH_RE.finditer(content):- url = m.group(1)- if url in method_urls:- continue- emit(method="GET", url=url, client="fetch", line=line_at(content, m.start()))-- # axios.<method>()- for m in _AXIOS_RE.finditer(content):- emit(- method=m.group(1).upper(),- url=m.group(2),- client="axios",- line=line_at(content, m.start()),- )-- # Wrapper calls — fetchJSON(`${BASE}/path`, { method: "POST" }) etc.- for m in _WRAPPER_CALL_RE.finditer(content):- callee = m.group(1)- if callee in _WRAPPER_SKIP:- continue- nl = content.find("\n", m.end())- window = content[m.end() :] if nl == -1 else content[m.end() : nl]- method_opt = _METHOD_OPT_RE.search(window)- # Require an HTTP signal: an HTTP-ish callee name or a method option.- if not (_HTTP_NAME_RE.search(callee) or method_opt):- continue- # No `method:` option: the callee name is the only verb evidence- # there is, and `apiPost`/`apiDelete` carry it.- method = (- method_opt.group(1).upper() if method_opt else method_from_callee(callee)- )- emit(- method=method,- url=m.group(2),- client="wrapper",- line=line_at(content, m.start()),- confidence=0.65,- )-- return out+ matches = [*fetch_calls(content), *axios_calls(content), *wrapper_calls(content)]+ return consumer_contracts(ctx, matches, JS_SYNTAX)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/kotlin_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/kotlin_clients.pynew file mode 100644index 000000000..2abdfc7ab--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/kotlin_clients.py@@ -0,0 +1,233 @@+"""Kotlin HTTP consumer dialect: Ktor client calls.++Ktor spells one request in three ways, and all three are recognised here:++* a verb with a URL argument: ``client.get("$TEST_SERVER/echo")``,+ ``client.post(path)``, optionally followed by a configuration block;+* a verb with only a block, where the URL is built inside it:+ ``client.get { url(path = "/widget", port = port) }``,+ ``client.post { url("http://host/widget") }``,+ ``client.get { url { takeFrom(base) } }``;+* ``client.request(...)`` with the verb set in the block:+ ``client.request("/echo") { method = HttpMethod.Post }``.++A block with no ``url(...)`` in it configures a request whose URL comes from+the client's ``defaultRequest``, which this file cannot see, so it is refused.+So is a ``request`` call with no ``method``, and the four-argument+``url(scheme, host, port, path)`` overload, whose path is positional and+indistinguishable from its scheme.++The receiver's type is unknown here: ``.get(...)`` is also how a map is read.+Three cheap gates stand in for it. The file has to name Ktor's client package,+the URL has to hold a ``/``, and the receiver may not be a type name, which is+what keeps a lookup key and a ``Paths.get`` from becoming routes.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from typing import TYPE_CHECKING++from ..langs import KOTLIN+from .client_calls import (+ KOTLIN_SYNTAX,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ match_paren,+ method_from_argument,+ string_constants,+)++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# Ktor's client package. A file that never names it is not a Ktor call site,+# whether it imports the package or declares it.+_KTOR_PACKAGE = "io.ktor.client"++_VERBS = r"get|post|put|patch|delete|head"++# client.get("/x"): a verb with an argument list.+_VERB_ARG_RE = re.compile(rf"\.({_VERBS})\s*\(")+# client.get { ... }: a verb whose only argument is the configuration block.+_VERB_BLOCK_RE = re.compile(rf"\.({_VERBS})\s*\{{")+# client.request("/x") { ... } / client.request { ... }+_REQUEST_RE = re.compile(r"\.request\s*(\(|\{)")++# url("...") / url(path = "...") inside a request block.+_URL_CALL_RE = re.compile(r"\burl\s*\(")+# url { takeFrom("...") }: the URL built through a nested builder block.+_URL_BLOCK_RE = re.compile(r"\burl\s*\{")+_URL_BUILDER_CALL_RE = re.compile(r"\b(?:path|takeFrom)\s*\(")+# method = HttpMethod.Post, the verb a `request` block carries.+_METHOD_ASSIGN_RE = re.compile(r"\bmethod\s*=\s*([\w.]+)")++_NAMED_ARG_RE = re.compile(r"([A-Za-z_]\w*)\s*=(?!=)\s*(.*)", re.DOTALL)++# The identifier a call hangs off, when the receiver is a plain name.+_RECEIVER_RE = re.compile(r"[A-Za-z_]\w*$")++_CONFIDENCE = 0.65+++def _block_end(content: str, open_idx: int) -> int:+ """Index of the ``}`` closing the lambda opened at *open_idx*, or -1."""+ return match_paren(content, open_idx, closer="}")+++def _skip_site(content: str, offset: int) -> bool:+ """True when the call at *offset* cannot be a request on a client value.++ Two things a text scan can still tell apart. A KDoc example: Ktor documents+ every builder with one, so the same call shapes appear dozens of times in+ prose, and ``wrappers.mask_source`` covers Python and JS-like files only.+ And a receiver that is a type rather than a value: Kotlin names values in+ lower camel case, so ``Paths.get("build.gradle")`` is a file, not a route,+ while ``client.get(...)`` and ``createClient().get(...)`` both stay.+ """+ # Bounded so a long generated line is not copied once per call on it.+ line_start = max(content.rfind("\n", 0, offset) + 1, offset - 200)+ line = content[line_start:offset]+ if line.lstrip().startswith(("*", "//", "/*")):+ return True+ receiver = _RECEIVER_RE.search(line)+ return receiver is not None and receiver.group()[0].isupper()+++def _url_argument(content: str, paren_offset: int) -> str | None:+ """The URL expression a ``url(...)`` call names, or ``None``.++ A named ``path`` argument wins; failing that the call has to carry exactly+ one positional argument, so the ``url(scheme, host, port, path)`` overload+ is refused rather than read as a URL string.+ """+ args = call_arguments(content, paren_offset)+ if not args:+ return None+ positional: list[str] = []+ for arg in args:+ named = _NAMED_ARG_RE.fullmatch(arg)+ if named is None:+ positional.append(arg)+ elif named.group(1) == "path":+ return named.group(2).strip()+ return positional[0] if len(positional) == 1 else None+++def _block_url(content: str, block_start: int, block_end: int) -> str | None:+ """The URL a request block builds."""+ call = _URL_CALL_RE.search(content, block_start, block_end)+ if call is not None:+ return _url_argument(content, call.end() - 1)+ builder = _URL_BLOCK_RE.search(content, block_start, block_end)+ if builder is None:+ return None+ inner_end = _block_end(content, builder.end() - 1)+ if inner_end < 0:+ return None+ call = _URL_BUILDER_CALL_RE.search(content, builder.end(), inner_end)+ if call is None:+ return None+ args = call_arguments(content, call.end() - 1)+ return args[0] if args and len(args) == 1 else None+++def _trailing_block(content: str, offset: int) -> int:+ """Index of the ``{`` opening a block right after *offset*, or -1."""+ i, n = offset, len(content)+ while i < n and content[i] in " \t\r\n":+ i += 1+ return i if i < n and content[i] == "{" else -1+++def ktor_calls(content: str) -> Iterator[ClientCallMatch]:+ for m in _VERB_ARG_RE.finditer(content):+ if _skip_site(content, m.start()):+ continue+ args = call_arguments(content, m.end() - 1)+ if not args:+ continue+ yield ClientCallMatch(+ client="ktor",+ url=args[0],+ offset=m.start(),+ method=m.group(1).upper(),+ confidence=_CONFIDENCE,+ )++ for m in _VERB_BLOCK_RE.finditer(content):+ if _skip_site(content, m.start()):+ continue+ end = _block_end(content, m.end() - 1)+ if end < 0:+ continue+ url = _block_url(content, m.end(), end)+ if url is None:+ continue+ yield ClientCallMatch(+ client="ktor",+ url=url,+ offset=m.start(),+ method=m.group(1).upper(),+ confidence=_CONFIDENCE,+ )++ for m in _REQUEST_RE.finditer(content):+ if _skip_site(content, m.start()):+ continue+ if m.group(1) == "(":+ close = match_paren(content, m.end() - 1)+ if close < 0:+ continue+ args = call_arguments(content, m.end() - 1, close)+ url = args[0] if args else None+ block = _trailing_block(content, close + 1)+ else:+ url, block = None, m.end() - 1+ if block < 0:+ continue+ end = _block_end(content, block)+ if end < 0:+ continue+ if url is None:+ url = _block_url(content, block + 1, end)+ if url is None:+ continue+ verb = _METHOD_ASSIGN_RE.search(content, block, end)+ method = method_from_argument(verb.group(1)) if verb is not None else None+ if method is None:+ continue # a request whose verb is not written here is not one we know+ yield ClientCallMatch(+ client="ktor",+ url=url,+ offset=m.start(),+ method=method,+ confidence=_CONFIDENCE,+ )+++class KotlinClientsDialect:+ name = "kotlin-clients"+ extensions = KOTLIN++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if _KTOR_PACKAGE not in content:+ return []+ rows = list(ktor_calls(content))+ if not rows:+ return []+ # `.get("key")` on a map has no slash; the receiver is anyone's. A+ # relative path composes onto the client's default request base.+ return consumer_contracts(+ ctx,+ rows,+ KOTLIN_SYNTAX,+ constants=string_constants(content, KOTLIN_SYNTAX),+ path_only=True,+ rooted_only=True,+ )diff --git a/packages/core/src/repowise/core/workspace/extractors/http/php_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/php_clients.pynew file mode 100644index 000000000..0e521154b--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/php_clients.py@@ -0,0 +1,175 @@+"""PHP HTTP consumer dialect: Guzzle and the Laravel ``Http`` facade.++Recognises the two shapes PHP application code actually uses:++* Guzzle's generic form, ``$client->request('GET', $url, ...)``, where the verb+ is the first argument and the URL the second, and its verb-named form,+ ``$client->get($url)``. The generic form is read only in a file that names+ Guzzle, because ``->request(...)`` and ``->get(...)`` are common method names+ on anything.+* The Laravel facade, ``Http::get($url)`` and its chained builders+ (``Http::withToken($t)->post($url)``), read from ``Http::`` forward along the+ chain to the call that names a verb.++The URL argument is handed to the shared resolver, so a literal, an+interpolated string and a concatenation onto a folded constant all resolve,+while a property (``$this->uri``) or a ``config(...)`` lookup is refused: PHP+does not settle either one inside the file.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from typing import TYPE_CHECKING++from ..langs import PHP+from .client_calls import (+ PHP_SYNTAX,+ VERBS,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ match_paren,+ method_from_argument,+ string_constants,+)++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# A receiver the call hangs off: a variable or one property of one.+_RECEIVER = r"\$[A-Za-z_]\w*(?:->[A-Za-z_]\w*)?"++_GUZZLE_REQUEST_RE = re.compile(rf"{_RECEIVER}\s*->\s*request\s*\(")+_GUZZLE_VERB_RE = re.compile(rf"{_RECEIVER}\s*->\s*(get|post|put|patch|delete|head)\s*\(")++# Guzzle is only claimed in a file that names a client: the client class, a+# construction, or the interface a constructor is typed against. Naming the+# package alone is not enough: a file importing only a PSR-7 helper from it+# still calls ``->get(...)`` on things that are not HTTP clients.+_GUZZLE_GATE_RE = re.compile(r"GuzzleHttp\\Client|new\s+(?:Guzzle)?Client\s*\(|\bClientInterface\b")++_HTTP_FACADE_RE = re.compile(r"\bHttp::")+_CHAIN_LINK_RE = re.compile(r"([A-Za-z_]\w*)\s*\(")+_CHAIN_ARROW_RE = re.compile(r"\s*->\s*")++# How far along a builder chain the verb call is looked for.+_MAX_CHAIN_LINKS = 8++_AMBIGUOUS_RECEIVER_CONFIDENCE = 0.65+++def _names_a_client(content: str) -> bool:+ return "Client" in content and _GUZZLE_GATE_RE.search(content) is not None+++def guzzle_request_calls(content: str) -> Iterator[ClientCallMatch]:+ """``$client->request('GET', $url, ...)``: verb first, URL second."""+ if not _names_a_client(content):+ return+ for m in _GUZZLE_REQUEST_RE.finditer(content):+ open_idx = m.end() - 1+ args = call_arguments(content, open_idx)+ if args is None or len(args) < 2:+ continue+ method = method_from_argument(args[0])+ if method is None:+ continue # a runtime verb: this layer has no way to know it+ yield ClientCallMatch(+ client="guzzle",+ url=args[1],+ offset=m.start(),+ method=method,+ )+++def guzzle_verb_calls(content: str) -> Iterator[ClientCallMatch]:+ """``$client->get($url)``: the verb is the callee's name."""+ if not _names_a_client(content):+ return+ for m in _GUZZLE_VERB_RE.finditer(content):+ open_idx = m.end() - 1+ args = call_arguments(content, open_idx)+ if not args:+ continue+ yield ClientCallMatch(+ client="guzzle",+ url=args[0],+ offset=m.start(),+ method=m.group(1).upper(),+ confidence=_AMBIGUOUS_RECEIVER_CONFIDENCE,+ )+++def laravel_http_calls(content: str) -> Iterator[ClientCallMatch]:+ """``Http::get($url)`` and the chained builders that end in a verb call."""+ if "Http::" not in content:+ return+ for m in _HTTP_FACADE_RE.finditer(content):+ pos = m.end()+ for _ in range(_MAX_CHAIN_LINKS):+ link = _CHAIN_LINK_RE.match(content, pos)+ if link is None:+ break+ open_idx = link.end() - 1+ close = match_paren(content, open_idx)+ if close < 0:+ break+ if link.group(1).lower() in VERBS:+ args = call_arguments(content, open_idx, close)+ if args:+ yield ClientCallMatch(+ client="laravel-http",+ url=args[0],+ offset=m.start(),+ method=link.group(1).upper(),+ )+ break+ arrow = _CHAIN_ARROW_RE.match(content, close + 1)+ if arrow is None:+ break # the chain ended before naming a verb+ pos = arrow.end()+++class PhpClientsDialect:+ name = "php-clients"+ extensions = PHP++ def extract(self, ctx: ScanContext) -> list[Contract]:+ request_rows = list(guzzle_request_calls(ctx.content))+ verb_rows = list(guzzle_verb_calls(ctx.content))+ facade_rows = list(laravel_http_calls(ctx.content))+ if not request_rows and not verb_rows and not facade_rows:+ return []+ constants = string_constants(ctx.content, PHP_SYNTAX)+ # A Guzzle client composes a relative path onto its `base_uri`, so only+ # a rooted or absolute URL names the route reached.+ out = consumer_contracts(+ ctx,+ request_rows,+ PHP_SYNTAX,+ constants=constants,+ rooted_only=True,+ )+ # `->get('key')` on anything is a lookup, and a bare host carries no+ # route, so both verb-named shapes need a path.+ out += consumer_contracts(+ ctx,+ verb_rows,+ PHP_SYNTAX,+ constants=constants,+ path_only=True,+ rooted_only=True,+ )+ out += consumer_contracts(+ ctx,+ facade_rows,+ PHP_SYNTAX,+ constants=constants,+ path_only=True,+ rooted_only=True,+ )+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/python_clients.pyindex fa4cba52b..0387bda23 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py@@ -1,13 +1,14 @@-"""Python HTTP consumer dialect — ``requests`` and ``httpx``."""+"""Python HTTP consumer dialect: ``requests`` and ``httpx``."""from __future__ import annotationsimport re+from collections.abc import Iteratorfrom typing import TYPE_CHECKING-from ..base import line_atfrom ..langs import PYTHON-from .dialect import METHODS, build_consumer_contract+from .client_calls import PYTHON_SYNTAX, ClientCallMatch, consumer_contracts, matches_in+from .dialect import METHODSif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -21,20 +22,13 @@ _REQUESTS_RE = re.compile()+def requests_calls(content: str) -> Iterator[ClientCallMatch]:+ yield from matches_in(content, _REQUESTS_RE, client="requests", url_group=2, method_group=1)++class PythonClientsDialect:name = "python-clients"extensions = PYTHONdef extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _REQUESTS_RE.finditer(ctx.content):- c = build_consumer_contract(- ctx,- method=m.group(1).upper(),- url=m.group(2),- client="requests",- line=line_at(ctx.content, m.start()),- )- if c is not None:- out.append(c)- return out+ return consumer_contracts(ctx, requests_calls(ctx.content), PYTHON_SYNTAX)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/python_urls.py b/packages/core/src/repowise/core/workspace/extractors/http/python_urls.pydeleted file mode 100644index bd33dcb41..000000000--- a/packages/core/src/repowise/core/workspace/extractors/http/python_urls.py+++ /dev/null@@ -1,123 +0,0 @@-"""Resolve a Python HTTP call's URL argument to text this package can normalize.--Python spells a client call's URL two ways the whole-literal test in-:mod:`.index_clients` cannot read: an f-string (``f"{base}/users"``), and a name-bound to one earlier (``url = f"..."`` then ``client.post(url)``). Both are-settled where they are written, so reading them is substitution rather than-analysis, and no dataflow is claimed by doing it.--**What folds and what is refused.** A name folds only when the file assigns it-exactly once, to a single string literal on one line. Assigned twice, or-assigned anything else anywhere in the file, it is left unresolved and the call-is *counted* as unresolved rather than guessed. File scope, not lexical scope: a-single static assignment means the same thing wherever it is read.--f-string interpolations come out in the ``${expr}`` form the rest of this-package already speaks, so :func:`.paths.strip_leading_base_expr` strips a-Python base placeholder and :func:`.paths.normalize_http_path` collapses a-Python path parameter with no per-language branch in either.-"""--from __future__ import annotations--import re--# A whole-argument string literal, prefix included. ``.*`` is greedy against an-# anchored end, so the quote-inside check below is what rejects a concatenation.-_LITERAL_RE = re.compile(- r"^(?P<prefix>[A-Za-z]*)(?P<q>'''|\"\"\"|'|\")(?P<body>.*)(?P=q)$", re.DOTALL-)--_NAME_RE = re.compile(r"[A-Za-z_]\w*")--# ``NAME = <expr>`` at any indentation, RHS to end of line. The whitespace-# around ``=`` is required, which excludes the usual unspaced keyword argument-# on its own line (``url=str(resp.url),``) — that otherwise reads as a second-# assignment and retires the very name being folded. A *spaced* kwarg still-# retires it, so the guard is partial; either way the cost is a lost fold, never-# a fabricated path.-_ASSIGN_RE = re.compile(- r"^[ \t]*([A-Za-z_]\w*)(?:[ \t]*:[^=\n]+)?[ \t]+=[ \t]+(.*)$", re.MULTILINE-)--# One ``{expr}`` interpolation.-_INTERP_RE = re.compile(r"(?<!\{)\{([^{}]+)\}(?!\})")--# ``{{`` / ``}}`` are an escaped brace, which no downstream step distinguishes-# from a path parameter: ``normalize_http_path`` would eat one half and leave-# the other dangling, and the surviving ``}`` passes the unusable-path check.-# A URL needing a literal brace is refused rather than corrupted.-_ESCAPED_BRACE_RE = re.compile(r"\{\{|\}\}")--# Dropped from a base expression (``settings.base.rstrip('/')``) so-# :func:`.paths.base_token_identifier` reads the attribute, not ``rstrip``.-_TRAILING_CALL_RE = re.compile(r"\.\s*\w+\s*\([^()]*\)\s*$")---def _parse_literal(text: str) -> tuple[str, str] | None:- """``(lowercased prefix, body)`` when *text* is exactly one string literal."""- m = _LITERAL_RE.match(text.strip())- if m is None:- return None- body = m.group("body")- if m.group("q") in body:- return None # the literal ended and something else followed it- return m.group("prefix").lower(), body---def string_constants(content: str, code: str) -> dict[str, str]:- """Names this file assigns exactly once, to one string literal.-- The value is the literal's raw text with its prefix, so an f-string keeps- its interpolations for :func:`resolve_url_argument` to fold.-- Assignments are located in *code* — the same text as *content* with comments- and string bodies blanked — and their values are then read from *content* at- the same offsets. Searching *content* directly would read the example code- in a docstring (`` url = "/docs/example"``) as a real assignment.- """- seen: dict[str, str | None] = {}- for m in _ASSIGN_RE.finditer(code):- name, rhs = m.group(1), content[m.start(2) : m.end(2)].rstrip()- # A second assignment retires the name whatever it assigns: the reader- # cannot tell which one reaches the call site.- seen[name] = None if name in seen or _parse_literal(rhs) is None else rhs.strip()- return {name: text for name, text in seen.items() if text is not None}---def _template(body: str, constants: dict[str, str]) -> str:- """An f-string body as ``${expr}`` text, folding names bound to a plain string."""-- def sub(m: re.Match[str]) -> str:- expr = m.group(1).strip()- const = constants.get(expr)- if const is not None:- inner = _parse_literal(const)- # Only a plain literal folds: an f-string constant would need its- # own interpolations resolved, which no case in the corpus needs.- if inner is not None and "f" not in inner[0]:- return inner[1]- return "${" + _TRAILING_CALL_RE.sub("", expr) + "}"-- return _INTERP_RE.sub(sub, body)---def resolve_url_argument(arg: str, constants: dict[str, str]) -> str | None:- """The URL text of *arg*, or ``None`` when it cannot be resolved."""- text = arg.strip()- parsed = _parse_literal(text)- if parsed is None:- # A bare name. Its folded value is a literal by construction, so one- # step always reaches the text.- if _NAME_RE.fullmatch(text) is None:- return None- folded = constants.get(text)- parsed = _parse_literal(folded) if folded is not None else None- if parsed is None:- return None- prefix, body = parsed- if "b" in prefix:- return None # bytes, not a URL this layer records- if "f" not in prefix:- return body- return None if _ESCAPED_BRACE_RE.search(body) else _template(body, constants)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/ruby_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/ruby_clients.pynew file mode 100644index 000000000..e2a72a0b6--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/ruby_clients.py@@ -0,0 +1,172 @@+"""Ruby HTTP consumer dialect: HTTParty, RestClient, Faraday and Net::HTTP.++The four libraries share one call shape, a module or connection receiver with+the verb as the method name, so one argument reader serves all of them:++* ``HTTParty.get(CLEARBIT_ENDPOINT, options)`` and its ``post``/``put``/+ ``patch``/``delete`` siblings, the URL a constant, an interpolated string+ (``"#{BASE_URL}/accounts/#{id}"``) or a concatenation;+* ``RestClient.post(url, body, headers)``, same shape, label ``restclient``;+* ``Faraday.get(url)`` on the module, and ``conn.get("/x")`` on a connection+ the file binds with ``conn = Faraday.new(...)``;+* ``Net::HTTP.get(URI(url))`` / ``get_response`` / ``post``, and the request+ object form ``http.request(Net::HTTP::Get.new(uri))`` where the verb is a+ class name.++Ruby allows the parentheses to be omitted, so an argument list that does not+start with ``(`` is read to the first top-level comma or the end of the line.++A URL the file does not settle is refused: a helper method (``ping_url``), a+parameter, and the ``uri`` local a ``Net::HTTP.start`` block receives all yield+no contract, because a guessed path is a wrong edge.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from typing import TYPE_CHECKING++from ..langs import RUBY+from .client_calls import (+ RUBY_SYNTAX,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ match_paren,+ method_from_argument,+ split_first_arg,+ string_constants,+)++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++_VERBS = r"get|post|put|patch|delete|head|options"++# The module receivers, each mapped to the client label its rows carry.+_MODULE_CLIENTS = {"HTTParty": "httparty", "RestClient": "restclient", "Faraday": "faraday"}++_MODULE_CALL_RE = re.compile(rf"\b(HTTParty|RestClient|Faraday)\.({_VERBS})\b")++# ``get_response`` leads the alternation so it is not read as ``get``.+_NET_HTTP_RE = re.compile(rf"\bNet::HTTP\.(get_response|{_VERBS})\b")++# ``http.request(Net::HTTP::Get.new(uri))``: the verb is the class name.+_REQUEST_OBJECT_RE = re.compile(r"\.request\s*\(\s*(Net::HTTP::\w+)\.new\s*\(")++_FARADAY_NEW_RE = re.compile(r"(?<![.\w])(@?[a-z_]\w*)\s*=\s*Faraday\.new\b")++_CONNECTION_CONFIDENCE = 0.65+++def _first_argument(content: str, end: int) -> str | None:+ """The URL argument of the call whose callee ends at *end*.++ Ruby lets the parentheses go, so without one the argument runs to the+ first top-level comma or the end of the line.+ """+ i = end+ while i < len(content) and content[i] in " \t":+ i += 1+ if i < len(content) and content[i] == "(":+ close = match_paren(content, i)+ if close < 0:+ return None+ first, _ = split_first_arg(content[i + 1 : close])+ return first or None+ line_end = content.find("\n", i)+ if line_end < 0:+ line_end = len(content)+ first, _ = split_first_arg(content[i:line_end])+ return first or None+++def module_calls(content: str) -> Iterator[ClientCallMatch]:+ """``HTTParty.get(...)`` / ``RestClient.post(...)`` / ``Faraday.get(...)``."""+ for m in _MODULE_CALL_RE.finditer(content):+ url = _first_argument(content, m.end())+ if url is None:+ continue+ yield ClientCallMatch(+ client=_MODULE_CLIENTS[m.group(1)],+ url=url,+ offset=m.start(),+ method=m.group(2).upper(),+ )+++def net_http_calls(content: str) -> Iterator[ClientCallMatch]:+ """``Net::HTTP.get(URI(url))`` and ``http.request(Net::HTTP::Get.new(uri))``."""+ for m in _NET_HTTP_RE.finditer(content):+ url = _first_argument(content, m.end())+ if url is None:+ continue+ verb = m.group(1)+ yield ClientCallMatch(+ client="net-http",+ url=url,+ offset=m.start(),+ method="GET" if verb == "get_response" else verb.upper(),+ )+ for m in _REQUEST_OBJECT_RE.finditer(content):+ method = method_from_argument(m.group(1))+ args = call_arguments(content, m.end() - 1)+ if method is None or not args:+ continue+ yield ClientCallMatch(+ client="net-http",+ url=args[0],+ offset=m.start(),+ method=method,+ )+++def faraday_connection_calls(content: str) -> Iterator[ClientCallMatch]:+ """``conn.get("/x")`` where the file binds ``conn`` with ``Faraday.new``."""+ receivers = {m.group(1) for m in _FARADAY_NEW_RE.finditer(content)}+ if not receivers:+ return+ alternation = "|".join(re.escape(r) for r in sorted(receivers, key=len, reverse=True))+ # The parenthesis is required here, unlike the module forms: an unqualified+ # receiver reads as a request only when it is called, so `conn.options` (a+ # Faraday connection's settings object) is not mistaken for an OPTIONS call.+ rx = re.compile(rf"(?<![.\w@])({alternation})\.({_VERBS})\s*\(")+ for m in rx.finditer(content):+ args = call_arguments(content, m.end() - 1)+ if not args:+ continue+ yield ClientCallMatch(+ client="faraday",+ url=args[0],+ offset=m.start(),+ method=m.group(2).upper(),+ confidence=_CONNECTION_CONFIDENCE,+ )+++class RubyClientsDialect:+ name = "ruby-clients"+ extensions = RUBY++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ rows = [*module_calls(content), *net_http_calls(content)]+ connection_rows = list(faraday_connection_calls(content))+ if not rows and not connection_rows:+ return []+ constants = string_constants(content, RUBY_SYNTAX)+ out = consumer_contracts(ctx, rows, RUBY_SYNTAX, constants=constants)+ # A connection variable's `.get` could be a hash lookup, so a URL with+ # no slash in it is not a route.+ out += consumer_contracts(+ ctx,+ connection_rows,+ RUBY_SYNTAX,+ constants=constants,+ path_only=True,+ rooted_only=True,+ )+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.pyindex 57508bf3b..bb59c40f6 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py@@ -1,24 +1,24 @@-"""Rust HTTP consumer dialect — ``reqwest`` client calls.+"""Rust HTTP consumer dialect: ``reqwest`` client calls.Recognises ``reqwest`` method calls whose URL is recoverable at the call site:-* string literals — ``client.get("http://host/path")`` / ``reqwest::get("...")``;-* ``format!`` templates — ``client.get(format!("{}/systems/{}", base, id))``,+* string literals: ``client.get("http://host/path")`` / ``reqwest::get("...")``;+* ``format!`` templates: ``client.get(format!("{}/systems/{}", base, id))``,where the leading ``{}`` is the base placeholder and interior ``{}`` collapseto ``{param}``.Calls with a bare variable URL (``client.get(&url)``) are left unmatched. Hyper-is lower level — its method is set apart from the URI — and is not modelled.+is lower level, its method is set apart from the URI, and is not modelled."""from __future__ import annotationsimport re+from collections.abc import Iteratorfrom typing import TYPE_CHECKING-from ..base import line_atfrom ..langs import RUST-from .dialect import build_consumer_contract+from .client_calls import RUST_SYNTAX, ClientCallMatch, consumer_contracts, matches_inif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -32,14 +32,29 @@ _METHOD_LIT_RE = re.compile(rf"""\.({_VERBS})\s*\(\s*&?\s*"([^"]*)\"""")# reqwest::get("...") — free function form._FREE_LIT_RE = re.compile(rf"""\breqwest::({_VERBS})\s*\(\s*&?\s*"([^"]*)\"""")# client.get(format!("{}/path", ...)) — receiver method with a format! template.-_METHOD_FMT_RE = re.compile(rf"""\.({_VERBS})\s*\(\s*&?\s*format!\s*\(\s*"([^"]*)\"""")+_METHOD_FMT_RE = re.compile(rf"""\.({_VERBS})\s*\(\s*&?\s*(format!\s*\(\s*"[^"]*")""")# reqwest::get(format!("...", ...))-_FREE_FMT_RE = re.compile(rf"""\breqwest::({_VERBS})\s*\(\s*&?\s*format!\s*\(\s*"([^"]*)\"""")--# A Rust format! placeholder: `{}`, `{0}`, `{name}`. Rewritten to the `${expr}`-# template form the shared path helpers understand (leading one stripped as the-# base, interior ones collapsed to {param}).-_FMT_PLACEHOLDER_RE = re.compile(r"\{[^}]*\}")+_FREE_FMT_RE = re.compile(rf"""\breqwest::({_VERBS})\s*\(\s*&?\s*(format!\s*\(\s*"[^"]*")""")++_CONFIDENCE = 0.65+++def reqwest_calls(content: str) -> Iterator[ClientCallMatch]:+ for rx in (_METHOD_LIT_RE, _FREE_LIT_RE):+ yield from matches_in(+ content, rx, client="reqwest", url_group=2, method_group=1, confidence=_CONFIDENCE+ )+ for rx in (_METHOD_FMT_RE, _FREE_FMT_RE):+ for m in rx.finditer(content):+ # Only the template is read; the closing paren completes the call+ # expression for the resolver without scanning the arguments.+ yield ClientCallMatch(+ client="reqwest",+ url=m.group(2) + ")",+ offset=m.start(),+ method=m.group(1).upper(),+ confidence=_CONFIDENCE,+ )class RustClientsDialect:@@ -47,25 +62,5 @@ class RustClientsDialect:extensions = RUSTdef extract(self, ctx: ScanContext) -> list[Contract]:- content = ctx.content- out: list[Contract] = []-- def emit(method: str, url: str, line: int) -> None:- if "/" not in url:- return # Not a URL path — skip map/collection .get("key") calls.- c = build_consumer_contract(- ctx, method=method.upper(), url=url, client="reqwest", line=line, confidence=0.65- )- if c is not None:- out.append(c)-- for rx in (_METHOD_LIT_RE, _FREE_LIT_RE):- for m in rx.finditer(content):- emit(m.group(1), m.group(2), line_at(content, m.start()))-- for rx in (_METHOD_FMT_RE, _FREE_FMT_RE):- for m in rx.finditer(content):- url = _FMT_PLACEHOLDER_RE.sub("${x}", m.group(2))- emit(m.group(1), url, line_at(content, m.start()))-- return out+ # `.get("key")` on a map has no slash; the receiver is anyone's.+ return consumer_contracts(ctx, reqwest_calls(ctx.content), RUST_SYNTAX, path_only=True)diff --git a/tests/unit/workspace/test_client_calls.py b/tests/unit/workspace/test_client_calls.pynew file mode 100644index 000000000..797e02ffb--- /dev/null+++ b/tests/unit/workspace/test_client_calls.py@@ -0,0 +1,291 @@+"""The shared HTTP client-call layer: URL expression resolution per language,+method inference from an argument, and the contract loop the dialects share.++The claim under test is that a URL argument is read as an *expression* and+refused when it cannot be settled in the file, so a guessed edge never forms.+"""++from __future__ import annotations++import pytest++from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http.client_calls import (+ CSHARP_SYNTAX,+ GO_SYNTAX,+ JAVA_SYNTAX,+ JS_SYNTAX,+ KOTLIN_SYNTAX,+ PHP_SYNTAX,+ PYTHON_SYNTAX,+ RUBY_SYNTAX,+ RUST_SYNTAX,+ ClientCallMatch,+ call_arguments,+ consumer_contracts,+ method_from_argument,+ resolve_url,+ split_first_arg,+ string_constants,+)+++class TestLiterals:+ @pytest.mark.parametrize(+ ("syntax", "expr", "expected"),+ [+ (JS_SYNTAX, "'/api/users'", "/api/users"),+ (JS_SYNTAX, "`${BASE}/users/${id}`", "${BASE}/users/${id}"),+ (PYTHON_SYNTAX, '"/api/users"', "/api/users"),+ (PYTHON_SYNTAX, 'f"{base}/users/{uid}"', "${base}/users/${uid}"),+ (PYTHON_SYNTAX, 'r"/raw"', "/raw"),+ (RUST_SYNTAX, '"http://svc/health"', "http://svc/health"),+ (CSHARP_SYNTAX, '$"{_baseUrl}/vix/{id}/bid"', "${_baseUrl}/vix/${id}/bid"),+ (CSHARP_SYNTAX, '@"/verbatim/{notinterp}"', "/verbatim/{notinterp}"),+ (GO_SYNTAX, '"/api/v1"', "/api/v1"),+ (GO_SYNTAX, "`/raw/path`", "/raw/path"),+ (+ RUBY_SYNTAX,+ '"#{BASE_URL}/accounts/#{@account_id}"',+ "${BASE_URL}/accounts/${@account_id}",+ ),+ (RUBY_SYNTAX, "'#{not_interpolated}'", "#{not_interpolated}"),+ (KOTLIN_SYNTAX, '"$TEST_SERVER/echo_query"', "${TEST_SERVER}/echo_query"),+ (KOTLIN_SYNTAX, '"${server.url}/x"', "${server.url}/x"),+ (KOTLIN_SYNTAX, '"""$BASE/raw"""', "${BASE}/raw"),+ (PHP_SYNTAX, '"$base/users/{$id}"', "${base}/users/${id}"),+ (PHP_SYNTAX, "'$literal/x'", "$literal/x"),+ ],+ )+ def test_literal_bodies(self, syntax, expr, expected):+ assert resolve_url(expr, syntax) == expected++ @pytest.mark.parametrize(+ ("syntax", "expr"),+ [+ (JS_SYNTAX, "path"),+ (JS_SYNTAX, '"/a" + id'),+ (JS_SYNTAX, "buildPath(id)"),+ (PYTHON_SYNTAX, 'b"/bytes"'),+ (PYTHON_SYNTAX, 'f"/x/{{literal}}"'),+ (RUST_SYNTAX, "&url"),+ (GO_SYNTAX, "u"),+ ],+ )+ def test_unsettled_expressions_are_refused(self, syntax, expr):+ assert resolve_url(expr, syntax) is None+++class TestFormatCalls:+ def test_rust_format(self):+ expr = 'format!("{}/systems/{}", base, id)'+ assert resolve_url(expr, RUST_SYNTAX) == "${x}/systems/${x}"++ def test_go_sprintf(self):+ expr = 'fmt.Sprintf("%s/%s/@v/%s.zip", proxy, mod, ver)'+ assert resolve_url(expr, GO_SYNTAX) == "${x}/${x}/@v/${x}.zip"++ def test_java_string_format(self):+ expr = 'String.format("https://api.example.com/v3/price?ids=%s", ids)'+ assert resolve_url(expr, JAVA_SYNTAX) == "https://api.example.com/v3/price?ids=${x}"++ def test_a_format_call_whose_template_is_not_a_literal_is_refused(self):+ assert resolve_url("fmt.Sprintf(tmpl, a)", GO_SYNTAX) is None+++class TestUnwrapAndConcat:+ def test_java_uri_create_is_unwrapped(self):+ assert resolve_url('URI.create(base + "/echo")', JAVA_SYNTAX) == "${base}/echo"++ def test_go_concat_with_a_trailing_name(self):+ assert resolve_url('"/users/" + id', GO_SYNTAX) == "/users/${id}"++ def test_php_concat(self):+ assert resolve_url("$this->base . '/contacts/' . $id", PHP_SYNTAX) == (+ "${$this->base}/contacts/${$id}"+ )++ def test_concat_with_a_call_is_refused(self):+ assert resolve_url('base + "/" + fmt(x)', GO_SYNTAX) is None++ def test_a_concat_of_two_names_carries_no_path(self):+ assert resolve_url("c.InfoAPIURL + id.Name", GO_SYNTAX) == "${c.InfoAPIURL}${id.Name}"+++class TestConstantFolding:+ def test_python_single_assignment_folds(self):+ content = 'BASE = "http://svc"\nurl = f"{BASE}/users"\nrequests.get(url)\n'+ constants = string_constants(content, PYTHON_SYNTAX)+ assert resolve_url("url", PYTHON_SYNTAX, constants) == "http://svc/users"++ def test_a_reassigned_name_is_retired(self):+ content = 'url = "/a"\nurl = "/b"\n'+ assert string_constants(content, PYTHON_SYNTAX) == {}++ def test_go_short_declaration(self):+ content = 'u := fmt.Sprintf("%s/x", base)\nresp, err := http.Get(u)\n'+ constants = string_constants(content, GO_SYNTAX)+ # A format call bound once folds at the call site like a literal.+ assert resolve_url("u", GO_SYNTAX, constants) == "${x}/x"+ assert resolve_url("other", GO_SYNTAX, constants) is None+ content = 'const liveReloadSourceURL = "https://example.com/livereload.js"\n'+ constants = string_constants(content, GO_SYNTAX)+ assert resolve_url("liveReloadSourceURL", GO_SYNTAX, constants) == (+ "https://example.com/livereload.js"+ )++ def test_ruby_frozen_constant(self):+ content = "CLEARBIT_ENDPOINT = 'https://person.clearbit.com/v2/find'.freeze\n"+ constants = string_constants(content, RUBY_SYNTAX)+ assert resolve_url("CLEARBIT_ENDPOINT", RUBY_SYNTAX, constants) == (+ "https://person.clearbit.com/v2/find"+ )++ def test_ruby_interpolated_constant_folds_inline(self):+ content = "BASE_URL = 'https://api.dyte.io/v2'\n"+ constants = string_constants(content, RUBY_SYNTAX)+ expr = '"#{BASE_URL}/accounts/#{@account_id}/kit"'+ assert resolve_url(expr, RUBY_SYNTAX, constants) == (+ "https://api.dyte.io/v2/accounts/${@account_id}/kit"+ )++ def test_java_field_initialiser(self):+ content = 'private static final String BASE = "https://svc/api";\n'+ constants = string_constants(content, JAVA_SYNTAX)+ assert resolve_url('BASE + "/users"', JAVA_SYNTAX, constants) == "https://svc/api/users"++ def test_kotlin_const_val(self):+ content = 'const val TEST_SERVER = "http://127.0.0.1:8080"\n'+ constants = string_constants(content, KOTLIN_SYNTAX)+ assert resolve_url('"$TEST_SERVER/echo"', KOTLIN_SYNTAX, constants) == (+ "http://127.0.0.1:8080/echo"+ )++ def test_php_variable_and_const(self):+ content = "$base = 'https://svc';\nconst PATH = '/x';\n"+ constants = string_constants(content, PHP_SYNTAX)+ assert resolve_url("$base . PATH", PHP_SYNTAX, constants) == "https://svc/x"++ def test_a_comparison_is_not_an_assignment(self):+ assert string_constants('if (a == "x") {}\n', JAVA_SYNTAX) == {}++ @pytest.mark.parametrize(+ ("syntax", "content"),+ [+ (GO_SYNTAX, 'base := "http://host"\nbase += "/v1"\n'),+ (GO_SYNTAX, 'url := "https://host/v1"\nurl, err = build(id)\n'),+ (PHP_SYNTAX, "$b = 'http://host';\n$b .= '/v1';\n"),+ (KOTLIN_SYNTAX, 'var b = "http://host"\nb += "/v1"\n'),+ ],+ )+ def test_a_compound_or_multiple_assignment_retires_the_name(self, syntax, content):+ assert string_constants(content, syntax) == {}++ def test_a_field_assignment_is_not_a_local(self):+ content = 'this.baseUrl = "https://prod/api";\nString f(String baseUrl) {}\n'+ assert string_constants(content, JAVA_SYNTAX) == {}++ @pytest.mark.parametrize(+ ("syntax", "content"),+ [+ (JAVA_SYNTAX, '/** String url = "/v1/example"; */\n'),+ (KOTLIN_SYNTAX, '// val base = "/v1/example"\n'),+ (RUBY_SYNTAX, "# BASE = 'https://h/root'\n"),+ ],+ )+ def test_an_assignment_in_a_comment_is_not_a_binding(self, syntax, content):+ assert string_constants(content, syntax) == {}++ def test_an_unwrap_or_format_call_must_be_the_whole_expression(self):+ constants = {"BASE": '"https://h/root"'}+ assert resolve_url('URI.create(BASE).resolve("/v2")', JAVA_SYNTAX, constants) is None+ assert resolve_url('fmt.Sprintf("%s/api", b) + "/v2"', GO_SYNTAX) is None+ assert resolve_url("URI.parse(BASE) + '/x'", RUBY_SYNTAX, constants) is None++ def test_a_doubled_percent_is_a_literal(self):+ assert resolve_url('fmt.Sprintf("/a/100%%/%s", x)', GO_SYNTAX) == "/a/100%/${x}"++ def test_csharp_escaped_braces_are_refused(self):+ assert resolve_url('$"/a/{{lit}}/{id}"', CSHARP_SYNTAX) is None+++class TestMethodFromArgument:+ @pytest.mark.parametrize(+ ("text", "expected"),+ [+ ("'GET'", "GET"),+ ('"post"', "POST"),+ ("http.MethodGet", "GET"),+ ("HttpMethod.POST", "POST"),+ ("HTTPMethods.Get", "GET"),+ ("Net::HTTP::Get", "GET"),+ ("o.Method", None),+ ("method", None),+ ("options", None),+ ("GET", "GET"),+ ('"BUY"', None),+ ],+ )+ def test_verbs(self, text, expected):+ assert method_from_argument(text) == expected+++class TestArgumentScanning:+ def test_call_arguments_split_at_top_level(self):+ src = 'http.NewRequest(http.MethodGet, fmt.Sprintf("%s/x", a), nil)'+ assert call_arguments(src, src.index("(")) == [+ "http.MethodGet",+ 'fmt.Sprintf("%s/x", a)',+ "nil",+ ]++ def test_an_unclosed_call_is_none_and_no_arguments_is_empty(self):+ assert call_arguments("f(a, b", 1) is None+ assert call_arguments("f( )", 1) == []++ def test_split_first_arg_keeps_the_rest(self):+ assert split_first_arg("`/a/${f(x, y)}`, { method: 'POST' }") == (+ "`/a/${f(x, y)}`",+ " { method: 'POST' }",+ )+++class TestLiteralSpan:+ def test_a_capture_cut_at_an_inner_quote_keeps_its_prefix(self):+ from repowise.core.workspace.extractors.http.js_clients import fetch_calls++ content = "fetch(`https://h/v1/links?${new URLSearchParams({ a: 'x' })}`)"+ (row,) = fetch_calls(content)+ assert row.url == "`https://h/v1/links?${new URLSearchParams({ a: `"+ assert resolve_url(row.url, JS_SYNTAX) == "https://h/v1/links?${new URLSearchParams({ a: "+++class TestConsumerContracts:+ def _ctx(self, content: str, suffix: str = ".go") -> ScanContext:+ return ScanContext("svc", f"client{suffix}", suffix, content, {}, None)++ def test_method_falls_back_to_the_callee_name(self):+ content = 'apiPost("/users")'+ rows = [ClientCallMatch(client="w", url='"/users"', offset=0, callee="apiPost")]+ (c,) = consumer_contracts(self._ctx(content), rows, GO_SYNTAX)+ assert c.contract_id == "http::POST::/users"+ assert c.line == 1+ assert c.meta["client"] == "w"++ def test_an_unresolved_url_emits_nothing(self):+ rows = [ClientCallMatch(client="w", url="u", offset=0, method="GET")]+ assert consumer_contracts(self._ctx("f(u)"), rows, GO_SYNTAX) == []++ def test_rooted_only_drops_a_base_relative_path(self):+ rows = [+ ClientCallMatch(client="w", url='"some/path"', offset=0, method="GET"),+ ClientCallMatch(client="w", url='"/rooted"', offset=0, method="GET"),+ ClientCallMatch(client="w", url='"${b}/x"', offset=0, method="GET"),+ ]+ got = consumer_contracts(self._ctx("x", ".js"), rows, JS_SYNTAX, rooted_only=True)+ assert [c.contract_id for c in got] == ["http::GET::/rooted", "http::GET::/x"]++ def test_path_only_drops_a_key_lookup(self):+ rows = [ClientCallMatch(client="w", url='"database_url"', offset=0, method="GET")]+ assert consumer_contracts(self._ctx("x"), rows, GO_SYNTAX, path_only=True) == []+ assert len(consumer_contracts(self._ctx("x"), rows, GO_SYNTAX)) == 1diff --git a/tests/unit/workspace/test_dialect_regressions.py b/tests/unit/workspace/test_dialect_regressions.pyindex f71461276..c3dacb479 100644--- a/tests/unit/workspace/test_dialect_regressions.py+++ b/tests/unit/workspace/test_dialect_regressions.py@@ -29,6 +29,7 @@ from repowise.core.workspace.extractors.base import (from repowise.core.workspace.extractors.data import DataExtractorfrom repowise.core.workspace.extractors.data.sql_strings import SqlStringsDialectfrom repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.jaxrs import JaxRsDialectdef _ctx(content: str, rel_path: str = "app/routers/chat.py") -> ScanContext:@@ -247,3 +248,50 @@ class TestDataExtractorEndToEnd:assert "data::git_metadata" in idsfor fabricated in ("data::ranked", "data::path", "data::would"):assert fabricated not in ids+++class TestQuarkusIsJaxRs:+ """A Quarkus REST resource is a JAX-RS resource and needs no dialect of its own.++ The JAX-RS dialect gates on ``@Path`` in the file, not on the stack, so the+ ``jakarta.ws.rs`` annotations Quarkus uses yield contracts as they are.+ """++ RESOURCE = """package org.acme;++import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import io.quarkus.runtime.annotations.RegisterForReflection;++@Path("/fruits")+public class FruitResource {++ @GET+ public List<Fruit> list() { return Fruit.listAll(); }++ @GET+ @Path("/{id}")+ public Fruit get(@PathParam("id") Long id) { return Fruit.findById(id); }++ @POST+ public Response add(Fruit fruit) { fruit.persist(); return Response.ok(fruit).build(); }+}+"""++ def test_quarkus_resource_yields_jaxrs_contracts(self) -> None:+ ctx = ScanContext(+ repo_alias="api",+ rel_path="src/main/java/org/acme/FruitResource.java",+ suffix=".java",+ content=self.RESOURCE,+ )+ contracts = JaxRsDialect().extract(ctx)+ assert _ids(contracts) == {+ "http::GET::/fruits",+ "http::GET::/fruits/{param}",+ "http::POST::/fruits",+ }+ assert {c.meta["framework"] for c in contracts} == {"jaxrs"}+diff --git a/tests/unit/workspace/test_go_clients.py b/tests/unit/workspace/test_go_clients.pynew file mode 100644index 000000000..e4c47e91e--- /dev/null+++ b/tests/unit/workspace/test_go_clients.py@@ -0,0 +1,301 @@+"""The Go ``net/http`` consumer dialect.++The claim under test is that a verb is read from the call and never invented,+and that a URL argument is resolved as an expression or refused, so a call whose+target the file does not settle produces no contract at all.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import match_contracts+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.go_clients import GoClientsDialect, net_http_calls++PACKAGE_VERBS = """package main++import "net/http"++func run() {+ http.Get("https://api.example.com/v1/items")+ http.Head("https://api.example.com/v1/items")+ http.Post("https://api.example.com/v1/items", "application/json", body)+ http.PostForm("https://api.example.com/v1/forms", values)+}+"""++NEW_REQUEST = """package main++import "net/http"++func run(ctx context.Context) {+ a, _ := http.NewRequest(http.MethodGet, "https://api.example.com/v1/items", nil)+ b, _ := http.NewRequest("DELETE", "https://api.example.com/v1/items/42", nil)+ c, _ := http.NewRequestWithContext(ctx, http.MethodPut, "https://api.example.com/v1/items/42", body)+}+"""++CONSTANT_URL = """package main++const verifyURL = "https://api.example.com/v1/verify"++func run() {+ http.Post(verifyURL, "application/json", body)+}+"""++SHORT_DECL_URL = """package main++func run() {+ endpoint := "https://api.example.com/v1/ping"+ http.Get(endpoint)+}+"""++SPRINTF_URL = """package main++func run(base, id string) {+ http.Get(fmt.Sprintf("%s/v1/items/%s", base, id))+}+"""++CONCAT_URL = """package main++func run(base string) {+ http.Get(base + "/v1/items")+}+"""++RAW_STRING_URL = """package main++func run() {+ http.Get(`https://api.example.com/v1/raw`)+}+"""++MULTILINE_CALL = """package main++func run(ctx context.Context) {+ req, err := http.NewRequestWithContext(+ ctx,+ http.MethodPost,+ "https://api.example.com/v1/token",+ strings.NewReader(post.Encode()),+ )+}+"""++RUNTIME_METHOD = """package main++func run(o options, url string) {+ req, err := http.NewRequest(o.Method, "https://api.example.com/v1/items", o.BodyReader())+}+"""++HELPER_URL = """package main++func run() {+ requestURL, err := formatPypiRegistryURL(baseURL, name, version)+ req, err := http.NewRequest(http.MethodGet, requestURL, nil)+}+"""++SPRINTF_INTO_VARIABLE = """package main++func run(proxy, name string) {+ u := fmt.Sprintf("%s/%s/@v/latest.zip", proxy, name)+ resp, err := http.Get(u)+}+"""++REASSIGNED_URL = """package main++func run(flag bool) {+ endpoint := "https://api.example.com/v1/a"+ endpoint = "https://api.example.com/v1/b"+ http.Get(endpoint)+}+"""++COMMENT_EXAMPLE = """package main++// Sign applies a signature to a request.+//+// Example usage:+//+// req, _ := http.NewRequest("GET", "https://my-bucket.example.com/my-object", nil)+func Sign(req *http.Request) error {+ return nil+}+"""++CLIENT_RECEIVER = """package main++func run() {+ client := &http.Client{}+ client.Get("https://api.example.com/v1/items")+}+"""++BARE_ROOT = """package main++func run() {+ req, _ := http.NewRequest(http.MethodGet, "/", nil)+}+"""++MAP_LOOKUP = """package main++func run(c cache, client apiClient) {+ v := c.Get("some-key")+ client.Post("/v1/items", body)+}+"""+++def _ctx(content: str, rel_path: str = "client.go") -> ScanContext:+ return ScanContext("repo", rel_path, ".go", content, {}, None)+++def _extract(content: str) -> list:+ return GoClientsDialect().extract(_ctx(content))+++def _ids(content: str) -> list[str]:+ return [c.contract_id for c in _extract(content)]+++class TestGoClientsRecognition:+ def test_package_verbs_carry_their_own_method(self) -> None:+ rows = list(net_http_calls(PACKAGE_VERBS))+ assert [r.method for r in rows] == ["GET", "HEAD", "POST", "POST"]+ assert {r.client for r in rows} == {"net/http"}++ def test_new_request_reads_the_method_argument(self) -> None:+ rows = list(net_http_calls(NEW_REQUEST))+ assert [r.method for r in rows] == ["GET", "DELETE", "PUT"]++ def test_new_request_url_is_the_second_argument(self) -> None:+ rows = list(net_http_calls(NEW_REQUEST))+ assert rows[0].url == '"https://api.example.com/v1/items"'++ def test_with_context_url_is_the_third_argument(self) -> None:+ rows = list(net_http_calls(NEW_REQUEST))+ assert rows[2].url == '"https://api.example.com/v1/items/42"'++ def test_arguments_split_across_lines(self) -> None:+ rows = list(net_http_calls(MULTILINE_CALL))+ assert [(r.method, r.url) for r in rows] == [("POST", '"https://api.example.com/v1/token"')]+++class TestGoClientsContracts:+ def test_package_verbs_emit_one_contract_each(self) -> None:+ assert _ids(PACKAGE_VERBS) == [+ "http::GET::/v1/items",+ "http::HEAD::/v1/items",+ "http::POST::/v1/items",+ "http::POST::/v1/forms",+ ]++ def test_new_request_forms_emit_their_argument_verb(self) -> None:+ assert _ids(NEW_REQUEST) == [+ "http::GET::/v1/items",+ "http::DELETE::/v1/items/42",+ "http::PUT::/v1/items/42",+ ]++ def test_meta_names_the_client_and_the_host(self) -> None:+ (contract,) = _extract(CONSTANT_URL)+ assert contract.meta["client"] == "net/http"+ assert contract.meta["host"] == "api.example.com"+ assert contract.confidence == 0.75++ def test_package_constant_folds(self) -> None:+ assert _ids(CONSTANT_URL) == ["http::POST::/v1/verify"]++ def test_short_declaration_folds(self) -> None:+ assert _ids(SHORT_DECL_URL) == ["http::GET::/v1/ping"]++ def test_sprintf_template_collapses_to_parameters(self) -> None:+ (contract,) = _extract(SPRINTF_URL)+ assert contract.contract_id == "http::GET::/v1/items/{param}"+ assert contract.meta["base_stripped"] is True++ def test_concatenated_base_is_stripped(self) -> None:+ (contract,) = _extract(CONCAT_URL)+ assert contract.contract_id == "http::GET::/v1/items"+ assert contract.meta["base_token"] == "base"++ def test_raw_string_literal_resolves(self) -> None:+ assert _ids(RAW_STRING_URL) == ["http::GET::/v1/raw"]++ def test_line_is_the_call_site(self) -> None:+ (contract,) = _extract(CONSTANT_URL)+ assert contract.line == 6+++class TestGoClientsRefusals:+ def test_runtime_method_variable_emits_nothing(self) -> None:+ assert _extract(RUNTIME_METHOD) == []++ def test_url_from_a_helper_call_emits_nothing(self) -> None:+ assert _extract(HELPER_URL) == []++ def test_variable_bound_once_to_a_format_call_folds(self) -> None:+ (c,) = _extract(SPRINTF_INTO_VARIABLE)+ assert c.contract_id == "http::GET::/{param}/@v/latest.zip"+ assert c.meta.get("base_stripped") is True++ def test_twice_assigned_name_emits_nothing(self) -> None:+ assert _extract(REASSIGNED_URL) == []++ def test_example_in_a_doc_comment_emits_nothing(self) -> None:+ assert _extract(COMMENT_EXAMPLE) == []++ def test_a_bare_root_path_emits_nothing(self) -> None:+ # A test server's `"/"` names no route to match on.+ assert _extract(BARE_ROOT) == []++ def test_client_receiver_call_emits_nothing(self) -> None:+ assert _extract(CLIENT_RECEIVER) == []++ def test_lookups_on_an_untyped_receiver_emit_nothing(self) -> None:+ assert _extract(MAP_LOOKUP) == []+++GO_CONSUMER = """package main++func fetchUser(base, id string) {+ http.Get(fmt.Sprintf("%s/users/%s", base, id))+}+"""++FASTAPI_PROVIDER = """from fastapi import FastAPI++app = FastAPI()++[email protected]("/users/{user_id}")+def read_user(user_id: str):+ return {"id": user_id}+"""+++class TestGoClientsCrossRepoLink:+ def test_go_consumer_links_to_a_python_provider(self) -> None:+ extractor = HttpExtractor()+ extractor.provider_dialects = (FastApiDialect(),)+ extractor.consumer_dialects = (GoClientsDialect(),)+ providers = extractor.extract(+ Path("."), "api", files=[("main.py", ".py", FASTAPI_PROVIDER)]+ )+ consumers = extractor.extract(+ Path("."), "worker", files=[("client.go", ".go", GO_CONSUMER)]+ )+ links = match_contracts(providers + consumers)+ assert len(links) == 1+ assert links[0].provider_repo == "api"+ assert links[0].consumer_repo == "worker"diff --git a/tests/unit/workspace/test_index_clients.py b/tests/unit/workspace/test_index_clients.pyindex e0cab0f0a..bd65033b6 100644--- a/tests/unit/workspace/test_index_clients.py+++ b/tests/unit/workspace/test_index_clients.py@@ -681,9 +681,9 @@ class TestSupersedeCannotSubtract:],)def test_literal_url_recognition(args: str, expected: str | None):- from repowise.core.workspace.extractors.http.index_clients import _literal_url+ from repowise.core.workspace.extractors.http.client_calls import JS_SYNTAX, resolve_url- assert _literal_url(args) == expected+ assert resolve_url(args, JS_SYNTAX) == expected# ---------------------------------------------------------------------------diff --git a/tests/unit/workspace/test_java_clients.py b/tests/unit/workspace/test_java_clients.pynew file mode 100644index 000000000..78e6acecc--- /dev/null+++ b/tests/unit/workspace/test_java_clients.py@@ -0,0 +1,479 @@+"""The Java HTTP consumer dialect.++The claim under test is that each Java shape carries its verb from a place the+file actually names (a Feign annotation, a builder terminal, a callee name, an+``HttpMethod`` constant) and that a URL is resolved as an expression or refused,+so a builder whose terminal or target the file does not settle emits nothing.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import match_contracts+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.java_clients import (+ JavaClientsDialect,+ feign_calls,+ java_net_http_calls,+ resttemplate_calls,+)++FEIGN_CLIENT = """package com.example.client;++import feign.Param;+import feign.RequestLine;++public interface ImagesApi {++ @RequestLine("POST /v1/{entityType}/{entityId}/images")+ void create(@Param("entityType") String entityType);++ @RequestLine("GET /v1/{entityType}/{entityId}/images")+ String read(@Param("entityType") String entityType);++ @RequestLine("DELETE /v1/{entityType}/{entityId}/images")+ void remove(@Param("entityType") String entityType);+}+"""++FEIGN_QUERY_AND_RELATIVE = """package com.example.client;++public interface LoansApi {++ @RequestLine("POST v1/internal/loans/{loanId}/activate?date={date}")+ void activate(@Param("loanId") Long loanId);+}+"""++FEIGN_NON_VERB = """package com.example.client;++public interface Odd {++ @RequestLine("TRACE /v1/diagnostics")+ void trace();+}+"""++BUILDER_LITERAL = """package com.example;++class Client {+ void ping() throws Exception {+ final HttpRequest request = HttpRequest.newBuilder()+ .uri(URI.create("https://api.example.com/v1/ping"))+ .GET()+ .build();+ }+}+"""++BUILDER_URI_FIRST_ARG = """package com.example;++class Client {+ HttpRequest post(String base) {+ return HttpRequest.newBuilder(URI.create(base + "/v1/echo"))+ .POST(HttpRequest.BodyPublishers.ofString("{}"))+ .header("Content-Type", "application/json")+ .build();+ }+}+"""++BUILDER_STRING_FORMAT = """package com.example;++class Client {+ HttpRequest fetch(String id) {+ return HttpRequest.newBuilder()+ .uri(URI.create(String.format("https://api.example.com/v1/items/%s", id)))+ .DELETE()+ .build();+ }+}+"""++BUILDER_METHOD_LITERAL = """package com.example;++class Client {+ HttpRequest patch() {+ return HttpRequest.newBuilder(URI.create("https://api.example.com/v1/items/7"))+ .method("PATCH", HttpRequest.BodyPublishers.ofString("{}"))+ .build();+ }+}+"""++BUILDER_FOLDED_CONSTANT = """package com.example;++class Client {+ private static final String ENDPOINT = "https://api.example.com/v1/status";++ HttpRequest status() {+ return HttpRequest.newBuilder().uri(URI.create(ENDPOINT)).GET().build();+ }+}+"""++BUILDER_NO_TERMINAL = """package com.example;++class Client {+ HttpRequest.Builder base() {+ return HttpRequest.newBuilder(URI.create("https://api.example.com/v1/items"))+ .header("Accept", "application/json");+ }+}+"""++BUILDER_VARIABLE_METHOD = """package com.example;++class Client {+ HttpRequest any(String method) {+ return HttpRequest.newBuilder()+ .uri(URI.create("https://api.example.com/v1/items"))+ .method(method, HttpRequest.BodyPublishers.noBody())+ .build();+ }+}+"""++BUILDER_OPAQUE_URI = """package com.example;++class Client {+ HttpRequest send(URI uri) {+ return HttpRequest.newBuilder().uri(uri).GET().build();+ }+}+"""++BUILDER_HELPER_URL = """package com.example;++class Client {+ HttpRequest copy() {+ return HttpRequest.newBuilder()+ .uri(URI.create(copyUrl()))+ .PUT(HttpRequest.BodyPublishers.ofString("{}"))+ .build();+ }+}+"""++BUILDER_NO_URI = """package com.example;++class Client {+ HttpRequest.Builder get() {+ return HttpRequest.newBuilder().GET();+ }+}+"""++BUILDER_NEIGHBOURING_VERB = """package com.example;++class Client {+ void run(String base) throws Exception {+ client.send(HttpRequest.newBuilder(URI.create(base + "/v1/first")).build(), handler);+ client.send(HttpRequest.newBuilder(URI.create(base + "/v1/second")).GET().build(), handler);+ }+}+"""++REST_TEMPLATE_CALLEES = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate restTemplate, String baseUrl) {+ restTemplate.getForObject(baseUrl + "/v1/pets", Pet.class);+ restTemplate.postForEntity(baseUrl + "/v1/pets", request, Pet.class);+ restTemplate.delete(baseUrl + "/v1/pets/7");+ }+}+"""++REST_TEMPLATE_EXCHANGE = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate rest, int port) {+ rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET, entity, String.class);+ rest.exchange("https://api.example.com/v1/sms", HttpMethod.POST, entity, String.class);+ }+}+"""++REST_TEMPLATE_VARIABLE_VERB = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate rest, HttpMethod verb) {+ rest.exchange("https://api.example.com/v1/sms", verb, entity, String.class);+ }+}+"""++REST_TEMPLATE_OPAQUE_URI = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate restTemplate, URI uri) {+ restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);+ }+}+"""++MAP_PUT_IN_REST_TEMPLATE_FILE = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(Map<String, String> headers) {+ headers.put("Accept", "application/json");+ headers.delete("Accept");+ }+}+"""++MAP_PUT_WITHOUT_REST_TEMPLATE = """package com.example;++class Cache {+ void run(Map<String, String> routes) {+ routes.put("/v1/pets", "handler");+ }+}+"""++MAP_PUT_BESIDE_A_TEMPLATE_PUT = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate restTemplate, HttpHeaders headers, Object body) {+ headers.put("Content-Type", "application/json");+ restTemplate.put("/v1/pets/7", body);+ }+}+"""++OKHTTP_BUILDER = """package com.example;++import okhttp3.Request;++class Client {+ Request build(String url) {+ return new Request.Builder().url(url).get().build();+ }+}+"""++REST_TEMPLATE_REQUEST_ENTITY = """package com.example;++import org.springframework.web.client.RestTemplate;++class Client {+ void run(RestTemplate template) {+ template.exchange(RequestEntity.get("/owners/1").build(), String.class);+ }+}+"""++BUILDER_INSTANCE_FORMATTED = """package com.example;++class Client {+ HttpRequest list(String prefix) {+ return HttpRequest.newBuilder()+ .uri(URI.create("%s%s".formatted(listUrl(), prefix)))+ .GET()+ .build();+ }+}+"""+++def contracts(content: str, rel_path: str = "Client.java") -> list:+ ctx = ScanContext("svc", rel_path, ".java", content, {}, None)+ return JavaClientsDialect().extract(ctx)+++def ids(content: str) -> set[str]:+ return {c.contract_id for c in contracts(content)}+++class TestJavaClientsRecognition:+ def test_feign_annotation_carries_verb_and_path(self) -> None:+ rows = list(feign_calls(FEIGN_CLIENT))+ assert [(r.method, r.url) for r in rows] == [+ ("POST", '"/v1/{entityType}/{entityId}/images"'),+ ("GET", '"/v1/{entityType}/{entityId}/images"'),+ ("DELETE", '"/v1/{entityType}/{entityId}/images"'),+ ]+ assert {r.client for r in rows} == {"feign"}++ def test_feign_ignores_a_word_that_is_not_a_verb(self) -> None:+ assert list(feign_calls(FEIGN_NON_VERB)) == []++ def test_builder_terminal_names_the_verb(self) -> None:+ rows = list(java_net_http_calls(BUILDER_LITERAL))+ assert [(r.client, r.method) for r in rows] == [("java-net-http", "GET")]++ def test_builder_reads_the_uri_from_its_own_argument(self) -> None:+ rows = list(java_net_http_calls(BUILDER_URI_FIRST_ARG))+ assert [(r.method, r.url) for r in rows] == [("POST", 'URI.create(base + "/v1/echo")')]++ def test_builder_method_call_reads_a_quoted_verb(self) -> None:+ rows = list(java_net_http_calls(BUILDER_METHOD_LITERAL))+ assert [r.method for r in rows] == ["PATCH"]++ def test_a_chain_does_not_borrow_the_next_call_s_terminal(self) -> None:+ rows = list(java_net_http_calls(BUILDER_NEIGHBOURING_VERB))+ assert [r.method for r in rows] == ["GET"]++ def test_resttemplate_verb_comes_from_the_callee_name(self) -> None:+ rows = list(resttemplate_calls(REST_TEMPLATE_CALLEES))+ assert [(r.callee, r.method) for r in rows] == [+ ("getForObject", None),+ ("postForEntity", None),+ ("delete", None),+ ]++ def test_resttemplate_exchange_verb_comes_from_the_second_argument(self) -> None:+ rows = list(resttemplate_calls(REST_TEMPLATE_EXCHANGE))+ assert [r.method for r in rows] == ["GET", "POST"]+++class TestJavaClientsContracts:+ def test_feign_paths_normalise_their_placeholders(self) -> None:+ assert ids(FEIGN_CLIENT) == {+ "http::POST::/v1/{param}/{param}/images",+ "http::GET::/v1/{param}/{param}/images",+ "http::DELETE::/v1/{param}/{param}/images",+ }++ def test_a_relative_feign_path_gains_a_slash_and_drops_its_query(self) -> None:+ assert ids(FEIGN_QUERY_AND_RELATIVE) == {"http::POST::/v1/internal/loans/{param}/activate"}++ def test_feign_rows_are_labelled_and_confident(self) -> None:+ (c,) = contracts(FEIGN_QUERY_AND_RELATIVE)+ assert c.role == "consumer"+ assert c.meta["client"] == "feign"+ assert c.confidence == 0.75++ def test_a_literal_uri_records_its_host(self) -> None:+ (c,) = contracts(BUILDER_LITERAL)+ assert c.contract_id == "http::GET::/v1/ping"+ assert c.meta["client"] == "java-net-http"+ assert c.meta["host"] == "api.example.com"++ def test_a_concatenated_base_is_stripped_and_recorded(self) -> None:+ (c,) = contracts(BUILDER_URI_FIRST_ARG)+ assert c.contract_id == "http::POST::/v1/echo"+ assert c.meta["base_stripped"] is True+ assert c.meta["base_token"] == "base"++ def test_string_format_holes_collapse_to_a_parameter(self) -> None:+ assert ids(BUILDER_STRING_FORMAT) == {"http::DELETE::/v1/items/{param}"}++ def test_a_same_file_constant_folds(self) -> None:+ assert ids(BUILDER_FOLDED_CONSTANT) == {"http::GET::/v1/status"}++ def test_resttemplate_rows_are_labelled_and_hedged(self) -> None:+ cs = contracts(REST_TEMPLATE_CALLEES)+ assert {c.contract_id for c in cs} == {+ "http::GET::/v1/pets",+ "http::POST::/v1/pets",+ "http::DELETE::/v1/pets/7",+ }+ assert {c.meta["client"] for c in cs} == {"resttemplate"}+ assert {c.confidence for c in cs} == {0.65}++ def test_an_exchange_host_expression_leaves_the_path(self) -> None:+ cs = contracts(REST_TEMPLATE_EXCHANGE)+ assert {c.contract_id for c in cs} == {+ "http::GET::/oups",+ "http::POST::/v1/sms",+ }+++class TestJavaClientsRefusals:+ def test_a_builder_with_no_terminal_verb_emits_nothing(self) -> None:+ assert contracts(BUILDER_NO_TERMINAL) == []++ def test_a_verb_held_in_a_variable_emits_nothing(self) -> None:+ assert contracts(BUILDER_VARIABLE_METHOD) == []++ def test_an_opaque_uri_variable_emits_nothing(self) -> None:+ assert contracts(BUILDER_OPAQUE_URI) == []++ def test_a_url_built_by_a_helper_call_emits_nothing(self) -> None:+ assert contracts(BUILDER_HELPER_URL) == []++ def test_a_builder_with_no_uri_emits_nothing(self) -> None:+ assert contracts(BUILDER_NO_URI) == []++ def test_an_exchange_with_a_variable_verb_emits_nothing(self) -> None:+ assert contracts(REST_TEMPLATE_VARIABLE_VERB) == []++ def test_an_exchange_with_an_opaque_uri_emits_nothing(self) -> None:+ assert contracts(REST_TEMPLATE_OPAQUE_URI) == []++ def test_a_map_call_in_a_resttemplate_file_emits_nothing(self) -> None:+ assert contracts(MAP_PUT_IN_REST_TEMPLATE_FILE) == []++ def test_a_file_that_never_names_resttemplate_is_not_read(self) -> None:+ assert list(resttemplate_calls(MAP_PUT_WITHOUT_REST_TEMPLATE)) == []+ assert contracts(MAP_PUT_WITHOUT_REST_TEMPLATE) == []++ def test_only_a_template_receiver_owns_a_bare_put(self) -> None:+ rows = list(resttemplate_calls(MAP_PUT_BESIDE_A_TEMPLATE_PUT))+ assert [(r.callee, r.url) for r in rows] == [("put", '"/v1/pets/7"')]+ assert ids(MAP_PUT_BESIDE_A_TEMPLATE_PUT) == {"http::PUT::/v1/pets/7"}++ def test_an_okhttp_request_builder_emits_nothing(self) -> None:+ assert contracts(OKHTTP_BUILDER) == []++ def test_an_exchange_whose_verb_lives_in_a_request_entity_emits_nothing(self) -> None:+ assert contracts(REST_TEMPLATE_REQUEST_ENTITY) == []++ def test_an_instance_formatted_call_is_not_a_format_head(self) -> None:+ assert contracts(BUILDER_INSTANCE_FORMATTED) == []+++JAVA_CONSUMER = """package com.example.client;++import feign.RequestLine;++public interface UsersApi {++ @RequestLine("GET /users/{userId}")+ String read(@Param("userId") String userId);+}+"""++FASTAPI_PROVIDER = """from fastapi import FastAPI++app = FastAPI()++[email protected]("/users/{user_id}")+def read_user(user_id: str):+ return {"id": user_id}+"""+++class TestJavaClientsCrossRepoLink:+ def test_java_consumer_links_to_a_python_provider(self) -> None:+ extractor = HttpExtractor()+ extractor.provider_dialects = (FastApiDialect(),)+ extractor.consumer_dialects = (JavaClientsDialect(),)+ providers = extractor.extract(+ Path("."), "api", files=[("main.py", ".py", FASTAPI_PROVIDER)]+ )+ consumers = extractor.extract(+ Path("."), "client", files=[("UsersApi.java", ".java", JAVA_CONSUMER)]+ )+ links = match_contracts(providers + consumers)+ assert len(links) == 1+ assert links[0].provider_repo == "api"+ assert links[0].consumer_repo == "client"diff --git a/tests/unit/workspace/test_kotlin_clients.py b/tests/unit/workspace/test_kotlin_clients.pynew file mode 100644index 000000000..8abff7550--- /dev/null+++ b/tests/unit/workspace/test_kotlin_clients.py@@ -0,0 +1,285 @@+"""The Kotlin HTTP consumer dialect: Ktor client calls.++The claim under test is that a Ktor call site is read only when the file names+Ktor's client package and the URL settles inside the file: a literal, an+interpolated string over a folded constant, a ``Url(...)`` wrapper, or the+``url(...)`` builder inside a request block. A block with no URL in it, a+``request`` with no verb, the four-argument ``url`` overload and a call on a+type name are refused rather than guessed.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import match_contracts+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.kotlin_clients import (+ KotlinClientsDialect,+ ktor_calls,+)++LITERALS = """package com.example.sync++import io.ktor.client.*+import io.ktor.client.request.*++const val TEST_SERVER = "http://127.0.0.1:8080"++suspend fun run(client: HttpClient, id: String) {+ client.get("$TEST_SERVER/echo_query?a=b")+ client.get("http://www.google.com/search").bodyAsText()+ client.post("/api/accounts")+ client.head("/api/accounts/${id}/status")+ client.delete(Url("/api/accounts/legacy"))+}+"""++BLOCKS = """package com.example.sync++import io.ktor.client.*+import io.ktor.client.request.*++suspend fun run(client: HttpClient, serverPort: Int, base: String) {+ client.post {+ setBody("x")+ url(path = "/widget", port = serverPort)+ }+ client.get { url("http://svc.example.com/widget/list") }+ client.put { url { takeFrom("/widget/replace") } }+}+"""++REQUESTS = """package com.example.sync++import io.ktor.client.*+import io.ktor.client.request.*++suspend fun run(client: HttpClient) {+ client.request("/api/accounts") { method = HttpMethod.Post }+ client.request {+ url("/api/accounts/search")+ method = HttpMethod.Get+ }+}+"""++REFUSALS = """package com.example.sync++import io.ktor.client.*+import io.ktor.client.request.*+import java.nio.file.Paths++suspend fun run(client: HttpClient, target: String, port: Int) {+ // A default-request block: the URL lives on the client, not here.+ client.get {+ header("X-Trace", "1")+ }+ // The verb is decided at run time.+ client.request("/api/accounts") { header("X-Trace", "1") }+ // The path is positional among a scheme, a host and a port.+ client.get { url("https", "svc.example.com", port, "/widget") }+ // A parameter: this file never says what it holds.+ client.get(target)+ // Not a request at all.+ Paths.get("jvm/test-resources/public.zip")+ client.get("lookup-key")+}++/**+ * Documentation, not a call site:+ *+ * val response = client.get("https://ktor.io/docs/example")+ */+fun documented() = Unit+"""++RELATIVE_AND_ROOTED = """package com.example.sync++import io.ktor.client.*+import io.ktor.client.request.*++const val BASE = "https://svc.example.com"++suspend fun run(client: HttpClient) {+ client.get("api/v1/users")+ client.get("/api/v1/users")+ client.get("$BASE/api/v1/orders")+}+"""++NOT_KTOR = """package com.example.cache++class Cache(private val entries: Map<String, String>) {+ fun read(): String? = entries.get("/api/accounts")+}+"""++PROVIDER_SOURCE = '''"""Accounts service."""++from fastapi import FastAPI++app = FastAPI()++[email protected]("/api/accounts")+def create_account():+ return {}+'''+++def contracts(source: str, rel_path: str = "src/Sync.kt") -> list:+ ctx = ScanContext("portal", rel_path, ".kt", source, {}, None)+ return KotlinClientsDialect().extract(ctx)+++def ids(source: str, rel_path: str = "src/Sync.kt") -> list[str]:+ return sorted(c.contract_id for c in contracts(source, rel_path))+++class TestKotlinClientsRecognition:+ def test_a_verb_call_carries_its_url_argument_and_verb(self):+ rows = [(m.method, m.url) for m in ktor_calls(LITERALS)]+ assert ("GET", '"$TEST_SERVER/echo_query?a=b"') in rows+ assert ("POST", '"/api/accounts"') in rows+ assert ("HEAD", '"/api/accounts/${id}/status"') in rows+ assert ("DELETE", 'Url("/api/accounts/legacy")') in rows++ def test_a_block_call_carries_the_url_the_block_builds(self):+ rows = [(m.method, m.url) for m in ktor_calls(BLOCKS)]+ assert rows == [+ ("POST", '"/widget"'),+ ("GET", '"http://svc.example.com/widget/list"'),+ ("PUT", '"/widget/replace"'),+ ]++ def test_a_request_call_takes_its_verb_from_the_block(self):+ rows = [(m.method, m.url) for m in ktor_calls(REQUESTS)]+ assert rows == [+ ("POST", '"/api/accounts"'),+ ("GET", '"/api/accounts/search"'),+ ]++ def test_every_row_is_labelled_ktor(self):+ assert {m.client for m in ktor_calls(LITERALS)} == {"ktor"}+++class TestKotlinClientsContracts:+ def test_a_literal_url_becomes_a_contract_id(self):+ assert "http::POST::/api/accounts" in ids(LITERALS)++ def test_an_interpolated_parameter_collapses(self):+ assert "http::HEAD::/api/accounts/{param}/status" in ids(LITERALS)++ def test_a_constant_this_file_assigns_folds_into_the_url(self):+ row = next(c for c in contracts(LITERALS) if c.contract_id.endswith("/echo_query"))+ assert row.contract_id == "http::GET::/echo_query"+ assert row.meta["host"] == "127.0.0.1"+ assert row.meta["client"] == "ktor"++ def test_a_base_declared_elsewhere_is_stripped_and_recorded(self):+ source = """import io.ktor.client.request.*++suspend fun f(client: HttpClient) {+ client.get("$TEST_SERVER/echo_query")+}+"""+ row = contracts(source)[0]+ assert row.contract_id == "http::GET::/echo_query"+ assert row.meta["base_stripped"] is True+ assert row.meta["base_token"] == "TEST_SERVER"++ def test_an_absolute_url_records_its_host(self):+ row = next(c for c in contracts(LITERALS) if c.contract_id.endswith("/search"))+ assert row.meta["host"] == "www.google.com"+ assert row.contract_id == "http::GET::/search"++ def test_a_url_wrapper_is_unwrapped(self):+ assert "http::DELETE::/api/accounts/legacy" in ids(LITERALS)++ def test_a_block_built_url_becomes_a_contract(self):+ assert ids(BLOCKS) == [+ "http::GET::/widget/list",+ "http::POST::/widget",+ "http::PUT::/widget/replace",+ ]++ def test_a_request_block_verb_becomes_the_contract_method(self):+ assert ids(REQUESTS) == [+ "http::GET::/api/accounts/search",+ "http::POST::/api/accounts",+ ]++ def test_the_receiver_is_ambiguous_so_confidence_is_lowered(self):+ assert {c.confidence for c in contracts(LITERALS)} == {0.65}+++class TestKotlinClientsRefusals:+ def test_a_file_without_ktors_client_package_emits_nothing(self):+ assert contracts(NOT_KTOR, "src/Cache.kt") == []++ def test_every_refused_shape_emits_nothing(self):+ assert contracts(REFUSALS) == []++ def test_a_block_with_no_url_emits_nothing(self):+ source = REFUSALS[: REFUSALS.index("// The verb is decided")]+ assert list(ktor_calls(source)) == []++ def test_a_request_with_no_method_emits_nothing(self):+ source = 'import io.ktor.client.request.*\nfun f() { client.request("/a") { } }\n'+ assert list(ktor_calls(source)) == []++ def test_the_four_argument_url_overload_emits_nothing(self):+ source = (+ 'import io.ktor.client.request.*\nfun f() { client.get { url("https", h, p, "/a") } }\n'+ )+ assert list(ktor_calls(source)) == []++ def test_a_call_on_a_type_name_emits_nothing(self):+ source = (+ 'import io.ktor.client.request.*\nfun f() = Paths.get("jvm/test-resources/a.zip")\n'+ )+ assert list(ktor_calls(source)) == []++ def test_a_documented_example_emits_nothing(self):+ source = 'import io.ktor.client.request.*\n/**\n * val r = client.get("https://ktor.io/docs")\n */\nfun f() = Unit\n'+ assert list(ktor_calls(source)) == []++ def test_a_slash_free_argument_emits_nothing(self):+ source = 'import io.ktor.client.request.*\nfun f() { client.get("lookup-key") }\n'+ assert contracts(source) == []++ def test_a_relative_path_emits_nothing_while_a_rooted_one_emits(self):+ assert [m.url for m in ktor_calls(RELATIVE_AND_ROOTED)] == [+ '"api/v1/users"',+ '"/api/v1/users"',+ '"$BASE/api/v1/orders"',+ ]+ assert ids(RELATIVE_AND_ROOTED) == [+ "http::GET::/api/v1/orders",+ "http::GET::/api/v1/users",+ ]+++class TestKotlinClientsCrossRepoLink:+ def test_a_ktor_call_links_to_a_python_route(self):+ provider_extractor = HttpExtractor()+ provider_extractor.provider_dialects = (FastApiDialect(),)+ provider_extractor.consumer_dialects = ()+ providers = provider_extractor.extract(+ Path("."), "accounts", files=[("app/main.py", ".py", PROVIDER_SOURCE)]+ )++ consumer_extractor = HttpExtractor()+ consumer_extractor.provider_dialects = ()+ consumer_extractor.consumer_dialects = (KotlinClientsDialect(),)+ consumers = consumer_extractor.extract(+ Path("."), "portal", files=[("src/Sync.kt", ".kt", REQUESTS)]+ )++ links = match_contracts(providers + consumers)+ assert [(link.provider_repo, link.consumer_repo, link.contract_id) for link in links] == [+ ("accounts", "portal", "http::POST::/api/accounts")+ ]diff --git a/tests/unit/workspace/test_php_clients.py b/tests/unit/workspace/test_php_clients.pynew file mode 100644index 000000000..1a6bc8497--- /dev/null+++ b/tests/unit/workspace/test_php_clients.py@@ -0,0 +1,290 @@+"""The PHP HTTP consumer dialect: Guzzle and the Laravel ``Http`` facade.++The claim under test is that a PHP call site is read only when the file names+an HTTP client and the URL argument settles inside the file: a literal, an+interpolated string, or a concatenation onto a folded constant. A property, a+``config(...)`` lookup and a runtime verb are refused rather than guessed.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import match_contracts+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.php_clients import (+ PhpClientsDialect,+ guzzle_request_calls,+ guzzle_verb_calls,+ laravel_http_calls,+)++GUZZLE_REQUEST = """<?php++use GuzzleHttp\\Client;++class Sync+{+ public function run(Client $client, string $id): void+ {+ $client->request('GET', '/api/accounts');+ $client->request('POST', "https://svc.example.com/api/accounts/{$id}/sync");+ }+}+"""++GUZZLE_VERBS = """<?php++use GuzzleHttp\\Client;++class Fetcher+{+ public function run(): void+ {+ $client = new Client();+ $client->get('http://billing/api/invoices');+ $this->client->delete('/api/invoices/1');+ }+}+"""++GUZZLE_CONCAT = """<?php++class Reports+{+ private ClientInterface $client;++ public function run(): void+ {+ $base = 'https://reports.internal';+ $this->client->get($base . '/api/reports');+ }+}+"""++GUZZLE_PROPERTY_BASE = """<?php++use GuzzleHttp\\Client;++class Contacts+{+ public function run(Client $client): void+ {+ $client->request('GET', $this->base . '/contacts');+ }+}+"""++GUZZLE_BASE_RELATIVE = """<?php++use GuzzleHttp\\Client;++class Mixed+{+ public function run(Client $client): void+ {+ $client->request('GET', 'some/path');+ $client->request('GET', '/some/path');+ $client->request('GET', 'https://h/x');+ }+}+"""++LARAVEL_HTTP = """<?php++use Illuminate\\Support\\Facades\\Http;++class Wikipedia+{+ public function run(string $lang, string $id): void+ {+ Http::get("https://$lang.example.org/w/api.php?format=json");+ Http::withToken('t')->post('https://svc.example.com/api/jobs');+ Http::withHeaders(['X-A' => 'b'])->get("/api/items/{$id}");+ }+}+"""++UNGATED = """<?php++class Repository+{+ public function run(): void+ {+ $cache->get('/config/settings');+ $store->request('GET', '/config/settings');+ }+}+"""++REFUSALS = """<?php++use GuzzleHttp\\Client;+use Illuminate\\Support\\Facades\\Http;++class Dav+{+ public function run(Client $client, string $verb): void+ {+ $client->request('GET', $this->uri);+ $client->request($verb, '/api/things');+ $client->get($url);+ $client->get(config('services.things.url') . '/api/things');+ Http::get($this->endpoint);+ Http::fake();+ Http::get('example.com');+ }+}+"""+++def _ctx(content: str, rel_path: str = "app/Client.php") -> ScanContext:+ return ScanContext("app", rel_path, ".php", content, {}, None)+++def _ids(content: str) -> list[str]:+ return [c.contract_id for c in PhpClientsDialect().extract(_ctx(content))]+++class TestPhpClientsRecognition:+ def test_request_form_reads_verb_and_url_arguments(self):+ rows = list(guzzle_request_calls(GUZZLE_REQUEST))+ assert [(r.method, r.client) for r in rows] == [+ ("GET", "guzzle"),+ ("POST", "guzzle"),+ ]+ assert rows[0].url == "'/api/accounts'"++ def test_verb_form_reads_the_callee_name(self):+ rows = list(guzzle_verb_calls(GUZZLE_VERBS))+ assert [r.method for r in rows] == ["GET", "DELETE"]+ assert all(r.confidence == 0.65 for r in rows)++ def test_facade_reads_the_direct_and_the_chained_call(self):+ rows = list(laravel_http_calls(LARAVEL_HTTP))+ assert [(r.method, r.client) for r in rows] == [+ ("GET", "laravel-http"),+ ("POST", "laravel-http"),+ ("GET", "laravel-http"),+ ]++ def test_guzzle_shapes_need_a_client_in_the_file(self):+ assert list(guzzle_request_calls(UNGATED)) == []+ assert list(guzzle_verb_calls(UNGATED)) == []+++class TestPhpClientsContracts:+ def test_request_form_contracts(self):+ contracts = PhpClientsDialect().extract(_ctx(GUZZLE_REQUEST))+ assert [c.contract_id for c in contracts] == [+ "http::GET::/api/accounts",+ "http::POST::/api/accounts/{param}/sync",+ ]+ assert contracts[0].meta["client"] == "guzzle"+ assert contracts[1].meta["host"] == "svc.example.com"+ assert contracts[0].confidence == 0.75++ def test_verb_form_contracts_carry_the_host_and_lower_confidence(self):+ contracts = PhpClientsDialect().extract(_ctx(GUZZLE_VERBS))+ assert [c.contract_id for c in contracts] == [+ "http::GET::/api/invoices",+ "http::DELETE::/api/invoices/1",+ ]+ assert contracts[0].meta["host"] == "billing"+ assert contracts[0].confidence == 0.65++ def test_concatenation_onto_a_folded_constant(self):+ contracts = PhpClientsDialect().extract(_ctx(GUZZLE_CONCAT))+ assert [c.contract_id for c in contracts] == ["http::GET::/api/reports"]+ assert contracts[0].meta["host"] == "reports.internal"++ def test_a_property_base_the_file_never_binds_is_stripped(self):+ (contract,) = PhpClientsDialect().extract(_ctx(GUZZLE_PROPERTY_BASE))+ assert contract.contract_id == "http::GET::/contacts"+ assert contract.meta["base_stripped"] is True+ assert contract.meta["base_token"] == "base"++ def test_facade_contracts(self):+ contracts = PhpClientsDialect().extract(_ctx(LARAVEL_HTTP))+ assert [c.contract_id for c in contracts] == [+ "http::GET::/w/api.php",+ "http::POST::/api/jobs",+ "http::GET::/api/items/{param}",+ ]+ assert {c.meta["client"] for c in contracts} == {"laravel-http"}++ def test_an_interpolated_host_leaves_no_host_in_meta(self):+ contracts = PhpClientsDialect().extract(_ctx(LARAVEL_HTTP))+ assert "host" not in contracts[0].meta+++class TestPhpClientsRefusals:+ def test_every_unsettled_shape_emits_nothing(self):+ assert _ids(REFUSALS) == []++ def test_a_file_without_a_client_emits_nothing(self):+ assert _ids(UNGATED) == []++ def test_a_property_url_is_refused(self):+ source = "<?php\nuse GuzzleHttp\\Client;\n$client->request('GET', $this->uri);\n"+ assert _ids(source) == []++ def test_a_runtime_verb_is_refused(self):+ source = "<?php\nuse GuzzleHttp\\Client;\n$client->request($method, '/api/things');\n"+ assert _ids(source) == []++ def test_a_base_relative_literal_is_dropped_beside_its_rooted_siblings(self):+ # A client composes `'some/path'` onto its configured `base_uri`, so+ # the path the request reaches has a prefix the file does not carry.+ assert _ids(GUZZLE_BASE_RELATIVE) == ["http::GET::/some/path", "http::GET::/x"]++ def test_a_bare_host_carries_no_route(self):+ source = "<?php\nuse Illuminate\\Support\\Facades\\Http;\nHttp::get('example.com');\n"+ assert _ids(source) == []++ def test_a_map_lookup_beside_a_client_is_not_a_route(self):+ # A file that does construct a client still calls ``->get('key')`` on+ # other things; only an argument with a path is read.+ source = "<?php\n$client = new Client();\n$options->get('timeout');\n"+ assert _ids(source) == []++ def test_a_psr7_import_alone_does_not_gate_the_file(self):+ source = "<?php\nuse GuzzleHttp\\Psr7\\Stream;\n$adapter->get('/foo.txt');\n"+ assert _ids(source) == []+++PROVIDER_SOURCE = '''"""Accounts service."""++from fastapi import FastAPI++app = FastAPI()++[email protected]("/api/accounts")+def list_accounts():+ return []+'''+++class TestPhpClientsCrossRepoLink:+ def test_a_php_call_links_to_a_python_route(self):+ provider_extractor = HttpExtractor()+ provider_extractor.provider_dialects = (FastApiDialect(),)+ provider_extractor.consumer_dialects = ()+ providers = provider_extractor.extract(+ Path("."), "accounts", files=[("app/main.py", ".py", PROVIDER_SOURCE)]+ )++ consumer_extractor = HttpExtractor()+ consumer_extractor.provider_dialects = ()+ consumer_extractor.consumer_dialects = (PhpClientsDialect(),)+ consumers = consumer_extractor.extract(+ Path("."), "portal", files=[("app/Sync.php", ".php", GUZZLE_REQUEST)]+ )++ links = match_contracts(providers + consumers)+ assert [(link.provider_repo, link.consumer_repo, link.contract_id) for link in links] == [+ ("accounts", "portal", "http::GET::/api/accounts")+ ]diff --git a/tests/unit/workspace/test_ruby_clients.py b/tests/unit/workspace/test_ruby_clients.pynew file mode 100644index 000000000..f4a368a8f--- /dev/null+++ b/tests/unit/workspace/test_ruby_clients.py@@ -0,0 +1,280 @@+"""Ruby HTTP client calls become consumer contracts.++A Rails service names its endpoint as a frozen constant and interpolates the+rest (``"#{BASE_URL}/accounts/#{id}"``), writes the call across several lines,+and sometimes drops the parentheses altogether. The claims under test are that+each of those reaches the same contract a quoted literal would, that a+connection variable's ``get`` counts only when the file bound it with+``Faraday.new``, and that a URL the file does not settle -- a helper method, a+parameter, the ``uri`` a ``Net::HTTP.start`` block receives -- emits nothing.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import match_contracts+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect+from repowise.core.workspace.extractors.http.ruby_clients import (+ RubyClientsDialect,+ faraday_connection_calls,+ module_calls,+ net_http_calls,+)++HTTPARTY_RB = """\+class Dyte+ BASE_URL = 'https://api.cloudflare.com/client/v4'.freeze++ def post(payload)+ HTTParty.post(+ "#{BASE_URL}/accounts/realtime/kit", {+ body: payload&.to_json+ }.compact+ )+ end++ def show+ HTTParty.get("#{BASE_URL}/accounts/#{@account_id}/meetings")+ end+end+"""++RESTCLIENT_RB = """\+class Hub+ ENDPOINT = 'https://hub.example.com/ping'.freeze++ def self.sync+ RestClient.post ENDPOINT, info.to_json, { content_type: :json }+ end++ def self.drop(id)+ RestClient.delete("https://hub.example.com/instances/" + id)+ end+end+"""++FARADAY_RB = """\+module KeyValidator+ def self.valid?+ connection = Faraday.new do |f|+ f.options.timeout = 5+ end+ connection.get('https://api.openai.com/v1/models')+ end+end+"""++FARADAY_UNBOUND_RB = """\+class Client+ def initialize(conn)+ @conn = conn+ end++ def show(name)+ @conn.get("/repos/#{name}")+ end+end+"""++NET_HTTP_RB = """\+require 'net/http'++class Probe+ HEALTH = 'https://search.example.com/_cluster/health'.freeze++ def self.check+ Net::HTTP.get_response(URI(HEALTH))+ end++ def self.report+ Net::HTTP.post(URI.parse('https://search.example.com/reports'), body)+ end+end+"""++NET_HTTP_OPAQUE_RB = """\+require 'net/http'++class Fetcher+ def fetch_once(uri, ip_address)+ request = build_request(uri)+ Net::HTTP.start(uri.hostname, uri.port) do |http|+ http.request(Net::HTTP::Get.new(uri))+ end+ end+end+"""++HELPER_URL_RB = """\+class Hub+ def self.base_url+ 'https://hub.example.com'+ end++ def self.ping_url+ "#{base_url}/ping"+ end++ def self.sync+ RestClient.post(ping_url, info.to_json)+ end++ def self.crawl(external_link)+ HTTParty.get(external_link)+ end+end+"""++LINK_CLIENT_RB = """\+class Meetings+ def show(account_id)+ HTTParty.get("#{api_base}/accounts/#{account_id}/meetings")+ end+end+"""++PROVIDER_PY = """\+from fastapi import FastAPI++app = FastAPI()++[email protected]("/accounts/{account_id}/meetings")+def meetings(account_id: str):+ return []+"""+++def _contracts(content: str, rel_path: str = "lib/client.rb", alias: str = "web") -> list:+ ctx = ScanContext(alias, rel_path, ".rb", content, {}, None)+ return RubyClientsDialect().extract(ctx)+++class TestRubyClientsRecognition:+ def test_multi_line_and_single_line_module_calls(self) -> None:+ rows = list(module_calls(HTTPARTY_RB))+ assert [(r.client, r.method) for r in rows] == [+ ("httparty", "POST"),+ ("httparty", "GET"),+ ]+ assert rows[0].url == '"#{BASE_URL}/accounts/realtime/kit"'++ def test_parentheses_may_be_omitted(self) -> None:+ rows = list(module_calls(RESTCLIENT_RB))+ assert [(r.client, r.method, r.url) for r in rows] == [+ ("restclient", "POST", "ENDPOINT"),+ ("restclient", "DELETE", '"https://hub.example.com/instances/" + id'),+ ]++ def test_net_http_verb_comes_from_the_callee(self) -> None:+ rows = list(net_http_calls(NET_HTTP_RB))+ # The URI wrapper is peeled by the shared resolver, so the row keeps+ # the argument as written.+ assert [(r.method, r.url) for r in rows] == [+ ("GET", "URI(HEALTH)"),+ ("POST", "URI.parse('https://search.example.com/reports')"),+ ]++ def test_request_object_names_the_verb_by_class(self) -> None:+ rows = list(net_http_calls(NET_HTTP_OPAQUE_RB))+ assert [(r.method, r.url) for r in rows] == [("GET", "uri")]++ def test_connection_receiver_comes_from_faraday_new(self) -> None:+ rows = list(faraday_connection_calls(FARADAY_RB))+ assert [(r.method, r.confidence) for r in rows] == [("GET", 0.65)]+++class TestRubyClientsContracts:+ def test_constant_folds_into_an_interpolated_url(self) -> None:+ ids = {c.contract_id for c in _contracts(HTTPARTY_RB)}+ assert "http::POST::/client/v4/accounts/realtime/kit" in ids+ assert "http::GET::/client/v4/accounts/{param}/meetings" in ids++ def test_client_label_and_host_are_recorded(self) -> None:+ by_id = {c.contract_id: c for c in _contracts(HTTPARTY_RB)}+ c = by_id["http::POST::/client/v4/accounts/realtime/kit"]+ assert c.meta["client"] == "httparty"+ assert c.meta["host"] == "api.cloudflare.com"+ assert c.role == "consumer"+ assert c.confidence == 0.75++ def test_concatenation_and_a_bare_constant_both_resolve(self) -> None:+ ids = {c.contract_id for c in _contracts(RESTCLIENT_RB)}+ assert ids == {"http::POST::/ping", "http::DELETE::/instances/{param}"}++ def test_restclient_rows_name_their_library(self) -> None:+ assert {c.meta["client"] for c in _contracts(RESTCLIENT_RB)} == {"restclient"}++ def test_uri_wrapper_is_peeled(self) -> None:+ by_id = {c.contract_id: c for c in _contracts(NET_HTTP_RB)}+ assert set(by_id) == {"http::GET::/_cluster/health", "http::POST::/reports"}+ assert by_id["http::GET::/_cluster/health"].meta["client"] == "net-http"++ def test_faraday_connection_call_is_lower_confidence(self) -> None:+ contracts = _contracts(FARADAY_RB)+ assert [(c.contract_id, c.confidence) for c in contracts] == [+ ("http::GET::/v1/models", 0.65)+ ]+ assert contracts[0].meta["client"] == "faraday"++ def test_base_expression_is_stripped_for_the_matcher(self) -> None:+ content = 'HTTParty.get("#{api_base_path}/v1/Content/#{content_sid}")\n'+ (c,) = _contracts(content)+ assert c.contract_id == "http::GET::/v1/content/{param}"+ assert c.meta["base_stripped"] is True+ assert c.meta["base_token"] == "api_base_path"+++class TestRubyClientsRefusals:+ def test_helper_method_url_emits_nothing(self) -> None:+ assert _contracts(HELPER_URL_RB) == []++ def test_opaque_uri_in_a_start_block_emits_nothing(self) -> None:+ assert _contracts(NET_HTTP_OPAQUE_RB) == []++ def test_connection_not_bound_by_faraday_new_emits_nothing(self) -> None:+ assert _contracts(FARADAY_UNBOUND_RB) == []++ def test_settings_reader_is_not_an_options_request(self) -> None:+ content = "conn = Faraday.new\nconn.options.timeout = 5\n"+ assert list(faraday_connection_calls(content)) == []++ def test_a_url_expression_ending_in_a_call_emits_nothing(self) -> None:+ content = "HTTParty.get(inbox.channel.media_url(attachment_payload[:id]))\n"+ assert _contracts(content) == []++ def test_name_assigned_twice_does_not_fold(self) -> None:+ content = (+ "path = 'meetings'\n"+ "path = 'participants'\n"+ 'HTTParty.get("https://api.example.com/accounts/#{path}")\n'+ )+ (c,) = _contracts(content)+ assert c.contract_id == "http::GET::/accounts/{param}"+++class TestRubyClientsLink:+ def test_consumer_links_to_a_fastapi_provider(self, tmp_path: Path) -> None:+ api = tmp_path / "api"+ api.mkdir()+ (api / "main.py").write_text(PROVIDER_PY, encoding="utf-8")+ web = tmp_path / "web"+ web.mkdir()+ (web / "client.rb").write_text(LINK_CLIENT_RB, encoding="utf-8")++ # `source_extensions` reads the class, so both sides are named on a+ # subclass rather than an instance: the test then depends on this pair+ # of dialects only, not on whatever the default tuples carry.+ class RubyExtractor(HttpExtractor):+ provider_dialects = (FastApiDialect(),)+ consumer_dialects = (RubyClientsDialect(),)++ extractor = RubyExtractor()+ providers = [c for c in extractor.extract(api, "api") if c.role == "provider"]+ consumers = [c for c in extractor.extract(web, "web") if c.role == "consumer"]++ links = match_contracts(providers + consumers)+ assert [(link.provider_repo, link.consumer_repo) for link in links] == [("api", "web")]