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): read queues, pub/sub and socket events across Laravel and Node (#2525)
Raghav Chamadiyaf10502a50061
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 4eba4730f..a4aec649a 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1039,10 +1039,12 @@ workspace/extractors/js_clients.py python_clients.py php_clients.py … # consumers__init__.py # HttpExtractor (adds router mounts + index passes)grpc/ # proto.py + languages.py (one table of stub shapes)- topic/ # dialect.py (TopicCall table) + kafka.py rabbitmq.py nats.py- socket/ # dialect.py + dotnet.py python.py+ calls.py # call_sites / call_chain: the table reader topic and socket share+ topic/ # dialect.py (TopicCall table) + kafka.py rabbitmq.py nats.py redis.py+ # bullmq.py aws.py nestjs.py laravel.py (a repo pass: dispatch <-> job class)+ socket/ # dialect.py (SocketCall table) + dotnet.py python.py socketio.py broadcasting.pydata/ # table providers (DDL / ORM entities) <-> SQL consumers-workspace/matching/ # shared exact pass + per-type passes (http.py, topic.py)+workspace/matching/ # shared exact pass + per-type passes (http.py, topic.py, data.py)```A dialect declares the file extensions it understands (via `langs.py`) and turns@@ -1050,16 +1052,20 @@ matches into `Contract`s through shared builders, so every dialect emitsidentically-shaped providers/consumers and normalization lives in one place.**Adding a framework or client** means dropping one module into `http/`,`grpc/`, `topic/`, `socket/` or `data/` and appending its dialect to the-relevant registry tuple, with no orchestrator edits. A contract type whose two-ends can name one thing differently (HTTP mount prefixes, a queue bound to an-exchange) registers its extra passes in `matching.MATCHERS`.+relevant registry tuple, with no orchestrator edits. A dialect whose contracts+span files (a Laravel job dispatched in one file runs on the queue its class+declares in another) offers a `repo_pass()` instead: it sees every file, then+names its contracts once. A contract type whose two ends can name one thing+differently (HTTP mount prefixes, a queue bound to an exchange, a pattern+subscription) registers its extra passes, or its own `keys`, in+`matching.MATCHERS`.| Contract | Providers | Consumers ||----------|-----------|-----------|| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` / URL-literal wrappers (JS/TS), `requests` / `httpx` (Python), `HttpClient` / `UnityWebRequest` / Best.HTTP (C#), `reqwest` (Rust) || **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |-| **Topic** | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika), NATS | The same libraries' consumers, plus RabbitMQ queue bindings |-| **Socket** | SignalR `MapHub`, FastAPI `@app.websocket` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp |+| **Topic** | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub, BullMQ / Bull, SQS / SNS, NestJS `ClientProxy`, Laravel job dispatch | The same libraries' consumers (including pattern subscriptions and Laravel `ShouldQueue` classes), plus RabbitMQ queue bindings |+| **Socket** | SignalR `MapHub`, FastAPI `@app.websocket`, `ws`, NestJS gateways; socket.io `emit`, Laravel broadcast events, Pusher `trigger` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp, `new WebSocket(url)`; socket.io `on`, Laravel Echo, pusher-js || **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, ORM entities (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table` |See [docs/scale/WORKSPACES.md](../scale/WORKSPACES.md) for the user-facingdiff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex eea41fc3b..faa3f5517 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -234,14 +234,32 @@ Scans source files for HTTP route handlers, gRPC service definitions, and messag| HTTP | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal API), Rust (Axum routes, Actix/Rocket attribute macros) | fetch/axios/URL-literal wrappers (JS/TS), requests/httpx (Python), HttpClient/UnityWebRequest/Best.HTTP (C#), reqwest (Rust) || gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs || Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), Alembic `op.create_table`, Laravel migrations (`Schema::create` / `Schema::table`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`), Laravel `DB::table(...)` |-| Topics | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika), NATS producers | The corresponding consumers, plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |-| Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)` |--Socket detection is C#/Python only and is toggled by `detect_socket` in the `contracts:` block below.+| Topics | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub (ioredis/node-redis, redis-py, Laravel `Redis::publish`), BullMQ / Bull (`new Queue`, `@InjectQueue`, flows), SQS and SNS (AWS SDK v2/v3, boto3), NestJS `ClientProxy.emit`/`send`, Laravel job dispatch (`X::dispatch()->onQueue()`, `dispatch()`, `Queue::push*`, scheduled jobs) | The corresponding consumers (`new Worker`, `@Processor`, `ReceiveMessageCommand`, sqs-consumer, `subscribe`/`psubscribe`, `@EventPattern`/`@MessagePattern`, Laravel `ShouldQueue` classes on the queues they run on), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |+| Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")`, `ws` `WebSocketServer({ path })`, NestJS `@WebSocketGateway`; events: socket.io `emit` (server and client), Laravel broadcast events (`broadcastOn` / `broadcastAs`), `Broadcast::on`, Pusher `trigger` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)`, browser/Node `new WebSocket(url)`; events: socket.io `on` / `@SubscribeMessage`, Laravel Echo `listen` and `useEcho`, pusher-js `bind` |++Socket detection is toggled by `detect_socket` in the `contracts:` block below.+An endpoint is identified by its path (`socket::/hubs/game`); a message by its+event within a scope, `socket::<scope>#<event>`, where the scope is a socket.io+namespace (`/` unless the file names one) or a broadcast channel. Channels keep+the wire prefix Pusher gives them (`private-orders.{param}`), and Echo's event+names are read the way Echo formats them, so `.listen('OrderShipped')` meets a+Laravel event class `App\Events\OrderShipped` and `.listen('.order.shipped')`+meets `broadcastAs()` returning `order.shipped`. The emitting side is the+provider. socket.io, amqplib's `publish`/`consume`, BullMQ, Redis and NestJS+calls are read only in a file importing the library, since `emit`, `on`,+`publish` and `subscribe` are common method names.A topic, queue or exchange name is read the way a URL is: a literal, or a name-the same file assigns exactly once to a literal (Python, Go and Java today), is-resolved; a name built at runtime is skipped rather than guessed. RabbitMQ+the same file assigns exactly once to a literal (Python, Go, Java, PHP class+constants, and JS/TS `const` including object and enum members such as+`QUEUES.ticketSold`), is resolved; a name built at runtime is skipped rather+than guessed. An SQS queue URL is named by its last path segment and an SNS+topic ARN by its last field. A subscription by pattern (NATS `orders.*` /+`orders.>`, Redis `psubscribe`, Kafka `topicPattern`) links to every publisher+whose name it matches. A Laravel job dispatched without a queue runs on the+queue its class declares (`public $queue`, `$this->onQueue()`, `viaQueue()`),+found by the class's fully qualified name; one left on the connection's+default queue is not recorded, since every app has one. RabbitMQpublishers name an exchange and a routing key while consumers name a queue, soa queue binding found anywhere in the workspace connects the two: each consumerof the bound queue links to the exchange's publishers whose routing key thediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.pyindex a26b4a6a0..6333ba858 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py@@ -32,8 +32,18 @@ from typing import TYPE_CHECKING, Anyfrom ..composer import repo_composer_manifestsfrom ..framework_facts import LARAVEL-from ..framework_routes import laravel_route_file, laravel_routes, match_paren-from ..languages.php_same_namespace import file_namespace, php_use_aliases, qualify_php_name+from ..framework_routes import (+ LARAVEL_SCHEDULED_JOB,+ laravel_route_file,+ laravel_routes,+ match_paren,+)+from ..languages.php_same_namespace import (+ PHP_CLASS_NAME,+ file_namespace,+ php_use_aliases,+ qualify_php_name,+)from ..resolvers import ResolverContextfrom ..resolvers.php import resolve_php_classfrom .base import (@@ -49,7 +59,7 @@ if TYPE_CHECKING:import networkx as nx-_NAME = r"\\?[A-Za-z_]\w*(?:\\[A-Za-z_]\w*)*"+_NAME = PHP_CLASS_NAME_CLASS_REF_RE = re.compile(rf"(?<![\w\\$])(?P<name>{_NAME})\s*::\s*class\b")_NEW_RE = re.compile(rf"\bnew\s+(?P<name>{_NAME})")@@ -67,7 +77,7 @@ _REGISTRY_RE = re.compile(r"\$(?:listen|subscribe|policies|commands|middlewareAliases|routeMiddleware"r"|middlewareGroups|middleware|observers)\s*=\s*(?P<open>\[)"r"|(?:\bEvent::(?:listen|subscribe)|\bGate::policy|->\s*with(?:Providers|Commands|Events)"- r"|\bSchedule::job|->\s*job)\s*(?P<call>\()"+ rf"|{LARAVEL_SCHEDULED_JOB})\s*(?P<call>\()")# Middleware aliases: `'auth' => Authenticate::class` inside `->alias([...])`diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.pyindex 19bf597c3..028e666d1 100644--- a/packages/core/src/repowise/core/ingestion/framework_routes.py+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py@@ -753,6 +753,11 @@ def laravel_route_file_prefixes(content: str) -> dict[str, str | None]:return out+#: A scheduled job, `Schedule::job(new X, 'queue')` or `$schedule->job(...)`,+#: up to its `(`: the graph links the job class, contracts read its queue.+LARAVEL_SCHEDULED_JOB = r"(?:\bSchedule::|->\s*)job"++def laravel_route_file(rel_path: str) -> bool:"""Whether *rel_path* is a route file: a PHP file under a ``routes`` directory.diff --git a/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py b/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.pyindex eb8cf8bbb..e58348185 100644--- a/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py+++ b/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py@@ -30,6 +30,8 @@ from ..cohesion import SAME_NAMESPACE_HINTfrom .scope_scan import FileScope, ScopeTier, emit_scope_edgesif TYPE_CHECKING:+ from collections.abc import Callable+import networkx as nx_NAMESPACE_RE = re.compile(r"^\s*namespace\s+\\?([A-Za-z_][\w\\]*)\s*[;{]", re.MULTILINE)@@ -44,6 +46,15 @@ _TYPE_KINDS = frozenset({"class", "interface", "trait", "enum"})QUALIFIED_NAME_HINT = "qualified_name"+#: A class name as code writes it: bare, relative or fully qualified.+PHP_CLASS_NAME = r"\\?[A-Za-z_]\w*(?:\\[A-Za-z_]\w*)*"++_DECLARATION = r"^[ \t]*(?:(?:final|abstract|readonly)[ \t]+)*"+#: A class declared at the start of a line, so "class" in a docblock is not one.+PHP_CLASS_DECL_RE = re.compile(_DECLARATION + r"class[ \t]+(?P<cls>[A-Za-z_]\w*)", re.MULTILINE)+# The first declaration of any kind: every `use` clause comes before it.+_FIRST_DECL_RE = re.compile(_DECLARATION + r"(?:class|interface|trait|enum|function)\b", re.MULTILINE)+def file_namespace(text: str) -> str | None:"""The one ``namespace`` a PHP file declares, or None.@@ -80,6 +91,38 @@ def qualify_php_name(name: str, namespace: str | None, aliases: dict[str, str])return f"{namespace}\\{name}" if namespace else name+def php_name_qualifier(path: str, text: str) -> Callable[[str], str]:+ """:func:`qualify_php_name` for a PHP file that has not been parsed yet.++ For a caller outside the graph build (the contract extractors) that has+ only the file's text: the ``use`` clauses are read by the same parser the+ import graph uses, so both qualify a name alike. Only the header before the+ first declaration is parsed, since PHP puts every ``use`` there.+ """+ from datetime import UTC, datetime++ from ..models import FileInfo+ from ..parser import parse_file++ first = _FIRST_DECL_RE.search(text)+ raw = (text[: first.start()] if first else text).encode("utf-8")+ info = FileInfo(+ path=path,+ abs_path=path,+ language="php",+ size_bytes=len(raw),+ git_hash="",+ last_modified=datetime.now(UTC),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ namespace = file_namespace(text)+ aliases = php_use_aliases(parse_file(info, raw))+ return lambda name: qualify_php_name(name, namespace, aliases)++def resolve_php_same_namespace_refs(graph: nx.DiGraph,parsed_files: dict[str, Any],diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 9e1d0a76c..aa74a95d5 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -55,20 +55,31 @@ CONTRACTS_FILENAME = "contracts.json"# Version 10 serves Laravel routes under their group and route-file prefixes# with resources expanded, and adds Laravel migration, model-convention and# query-builder table contracts.-CONTRACTS_VERSION = 10+# Version 11 adds Laravel queues, BullMQ, SQS/SNS, Redis pub/sub, NestJS+# microservices, php-amqplib, pattern subscriptions, and socket.io, ws and+# Laravel broadcasting sockets; JS/TS constants fold.+CONTRACTS_VERSION = 11#: ``meta["kind"]`` of a topic contract: the destination a broker call names.-#: A queue is read by one consumer group; a topic or subject fans out; an-#: exchange routes to the queues bound to it; a binding is a queue subscribing-#: to an exchange, recorded as a consumer of that exchange.+#: A queue is read by one consumer group; a topic, subject or channel fans+#: out; an exchange routes to the queues bound to it; a binding is a queue+#: subscribing to an exchange, recorded as a consumer of that exchange.+TOPIC_PREFIX = "topic::"TOPIC_KIND_TOPIC = "topic"TOPIC_KIND_QUEUE = "queue"TOPIC_KIND_EXCHANGE = "exchange"TOPIC_KIND_SUBJECT = "subject"+TOPIC_KIND_CHANNEL = "channel"TOPIC_KIND_BINDING = "binding"#: Set on a publish or binding whose routing key the file does not settle; the#: topic matcher refuses to route through it rather than read it as match-all.TOPIC_ROUTING_KEY_UNRESOLVED = "routing_key_unresolved"+#: ``meta`` key of a consumer subscribed by pattern (``orders.*``); its value+#: names the pattern syntax.+TOPIC_PATTERN = "pattern"+TOPIC_PATTERN_NATS = "nats"+TOPIC_PATTERN_GLOB = "glob"+TOPIC_PATTERN_REGEX = "regex"# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/workspace/extractors/calls.py b/packages/core/src/repowise/core/workspace/extractors/calls.pynew file mode 100644index 000000000..8a11f87ff--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/calls.py@@ -0,0 +1,135 @@+"""Call sites as a table-driven dialect reads them.++A topic or socket recogniser is a table of call shapes: a *head* regex ending+at the call's opening parenthesis, the extensions it applies to, and the+substrings one of which the file must contain (the library's import) before+the head is tried at all. :func:`call_sites` walks one file through such a+table and yields each call's argument list with the file's+:class:`FileStrings`, which reads the file's constants once, on first use.+:func:`call_chain` reads the calls chained onto one (``X::dispatch(...)+->onQueue('q')``, ``Echo.private(c).listen(e)``).+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import TYPE_CHECKING, Protocol++from .strings import (+ call_arguments,+ match_paren,+ resolve_argument,+ string_constants,+ syntax_for_suffix,+)++if TYPE_CHECKING:+ from collections.abc import Callable, Iterable, Iterator++ from .base import ScanContext+ from .strings import Arg, StringSyntax+++class CallShape(Protocol):+ """What :func:`call_sites` reads from a table row."""++ head: re.Pattern[str]+ extensions: frozenset[str]+ requires: tuple[str, ...]+++class FileStrings:+ """One file's string syntax, and its constants, read the first time they are needed."""++ __slots__ = ("_code", "_constants", "content", "syntax")++ def __init__(self, content: str, syntax: StringSyntax, code: str | None = None) -> None:+ self.content = content+ self.syntax = syntax+ self._code = code+ self._constants: dict[str, str] | None = None++ @property+ def constants(self) -> dict[str, str]:+ if self._constants is None:+ self._constants = string_constants(self.content, self.syntax, self._code)+ return self._constants++ def resolve(+ self, args: list[str], arg: Arg, normalize: Callable[[str], str | None] | None = None+ ) -> tuple[list[str], bool]:+ """:func:`..strings.resolve_argument` against this file's constants."""+ return resolve_argument(args, arg, self.syntax, self.constants, normalize)+++def file_strings(ctx: ScanContext) -> FileStrings | None:+ """The :class:`FileStrings` for *ctx*, or ``None`` for a language with no string syntax."""+ syntax = syntax_for_suffix(ctx.suffix)+ return FileStrings(ctx.content, syntax) if syntax is not None else None+++def call_sites(+ ctx: ScanContext, calls: Iterable[CallShape], strings: FileStrings | None = None+) -> Iterator[tuple[CallShape, list[str], re.Match[str], FileStrings]]:+ """Each call in *ctx* one of *calls* recognises, with its non-empty argument list.++ Pass *strings* when the caller already holds the file's, so its constants+ are read once.+ """+ present: dict[tuple[str, ...], bool] = {} # rows of one library share a gate+ for call in calls:+ if ctx.suffix not in call.extensions:+ continue+ if call.requires:+ if call.requires not in present:+ present[call.requires] = any(r in ctx.content for r in call.requires)+ if not present[call.requires]:+ continue+ for m in call.head.finditer(ctx.content):+ args = call_arguments(ctx.content, m.end() - 1)+ if not args:+ continue+ if strings is None:+ strings = file_strings(ctx)+ if strings is None:+ return+ yield call, args, m, strings+++# One link of a method chain: `->name(` (PHP) or `.name(` / `?.name(` (JS).+_CHAIN_LINK_RE = re.compile(r"\s*(?:->|\?->|\??\.)\s*(?P<name>[A-Za-z_]\w*)\s*\(")+++@dataclass(frozen=True)+class ChainLink:+ """One call chained onto another: its method name, arguments and offset."""++ name: str+ args: list[str]+ offset: int+++def call_chain(content: str, close: int) -> Iterator[ChainLink]:+ """The calls chained onto the one whose ``)`` is at *close*, in order."""+ pos = close + 1+ while True:+ m = _CHAIN_LINK_RE.match(content, pos)+ if m is None:+ return+ end = match_paren(content, m.end() - 1)+ if end < 0:+ return+ args = call_arguments(content, m.end() - 1, end) or []+ yield ChainLink(m.group("name"), args, m.start("name"))+ pos = end + 1+++__all__ = [+ "CallShape",+ "ChainLink",+ "FileStrings",+ "call_chain",+ "call_sites",+ "file_strings",+]diff --git a/packages/core/src/repowise/core/workspace/extractors/dialect.py b/packages/core/src/repowise/core/workspace/extractors/dialect.pyindex d5655c188..93494fbba 100644--- a/packages/core/src/repowise/core/workspace/extractors/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/dialect.py@@ -33,6 +33,21 @@ class ContractDialect(Protocol):...+class RepoPass(Protocol):+ """One extraction run's state for a dialect whose contracts span files.++ A dialect with a ``repo_pass()`` factory is handed each file through+ :meth:`scan` instead of ``extract``, and names its contracts in+ :meth:`finish` once the whole repo has been read: a Laravel job+ dispatched in a controller runs on the queue its own class declares.+ A fresh pass per run keeps repos extracted concurrently apart.+ """++ def scan(self, ctx: ScanContext) -> None: ...++ def finish(self) -> list[Contract]: ...++def build_contract(ctx: ScanContext,*,@@ -111,21 +126,34 @@ class DialectExtractor:) -> list[Contract]:"""Scan *repo_path* (or the already-walked *files*) for contracts."""contracts: list[Contract] = []+ passes: dict[int, RepoPass] = {+ id(d): d.repo_pass() for d in self.dialects if hasattr(d, "repo_pass")+ }for rel_path, suffix, content in select_files(repo_path, self.source_extensions(), exclude, files):ctx = ScanContext(repo_alias, rel_path, suffix, content)found: list[Contract] = []for dialect in self.dialects:- if suffix in dialect.extensions:+ if suffix not in dialect.extensions:+ continue+ repo_pass = passes.get(id(dialect))+ if repo_pass is not None:+ repo_pass.scan(ctx)+ else:found.extend(dialect.extract(ctx))contracts.extend(found if self.identity is None else dedupe(found, self.identity))+ for repo_pass in passes.values():+ found = repo_pass.finish()+ # Every identity names the file, so a whole-repo dedupe is per file.+ contracts.extend(found if self.identity is None else dedupe(found, self.identity))return contracts__all__ = ["ContractDialect","DialectExtractor",+ "RepoPass","build_contract","dedupe","file_identity",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 fc448f50e..1a2952695 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@@ -31,6 +31,7 @@ import refrom typing import TYPE_CHECKINGfrom ..base import line_at+from ..calls import FileStringsfrom ..langs import PYTHONfrom ..strings import (JS_SYNTAX,@@ -38,7 +39,6 @@ from ..strings import (match_paren,resolve_string,split_first_arg,- string_constants,)from .client_calls import VERBS, is_rooted_urlfrom .dialect import build_consumer_contract@@ -88,16 +88,19 @@ _match_paren = match_paren_split_first_arg = split_first_arg-def _first_arg_url(arg: str, is_python: bool, constants: dict[str, str]) -> str | None:+def _first_arg_url(arg: str, strings: FileStrings) -> str | None:"""The URL a call's first argument names, or ``None`` if it is not one.- 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.+ The argument must resolve through the file's string syntax: a literal, an+ f-string or template, a concatenation, or a name the file binds once to+ one of those. A name it does not bind returns ``None``, because that is+ not a path this layer may claim to know. The result then faces the same+ concreteness test in every language."""- url = resolve_string(arg, PYTHON_SYNTAX if is_python else JS_SYNTAX, constants)+ url = resolve_string(arg, strings.syntax)+ if url is None or "${" in url:+ # Only an expression that is not a plain literal reads the constants.+ url = resolve_string(arg, strings.syntax, strings.constants)return url if url is not None and is_rooted_url(url) else None@@ -183,7 +186,7 @@ def extract_consumers(if not confirmed and not sinks and not clients:return [], 0- constants = string_constants(content, PYTHON_SYNTAX, code) if is_python else {}+ strings = FileStrings(content, PYTHON_SYNTAX if is_python else JS_SYNTAX, code or None)declarations = _declaration_sites(symbols)# Pass 1: every call site of a confirmed wrapper, split into resolved@@ -224,7 +227,7 @@ def extract_consumers(parse_failures += 1continuefirst, rest = _split_first_arg(content[open_idx + 1 : close_idx])- url = _first_arg_url(first, is_python, constants)+ url = _first_arg_url(first, strings)if url is None:# The wrapper's own plumbing — ``fetch(path)`` inside the very# function that wraps it — is not a lost endpoint. Whatever flows@@ -255,7 +258,7 @@ def extract_consumers(parse_failures += 1continuefirst, _ = _split_first_arg(content[open_idx + 1 : close_idx])- url = _first_arg_url(first, is_python, constants)+ url = _first_arg_url(first, strings)if url is None:# Unconditional, unlike the wrapper tally above: a client's# ``.post`` takes a URL by definition, so ``path_taking`` has nodiff --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 dbfe00acc..8a6e3e3b4 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@@ -14,7 +14,7 @@ from collections.abc import Iteratorfrom typing import TYPE_CHECKINGfrom ..langs import JS_TS-from ..strings import JS_SYNTAX, literal_span+from ..strings import JS_SYNTAX, literal_span, string_constantsfrom .client_calls import ClientCallMatch, consumer_contracts, matches_infrom .dialect import METHODS@@ -105,4 +105,6 @@ class JsClientsDialect:def extract(self, ctx: ScanContext) -> list[Contract]:content = ctx.contentmatches = [*fetch_calls(content), *axios_calls(content), *wrapper_calls(content)]- return consumer_contracts(ctx, matches, JS_SYNTAX)+ # A `${BASE}` interpolation folds when the file binds BASE to a constant.+ constants = string_constants(content, JS_SYNTAX) if any("${" in m.url for m in matches) else {}+ return consumer_contracts(ctx, matches, JS_SYNTAX, constants=constants)diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/__init__.py b/packages/core/src/repowise/core/workspace/extractors/socket/__init__.pyindex 38ee447e3..084713283 100644--- a/packages/core/src/repowise/core/workspace/extractors/socket/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/socket/__init__.py@@ -1,16 +1,25 @@"""Socket / websocket contract extraction.-Each language's endpoint and connect shapes are a :class:`.dialect.SocketDialect`-table registered in :data:`DIALECTS`.+Each library's endpoints, connections and events are a dialect (usually a+:class:`.dialect.SocketDialect` table) registered in :data:`DIALECTS`."""from __future__ import annotationsfrom ..dialect import ContractDialect, DialectExtractor, file_identity+from .broadcasting import ECHO, LARAVEL_BROADCASTfrom .dotnet import DOTNETfrom .python import PYTHON_SOCKETS--DIALECTS: tuple[ContractDialect, ...] = (DOTNET, PYTHON_SOCKETS)+from .socketio import SOCKET_IO, WEBSOCKETS++DIALECTS: tuple[ContractDialect, ...] = (+ DOTNET,+ PYTHON_SOCKETS,+ WEBSOCKETS,+ SOCKET_IO,+ LARAVEL_BROADCAST,+ ECHO,+)class SocketExtractor(DialectExtractor):diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/broadcasting.py b/packages/core/src/repowise/core/workspace/extractors/socket/broadcasting.pynew file mode 100644index 000000000..c126ddca3--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/socket/broadcasting.py@@ -0,0 +1,260 @@+"""Broadcast channels over the Pusher protocol: Laravel events, Echo, Reverb, Pusher.++A Laravel event with a ``broadcastOn()`` method is broadcast on the channels+it returns, under the name its ``broadcastAs()`` returns or else its fully+qualified class name. Laravel Echo (and its ``useEcho`` hooks) listens on a+channel for an event, prefixing a bare event name with the ``App\\Events``+namespace exactly as Echo's own formatter does, so ``.listen('OrderShipped')``+meets ``App\\Events\\OrderShipped`` and ``.listen('.order.shipped')`` meets+``broadcastAs() { return 'order.shipped'; }``. Private and presence channels+travel as ``private-`` / ``presence-`` names, which is how raw Pusher clients+and ``$pusher->trigger`` spell them. Reverb speaks the same protocol.++Each contract is ``socket::<channel>#<event>``, the channel's interpolated+parts collapsed to ``{param}``. A notification's ``broadcastOn`` is not read:+Laravel sends every notification as one framework event, which Echo receives+through ``.notification()``, not ``.listen()``.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from repowise.core.ingestion.languages.php_same_namespace import (+ PHP_CLASS_DECL_RE,+ file_namespace,+ qualify_php_name,+)++from ..calls import call_chain, call_sites, file_strings+from ..langs import JS_TS, PHP+from ..strings import Arg, call_arguments, match_paren, unescape_backslashes+from .dialect import SocketCall, channel_scope, event_contracts++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+ from ..calls import FileStrings++_TRANSPORT = "pusher"+_ECHO_NAMESPACE = "App\\Events"+_FIRST = Arg(pos=0)+_SECOND = Arg(pos=1)++# Channel classes and Echo methods, with the prefix each puts on the wire.+_PHP_CHANNEL_PREFIX = {+ "Channel": "",+ "PrivateChannel": "private-",+ "PresenceChannel": "presence-",+ "EncryptedPrivateChannel": "private-encrypted-",+}+_ANONYMOUS_PREFIX = {"on": "", "private": "private-", "presence": "presence-"}+_ECHO_PREFIX = {+ "channel": "",+ "private": "private-",+ "join": "presence-",+ "encryptedPrivate": "private-encrypted-",+ "useEcho": "private-",+ "useEchoPublic": "",+ "useEchoPresence": "presence-",+}++_BROADCAST_ON_RE = re.compile(r"function\s+broadcastOn\s*\([^)]*\)[^{;]*\{")+_BROADCAST_AS_RE = re.compile(r"function\s+broadcastAs\s*\([^)]*\)[^{;]*\{\s*return\s+(?P<value>[^;]+);")+_NEW_CHANNEL_RE = re.compile(+ r"\bnew\s+\\?(?:[\w\\]*\\)?(?P<cls>" + "|".join(_PHP_CHANNEL_PREFIX) + r")\s*\("+)+# `Echo.private(`, `window.Echo.join(`; the boundary is checked behind the+# literal so the regex keeps a literal-led start.+_ECHO_RE = re.compile(+ r"[Ee]cho(?<![\w$][Ee]cho)\s*\.\s*(?P<kind>private|channel|join|encryptedPrivate)\s*\("+)+# `const channel = pusher.subscribe(`, `this.channel = this.pusher.subscribe(`.+_ASSIGNED_RE = re.compile(r"(?P<var>[A-Za-z_$][\w$.]*)\s*=\s*(?:await\s+)?[\w$.]*$")++_BROADCAST_EVENT = SocketCall(+ head=_BROADCAST_ON_RE,+ role="provider",+ transport=_TRANSPORT,+ label="broadcastOn",+ extensions=PHP,+ name=_FIRST,+)+_PUSHER_TRIGGER = SocketCall(+ head=re.compile(r"->\s*trigger\s*\("),+ role="provider",+ transport=_TRANSPORT,+ label="Pusher::trigger",+ extensions=PHP,+ name=_FIRST,+ requires=("Pusher",),+)+_ANONYMOUS = SocketCall(+ head=re.compile(r"Broadcast::(?P<kind>on|private|presence)\s*\("),+ role="provider",+ transport=_TRANSPORT,+ label="Broadcast::on",+ extensions=PHP,+ name=_FIRST,+ requires=("Broadcast::",),+)+_ECHO_LISTEN = SocketCall(+ head=_ECHO_RE,+ role="consumer",+ transport=_TRANSPORT,+ label="Echo.listen",+ extensions=JS_TS,+ name=_FIRST,+ requires=("cho",),+)+_USE_ECHO = SocketCall(+ head=re.compile(r"\b(?P<kind>useEcho(?:Public|Presence)?)\s*(?:<[^>()]*>)?\s*\("),+ role="consumer",+ transport=_TRANSPORT,+ label="useEcho",+ extensions=JS_TS,+ name=_FIRST,+ requires=("useEcho",),+)+_PUSHER_SUBSCRIBE = SocketCall(+ head=re.compile(r"\.\s*subscribe\s*\("),+ role="consumer",+ transport=_TRANSPORT,+ label="channel.bind",+ extensions=JS_TS,+ name=_FIRST,+ requires=("pusher-js",),+)+++def _channels(args: list[str], arg: Arg, strings: FileStrings, prefix: str) -> list[str]:+ """The channels *arg* names, holes as ``{param}``, with the wire *prefix*."""+ scopes, _ = strings.resolve(args, arg, channel_scope)+ return [prefix + scope for scope in scopes]+++def _names(args: list[str], arg: Arg, strings: FileStrings) -> list[str]:+ """Event names as the wire carries them: a source ``\\\\`` is one backslash."""+ values, _ = strings.resolve(args, arg)+ return [unescape_backslashes(v) for v in values]+++def _echo_event(name: str) -> str:+ """The wire name Echo's formatter gives *name*."""+ if name[:1] in (".", "\\"):+ return name[1:]+ return f"{_ECHO_NAMESPACE}.{name}".replace(".", "\\")+++class LaravelBroadcastDialect:+ """The PHP side: broadcast events, anonymous broadcasts, ``$pusher->trigger``."""++ name = "laravel-broadcast"+ extensions = PHP++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ strings = file_strings(ctx)+ if strings is None:+ return []+ out: list[Contract] = []+ if "broadcastOn" in content and "extends Notification" not in content:+ out.extend(self._event_class(ctx, strings))+ for call, args, m, _s in call_sites(ctx, (_PUSHER_TRIGGER, _ANONYMOUS), strings):+ if call is _ANONYMOUS:+ prefix = _ANONYMOUS_PREFIX[m.group("kind")]+ close = match_paren(content, m.end() - 1)+ named = next((ln for ln in call_chain(content, close) if ln.name == "as"), None)+ events = _names(named.args, _FIRST, strings) if named else ["AnonymousEvent"]+ else:+ prefix, events = "", _names(args, _SECOND, strings)+ channels = _channels(args, _FIRST, strings, prefix)+ out.extend(event_contracts(ctx, call, channels, events, m.start()))+ return out++ @staticmethod+ def _event_class(ctx: ScanContext, strings: FileStrings) -> list[Contract]:+ content = ctx.content+ on = _BROADCAST_ON_RE.search(content)+ cls = PHP_CLASS_DECL_RE.search(content)+ if on is None or cls is None:+ return []+ close = match_paren(content, on.end() - 1, closer="}")+ body = content[on.end() : close] if close > 0 else ""+ channels: list[str] = []+ for m in _NEW_CHANNEL_RE.finditer(body):+ args = call_arguments(body, m.end() - 1) or []+ channels.extend(_channels(args, _FIRST, strings, _PHP_CHANNEL_PREFIX[m.group("cls")]))+ alias = _BROADCAST_AS_RE.search(content)+ if alias is not None:+ events = _names([alias.group("value")], _FIRST, strings)+ else:+ events = [qualify_php_name(cls.group("cls"), file_namespace(content), {})]+ return event_contracts(+ ctx, _BROADCAST_EVENT, channels, events, cls.start("cls"), label=cls.group("cls")+ )+++class EchoDialect:+ """The JS side: Laravel Echo, its ``useEcho`` hooks, and pusher-js."""++ name = "echo"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ out: list[Contract] = []+ for call, args, m, strings in call_sites(ctx, (_ECHO_LISTEN, _USE_ECHO, _PUSHER_SUBSCRIBE)):+ kind = m.groupdict().get("kind") or ""+ if call is _PUSHER_SUBSCRIBE:+ channels = _channels(args, _FIRST, strings, "")+ close = match_paren(content, m.end() - 1)+ events = [+ e+ for ln in call_chain(content, close)+ if ln.name == "bind"+ for e in _names(ln.args, _FIRST, strings)+ ]+ events.extend(self._bound_later(content, m.start(), close, strings))+ elif call is _USE_ECHO:+ channels = _channels(args, _FIRST, strings, _ECHO_PREFIX[kind])+ events = [_echo_event(e) for e in _names(args, _SECOND, strings)]+ else:+ channels = _channels(args, _FIRST, strings, _ECHO_PREFIX[kind])+ close = match_paren(content, m.end() - 1)+ events = [+ _echo_event(e)+ for ln in call_chain(content, close)+ if ln.name == "listen"+ for e in _names(ln.args, _FIRST, strings)+ ]+ out.extend(event_contracts(ctx, call, channels, events, m.start()))+ return out++ @staticmethod+ def _bound_later(content: str, start: int, close: int, strings: FileStrings) -> list[str]:+ """``const ch = pusher.subscribe(c); ch.bind('e')``: the events bound on the variable.++ Only binds after this assignment and before the variable is assigned+ again, so two subscriptions reusing one name keep their own events.+ """+ line_start = content.rfind("\n", 0, start) + 1+ assigned = _ASSIGNED_RE.search(content, line_start, start)+ if assigned is None:+ return []+ var = re.escape(assigned.group("var"))+ boundary = r"(?<![\w$.])"+ again = re.compile(boundary + var + r"\s*=(?!=)").search(content, close)+ end = again.start() if again else len(content)+ out: list[str] = []+ for m in re.compile(boundary + var + r"\s*\??\.\s*bind\s*\(").finditer(content, close, end):+ out.extend(_names(call_arguments(content, m.end() - 1) or [], _FIRST, strings))+ return out+++LARAVEL_BROADCAST = LaravelBroadcastDialect()+ECHO = EchoDialect()++__all__ = ["ECHO", "LARAVEL_BROADCAST"]diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/dialect.py b/packages/core/src/repowise/core/workspace/extractors/socket/dialect.pyindex bf4893f7e..f90fa9271 100644--- a/packages/core/src/repowise/core/workspace/extractors/socket/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/socket/dialect.py@@ -1,8 +1,18 @@-"""Socket dialects: a transport's endpoint and connect calls as a pattern table.--A socket contract is identified by its path, normalized exactly as an HTTP path-is, so ``socket::/hubs/game`` links a hub mapped at ``/hubs/game`` to a client-connecting to ``wss://host/hubs/game``.+"""Socket dialects: a transport's endpoints, connections and events as call tables.++Two identities name a socket contract. An endpoint or a connection is its path,+normalized exactly as an HTTP path is, so ``socket::/hubs/game`` links a hub+mapped at ``/hubs/game`` to a client connecting to ``wss://host/hubs/game``.+A message is its event within a scope, ``socket::<scope>#<event>``: the scope+is a socket.io namespace (``/`` by default) or a broadcast channel+(``private-orders.{param}``), and the side that emits it is the provider.++A :class:`SocketCall` names a call head, where the value sits+(:class:`..strings.Arg`) and the function that turns the resolved value into+an identity; :class:`SocketDialect` reads a table of them through+:func:`..calls.call_sites`, so a URL held in a constant folds as it does for+HTTP. Dialects whose identity needs more than one call (a namespace, a+channel and its event) build contracts with :func:`event_contract`."""from __future__ import annotations@@ -12,6 +22,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKINGfrom ..base import line_at+from ..calls import call_sitesfrom ..dialect import build_contractfrom ..http.paths import (extract_path_from_url,@@ -21,42 +32,19 @@ from ..http.paths import ()if TYPE_CHECKING:+ from collections.abc import Callable+from repowise.core.workspace.contracts import Contractfrom ..base import ScanContext+ from ..strings import Arg-#: A C# string literal, capturing its ``$``/``@`` prefix and its body.-CSHARP_STRING = r"""(\$?@?)"([^"]*)\""""---@dataclass(frozen=True)-class SocketPattern:- """One endpoint or connect shape.-- ``context`` must appear somewhere in the file for the pattern to run, which- is how two libraries spelling ``new WebSocket("...")`` are told apart.- """-- regex: re.Pattern[str]- role: str- transport: str- confidence: float- label: str- identity_group: int- prefix_group: int | None = None- context: re.Pattern[str] | None = None-+_HOLE_RE = re.compile(r"\$\{[^{}]*\}")-def _to_template(prefix: str, text: str) -> str:- """Rewrite a C# interpolated string body into ``${expr}`` template form."""- if "$" in prefix:- return text.replace("{", "${")- return text--def socket_identity(raw: str, prefix: str = "") -> str | None:- """The stable path identity of a socket URL-like string, or ``None``."""- value = _to_template(prefix, raw).strip()+def path_identity(text: str) -> str | None:+ """The stable path identity of a resolved socket URL, or ``None``."""+ value = text.strip()if not value or "/" not in value:return Nonepath = extract_path_from_url(value)@@ -67,40 +55,133 @@ def socket_identity(raw: str, prefix: str = "") -> str | None:return norm+def channel_scope(text: str) -> str | None:+ """A channel name with each interpolated part as ``{param}``; ``None`` when nothing is fixed."""+ scope = _HOLE_RE.sub("{param}", text.strip())+ return scope if scope.replace("{param}", "").strip(".-_:") else None+++@dataclass(frozen=True)+class SocketCall:+ """One endpoint, connect or event call shape.++ ``normalize`` maps the resolved value to the contract's identity: a URL to+ its path for an endpoint, a channel with ``{param}`` holes for an event.+ """++ head: re.Pattern[str]+ role: str+ transport: str+ label: str+ extensions: frozenset[str]+ name: Arg+ confidence: float = 0.8+ requires: tuple[str, ...] = ()+ normalize: Callable[[str], str | None] = path_identity+++def _socket_contract(+ ctx: ScanContext,+ *,+ contract_id: str,+ role: str,+ symbol: str,+ confidence: float,+ offset: int,+ meta: dict[str, str],+) -> Contract:+ return build_contract(+ ctx,+ contract_type="socket",+ contract_id=f"socket::{contract_id}",+ role=role,+ symbol_name=symbol,+ confidence=confidence,+ line=line_at(ctx.content, offset),+ meta=meta,+ )+++def event_contract(+ ctx: ScanContext,+ *,+ scope: str,+ event: str,+ role: str,+ transport: str,+ label: str,+ confidence: float,+ offset: int,+) -> Contract:+ """One message: *event* within *scope*, emitted by a provider, received by a consumer."""+ return _socket_contract(+ ctx,+ contract_id=f"{scope}#{event}",+ role=role,+ symbol=f"{label}('{event}')",+ confidence=confidence,+ offset=offset,+ meta={"scope": scope, "event": event, "transport": transport},+ )+++def event_contracts(+ ctx: ScanContext,+ call: SocketCall,+ scopes: list[str],+ events: list[str],+ offset: int,+ label: str | None = None,+) -> list[Contract]:+ """One contract per scope and event of one call site of *call*."""+ return [+ event_contract(+ ctx,+ scope=scope,+ event=event,+ role=call.role,+ transport=call.transport,+ label=label or call.label,+ confidence=call.confidence,+ offset=offset,+ )+ for scope in scopes+ for event in events+ ]++class SocketDialect:- """One socket library's patterns, for the given file extensions."""+ """One socket library's endpoint and connect calls."""- def __init__(- self, name: str, extensions: frozenset[str], patterns: tuple[SocketPattern, ...]- ) -> None:+ def __init__(self, name: str, calls: tuple[SocketCall, ...]) -> None:self.name = name- self.extensions = extensions- self.patterns = patterns+ self.calls = calls+ self.extensions = frozenset().union(*(c.extensions for c in calls))def extract(self, ctx: ScanContext) -> list[Contract]:- content = ctx.contentout: list[Contract] = []- for p in self.patterns:- if p.context is not None and not p.context.search(content):- continue- for m in p.regex.finditer(content):- prefix = m.group(p.prefix_group) if p.prefix_group else ""- identity = socket_identity(m.group(p.identity_group), prefix)- if identity is None:- continue- out.append(- build_contract(- ctx,- contract_type="socket",- contract_id=f"socket::{identity}",- role=p.role,- symbol_name=f"{p.label}('{identity}')",- confidence=p.confidence,- line=line_at(content, m.start()),- meta={"path": identity, "transport": p.transport},- )+ for call, args, m, strings in call_sites(ctx, self.calls):+ paths, _ = strings.resolve(args, call.name, call.normalize)+ out.extend(+ _socket_contract(+ ctx,+ contract_id=path,+ role=call.role,+ symbol=f"{call.label}('{path}')",+ confidence=call.confidence,+ offset=m.start(),+ meta={"path": path, "transport": call.transport},)+ for path in paths+ )return out-__all__ = ["CSHARP_STRING", "SocketDialect", "SocketPattern", "socket_identity"]+__all__ = [+ "SocketCall",+ "SocketDialect",+ "channel_scope",+ "event_contract",+ "event_contracts",+ "path_identity",+]diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/dotnet.py b/packages/core/src/repowise/core/workspace/extractors/socket/dotnet.pyindex 7fea76a5e..32f2e257d 100644--- a/packages/core/src/repowise/core/workspace/extractors/socket/dotnet.py+++ b/packages/core/src/repowise/core/workspace/extractors/socket/dotnet.py@@ -1,72 +1,68 @@-"""C# socket endpoints and clients: SignalR hubs, ClientWebSocket, Unity websocket libraries."""+"""C# socket endpoints and clients: SignalR hubs, ClientWebSocket, Unity websocket libraries.++``new WebSocket(...)`` is spelled alike by two Unity libraries, so each is read+only in a file naming its own namespace.+"""from __future__ import annotationsimport refrom ..langs import CSHARP-from .dialect import CSHARP_STRING, SocketDialect, SocketPattern+from ..strings import Arg+from .dialect import SocketCall, SocketDialect++_URL = Arg(pos=0)DOTNET = SocketDialect(name="dotnet-sockets",- extensions=CSHARP,- patterns=(- SocketPattern(- regex=re.compile(- rf"""\bConnectAsync\s*\(\s*new\s+Uri\s*\(\s*{CSHARP_STRING}\s*\)""",- re.IGNORECASE,- ),+ calls=(+ SocketCall(+ head=re.compile(r"\bConnectAsync\s*\(\s*new\s+Uri\s*\(", re.IGNORECASE),role="consumer",transport="clientwebsocket",- confidence=0.75,label="ClientWebSocket.ConnectAsync",- prefix_group=1,- identity_group=2,+ extensions=CSHARP,+ name=_URL,+ confidence=0.75,),- SocketPattern(- regex=re.compile(rf"""\bWithUrl\s*\(\s*{CSHARP_STRING}""", re.IGNORECASE),+ SocketCall(+ head=re.compile(r"\bWithUrl\s*\(", re.IGNORECASE),role="consumer",transport="signalr",- confidence=0.8,label="HubConnectionBuilder.WithUrl",- prefix_group=1,- identity_group=2,- context=re.compile(- r"\bHubConnectionBuilder\b|SignalR\.Client|Microsoft\.AspNetCore\.SignalR\.Client"- ),+ extensions=CSHARP,+ name=_URL,+ requires=("HubConnectionBuilder", "SignalR.Client"),),- SocketPattern(- regex=re.compile(rf"""\bnew\s+WebSocket\s*\(\s*{CSHARP_STRING}""", re.IGNORECASE),+ SocketCall(+ head=re.compile(r"\bnew\s+WebSocket\s*\(", re.IGNORECASE),role="consumer",transport="nativewebsocket",- confidence=0.75,label="NativeWebSocket.WebSocket",- prefix_group=1,- identity_group=2,- context=re.compile(r"\bNativeWebSocket\b"),+ extensions=CSHARP,+ name=_URL,+ confidence=0.75,+ requires=("NativeWebSocket",),),- SocketPattern(- regex=re.compile(- rf"""\bnew\s+(?:\w+\.)?WebSocket\s*\(\s*{CSHARP_STRING}""", re.IGNORECASE- ),+ SocketCall(+ head=re.compile(r"\bnew\s+(?:\w+\.)?WebSocket\s*\(", re.IGNORECASE),role="consumer",transport="websocketsharp",- confidence=0.75,label="WebSocketSharp.WebSocket",- prefix_group=1,- identity_group=2,- context=re.compile(r"\bWebSocketSharp\b"),+ extensions=CSHARP,+ name=_URL,+ confidence=0.75,+ requires=("WebSocketSharp",),),- SocketPattern(- regex=re.compile(- rf"""\.\s*MapHub\s*<\s*\w+\s*>\s*\(\s*{CSHARP_STRING}""", re.IGNORECASE- ),+ SocketCall(+ head=re.compile(r"\.\s*MapHub\s*<\s*\w+\s*>\s*\(", re.IGNORECASE),role="provider",transport="signalr",- confidence=0.85,label="MapHub",- prefix_group=1,- identity_group=2,+ extensions=CSHARP,+ name=_URL,+ confidence=0.85,),),)diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/python.py b/packages/core/src/repowise/core/workspace/extractors/socket/python.pyindex da85c8183..1a59f2327 100644--- a/packages/core/src/repowise/core/workspace/extractors/socket/python.py+++ b/packages/core/src/repowise/core/workspace/extractors/socket/python.py@@ -5,21 +5,19 @@ from __future__ import annotationsimport refrom ..langs import PYTHON-from .dialect import SocketDialect, SocketPattern+from ..strings import Arg+from .dialect import SocketCall, SocketDialectPYTHON_SOCKETS = SocketDialect(name="python-sockets",- extensions=PYTHON,- patterns=(- SocketPattern(- regex=re.compile(- r"""@(?:app|router)\.websocket\s*\(\s*['"]([^'"]+)['"]""", re.IGNORECASE- ),+ calls=(+ SocketCall(+ head=re.compile(r"@(?:app|router)\.websocket\s*\(", re.IGNORECASE),role="provider",transport="fastapi-websocket",- confidence=0.8,label="@app.websocket",- identity_group=1,+ extensions=PYTHON,+ name=Arg(keys=("path",), pos=0),),),)diff --git a/packages/core/src/repowise/core/workspace/extractors/socket/socketio.py b/packages/core/src/repowise/core/workspace/extractors/socket/socketio.pynew file mode 100644index 000000000..f906aefcf--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/socket/socketio.py@@ -0,0 +1,265 @@+"""socket.io events, NestJS gateways, and ``ws`` / browser websocket endpoints.++A socket.io message is an event in a namespace: whoever calls ``emit`` is its+provider, whoever registers ``on`` its consumer, on the server and the client+alike. ``emit`` and ``on`` are every EventEmitter's too, so events are read+only in a file importing socket.io (or a NestJS gateway), on a receiver whose+name says it is a socket (``socket``, ``io``, ``nsp``, ``server``,+``client``, ...) or that the file binds to one (``const s = io(url)``), and+never for the library's own lifecycle events.++The namespace is the one the file names: ``io.of('/admin')`` on the server,+``io('https://host/admin')`` on the client, ``@WebSocketGateway({ namespace })``+in NestJS, else ``/``. An emit chained on ``.of('/x')`` is in ``/x``. A server+file that uses the default namespace beside a named one, or a file naming+two, leaves its other events unread rather than guess which is which.++``ws`` servers and every ``new WebSocket(url)`` connection are endpoints,+identified by path like any other socket endpoint.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from ..calls import call_chain, call_sites, file_strings+from ..langs import JS_TS+from ..strings import Arg, call_arguments, match_paren+from .dialect import SocketCall, SocketDialect, event_contract, event_contracts, path_identity++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+ from ..calls import FileStrings++_SOCKET_IO = ("socket.io", "@nestjs/websockets")+_TRANSPORT = "socket.io"++# Events the library raises itself (emitting one is refused by socket.io), and+# the stream events a `client` of another library emits in the same file.+_RESERVED = frozenset({+ "connect", "connection", "connect_error", "disconnect", "disconnecting", "error",+ "newListener", "removeListener", "reconnect", "reconnect_attempt", "reconnect_error",+ "reconnect_failed", "ping", "pong", "open", "close", "upgrade",+ "end", "data", "finish", "drain", "exit", "readable", "timeout",+}) # fmt: skip++# The role of each event call: whoever emits provides the event.+_VERBS = {+ "emit": "provider",+ "emitWithAck": "provider",+ "serverSideEmit": "provider",+ "serverSideEmitWithAck": "provider",+ "on": "consumer",+ "once": "consumer",+}+# Receiver names that say "socket". `client` and `server` are also any other+# library's (a Redis client, an HTTP server), so they count only in a NestJS+# gateway, where they are the socket and its server, or when the file binds+# them to socket.io itself.+_RECEIVER_RE = re.compile(r"(?i)socket|^io$|^nsp$|namespace")+_GATEWAY_RECEIVERS = frozenset({"client", "server"})+# What sits between a receiver and `.emit(` / `.on(`: `.to(room)`, `.broadcast`, `.of('/x')`.+_MODIFIERS = (+ r"(?:\s*\??\.\s*(?:to|in|except|broadcast|volatile|compress|timeout|local|of)\b"+ r"(?:\s*\([^()]*\))?)*"+)+_OWNER_RE = re.compile(rf"(?P<recv>[A-Za-z_$][\w$]*){_MODIFIERS}\s*$")+_OF_RE = re.compile(r"\.\s*of\s*\(")+_EVENT_RE = re.compile(r"\??\.\s*(?P<verb>" + "|".join(sorted(_VERBS, key=len, reverse=True)) + r")\s*\(")+_FIRST = Arg(pos=0)+++def _namespace(text: str) -> str | None:+ """A namespace as written (``admin``, ``/admin``, a client URL) as ``/admin``.++ A URL names the namespace by its path: ``${API_URL}/chat`` is ``/chat``+ and a bare host or base is ``/``. A namespace with a hole is ``None``.+ """+ if "://" in text or text.startswith("${"):+ if "/" not in text.split("://", 1)[-1]:+ return "/"+ path = path_identity(text)+ return None if path is None or "{" in path else path+ if "${" in text:+ return None+ return "/" + text.strip("/")+++def _event(text: str) -> str | None:+ return None if text in _RESERVED else text+++_CLIENT_CONNECT = SocketCall(+ head=re.compile(r"(?<![\w$.])io(?:\s*\.\s*connect)?\s*\("),+ role="consumer",+ transport=_TRANSPORT,+ label="io",+ extensions=JS_TS,+ name=_FIRST,+ requires=("socket.io-client",),+ normalize=_namespace,+)+_NAMESPACE_CALLS = (+ SocketCall(+ head=re.compile(r"\.\s*of\s*\("),+ role="provider",+ transport=_TRANSPORT,+ label="io.of",+ extensions=JS_TS,+ name=_FIRST,+ requires=("socket.io",),+ normalize=_namespace,+ ),+ _CLIENT_CONNECT,+ SocketCall(+ head=re.compile(r"@WebSocketGateway\s*\("),+ role="provider",+ transport=_TRANSPORT,+ label="@WebSocketGateway",+ extensions=JS_TS,+ name=Arg(keys=("namespace",)),+ requires=("@nestjs/websockets",),+ normalize=_namespace,+ ),+)+_SUBSCRIBE_MESSAGE = SocketCall(+ head=re.compile(r"@SubscribeMessage\s*\("),+ role="consumer",+ transport=_TRANSPORT,+ label="@SubscribeMessage",+ extensions=JS_TS,+ name=_FIRST,+ requires=("@nestjs/websockets",),+ normalize=_event,+)+# `const s = io(url)`, `const admin = io.of('/admin')`, `const io = new Server(http)`.+_BOUND_RE = re.compile(+ r"(?P<var>[A-Za-z_$][\w$]*)\s*(?::[^=;\n]+)?=\s*(?:await\s+)?(?:io|new\s+Server|[\w$.]+\s*\.\s*of)\s*\("+)+# The default namespace used directly on the server: `io.on(...)`, `io.emit(...)`.+_DEFAULT_NAMESPACE_RE = re.compile(r"(?<![\w$.])io\s*\.\s*(?:on|emit|to|in)\s*\(")+++class SocketIoDialect:+ name = "socket.io"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if not any(r in content for r in _SOCKET_IO):+ return []+ strings = file_strings(ctx)+ if strings is None:+ return []+ default = self._file_namespace(ctx, strings)+ bound = {m.group("var") for m in _BOUND_RE.finditer(content)}+ if "@nestjs/websockets" in content:+ bound |= _GATEWAY_RECEIVERS+ out: list[Contract] = []+ for m in _EVENT_RE.finditer(content):+ # The receiver ends where the call's `.` begins; `$` holds at *endpos*.+ owner = _OWNER_RE.search(content, max(0, m.start() - 200), m.start())+ recv = owner.group("recv") if owner else ""+ if not recv or not (recv in bound or _RECEIVER_RE.search(recv)):+ continue+ scope = self._chained_namespace(owner.group(0), strings) or default+ close = match_paren(content, m.end() - 1)+ if scope is None or close < 0:+ continue+ calls = [(m.group("verb"), call_arguments(content, m.end() - 1, close) or [], m.start())]+ # `socket.on('a', f).on('b', g)`: every link of the chain has this receiver.+ calls.extend(+ (link.name, link.args, link.offset)+ for link in call_chain(content, close)+ if link.name in _VERBS+ )+ for verb, args, offset in calls:+ events, _ = strings.resolve(args, _FIRST, _event)+ out.extend(+ event_contract(+ ctx,+ scope=scope,+ event=event,+ role=_VERBS[verb],+ transport=_TRANSPORT,+ label=f"{recv}.{verb}",+ confidence=0.75,+ offset=offset,+ )+ for event in events+ )+ for call, args, m, _s in call_sites(ctx, (_SUBSCRIBE_MESSAGE,) if default else (), strings):+ events, _ = strings.resolve(args, call.name, call.normalize)+ out.extend(event_contracts(ctx, call, [default], events, m.start()))+ return out++ @staticmethod+ def _file_namespace(ctx: ScanContext, strings: FileStrings) -> str | None:+ """The one namespace the file's unchained events are in, or ``None`` when unsure."""+ namespaces: set[str] = set()+ for call, args, _m, _s in call_sites(ctx, _NAMESPACE_CALLS, strings):+ values, refused = strings.resolve(args, call.name, call.normalize)+ namespaces.update(values)+ # A server namespace this file cannot name makes every event+ # ambiguous. A client URL it cannot read is the configured server+ # address, which names no namespace.+ if refused and call is not _CLIENT_CONNECT:+ return None+ if len(namespaces) == 1 and "/" not in namespaces and _DEFAULT_NAMESPACE_RE.search(ctx.content):+ return None # the default namespace beside a named one+ if len(namespaces) > 1:+ return None+ return next(iter(namespaces), "/")++ @staticmethod+ def _chained_namespace(owner: str, strings: FileStrings) -> str | None:+ """The namespace of ``io.of('/x').emit(...)``, read from the receiver chain."""+ m = _OF_RE.search(owner)+ if m is None:+ return None+ values, _ = strings.resolve(call_arguments(owner, m.end() - 1) or [], _FIRST, _namespace)+ return values[0] if values else None+++_WS = ("'ws'", '"ws"')++WEBSOCKETS = SocketDialect(+ name="websocket",+ calls=(+ SocketCall(+ head=re.compile(r"\bnew\s+(?:WebSocketServer|WebSocket\s*\.\s*Server)\s*\("),+ role="provider",+ transport="ws",+ label="WebSocketServer",+ extensions=JS_TS,+ name=Arg(keys=("path",)),+ requires=_WS,+ ),+ SocketCall(+ head=re.compile(r"@WebSocketGateway\s*\("),+ role="provider",+ transport="websocket",+ label="@WebSocketGateway",+ extensions=JS_TS,+ name=Arg(keys=("path",)),+ requires=("@nestjs/websockets",),+ ),+ SocketCall(+ head=re.compile(r"\bnew\s+WebSocket\s*\("),+ role="consumer",+ transport="websocket",+ label="new WebSocket",+ extensions=JS_TS,+ name=_FIRST,+ confidence=0.75,+ requires=("WebSocket",),+ ),+ ),+)++SOCKET_IO = SocketIoDialect()++__all__ = ["SOCKET_IO", "WEBSOCKETS"]diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.pyindex f9215c27c..d83944482 100644--- a/packages/core/src/repowise/core/workspace/extractors/strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py@@ -25,6 +25,7 @@ comments; ``ingestion.framework_routes`` keeps its own comment-aware scanner.from __future__ import annotationsimport re+from collections.abc import Callablefrom dataclasses import dataclassfrom functools import cachefrom itertools import pairwise@@ -48,6 +49,9 @@ class StringSyntax:the language's dialects do not fold concatenation. ``assignment`` locates``name = rhs`` statements for constant folding; ``assignment_strip`` drops atrailing decoration from the right-hand side (Ruby's ``.freeze``).+ ``members`` locates a constant object or enum (``const Q = {``,+ ``enum Q {``), ending at its opening brace; each ``key: value`` or+ ``key = value`` entry folds as ``Q.key``."""quotes: str = "\"'"@@ -63,6 +67,7 @@ class StringSyntax:concat: str = ""assignment: re.Pattern[str] | None = Noneassignment_strip: re.Pattern[str] | None = None+ members: re.Pattern[str] | None = None# ---------------------------------------------------------------------------@@ -241,6 +246,8 @@ 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+ if const is None and name.startswith(("self::", "static::")):+ const = constants.get(name.partition("::")[2]) # a PHP class constantreturn const@@ -406,6 +413,11 @@ def string_constants(# A second assignment retires the name whatever it assigns: the reader# cannot tell which one reaches the use site.seen[name] = None if name in seen or resolve_string(rhs, syntax) is None else rhs+ if syntax.members is not None:+ for m in syntax.members.finditer(text):+ if code is None and _on_comment_line(content, m.start()):+ continue+ _fold_members(content, m.end() - 1, m.group("name"), syntax, seen)# `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@@ -415,6 +427,70 @@ def string_constants(return {name: text for name, text in seen.items() if text is not None}+# One object or enum entry: comments before it, an identifier or quoted key,+# then `:` or `=`.+_MEMBER_RE = re.compile(+ r"""^(?:\s*(?://[^\n]*|/\*.*?\*/))*\s*"""+ r"""(?:(?P<id>[A-Za-z_$][\w$]*)|['"](?P<quoted>[\w$.-]+)['"])\s*[:=](?![=>])\s*(?P<value>.+?)\s*$""",+ re.DOTALL,+)+# A member value worth resolving: a string, a template, a name, or an object.+# A function body or a long expression is neither a constant nor cheap to read.+_MEMBER_VALUE_MAX = 512+_MEMBER_VALUE_START = frozenset("'\"`{$_") | frozenset(+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+)+++def map_entry(entry: str) -> tuple[str, str, int] | None:+ """``(key, value source, value offset)`` of one ``key: value`` / ``key = value`` entry.++ Leading comments are skipped; a spread, a method or a bare enum member is+ ``None``.+ """+ m = _MEMBER_RE.match(entry)+ if m is None:+ return None+ return m.group("id") or m.group("quoted"), m.group("value"), m.start("value")+++def _fold_members(+ content: str,+ brace: int,+ prefix: str,+ syntax: StringSyntax,+ seen: dict[str, str | None],+ close: int | None = None,+) -> None:+ """Record each entry of the object literal opening at *brace* as ``prefix.key``.++ A nested object folds one level deeper (``Q.orders.created``); an entry+ that is not a string expression retires its name like any assignment.+ """+ if close is None:+ close = match_paren(content, brace, closer="}")+ if close < 0:+ return+ _, seps = _scan(content, brace + 1, close, sep=",")+ for start, end in pairwise([brace, *seps, close]):+ member = map_entry(content[start + 1 : end])+ if member is None:+ continue+ key, value, value_at = member+ name = f"{prefix}.{key}"+ if value[0] not in _MEMBER_VALUE_START or len(value) > _MEMBER_VALUE_MAX:+ seen[name] = None+ continue+ if value[0] == "{":+ if value.endswith("}"):+ offset = start + 1 + value_at+ _fold_members(content, offset, name, syntax, seen, offset + len(value) - 1)+ continue+ if syntax.assignment_strip is not None:+ value = syntax.assignment_strip.sub("", value).strip()+ seen[name] = None if name in seen or resolve_string(value, syntax) is None else value++# ``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.@@ -429,6 +505,16 @@ def _on_comment_line(content: str, offset: int) -> bool:return content[start:offset].lstrip().startswith(("//", "#", "*", "/*"))+def unescape_backslashes(text: str) -> str:+ """A literal body's ``\\\\`` as the one backslash it stands for.++ Bodies are read raw, which keeps a path or queue name byte-exact; a value+ that is itself a pattern or a namespaced name (a Java regex, a PHP class+ in a JS string) is compared after this.+ """+ return text.replace("\\\\", "\\")++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*.@@ -511,18 +597,26 @@ def select_argument(args: list[str], arg: Arg) -> list[str]:def resolve_argument(- args: list[str], arg: Arg, syntax: StringSyntax, constants: dict[str, str]+ args: list[str],+ arg: Arg,+ syntax: StringSyntax,+ constants: dict[str, str],+ normalize: Callable[[str], str | None] | None = None,) -> tuple[list[str], bool]:"""``(values, refused)`` for *arg*: each selected value resolved to plain text.A value that does not resolve, or resolves to a template with a hole init, is dropped and ``refused`` is set, so a caller can tell "the call didnot say" from "the call said something this file cannot settle".+ *normalize* maps the resolved text first (a queue URL to its last+ segment, a parameter to ``{param}``), so a hole it removes is no hole."""values: list[str] = []refused = Falsefor raw in select_argument(args, arg):text = resolve_string(raw, syntax, constants)+ if text is not None and normalize is not None:+ text = normalize(text)if text is None or "${" in text:refused = Trueelse:@@ -539,7 +633,26 @@ _BRACE_PLACEHOLDER_RE = re.compile(r"\{[^}]*\}")_BRACE_INTERP_RE = re.compile(r"(?<!\{)\{([^{}]+)\}(?!\})")_ESCAPED_BRACE_RE = re.compile(r"\{\{|\}\}")-JS_SYNTAX = StringSyntax(quotes="\"'`", template_quotes="`")+# ``const NAME = <expr>`` only: a ``let`` or ``var`` may be reassigned by a+# plain ``NAME = ...`` this reader does not track. ``as const`` and the+# statement's ``;`` (with any comment after it) are not part of the value.+JS_SYNTAX = StringSyntax(+ quotes="\"'`",+ template_quotes="`",+ concat="+",+ assignment=re.compile(+ # The boundary is checked behind the literal, so the regex keeps its+ # literal prefix and is not tried at every offset of the file.+ r"const(?<![\w$]const)[ \t]+(?P<name>[A-Za-z_$][\w$]*)(?:[ \t]*:[^=\n]+)?[ \t]*=(?![=>])"+ r"[ \t]*(?P<rhs>[^\n]+)$",+ re.MULTILINE,+ ),+ assignment_strip=re.compile(r"\s*(?:as\s+const\s*)?;[^'\"`]*$|\s+as\s+const\s*$"),+ members=re.compile(+ r"(?:const(?<![\w$]const)|enum(?<![\w$]enum))[ \t]+(?P<name>[A-Za-z_$][\w$]*)[ \t]*(?::[^=\n{]+)?"+ r"(?:=[ \t]*(?:Object\.freeze[ \t]*\([ \t]*)?)?\{"+ ),+)# ``NAME = <expr>`` at any indentation, RHS to end of line. The whitespace# around ``=`` is required, which excludes the usual unspaced keyword argument@@ -662,6 +775,7 @@ __all__ = ["StringSyntax","call_arguments","literal_span",+ "map_entry","match_paren","resolve_argument","resolve_string",@@ -670,4 +784,5 @@ __all__ = ["split_top_level","string_constants","syntax_for_suffix",+ "unescape_backslashes",]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.pyindex 130ec6a4a..0cbe4e4cf 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py@@ -1,19 +1,38 @@"""Message topic and queue contract extraction.-Each broker is a :class:`.dialect.TopicDialect` table in its own module,-registered in :data:`DIALECTS`. Matching, including queues reached through an-exchange binding, happens downstream in :mod:`repowise.core.workspace.matching`.+Each broker is a :class:`.dialect.TopicDialect` table (or a dialect of its own+shape) in its own module, registered in :data:`DIALECTS`. Matching, including+queues reached through an exchange binding and pattern subscriptions, happens+downstream in :mod:`repowise.core.workspace.matching`."""from __future__ import annotationsfrom ..dialect import ContractDialect, DialectExtractor+from .aws import SNS, SQS+from .bullmq import BULLMQfrom .dialect import topic_identityfrom .kafka import KAFKA+from .laravel import LARAVEL_QUEUESfrom .nats import NATS+from .nestjs import NESTJSfrom .rabbitmq import RABBITMQ--DIALECTS: tuple[ContractDialect, ...] = (KAFKA, RABBITMQ, NATS)+from .redis import REDIS++# Order settles which broker names a call two dialects read alike: the first+# contract per file, id and role is kept, so Redis (read only where a Redis+# client is imported) precedes NATS (read on any `client.publish`).+DIALECTS: tuple[ContractDialect, ...] = (+ KAFKA,+ RABBITMQ,+ REDIS,+ NATS,+ BULLMQ,+ SQS,+ SNS,+ NESTJS,+ LARAVEL_QUEUES,+)class TopicExtractor(DialectExtractor):diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/aws.py b/packages/core/src/repowise/core/workspace/extractors/topic/aws.pynew file mode 100644index 000000000..84b8b75fa--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/topic/aws.py@@ -0,0 +1,78 @@+"""Amazon SQS queues and SNS topics: AWS SDK v3 commands, v2 client calls, sqs-consumer, boto3.++Every call names its destination by URL or ARN (``QueueUrl``, ``TopicArn``),+never by name, so the name is the URL's last path segment or the ARN's last+field: ``https://sqs.eu-west-1.amazonaws.com/123/orders`` and+``arn:aws:sns:eu-west-1:123:orders`` are both ``orders``. A URL built as+``${base}/orders`` still names its queue. A call is read only when its file+spells the key, so ``bot.sendMessage(chatId, text)`` is never a queue.+"""++from __future__ import annotations++import re++from repowise.core.workspace.contracts import TOPIC_KIND_QUEUE, TOPIC_KIND_TOPIC++from ..langs import JS_TS, PYTHON+from ..strings import Arg+from .dialect import TopicCall, TopicDialect, last_segment++_QUEUE_URL = Arg(keys=("QueueUrl", "queueUrl"))+_TOPIC_ARN = Arg(keys=("TopicArn",))+_SQS = ("QueueUrl", "queueUrl")+_SNS = ("TopicArn",)+_queue_name = last_segment("/")+_topic_name = last_segment(":")+++def _sqs(head: str, role: str, label: str, extensions: frozenset[str]) -> TopicCall:+ return TopicCall(+ head=re.compile(head),+ role=role,+ label=label,+ extensions=extensions,+ name=_QUEUE_URL,+ kind=TOPIC_KIND_QUEUE,+ requires=_SQS,+ normalize=_queue_name,+ )+++def _sns(head: str, role: str, label: str, extensions: frozenset[str]) -> TopicCall:+ return TopicCall(+ head=re.compile(head),+ role=role,+ label=label,+ extensions=extensions,+ name=_TOPIC_ARN,+ kind=TOPIC_KIND_TOPIC,+ requires=_SNS,+ normalize=_topic_name,+ )+++SQS = TopicDialect(+ name="sqs",+ calls=(+ _sqs(r"\bnew\s+SendMessage(?:Batch)?Command\s*\(", "provider", "SendMessageCommand", JS_TS),+ _sqs(r"\bnew\s+ReceiveMessageCommand\s*\(", "consumer", "ReceiveMessageCommand", JS_TS),+ _sqs(r"\.\s*sendMessage(?:Batch)?\s*\(", "provider", "sqs.sendMessage", JS_TS),+ _sqs(r"\.\s*receiveMessage\s*\(", "consumer", "sqs.receiveMessage", JS_TS),+ _sqs(r"\bConsumer\s*\.\s*create\s*\(", "consumer", "Consumer.create", JS_TS),+ _sqs(r"\.\s*send_message(?:_batch)?\s*\(", "provider", "send_message", PYTHON),+ _sqs(r"\.\s*receive_message\s*\(", "consumer", "receive_message", PYTHON),+ ),+)++SNS = TopicDialect(+ name="sns",+ calls=(+ _sns(r"\bnew\s+PublishCommand\s*\(", "provider", "PublishCommand", JS_TS),+ _sns(r"\bnew\s+SubscribeCommand\s*\(", "consumer", "SubscribeCommand", JS_TS),+ _sns(r"\.\s*publish\s*\(", "provider", "sns.publish", JS_TS | PYTHON),+ _sns(r"\.\s*subscribe\s*\(", "consumer", "sns.subscribe", JS_TS | PYTHON),+ ),+)++__all__ = ["SNS", "SQS"]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/bullmq.py b/packages/core/src/repowise/core/workspace/extractors/topic/bullmq.pynew file mode 100644index 000000000..e651c564f--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/topic/bullmq.py@@ -0,0 +1,60 @@+"""BullMQ and Bull job queues, directly and through ``@nestjs/bullmq``.++A ``Queue`` adds jobs and a ``Worker`` processes them, both named by the queue.+``Queue`` and ``Worker`` are common class names, so each call is read only in+a file importing one of the libraries.+"""++from __future__ import annotations++import re++from repowise.core.workspace.contracts import TOPIC_KIND_QUEUE++from ..langs import JS_TS+from ..strings import Arg+from .dialect import TopicCall, TopicDialect++# The import specifiers `bullmq`, `bull`, `@nestjs/bull(mq)` and `bee-queue`.+_BULL = ("bullmq", "'bull'", '"bull"', "/bull", "bee-queue")+_NEST_BULL = ("@nestjs/bull",)+_FIRST = Arg(pos=0)+++def _queue(head: str, role: str, label: str, name: Arg, requires: tuple[str, ...]) -> TopicCall:+ return TopicCall(+ head=re.compile(head),+ role=role,+ label=label,+ extensions=JS_TS,+ name=name,+ kind=TOPIC_KIND_QUEUE,+ requires=requires,+ )+++BULLMQ = TopicDialect(+ name="bullmq",+ calls=(+ _queue(r"\bnew\s+Queue\s*(?:<[^>()]*>)?\s*\(", "provider", "new Queue", _FIRST, _BULL),+ _queue(r"\bnew\s+Worker\s*(?:<[^>()]*>)?\s*\(", "consumer", "new Worker", _FIRST, _BULL),+ # A flow adds jobs to the queue its `queueName` names.+ _queue(+ r"\.\s*add(?:Bulk)?\s*\(",+ "provider",+ "FlowProducer.add",+ Arg(keys=("queueName",)),+ ("FlowProducer",),+ ),+ _queue(+ r"@Processor\s*\(",+ "consumer",+ "@Processor",+ Arg(keys=("name",), pos=0),+ _NEST_BULL,+ ),+ _queue(r"@InjectQueue\s*\(", "provider", "@InjectQueue", _FIRST, _NEST_BULL),+ ),+)++__all__ = ["BULLMQ"]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.pyindex f3c37c3d3..2589fd355 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py@@ -3,10 +3,9 @@A :class:`TopicCall` names a call head (a regex ending at the openingparenthesis), the role it plays, and where in the argument list thedestination name sits (:class:`..strings.Arg`). :class:`TopicDialect` reads-the argument list with the shared bracket scanner and resolves each value-through :func:`..strings.resolve_argument`, so a queue named by a constant-folds exactly as a URL does. A value that cannot be settled inside the file is-refused.+each call through :func:`..calls.call_sites` and resolves the name with the+file's constants, so a queue named by a constant folds exactly as a URL does.+A value that cannot be settled inside the file is refused."""from __future__ import annotations@@ -17,20 +16,31 @@ from typing import TYPE_CHECKINGfrom repowise.core.workspace.contracts import (TOPIC_KIND_QUEUE,TOPIC_KIND_TOPIC,+ TOPIC_PATTERN,+ TOPIC_PATTERN_GLOB,+ TOPIC_PATTERN_NATS,+ TOPIC_PATTERN_REGEX,+ TOPIC_PREFIX,TOPIC_ROUTING_KEY_UNRESOLVED,)from ..base import line_at+from ..calls import call_sitesfrom ..dialect import build_contract-from ..strings import call_arguments, resolve_argument, string_constants, syntax_for_suffixif TYPE_CHECKING:import re+ from collections.abc import Callablefrom repowise.core.workspace.contracts import Contractfrom ..base import ScanContext- from ..strings import Arg, StringSyntax+ from ..calls import FileStrings+ from ..strings import Arg++#: Wildcard characters of each subscription-pattern syntax, which a name must+#: contain to be read as a pattern (``regex`` names are patterns outright).+_PATTERN_WILDCARDS = {TOPIC_PATTERN_NATS: "*>", TOPIC_PATTERN_GLOB: "*?[", TOPIC_PATTERN_REGEX: ""}@dataclass(frozen=True)@@ -39,7 +49,11 @@ class TopicCall:``default_exchange`` marks a publish whose empty exchange name is thebroker's default exchange, which delivers to the queue the routing key- names. ``queue`` is the bound queue of a binding call.+ names. ``queue`` is the bound queue of a binding call. ``requires`` are+ substrings (the library's import) one of which the file must contain.+ ``normalize`` maps a resolved name to the broker's own (a queue URL to its+ last segment). ``pattern`` is the subscription-pattern syntax of a+ consumer whose name may carry wildcards."""head: re.Pattern[str]@@ -52,6 +66,91 @@ class TopicCall:routing_key: Arg | None = Nonequeue: Arg | None = Nonedefault_exchange: bool = False+ requires: tuple[str, ...] = ()+ normalize: Callable[[str], str | None] | None = None+ pattern: str = ""+++def topic_contract(+ ctx: ScanContext,+ *,+ name: str,+ broker: str,+ kind: str,+ role: str,+ label: str,+ confidence: float,+ offset: int,+ **extra: str | bool,+) -> Contract:+ """One topic contract for destination *name*; *extra* goes into ``meta``."""+ meta: dict[str, str | bool] = {"topic": name, "broker": broker, "kind": kind, **extra}+ return build_contract(+ ctx,+ contract_type="topic",+ contract_id=f"{TOPIC_PREFIX}{name.lower()}",+ role=role,+ symbol_name=f"{label}('{name}')",+ confidence=confidence,+ line=line_at(ctx.content, offset),+ meta=meta,+ )+++def call_contracts(+ ctx: ScanContext,+ broker: str,+ call: TopicCall,+ args: list[str],+ offset: int,+ strings: FileStrings,+) -> list[Contract]:+ """The contracts one call site of *call* yields."""+ keys, key_refused = (+ strings.resolve(args, call.routing_key) if call.routing_key else ([], False)+ )+ routing_key = keys[0] if keys else ""+ queues: list[str] = []+ if call.queue is not None:+ queues, _ = strings.resolve(args, call.queue)+ if not queues:+ return [] # a binding with no readable queue binds nothing we can name+ names, _ = strings.resolve(args, call.name, call.normalize)+ out: list[Contract] = []+ for name in names:+ kind, key, unresolved = call.kind, routing_key, key_refused+ if not name and call.default_exchange:+ if not routing_key:+ continue # the queue the default exchange delivers to is unknown+ name, kind, key, unresolved = routing_key, TOPIC_KIND_QUEUE, "", False+ if not name:+ continue+ extra: dict[str, str | bool] = {}+ if key:+ extra["routing_key"] = key+ if unresolved:+ extra[TOPIC_ROUTING_KEY_UNRESOLVED] = True+ if queues:+ extra["queue"] = queues[0]+ if call.pattern and (+ not _PATTERN_WILDCARDS[call.pattern]+ or any(ch in name for ch in _PATTERN_WILDCARDS[call.pattern])+ ):+ extra[TOPIC_PATTERN] = call.pattern+ out.append(+ topic_contract(+ ctx,+ name=name,+ broker=broker,+ kind=kind,+ role=call.role,+ label=call.label,+ confidence=call.confidence,+ offset=offset,+ **extra,+ )+ )+ return outclass TopicDialect:@@ -63,73 +162,9 @@ class TopicDialect:self.extensions = frozenset().union(*(c.extensions for c in calls))def extract(self, ctx: ScanContext) -> list[Contract]:- syntax = syntax_for_suffix(ctx.suffix)- if syntax is None:- return []- content = ctx.content- constants: dict[str, str] | None = None- out: list[Contract] = []- for call in self.calls:- if ctx.suffix not in call.extensions:- continue- for m in call.head.finditer(content):- args = call_arguments(content, m.end() - 1)- if not args:- continue- if constants is None:- constants = string_constants(content, syntax)- out.extend(self._contracts(ctx, call, args, m.start(), syntax, constants))- return out-- def _contracts(- self,- ctx: ScanContext,- call: TopicCall,- args: list[str],- offset: int,- syntax: StringSyntax,- constants: dict[str, str],- ) -> list[Contract]:- keys, key_refused = (- resolve_argument(args, call.routing_key, syntax, constants)- if call.routing_key- else ([], False)- )- routing_key = keys[0] if keys else ""- queues: list[str] = []- if call.queue is not None:- queues, _ = resolve_argument(args, call.queue, syntax, constants)- if not queues:- return [] # a binding with no readable queue binds nothing we can name- names, _ = resolve_argument(args, call.name, syntax, constants)out: list[Contract] = []- for name in names:- kind, key, unresolved = call.kind, routing_key, key_refused- if not name and call.default_exchange:- if not routing_key:- continue # the queue the default exchange delivers to is unknown- name, kind, key, unresolved = routing_key, TOPIC_KIND_QUEUE, "", False- if not name:- continue- meta: dict[str, str | bool] = {"topic": name, "broker": self.name, "kind": kind}- if key:- meta["routing_key"] = key- if unresolved:- meta[TOPIC_ROUTING_KEY_UNRESOLVED] = True- if queues:- meta["queue"] = queues[0]- out.append(- build_contract(- ctx,- contract_type="topic",- contract_id=f"topic::{name.lower()}",- role=call.role,- symbol_name=f"{call.label}('{name}')",- confidence=call.confidence,- line=line_at(ctx.content, offset),- meta=meta,- )- )+ for call, args, m, strings in call_sites(ctx, self.calls):+ out.extend(call_contracts(ctx, self.name, call, args, m.start(), strings))return out@@ -145,4 +180,20 @@ def topic_identity(c: Contract) -> tuple[str, ...]:)-__all__ = ["TopicCall", "TopicDialect", "topic_identity"]+def last_segment(sep: str) -> Callable[[str], str | None]:+ """A normalizer keeping what follows the last *sep* (a queue URL's name, an ARN's)."""++ def normalize(text: str) -> str | None:+ tail = text.rstrip(sep).rpartition(sep)[2]+ return tail or None++ return normalize+++__all__ = [+ "TopicCall",+ "TopicDialect",+ "last_segment",+ "topic_contract",+ "topic_identity",+]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py b/packages/core/src/repowise/core/workspace/extractors/topic/kafka.pyindex 5bf42a1f1..ae9353ab2 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py@@ -4,8 +4,10 @@ from __future__ import annotationsimport re+from repowise.core.workspace.contracts import TOPIC_PATTERN_REGEX+from ..langs import GO, JAVA, JS_TS, PYTHON-from ..strings import Arg+from ..strings import Arg, unescape_backslashesfrom .dialect import TopicCall, TopicDialect_TOPIC = Arg(keys=("topics", "topic"))@@ -21,6 +23,15 @@ KAFKA = TopicDialect(extensions=JAVA,name=_TOPIC,),+ TopicCall(+ head=re.compile(r"@KafkaListener\s*\("),+ role="consumer",+ label="@KafkaListener",+ extensions=JAVA,+ name=Arg(keys=("topicPattern",)),+ pattern=TOPIC_PATTERN_REGEX,+ normalize=unescape_backslashes,+ ),TopicCall(head=re.compile(r"kafkaTemplate\.send\s*\("),role="provider",diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/laravel.py b/packages/core/src/repowise/core/workspace/extractors/topic/laravel.pynew file mode 100644index 000000000..8a185bac1--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/topic/laravel.py@@ -0,0 +1,307 @@+"""Laravel queued jobs: where each is dispatched, and the queue it runs on.++A job reaches a queue two ways. The dispatch site can name it+(``NotifyTicketSold::dispatch($t)->onQueue('ticket.sold')``,+``dispatch((new X)->onQueue('q'))``, ``Queue::pushOn('q', new X)``,+``$schedule->job(new X, 'q')``), or the job class can declare it+(``public $queue = 'q'``, ``$this->onQueue('q')`` in its constructor, a+queued listener's ``viaQueue()``). Each dispatch site is a provider of its+queue and each ``ShouldQueue`` class a consumer of every queue it runs on.++The two meet across files, so this dialect is a repo pass: a site that names+no queue takes the one its job class declares, and a class runs on the+queues its dispatch sites name. Classes are joined by fully qualified name,+qualified the way the import graph qualifies them+(:func:`...ingestion.languages.php_same_namespace.php_name_qualifier`). A job+on the connection's default queue names no queue here and is not recorded:+every app has a ``default`` queue, and linking them all would be noise.+"""++from __future__ import annotations++import re+from collections import defaultdict+from dataclasses import dataclass, field+from typing import TYPE_CHECKING++from repowise.core.ingestion.framework_routes import LARAVEL_SCHEDULED_JOB+from repowise.core.ingestion.languages.php_same_namespace import (+ PHP_CLASS_DECL_RE,+ PHP_CLASS_NAME,+ file_namespace,+ php_name_qualifier,+ qualify_php_name,+)+from repowise.core.workspace.contracts import TOPIC_KIND_QUEUE++from ..calls import FileStrings, call_chain+from ..langs import PHP+from ..strings import PHP_SYNTAX, Arg, call_arguments, match_paren+from .dialect import topic_contract++if TYPE_CHECKING:+ from collections.abc import Callable, Iterator++ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++_BROKER = "laravel"+_NAME = PHP_CLASS_NAME+# Every app has this queue: two apps naming it share nothing.+_DEFAULT_QUEUE = "default"++# A file must contain one of these for any pattern below to run.+_HINTS = ("dispatch", "Queue::", "ShouldQueue", "job")++# Literal-led heads; the text before a `dispatch(` says which form it is.+_DISPATCH_RE = re.compile(r"dispatch(?:If|Unless)?\s*\(")+_STATIC_OWNER_RE = re.compile(rf"(?P<cls>{_NAME})\s*::\s*$")+_QUEUE_FACADE_RE = re.compile(+ r"Queue::\s*(?:connection\s*\([^()]*\)\s*->\s*)?(?P<verb>pushOn|push|laterOn|later|bulk)\s*\("+)+_SCHEDULED_JOB_RE = re.compile(LARAVEL_SCHEDULED_JOB + r"\s*\(")+_ON_QUEUE_RE = re.compile(r"->\s*onQueue\s*\(", re.IGNORECASE)+# PHP method names are case-insensitive.+_ON_QUEUE_LINKS = frozenset({"onqueue", "allonqueue"})++# `(queue position, job position)` of each `Queue::` call.+_QUEUE_FACADE_ARGS = {+ "push": (2, 0),+ "pushOn": (0, 1),+ "later": (3, 1),+ "laterOn": (0, 2),+ "bulk": (2, None),+}++# A job argument: `new X(...)`, `(new X)->onQueue(...)`, or `X::class`.+_JOB_ARG_RE = re.compile(rf"^\(?\s*new\s+(?P<new>{_NAME})|^(?P<ref>{_NAME})\s*::\s*class\s*$")++_QUEUED_CLASS_RE = re.compile(+ PHP_CLASS_DECL_RE.pattern + r"[^{;]*?\bShouldQueue\b", re.MULTILINE+)+# A class's own queue: `public $queue = 'q';` / `$this->queue = 'q';`, and a+# queued listener's `viaQueue(): string { return 'q'; }`.+_QUEUE_PROPERTY_RE = re.compile(r"(?:\$|->\s*)queue\s*=(?![=>])\s*(?P<value>[^;]+);")+_VIA_QUEUE_RE = re.compile(r"function\s+viaQueue\s*\([^)]*\)[^{]*\{\s*return\s+(?P<value>[^;]+);")+_THIS_ON_QUEUE_RE = re.compile(r"\$this\s*->\s*onQueue\s*\(")++# Static `X::dispatch` owners that are not job classes.+_NOT_JOBS = frozenset({"Event", "Bus", "self", "static", "parent"})+++@dataclass+class _Site:+ ctx: ScanContext+ offset: int+ label: str+ job: str | None+ queue: str | None+++@dataclass+class _Job:+ ctx: ScanContext+ offset: int+ name: str+ queues: set[str] = field(default_factory=set)+++def _short(name: str) -> str:+ return name.rpartition("\\")[2]+++def _job_name(arg: str) -> str | None:+ m = _JOB_ARG_RE.match(arg.strip())+ return (m.group("new") or m.group("ref")) if m else None+++class _FileReader:+ """One PHP file's queue facts, its strings and names read on first use."""++ def __init__(self, ctx: ScanContext) -> None:+ self.ctx = ctx+ self.content = ctx.content+ self.strings = FileStrings(ctx.content, PHP_SYNTAX)+ self._qualify: Callable[[str], str] | None = None++ def qualify(self, name: str) -> str:+ if self._qualify is None:+ self._qualify = php_name_qualifier(self.ctx.rel_path, self.content)+ return self._qualify(name)++ def queue(self, args: list[str], pos: int = 0) -> str | None:+ """The queue *args* names at *pos*; ``""`` when it names one this file cannot settle."""+ if pos >= len(args):+ return None+ values, _ = self.strings.resolve(args, Arg(pos=pos))+ return values[0] if values else ""++ def chained_queue(self, close: int) -> str | None:+ for link in call_chain(self.content, close):+ if link.name.lower() in _ON_QUEUE_LINKS:+ return self.queue(link.args)+ return None++ def inner_queue(self, arg: str) -> str | None:+ """The queue of ``(new X(...))->onQueue('q')`` passed as an argument."""+ m = _ON_QUEUE_RE.search(arg)+ if m is None:+ return None+ return self.queue(call_arguments(arg, m.end() - 1) or [])++ def site(self, offset: int, label: str, job: str | None, queue: str | None) -> _Site | None:+ if queue == "":+ return None # named a queue this file cannot settle: never guess another+ return _Site(self.ctx, offset, label, self.qualify(job) if job else None, queue)++ def dispatches(self) -> Iterator[_Site]:+ content = self.content+ for m in _DISPATCH_RE.finditer(content):+ start = m.start()+ before = content[max(0, start - 200) : start]+ if before.endswith("::") or before.rstrip().endswith("::"):+ owner = _STATIC_OWNER_RE.search(before)+ if owner is None:+ continue+ cls = owner.group("cls")+ static = _short(cls) not in _NOT_JOBS+ elif start and (content[start - 1].isalnum() or content[start - 1] in "_$"):+ continue # `redispatch(`, `$dispatch(`+ elif before.rstrip().endswith("function"):+ continue+ else:+ static = False+ close = match_paren(content, m.end() - 1)+ if close < 0:+ continue+ args = call_arguments(content, m.end() - 1, close) or []+ if static:+ job, label = cls, f"{_short(cls)}::dispatch"+ queue = self.chained_queue(close)+ else:+ # `dispatch(new X)`, `Bus::dispatch(...)`, `$this->dispatch(...)`.+ job = _job_name(args[0]) if args else None+ if job is None:+ continue # a Livewire or browser event, not a job+ label = "dispatch"+ queue = self.chained_queue(close)+ if queue is None:+ queue = self.inner_queue(args[0])+ site = self.site(start, label, job, queue)+ if site is not None:+ yield site++ def facade_pushes(self) -> Iterator[_Site]:+ for m in _QUEUE_FACADE_RE.finditer(self.content):+ verb = m.group("verb")+ args = call_arguments(self.content, m.end() - 1) or []+ queue_pos, job_pos = _QUEUE_FACADE_ARGS[verb]+ job = _job_name(args[job_pos]) if job_pos is not None and job_pos < len(args) else None+ site = self.site(m.start(), f"Queue::{verb}", job, self.queue(args, queue_pos))+ if site is not None:+ yield site++ def scheduled_jobs(self) -> Iterator[_Site]:+ for m in _SCHEDULED_JOB_RE.finditer(self.content):+ args = call_arguments(self.content, m.end() - 1) or []+ job = _job_name(args[0]) if args else None+ if job is None:+ continue+ site = self.site(m.start(), "schedule->job", job, self.queue(args, 1))+ if site is not None:+ yield site++ def queued_class(self) -> _Job | None:+ m = _QUEUED_CLASS_RE.search(self.content)+ if m is None:+ return None+ name = qualify_php_name(m.group("cls"), file_namespace(self.content), {})+ job = _Job(self.ctx, m.start("cls"), name)+ body = self.content[m.end() :]+ values = [v.group("value") for r in (_QUEUE_PROPERTY_RE, _VIA_QUEUE_RE) for v in r.finditer(body)]+ values.extend(+ (call_arguments(body, t.end() - 1) or [""])[0] for t in _THIS_ON_QUEUE_RE.finditer(body)+ )+ for value in values:+ queue = self.queue([value])+ if queue and queue != _DEFAULT_QUEUE:+ job.queues.add(queue)+ return job+++class _LaravelQueuePass:+ def __init__(self) -> None:+ self.sites: list[_Site] = []+ self.jobs: dict[str, _Job] = {}++ def scan(self, ctx: ScanContext) -> None:+ content = ctx.content+ if not any(h in content for h in _HINTS):+ return+ reader = _FileReader(ctx)+ if "ShouldQueue" in content and (job := reader.queued_class()) is not None:+ self.jobs.setdefault(job.name, job)+ if "dispatch" in content:+ self.sites.extend(reader.dispatches())+ if "Queue::" in content:+ self.sites.extend(reader.facade_pushes())+ if "job" in content:+ self.sites.extend(reader.scheduled_jobs())++ def finish(self) -> list[Contract]:+ out: list[Contract] = []+ named: dict[str, set[str]] = defaultdict(set)+ for site in self.sites:+ if site.queue:+ queues = [site.queue]+ if site.job:+ named[site.job].add(site.queue)+ else:+ job = self.jobs.get(site.job or "")+ queues = sorted(job.queues) if job else []+ extra = {"job": site.job} if site.job else {}+ for queue in queues:+ if queue == _DEFAULT_QUEUE:+ continue+ out.append(self._contract(site.ctx, site.offset, queue, "provider", site.label, extra))+ for job in self.jobs.values():+ short = _short(job.name)+ for queue in sorted((job.queues | named.get(job.name, set())) - {_DEFAULT_QUEUE}):+ out.append(self._contract(job.ctx, job.offset, queue, "consumer", short, {"job": job.name}))+ return out++ @staticmethod+ def _contract(+ ctx: ScanContext, offset: int, queue: str, role: str, label: str, extra: dict[str, str]+ ) -> Contract:+ return topic_contract(+ ctx,+ name=queue,+ broker=_BROKER,+ kind=TOPIC_KIND_QUEUE,+ role=role,+ label=label,+ confidence=0.8,+ offset=offset,+ **extra,+ )+++class LaravelQueueDialect:+ name = _BROKER+ extensions = PHP++ def repo_pass(self) -> _LaravelQueuePass:+ return _LaravelQueuePass()++ def extract(self, ctx: ScanContext) -> list[Contract]:+ """One file on its own (the extractor uses :meth:`repo_pass` instead)."""+ repo_pass = self.repo_pass()+ repo_pass.scan(ctx)+ return repo_pass.finish()+++LARAVEL_QUEUES = LaravelQueueDialect()++__all__ = ["LARAVEL_QUEUES"]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/nats.py b/packages/core/src/repowise/core/workspace/extractors/topic/nats.pyindex 697a3cdc0..7fe0e5cab 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/nats.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/nats.py@@ -1,20 +1,21 @@"""NATS publishers and subscribers.The receiver must carry a NATS-idiomatic name, so an RxJS or EventEmitter-``subscribe``/``publish`` is not read as a subject.+``subscribe``/``publish`` is not read as a subject. A subscription subject+with ``*`` or ``>`` is a pattern the matcher expands."""from __future__ import annotationsimport re-from repowise.core.workspace.contracts import TOPIC_KIND_SUBJECT+from repowise.core.workspace.contracts import TOPIC_KIND_SUBJECT, TOPIC_PATTERN_NATSfrom ..langs import GO, JAVA, JS_TS, PYTHONfrom ..strings import Argfrom .dialect import TopicCall, TopicDialect-_RECEIVER = r"(?:nc|nats|conn|js|sub|client)\s*\.\s*"+_RECEIVER = r"(?:nc|nats|conn|js|client)\s*\.\s*"_LANGUAGES = GO | JAVA | JS_TS | PYTHONNATS = TopicDialect(@@ -27,6 +28,7 @@ NATS = TopicDialect(extensions=_LANGUAGES,name=Arg(pos=0),kind=TOPIC_KIND_SUBJECT,+ pattern=TOPIC_PATTERN_NATS,),TopicCall(head=re.compile(_RECEIVER + r"(?:Publish|publish)\s*\("),diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/nestjs.py b/packages/core/src/repowise/core/workspace/extractors/topic/nestjs.pynew file mode 100644index 000000000..cae06c43b--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/topic/nestjs.py@@ -0,0 +1,130 @@+"""NestJS microservice messages: ``@EventPattern`` / ``@MessagePattern`` and ``ClientProxy``.++A handler is decorated with the pattern it serves; a caller emits an event or+sends a message through a ``ClientProxy``. ``emit`` and ``send`` are far too+common to read on any receiver, so only the names the file types as a+``ClientProxy`` (or one of its transport subclasses) are read, whatever they+are called. A pattern may be a string or an object (``{ cmd: 'sum' }``), which+Nest serializes with sorted keys; an object pattern is named that way here, so+the handler and the caller agree.+"""++from __future__ import annotations++import json+import re+from functools import lru_cache+from typing import TYPE_CHECKING++from ..calls import call_sites+from ..langs import JS_TS+from ..strings import Arg, map_entry, select_argument, split_top_level+from .dialect import TopicCall, topic_contract++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+ from ..calls import FileStrings++_MICROSERVICES = ("@nestjs/microservices",)+_FIRST = Arg(pos=0)++_HANDLERS = (+ TopicCall(+ head=re.compile(r"@EventPattern\s*\("),+ role="consumer",+ label="@EventPattern",+ extensions=JS_TS,+ name=_FIRST,+ requires=_MICROSERVICES,+ ),+ TopicCall(+ head=re.compile(r"@MessagePattern\s*\("),+ role="consumer",+ label="@MessagePattern",+ extensions=JS_TS,+ name=_FIRST,+ requires=_MICROSERVICES,+ ),+)++# `private readonly client: ClientProxy`, `@Inject('X') billing: ClientKafka`.+_PROXY_FIELD_RE = re.compile(+ r"\b(?P<name>[A-Za-z_$][\w$]*)\s*[?!]?\s*:\s*Client(?:Proxy|Kafka|RMQ|Nats|Redis|Mqtt)\b"+)+++@lru_cache(maxsize=256)+def _proxy_calls(receivers: tuple[str, ...]) -> tuple[TopicCall, ...]:+ alts = "|".join(re.escape(r) for r in receivers)+ return tuple(+ TopicCall(+ # `send<number>(...)` carries a type argument.+ head=re.compile(+ rf"(?<![\w$])(?:this\s*\.\s*)?(?:{alts})\s*\.\s*{verb}\s*(?:<[^>()]*>)?\s*\("+ ),+ role="provider",+ label=f"ClientProxy.{verb}",+ extensions=JS_TS,+ name=_FIRST,+ )+ for verb in ("emit", "send")+ )+++def _pattern(raw: str, strings: FileStrings) -> str | None:+ """A string pattern's text, or an object pattern as Nest serializes it."""+ raw = raw.strip()+ if not raw.startswith("{"):+ values, _ = strings.resolve([raw], _FIRST)+ return values[0] if values else None+ if not raw.endswith("}"):+ return None+ fields: dict[str, str] = {}+ for entry in split_top_level(raw[1:-1], ","):+ member = map_entry(entry)+ if member is None:+ return None+ values, _ = strings.resolve([member[1]], _FIRST)+ if not values:+ return None+ fields[member[0]] = values[0]+ return json.dumps(fields, sort_keys=True, separators=(",", ":")) if fields else None+++class NestMicroservicesDialect:+ name = "nestjs"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if not any(r in content for r in _MICROSERVICES):+ return [] # handlers and ClientProxy both come from this package+ calls = list(_HANDLERS)+ names = {m.group("name") for m in _PROXY_FIELD_RE.finditer(content)}+ if names:+ calls.extend(_proxy_calls(tuple(sorted(names))))+ out: list[Contract] = []+ for call, args, m, strings in call_sites(ctx, calls):+ for raw in select_argument(args, call.name):+ name = _pattern(raw, strings)+ if name:+ out.append(+ topic_contract(+ ctx,+ name=name,+ broker=self.name,+ kind=call.kind,+ role=call.role,+ label=call.label,+ confidence=call.confidence,+ offset=m.start(),+ )+ )+ return out+++NESTJS = NestMicroservicesDialect()++__all__ = ["NESTJS"]diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py b/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.pyindex dad606a9f..d6c044294 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py@@ -1,7 +1,13 @@-"""RabbitMQ publishers, consumers and queue bindings: Spring AMQP, amqplib, pika.+"""RabbitMQ publishers, consumers and queue bindings: Spring AMQP, amqplib, pika, php-amqplib.A publish names an exchange and a routing key, a consume names a queue, and abinding connects the two; see :mod:`repowise.core.workspace.matching.topic`.++amqplib's ``publish`` and ``consume`` are names half the event libraries+share, so they are read only in a file that imports amqplib, whatever the+channel variable is called. ``sendToQueue`` and ``bindQueue`` are amqplib's+alone and are read anywhere, including on a channel handed in from another+module."""from __future__ import annotations@@ -14,10 +20,13 @@ from repowise.core.workspace.contracts import (TOPIC_KIND_QUEUE,)-from ..langs import JAVA, JS_TS, PYTHON+from ..langs import JAVA, JS_TS, PHP, PYTHONfrom ..strings import Argfrom .dialect import TopicCall, TopicDialect+_AMQPLIB = ("amqplib", "amqp-connection-manager")+_PHP_AMQPLIB = ("PhpAmqpLib",)+RABBITMQ = TopicDialect(name="rabbitmq",calls=(@@ -41,15 +50,16 @@ RABBITMQ = TopicDialect(routing_key=Arg(pos=1),),TopicCall(- head=re.compile(r"channel\.consume\s*\("),+ head=re.compile(r"\.\s*consume\s*\("),role="consumer",label="channel.consume",extensions=JS_TS,name=Arg(pos=0),kind=TOPIC_KIND_QUEUE,+ requires=_AMQPLIB,),TopicCall(- head=re.compile(r"channel\.publish\s*\("),+ head=re.compile(r"\.\s*publish\s*\("),role="provider",label="channel.publish",extensions=JS_TS,@@ -57,17 +67,19 @@ RABBITMQ = TopicDialect(kind=TOPIC_KIND_EXCHANGE,routing_key=Arg(pos=1),default_exchange=True,+ requires=_AMQPLIB,),TopicCall(- head=re.compile(r"channel\.sendToQueue\s*\("),+ head=re.compile(r"\.\s*sendToQueue\s*\("),role="provider",label="channel.sendToQueue",extensions=JS_TS,name=Arg(pos=0),kind=TOPIC_KIND_QUEUE,+ requires=("sendToQueue",),),TopicCall(- head=re.compile(r"channel\.bindQueue\s*\("),+ head=re.compile(r"\.\s*bindQueue\s*\("),role="consumer",label="channel.bindQueue",extensions=JS_TS,@@ -75,6 +87,7 @@ RABBITMQ = TopicDialect(kind=TOPIC_KIND_BINDING,routing_key=Arg(pos=2),queue=Arg(pos=0),+ requires=("bindQueue",),),TopicCall(head=re.compile(r"channel\.basic_consume\s*\("),@@ -107,6 +120,38 @@ RABBITMQ = TopicDialect(routing_key=Arg(keys=("routing_key",), pos=2),queue=Arg(keys=("queue",), pos=0),),+ # php-amqplib: `basic_publish($msg, $exchange = '', $routing_key = '')`.+ TopicCall(+ head=re.compile(r"->\s*basic_consume\s*\("),+ role="consumer",+ label="basic_consume",+ extensions=PHP,+ name=Arg(keys=("queue",), pos=0),+ kind=TOPIC_KIND_QUEUE,+ requires=_PHP_AMQPLIB,+ ),+ TopicCall(+ head=re.compile(r"->\s*basic_publish\s*\("),+ role="provider",+ label="basic_publish",+ extensions=PHP,+ name=Arg(keys=("exchange",), pos=1),+ kind=TOPIC_KIND_EXCHANGE,+ routing_key=Arg(keys=("routing_key",), pos=2),+ default_exchange=True,+ requires=_PHP_AMQPLIB,+ ),+ TopicCall(+ head=re.compile(r"->\s*queue_bind\s*\("),+ role="consumer",+ label="queue_bind",+ extensions=PHP,+ name=Arg(keys=("exchange",), pos=1),+ kind=TOPIC_KIND_BINDING,+ routing_key=Arg(keys=("routing_key",), pos=2),+ queue=Arg(keys=("queue",), pos=0),+ requires=_PHP_AMQPLIB,+ ),),)diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/redis.py b/packages/core/src/repowise/core/workspace/extractors/topic/redis.pynew file mode 100644index 000000000..46d4f2f03--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/topic/redis.py@@ -0,0 +1,60 @@+"""Redis pub/sub channels: ioredis / node-redis, redis-py, Laravel's ``Redis`` facade.++``publish`` and ``subscribe`` are names RxJS, EventEmitters and every other+broker share, so the JS and Python calls are read only in a file importing a+Redis client; the name must then still resolve to a string, which an RxJS+observer never does. ``psubscribe`` subscribes by glob pattern.+"""++from __future__ import annotations++import re++from repowise.core.workspace.contracts import TOPIC_KIND_CHANNEL, TOPIC_PATTERN_GLOB++from ..langs import JS_TS, PHP, PYTHON+from ..strings import Arg+from .dialect import TopicCall, TopicDialect++_FIRST = Arg(pos=0)+_FACADE = ("Redis::",)+# `ioredis`, `redis`, `@redis/client` specifiers; `import redis` / `from redis`.+_CLIENT = ("ioredis", "'redis'", '"redis"', "@redis/", "import redis", "from redis")+++def _call(+ head: str,+ role: str,+ label: str,+ extensions: frozenset[str],+ requires: tuple[str, ...] = _CLIENT,+ pattern: str = "",+) -> TopicCall:+ return TopicCall(+ head=re.compile(head),+ role=role,+ label=label,+ extensions=extensions,+ name=_FIRST,+ kind=TOPIC_KIND_CHANNEL,+ requires=requires,+ pattern=pattern,+ )+++REDIS = TopicDialect(+ name="redis",+ calls=(+ _call(r"\.\s*publish\s*\(", "provider", "redis.publish", JS_TS | PYTHON),+ _call(r"\.\s*subscribe\s*\(", "consumer", "redis.subscribe", JS_TS | PYTHON),+ _call(+ r"\.\s*p[sS]ubscribe\s*\(", "consumer", "redis.psubscribe", JS_TS | PYTHON,+ pattern=TOPIC_PATTERN_GLOB,+ ),+ _call(r"\bRedis::publish\s*\(", "provider", "Redis::publish", PHP, _FACADE),+ _call(r"\bRedis::subscribe\s*\(", "consumer", "Redis::subscribe", PHP, _FACADE),+ _call(r"\bRedis::psubscribe\s*\(", "consumer", "Redis::psubscribe", PHP, _FACADE, TOPIC_PATTERN_GLOB),+ ),+)++__all__ = ["REDIS"]diff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.pyindex 7e6db6f67..8f30573dc 100644--- a/packages/core/src/repowise/core/workspace/matching/__init__.py+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py@@ -16,6 +16,8 @@ from collections.abc import Callablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING+from repowise.core.workspace.contracts import normalize_contract_id+from . import data, http, topicfrom .common import MatchState, find_matching_keys, internal, prefer_target_repofrom .http import annotate_consumer_targets@@ -26,11 +28,17 @@ if TYPE_CHECKING:@dataclass(frozen=True)class TypeMatcher:- """What one contract type adds to the shared exact pass."""+ """What one contract type adds to the shared exact pass.++ ``keys`` replaces :func:`.common.find_matching_keys` for the type: the+ provider index keys a consumer reaches (a pattern subscription reaches+ every name its pattern matches).+ """deferred: Callable[[Contract], bool] | None = Noneaccepts: Callable[[Contract, Contract], bool] | None = Nonepasses: tuple[Callable[[MatchState], None], ...] = ()+ keys: Callable[[Contract, dict[str, list[Contract]]], list[str]] | None = NoneMATCHERS: dict[str, TypeMatcher] = {@@ -39,7 +47,10 @@ MATCHERS: dict[str, TypeMatcher] = {passes=(http.base_resolved_pass, http.candidate_pass),),"topic": TypeMatcher(- deferred=topic.is_binding, accepts=topic.accepts, passes=(topic.binding_pass,)+ deferred=topic.is_binding,+ accepts=topic.accepts,+ passes=(topic.binding_pass,),+ keys=topic.matching_keys,),"data": TypeMatcher(passes=(data.shared_table_pass,)),}@@ -52,14 +63,27 @@ def _exact_pass(state: MatchState) -> None:rules = MATCHERS.get(consumer.contract_type, _NO_RULES)if rules.deferred is not None and rules.deferred(consumer):continue- keys = find_matching_keys(consumer.contract_id, state.provider_index)+ own = normalize_contract_id(consumer.contract_id)+ if rules.keys is not None:+ keys = rules.keys(consumer, state.provider_index)+ else:+ keys = find_matching_keys(consumer.contract_id, state.provider_index)providers = [p for k in keys for p in state.provider_index[k]]for provider in prefer_target_repo(providers, consumer):if internal(provider, consumer):continueif rules.accepts is not None and not rules.accepts(provider, consumer):continue- state.add(consumer, provider, "exact", min(provider.confidence, consumer.confidence))+ state.add(+ consumer,+ provider,+ "exact",+ min(provider.confidence, consumer.confidence),+ # A key the type's own rule reached under another name (a+ # pattern subscription) links under the provider's name.+ via_alias=rules.keys is not None+ and normalize_contract_id(provider.contract_id) != own,+ )def match_contracts(contracts: list[Contract]) -> list[ContractLink]:diff --git a/packages/core/src/repowise/core/workspace/matching/topic.py b/packages/core/src/repowise/core/workspace/matching/topic.pyindex f4e2bbeb6..6d19e8e82 100644--- a/packages/core/src/repowise/core/workspace/matching/topic.py+++ b/packages/core/src/repowise/core/workspace/matching/topic.py@@ -14,18 +14,25 @@ whose key it would never receive.from __future__ import annotations+import refrom collections import defaultdict-from functools import cache+from fnmatch import fnmatchcase+from functools import lru_cachefrom typing import TYPE_CHECKINGfrom repowise.core.workspace.contracts import (TOPIC_KIND_BINDING,TOPIC_KIND_QUEUE,+ TOPIC_PATTERN,+ TOPIC_PATTERN_GLOB,+ TOPIC_PATTERN_NATS,+ TOPIC_PATTERN_REGEX,+ TOPIC_PREFIX,TOPIC_ROUTING_KEY_UNRESOLVED,normalize_contract_id,)-from .common import internal+from .common import find_matching_keys, internalif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -33,7 +40,7 @@ if TYPE_CHECKING:from .common import MatchState-@cache+@lru_cache(maxsize=4096)def _words_match(pattern: tuple[str, ...], key: tuple[str, ...]) -> bool:"""AMQP topic matching over dot-separated words: ``*`` is one, ``#`` is zero or more."""if not pattern:@@ -58,6 +65,74 @@ def routing_matches(pattern: str, key: str) -> bool:return _words_match(tuple(pattern.split(".")), tuple(key.split(".")))+@lru_cache(maxsize=256)+def _compiled(pattern: str) -> re.Pattern[str] | None:+ try:+ return re.compile(pattern, re.IGNORECASE)+ except re.error:+ return None+++# What a pattern needs besides wildcards to name anything: `>` or `.*` alone+# subscribes to everything, which says nothing about which service it reads.+_WILDCARD_CHARS_RE = re.compile(r"[*>#?.\[\]\\^$+(){}|]")+++def pattern_matches(syntax: str, pattern: str, name: str) -> bool:+ """True when a subscription on *pattern* (in *syntax*) receives topic *name*.++ ``nats``: ``*`` is one dot-separated token, a final ``>`` one or more.+ ``glob`` (Redis ``PSUBSCRIBE``): shell wildcards over the whole name.+ ``regex`` (Kafka ``topicPattern``): the whole name.+ """+ if syntax == TOPIC_PATTERN_NATS:+ words = pattern.lower().split(".")+ if words[-1] == ">":+ words[-1:] = ["*", "#"]+ return _words_match(tuple(words), tuple(name.split(".")))+ if syntax == TOPIC_PATTERN_GLOB:+ return fnmatchcase(name, pattern.lower())+ if syntax == TOPIC_PATTERN_REGEX:+ compiled = _compiled(pattern)+ return compiled is not None and compiled.fullmatch(name) is not None+ return False+++def matching_keys(consumer: Contract, provider_index: dict[str, list[Contract]]) -> list[str]:+ """The provider keys *consumer* reaches: its own id, and every name its pattern matches."""+ keys = find_matching_keys(consumer.contract_id, provider_index)+ syntax = consumer.meta.get(TOPIC_PATTERN)+ pattern = str(consumer.meta.get("topic", ""))+ if not syntax or not _WILDCARD_CHARS_RE.sub("", pattern):+ return keys+ return keys + [+ k+ for k in provider_index+ if k.startswith(TOPIC_PREFIX)+ and k not in keys+ and pattern_matches(syntax, pattern, k[len(TOPIC_PREFIX) :])+ ]+++# Brokers that meet only their own kind: a BullMQ queue is a set of Redis keys+# only BullMQ reads. Laravel and NestJS name a queue or pattern whose transport+# is configured outside the code (RabbitMQ, SQS, Redis, Kafka, NATS), so either+# meets any broker but those. Every other pair must be the same broker: a Kafka+# topic and a RabbitMQ queue that share a name are two things.+_OWN_KIND_ONLY = frozenset({"bullmq"})+_ANY_TRANSPORT = frozenset({"laravel", "nestjs"})+++def same_transport(provider: Contract, consumer: Contract) -> bool:+ """Whether the two ends can be one broker's destination."""+ a, b = provider.meta.get("broker"), consumer.meta.get("broker")+ if a == b or not a or not b:+ return True+ if a in _OWN_KIND_ONLY or b in _OWN_KIND_ONLY:+ return False+ return a in _ANY_TRANSPORT or b in _ANY_TRANSPORT++def is_binding(consumer: Contract) -> bool:"""A binding row is linked by :func:`binding_pass`, never by the exact pass."""return consumer.meta.get("kind") == TOPIC_KIND_BINDING@@ -67,12 +142,21 @@ def accepts(provider: Contract, consumer: Contract) -> bool:"""Whether *consumer* receives what *provider* publishes, on routing grounds.A key the source did not settle routes nowhere: reading it as match-all- would link every binding on the exchange.+ would link every binding on the exchange. The two ends must be able to be+ one broker's destination (:func:`same_transport`), and a Laravel job is+ read by a Laravel worker only if it is the worker's own class."""if provider.meta.get(TOPIC_ROUTING_KEY_UNRESOLVED) or consumer.meta.get(TOPIC_ROUTING_KEY_UNRESOLVED):return False+ if not same_transport(provider, consumer):+ return False+ if (+ provider.meta.get("broker") == consumer.meta.get("broker") == "laravel"+ and provider.meta.get("job") != consumer.meta.get("job")+ ):+ return Falsereturn routing_matches(consumer.meta.get("routing_key", ""), provider.meta.get("routing_key", ""))@@ -116,4 +200,12 @@ def binding_pass(state: MatchState) -> None:)-__all__ = ["accepts", "binding_pass", "is_binding", "routing_matches"]+__all__ = [+ "accepts",+ "binding_pass",+ "is_binding",+ "matching_keys",+ "pattern_matches",+ "routing_matches",+ "same_transport",+]diff --git a/tests/unit/workspace/test_async_links.py b/tests/unit/workspace/test_async_links.pynew file mode 100644index 000000000..8433b885e--- /dev/null+++ b/tests/unit/workspace/test_async_links.py@@ -0,0 +1,141 @@+"""Async contracts end to end: extracted in one repo, linked to another by the matcher."""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.extractors import SocketExtractor, TopicExtractor+from repowise.core.workspace.matching import match_contracts+++def _repo(tmp_path: Path, alias: str, files: dict[str, str]) -> list[Contract]:+ root = tmp_path / alias+ for rel, content in files.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ return TopicExtractor().extract(root, alias) + SocketExtractor().extract(root, alias)+++def _links(*repos: list[Contract]) -> set[tuple[str, str, str]]:+ return {+ (link.provider_repo, link.consumer_repo, link.contract_id)+ for link in match_contracts([c for repo in repos for c in repo])+ }+++_JOB = (+ "<?php\nnamespace App\\Jobs;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\n"+ "class NotifyTicketSold implements ShouldQueue\n{\n public function handle() {}\n}\n"+)+_CONTROLLER = (+ "<?php\nnamespace App\\Http\\Controllers;\nuse App\\Jobs\\NotifyTicketSold;\n"+ "class TicketController\n{\n public function store($t)\n {\n"+ " NotifyTicketSold::dispatch($t)->onQueue('ticket.sold');\n }\n}\n"+)+_AMQP = "import amqp from 'amqplib';\n"+++def test_a_laravel_dispatch_reaches_a_node_consumer(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"app/Jobs/NotifyTicketSold.php": _JOB, "app/Http/C.php": _CONTROLLER})+ worker = _repo(tmp_path, "worker", {"w.ts": _AMQP + "channel.consume('ticket.sold', h);\n"})+ assert _links(api, worker) == {("api", "worker", "topic::ticket.sold")}+++def test_sqs_links_across_languages(tmp_path: Path) -> None:+ api = _repo(+ tmp_path,+ "api",+ {"q.ts": "new SendMessageCommand({ QueueUrl: 'https://sqs.r.amazonaws.com/1/orders' });\n"},+ )+ worker = _repo(+ tmp_path, "worker", {"w.py": "sqs.receive_message(QueueUrl=f'{BASE}/orders')\n"}+ )+ assert _links(api, worker) == {("api", "worker", "topic::orders")}+++def test_bullmq_queue_to_worker(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"q.ts": "import { Queue } from 'bullmq';\nnew Queue('emails');\n"})+ worker = _repo(+ tmp_path, "worker", {"w.ts": "import { Worker } from 'bullmq';\nnew Worker('emails', f);\n"}+ )+ assert _links(api, worker) == {("api", "worker", "topic::emails")}+++def test_a_bullmq_queue_is_not_a_laravel_queue_of_the_same_name(tmp_path: Path) -> None:+ api = _repo(+ tmp_path,+ "api",+ {"C.php": "<?php\nuse App\\Jobs\\Mail;\nMail::dispatch()->onQueue('emails');\n"},+ )+ worker = _repo(+ tmp_path, "worker", {"w.ts": "import { Worker } from 'bullmq';\nnew Worker('emails', f);\n"}+ )+ assert _links(api, worker) == set()+++def test_a_nats_wildcard_subscription(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"p.go": 'nc.Publish("orders.created", d)\n'})+ audit = _repo(tmp_path, "audit", {"s.ts": "nc.subscribe('orders.>');\n"})+ assert _links(api, audit) == {("api", "audit", "topic::orders.created")}+++def test_a_redis_pattern_subscription(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"p.py": "import redis\nr.publish('scores.eu', x)\n"})+ board = _repo(tmp_path, "board", {"s.ts": "import Redis from 'ioredis';\nsub.psubscribe('scores.*');\n"})+ assert _links(api, board) == {("api", "board", "topic::scores.eu")}+++def test_php_amqplib_publish_reaches_an_amqplib_queue_through_a_binding(tmp_path: Path) -> None:+ api = _repo(+ tmp_path,+ "api",+ {"P.php": "<?php\nuse PhpAmqpLib\\Message\\AMQPMessage;\n$ch->basic_publish($m, 'orders', 'order.created');\n"},+ )+ audit = _repo(+ tmp_path,+ "audit",+ {"w.ts": _AMQP + "ch.bindQueue('audit', 'orders', 'order.*');\nch.consume('audit', h);\n"},+ )+ assert _links(api, audit) == {("api", "audit", "topic::orders")}+++def test_a_nestjs_object_pattern_across_repos(tmp_path: Path) -> None:+ imp = "import { ClientProxy, MessagePattern } from '@nestjs/microservices';\n"+ api = _repo(+ tmp_path,+ "api",+ {"c.ts": imp + "client: ClientProxy;\nthis.client.send<number>({ role: 'math', cmd: 'sum' }, [1]);\n"},+ )+ math = _repo(tmp_path, "math", {"m.ts": imp + "@MessagePattern({ cmd: 'sum', role: 'math' })\nf() {}\n"})+ assert _links(api, math) == {("api", "math", 'topic::{"cmd":"sum","role":"math"}')}+++def test_fastapi_websocket_to_browser(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"ws.py": '@app.websocket("/ws/chat/{room_id}")\nasync def chat(): ...\n'})+ web = _repo(tmp_path, "web", {"c.ts": "new WebSocket(`wss://${host}/ws/chat/${room}`);\n"})+ assert _links(api, web) == {("api", "web", "socket::/ws/chat/{param}")}+++def test_a_socket_io_namespace_across_repos(tmp_path: Path) -> None:+ api = _repo(+ tmp_path, "api", {"s.ts": "import { Server } from 'socket.io';\nio.of('/admin').emit('stats', s);\n"}+ )+ web = _repo(+ tmp_path,+ "web",+ {"c.ts": "import { io } from 'socket.io-client';\nconst socket = io('https://h/admin');\nsocket.on('stats', f);\n"},+ )+ root = _repo(+ tmp_path,+ "other",+ {"c.ts": "import { io } from 'socket.io-client';\nconst socket = io();\nsocket.on('stats', f);\n"},+ )+ assert _links(api, web, root) == {("api", "web", "socket::/admin#stats")}+++def test_an_anonymous_broadcast_reaches_echo(tmp_path: Path) -> None:+ api = _repo(tmp_path, "api", {"S.php": "<?php\nBroadcast::on('news')->send();\n"})+ web = _repo(tmp_path, "web", {"a.js": "Echo.channel('news').listen('.AnonymousEvent', f);\n"})+ assert _links(api, web) == {("api", "web", "socket::news#AnonymousEvent")}diff --git a/tests/unit/workspace/test_client_calls.py b/tests/unit/workspace/test_client_calls.pyindex 36a06b41f..e04fe8afc 100644--- a/tests/unit/workspace/test_client_calls.py+++ b/tests/unit/workspace/test_client_calls.py@@ -66,7 +66,7 @@ class TestLiterals:("syntax", "expr"),[(JS_SYNTAX, "path"),- (JS_SYNTAX, '"/a" + id'),+ (JS_SYNTAX, '"/a" + buildPath(id)'),(JS_SYNTAX, "buildPath(id)"),(PYTHON_SYNTAX, 'b"/bytes"'),(PYTHON_SYNTAX, 'f"/x/{{literal}}"'),@@ -99,6 +99,9 @@ class TestUnwrapAndConcat:def test_java_uri_create_is_unwrapped(self):assert resolve_string('URI.create(base + "/echo")', JAVA_SYNTAX) == "${base}/echo"+ def test_js_concat_with_a_trailing_name(self):+ assert resolve_string("'/users/' + id", JS_SYNTAX) == "/users/${id}"+def test_go_concat_with_a_trailing_name(self):assert resolve_string('"/users/" + id', GO_SYNTAX) == "/users/${id}"diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.pyindex 8709641f6..288652cbd 100644--- a/tests/unit/workspace/test_contracts.py+++ b/tests/unit/workspace/test_contracts.py@@ -287,6 +287,16 @@ class TestHttpExtractor:assert consumers[0].contract_id == "http::GET::/api/users"assert consumers[0].meta.get("base_stripped") is True+ def test_fetch_consumer_folds_a_const_base(self, tmp_path: Path) -> None:+ self._write_file(tmp_path, "src/api.ts", """+ const API = 'http://ticketing:8000/api';+ const users = await fetch(`${API}/users`);+ """)+ contracts = HttpExtractor().extract(tmp_path, "frontend")+ consumers = [c for c in contracts if c.role == "consumer"]+ assert [c.contract_id for c in consumers] == ["http::GET::/api/users"]+ assert "base_stripped" not in consumers[0].meta+def test_fetch_consumer_keeps_interior_param(self, tmp_path: Path) -> None:self._write_file(tmp_path, "src/api.ts", """const u = await fetch(`/users/${id}`);diff --git a/tests/unit/workspace/test_index_clients.py b/tests/unit/workspace/test_index_clients.pyindex fb16d11bc..623343bc1 100644--- a/tests/unit/workspace/test_index_clients.py+++ b/tests/unit/workspace/test_index_clients.py@@ -676,7 +676,8 @@ class TestSupersedeCannotSubtract:('"/a/b"', "/a/b"),("`/a/${id}`", "/a/${id}"),("path", None),- ('"/a" + id', None),+ ('"/a/" + id', "/a/${id}"),+ ('"/a/" + buildPath(id)', None),("buildPath(id)", None),],)diff --git a/tests/unit/workspace/test_laravel_queues.py b/tests/unit/workspace/test_laravel_queues.pynew file mode 100644index 000000000..121879d6d--- /dev/null+++ b/tests/unit/workspace/test_laravel_queues.py@@ -0,0 +1,249 @@+"""Laravel queued jobs: dispatch sites, class-declared queues, and the join between them."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.workspace.extractors.topic import TopicExtractor+++def _extract(tmp_path: Path, files: dict[str, str]):+ for rel, content in files.items():+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ return TopicExtractor().extract(tmp_path, "api")+++def _rows(contracts) -> set[tuple[str, str, str]]:+ return {(c.role, c.contract_id, c.file_path) for c in contracts}+++def _job(name: str, body: str = "", namespace: str = "App\\Jobs") -> str:+ return (+ f"<?php\n\nnamespace {namespace};\n\n"+ "use Illuminate\\Contracts\\Queue\\ShouldQueue;\n\n"+ f"class {name} implements ShouldQueue\n{{\n{body}\n public function handle(): void {{}}\n}}\n"+ )+++def _controller(body: str, uses: str = "use App\\Jobs\\SendReceipt;\n") -> str:+ return (+ "<?php\n\nnamespace App\\Http\\Controllers;\n\n"+ f"{uses}\nclass OrderController\n{{\n public function store()\n {{\n {body}\n }}\n}}\n"+ )+++_JOB = "app/Jobs/SendReceipt.php"+_CTRL = "app/Http/Controllers/OrderController.php"+++class TestDispatchSites:+ def test_on_queue_names_the_queue_at_both_ends(self, tmp_path: Path) -> None:+ rows = _extract(+ tmp_path,+ {+ _JOB: _job("SendReceipt"),+ _CTRL: _controller("SendReceipt::dispatch($order)->onQueue('receipts');"),+ },+ )+ assert _rows(rows) == {+ ("provider", "topic::receipts", _CTRL),+ ("consumer", "topic::receipts", _JOB),+ }+ provider = next(c for c in rows if c.role == "provider")+ assert provider.meta == {+ "topic": "receipts",+ "broker": "laravel",+ "kind": "queue",+ "job": "App\\Jobs\\SendReceipt",+ }+ assert provider.symbol_name == "SendReceipt::dispatch('receipts')"++ @pytest.mark.parametrize(+ "body",+ [+ "dispatch((new SendReceipt($order))->onQueue('receipts'));",+ "dispatch(new SendReceipt($order))->onQueue('receipts');",+ "Bus::dispatch((new SendReceipt($order))->onQueue('receipts'));",+ "Queue::pushOn('receipts', new SendReceipt($order));",+ "Queue::push(new SendReceipt($order), '', 'receipts');",+ "Queue::later(60, new SendReceipt($order), '', 'receipts');",+ "$schedule->job(new SendReceipt, 'receipts')->daily();",+ ],+ )+ def test_every_dispatch_spelling(self, tmp_path: Path, body: str) -> None:+ rows = _extract(tmp_path, {_JOB: _job("SendReceipt"), _CTRL: _controller(body)})+ assert ("provider", "topic::receipts", _CTRL) in _rows(rows)+ assert ("consumer", "topic::receipts", _JOB) in _rows(rows)++ def test_a_queue_constant_folds(self, tmp_path: Path) -> None:+ body = "SendReceipt::dispatch($o)->onQueue(self::QUEUE);\n }\n const QUEUE = 'receipts';\n function x() {"+ rows = _extract(tmp_path, {_CTRL: _controller(body)})+ assert _rows(rows) == {("provider", "topic::receipts", _CTRL)}++ def test_the_default_queue_is_not_recorded(self, tmp_path: Path) -> None:+ rows = _extract(tmp_path, {_JOB: _job("SendReceipt"), _CTRL: _controller("SendReceipt::dispatch($o);")})+ assert rows == []++ def test_an_unsettled_queue_is_refused_not_replaced(self, tmp_path: Path) -> None:+ rows = _extract(+ tmp_path,+ {+ _JOB: _job("SendReceipt", " public $queue = 'receipts';"),+ _CTRL: _controller("SendReceipt::dispatch($o)->onQueue($this->queueName());"),+ },+ )+ # The class still runs on its own queue; the site named another it did not say.+ assert _rows(rows) == {("consumer", "topic::receipts", _JOB)}++ @pytest.mark.parametrize(+ "body",+ [+ "$this->dispatch('order-saved');", # a Livewire browser event+ "Event::dispatch(new OrderShipped($o));",+ "event(new OrderShipped($o));",+ "$this->redispatch($o);",+ ],+ )+ def test_events_are_not_jobs(self, tmp_path: Path, body: str) -> None:+ assert _extract(tmp_path, {_CTRL: _controller(body)}) == []+++class TestClassDeclaredQueues:+ @pytest.mark.parametrize(+ "body",+ [+ " public $queue = 'receipts';",+ " public ?string $queue = 'receipts';",+ " public function __construct() { $this->onQueue('receipts'); }",+ " public function viaQueue(): string { return 'receipts'; }",+ ],+ )+ def test_a_class_declares_its_queue(self, tmp_path: Path, body: str) -> None:+ rows = _extract(tmp_path, {_JOB: _job("SendReceipt", body)})+ assert _rows(rows) == {("consumer", "topic::receipts", _JOB)}++ def test_a_site_naming_no_queue_takes_the_class_queue(self, tmp_path: Path) -> None:+ rows = _extract(+ tmp_path,+ {+ _JOB: _job("SendReceipt", " public $queue = 'receipts';"),+ _CTRL: _controller("SendReceipt::dispatch($o);"),+ },+ )+ assert _rows(rows) == {+ ("provider", "topic::receipts", _CTRL),+ ("consumer", "topic::receipts", _JOB),+ }++ def test_a_site_override_adds_a_queue_the_class_runs_on(self, tmp_path: Path) -> None:+ rows = _extract(+ tmp_path,+ {+ _JOB: _job("SendReceipt", " public $queue = 'receipts';"),+ _CTRL: _controller("SendReceipt::dispatch($o)->onQueue('urgent');"),+ },+ )+ assert {(c.role, c.contract_id) for c in rows} == {+ ("provider", "topic::urgent"),+ ("consumer", "topic::receipts"),+ ("consumer", "topic::urgent"),+ }++ def test_a_class_that_is_not_queued_consumes_nothing(self, tmp_path: Path) -> None:+ src = "<?php\nnamespace App\\Jobs;\nclass SendReceipt\n{\n public $queue = 'receipts';\n}\n"+ assert _extract(tmp_path, {_JOB: src}) == []+++class TestRefusals:+ @pytest.mark.parametrize(+ "body",+ ["SendReceipt::dispatch($o)->onQueue('default');", "SendReceipt::dispatchSync($o);"],+ )+ def test_the_default_queue_and_a_sync_dispatch_name_no_queue(+ self, tmp_path: Path, body: str+ ) -> None:+ rows = _extract(tmp_path, {_JOB: _job("SendReceipt"), _CTRL: _controller(body)})+ assert rows == []++ def test_a_class_declaring_the_default_queue_consumes_nothing(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, {_JOB: _job("SendReceipt", " public $queue = 'default';")}) == []++ def test_php_method_names_are_case_insensitive(self, tmp_path: Path) -> None:+ rows = _extract(tmp_path, {_CTRL: _controller("SendReceipt::dispatch($o)->ONQUEUE('receipts');")})+ assert _rows(rows) == {("provider", "topic::receipts", _CTRL)}++ def test_the_word_class_in_a_docblock_is_not_the_job(self, tmp_path: Path) -> None:+ src = _job("SendReceipt", " public $queue = 'receipts';").replace(+ "class SendReceipt", "/**\n * This class sends mail.\n */\nclass SendReceipt"+ )+ rows = _extract(tmp_path, {_JOB: src, _CTRL: _controller("SendReceipt::dispatch($o);")})+ assert {c.meta["job"] for c in rows} == {"App\\Jobs\\SendReceipt"}+ assert ("provider", "topic::receipts", _CTRL) in _rows(rows)+++class TestRepoPass:+ def test_two_passes_share_nothing(self) -> None:+ from repowise.core.workspace.extractors.base import ScanContext+ from repowise.core.workspace.extractors.topic.laravel import LARAVEL_QUEUES++ a, b = LARAVEL_QUEUES.repo_pass(), LARAVEL_QUEUES.repo_pass()+ a.scan(ScanContext("a", _JOB, ".php", _job("SendReceipt", " public $queue = 'a-q';")))+ b.scan(ScanContext("b", _CTRL, ".php", _controller("SendReceipt::dispatch($o);")))+ a.scan(ScanContext("a", _CTRL, ".php", _controller("SendReceipt::dispatch($o);")))+ assert b.finish() == []+ assert {(c.repo, c.role, c.contract_id) for c in a.finish()} == {+ ("a", "provider", "topic::a-q"),+ ("a", "consumer", "topic::a-q"),+ }++ def test_one_extractor_reused_across_repos(self, tmp_path: Path) -> None:+ from repowise.core.workspace.extractors.topic import TopicExtractor++ extractor = TopicExtractor()+ for alias, rel, src in (+ ("worker", _JOB, _job("SendReceipt", " public $queue = 'receipts';")),+ ("web", _CTRL, _controller("SendReceipt::dispatch($o);")),+ ):+ (tmp_path / alias / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / alias / rel).write_text(src, encoding="utf-8")+ assert len(extractor.extract(tmp_path / "worker", "worker")) == 1+ # The class that names the queue is in the other repo: nothing joins.+ assert extractor.extract(tmp_path / "web", "web") == []+++class TestNameResolution:+ def test_the_join_follows_use_aliases(self, tmp_path: Path) -> None:+ rows = _extract(+ tmp_path,+ {+ _JOB: _job("SendReceipt", " public $queue = 'receipts';"),+ _CTRL: _controller(+ "Receipt::dispatch($o);", uses="use App\\Jobs\\SendReceipt as Receipt;\n"+ ),+ },+ )+ assert ("provider", "topic::receipts", _CTRL) in _rows(rows)++ def test_a_same_short_name_in_another_namespace_is_not_joined(self, tmp_path: Path) -> None:+ other = "app/Billing/SendReceipt.php"+ rows = _extract(+ tmp_path,+ {+ other: _job("SendReceipt", " public $queue = 'billing';", "App\\Billing"),+ _CTRL: _controller("SendReceipt::dispatch($o);"),+ },+ )+ assert _rows(rows) == {("consumer", "topic::billing", other)}++ def test_a_same_namespace_class_needs_no_use(self, tmp_path: Path) -> None:+ dispatcher = "app/Jobs/Fanout.php"+ src = "<?php\nnamespace App\\Jobs;\nclass Fanout\n{\n function run() { SendReceipt::dispatch(); }\n}\n"+ rows = _extract(+ tmp_path,+ {_JOB: _job("SendReceipt", " public $queue = 'receipts';"), dispatcher: src},+ )+ assert ("provider", "topic::receipts", dispatcher) in _rows(rows)diff --git a/tests/unit/workspace/test_socket_dialects.py b/tests/unit/workspace/test_socket_dialects.pynew file mode 100644index 000000000..2957e4645--- /dev/null+++ b/tests/unit/workspace/test_socket_dialects.py@@ -0,0 +1,291 @@+"""Socket dialects: socket.io events, websocket endpoints, and broadcast channels."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.extractors.socket import SocketExtractor+from repowise.core.workspace.matching import match_contracts+++def _extract(tmp_path: Path, files: dict[str, str], alias: str = "svc") -> list[Contract]:+ root = tmp_path / alias+ for rel, content in files.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ return SocketExtractor().extract(root, alias)+++def _ids(contracts: list[Contract]) -> set[tuple[str, str]]:+ return {(c.role, c.contract_id) for c in contracts}+++_SERVER = "import { Server } from 'socket.io';\n"+_CLIENT = "import { io } from 'socket.io-client';\n"+++class TestSocketIo:+ def test_server_and_client_events(self, tmp_path: Path) -> None:+ server = _SERVER + (+ "io.on('connection', (socket) => {\n"+ " socket.on('chat message', (m) => io.emit('chat message', m));\n"+ " socket.to(room).emit('typing', u);\n"+ "});\n"+ )+ assert _ids(_extract(tmp_path, {"server.ts": server})) == {+ ("consumer", "socket::/#chat message"),+ ("provider", "socket::/#chat message"),+ ("provider", "socket::/#typing"),+ }++ def test_lifecycle_events_are_not_contracts(self, tmp_path: Path) -> None:+ src = _CLIENT + "const socket = io();\nsocket.on('connect', f);\nsocket.on('disconnect', g);\n"+ assert _extract(tmp_path, {"c.ts": src}) == []++ def test_an_event_emitter_is_not_a_socket(self, tmp_path: Path) -> None:+ src = _SERVER + "emitter.on('ready', f);\nprocess.on('SIGTERM', g);\nbus.emit('tick');\n"+ assert _extract(tmp_path, {"s.ts": src}) == []++ def test_another_librarys_client_or_server_is_not_a_socket(self, tmp_path: Path) -> None:+ src = _SERVER + (+ "const client = mqtt.connect(url);\nclient.on('message', f);\n"+ "server.on('request', g);\n"+ )+ assert _extract(tmp_path, {"s.ts": src}) == []++ def test_a_client_bound_to_socket_io_is_a_socket(self, tmp_path: Path) -> None:+ src = _CLIENT + "const client = io('/');\nclient.on('stats', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/#stats")}++ def test_a_client_url_with_a_base_names_its_namespace(self, tmp_path: Path) -> None:+ src = _CLIENT + "const socket = io(API_URL + '/chat');\nsocket.on('message', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/chat#message")}++ def test_io_connect_names_its_namespace(self, tmp_path: Path) -> None:+ src = _CLIENT + "const socket = io.connect(`${base}/chat`);\nsocket.on('message', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/chat#message")}++ def test_an_unreadable_server_namespace_refuses_unchained_events(self, tmp_path: Path) -> None:+ src = _SERVER + "const nsp = io.of(name);\nnsp.on('connection', (socket) => socket.emit('x'));\n"+ assert _extract(tmp_path, {"s.ts": src}) == []++ def test_nothing_without_socket_io(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, {"s.ts": "socket.on('chat', f);\n"}) == []++ def test_a_chain_of_listeners_shares_its_receiver(self, tmp_path: Path) -> None:+ src = _CLIENT + (+ "const websocket = io({ path: '/api/socket.io' });\n"+ "websocket\n .on('connect', f)\n .on('on_upload', g)\n ?.on('on_delete', h);\n"+ )+ assert _ids(_extract(tmp_path, {"ws.ts": src})) == {+ ("consumer", "socket::/#on_upload"),+ ("consumer", "socket::/#on_delete"),+ }++ def test_the_client_url_names_the_namespace(self, tmp_path: Path) -> None:+ src = _CLIENT + "const s = io('https://api.example.com/admin');\ns.on('stats', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/admin#stats")}++ def test_an_unreadable_client_url_is_the_default_namespace(self, tmp_path: Path) -> None:+ src = _CLIENT + "const socket = io(process.env.API_URL);\nsocket.on('stats', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/#stats")}++ def test_a_server_namespace(self, tmp_path: Path) -> None:+ src = _SERVER + "const admin = io.of('/admin');\nadmin.on('connection', (socket) => socket.emit('stats', s));\n"+ assert _ids(_extract(tmp_path, {"s.ts": src})) == {("provider", "socket::/admin#stats")}++ def test_default_beside_a_named_namespace_reads_only_chained_events(self, tmp_path: Path) -> None:+ src = _SERVER + (+ "io.of('/admin').emit('stats', s);\n"+ "io.on('connection', (socket) => socket.emit('hello'));\n"+ )+ assert _ids(_extract(tmp_path, {"s.ts": src})) == {("provider", "socket::/admin#stats")}++ def test_server_to_client_link(self, tmp_path: Path) -> None:+ server = _extract(tmp_path, {"s.ts": _SERVER + "io?.emit('order.ready', o);\n"}, "api")+ client = _extract(tmp_path, {"c.ts": _CLIENT + "socket.on('order.ready', f);\n"}, "web")+ links = match_contracts(server + client)+ assert [(lk.provider_repo, lk.consumer_repo, lk.contract_id) for lk in links] == [+ ("api", "web", "socket::/#order.ready")+ ]+++class TestNestGateways:+ _IMPORT = "import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';\n"++ def test_subscribe_message_in_the_gateway_namespace(self, tmp_path: Path) -> None:+ src = self._IMPORT + (+ "@WebSocketGateway({ namespace: 'chat' })\nexport class ChatGateway {\n"+ " @SubscribeMessage('send')\n handle(client) { client.emit('sent', 1); }\n}\n"+ )+ assert _ids(_extract(tmp_path, {"g.ts": src})) == {+ ("consumer", "socket::/chat#send"),+ ("provider", "socket::/chat#sent"),+ }++ def test_a_gateway_path_is_an_endpoint(self, tmp_path: Path) -> None:+ src = self._IMPORT + "@WebSocketGateway({ path: '/ws' })\nexport class G {}\n"+ assert _ids(_extract(tmp_path, {"g.ts": src})) == {("provider", "socket::/ws")}+++class TestPortedEndpoints:+ """The C# and FastAPI shapes, now read through the shared string resolver."""++ @pytest.mark.parametrize(+ "src",+ [+ '@router.websocket(path="/ws/feed")\nasync def f(): ...\n',+ 'WS = "/ws/feed"\[email protected](WS)\nasync def f(): ...\n',+ ],+ )+ def test_fastapi_keyword_and_constant(self, tmp_path: Path, src: str) -> None:+ assert _ids(_extract(tmp_path, {"ws.py": src})) == {("provider", "socket::/ws/feed")}++ @pytest.mark.parametrize(+ "src",+ [+ 'await ws.ConnectAsync(new Uri(@"wss://h/hubs/game"), t);',+ 'await ws.ConnectAsync(new Uri($@"{b}/hubs/game"), t);',+ 'app.MapHub<GameHub>("/hubs/game", o => { o.X = 1; });',+ 'new HubConnectionBuilder()\n .WithUrl(\n "wss://h/hubs/game",\n opts => {})',+ ],+ )+ def test_csharp_spellings(self, tmp_path: Path, src: str) -> None:+ rows = _extract(tmp_path, {"S.cs": src})+ assert {c.contract_id for c in rows} == {"socket::/hubs/game"}++ def test_csharp_escaped_braces_are_refused(self, tmp_path: Path) -> None:+ src = 'var c = new HubConnectionBuilder().WithUrl($"{b}/hubs/{{x}}");'+ assert _extract(tmp_path, {"S.cs": src}) == []+++class TestWebsocketEndpoints:+ def test_ws_server_and_browser_client(self, tmp_path: Path) -> None:+ server = _extract(+ tmp_path,+ {"s.ts": "import { WebSocketServer } from 'ws';\nnew WebSocketServer({ server, path: '/live' });\n"},+ "api",+ )+ client = _extract(+ tmp_path, {"c.ts": "const ws = new WebSocket(`wss://${host}/live`);\n"}, "web"+ )+ assert _ids(server) == {("provider", "socket::/live")}+ assert _ids(client) == {("consumer", "socket::/live")}+ assert len(match_contracts(server + client)) == 1++ def test_a_url_constant_folds(self, tmp_path: Path) -> None:+ src = "const URL = 'wss://example.com/feed';\nconst ws = new WebSocket(URL);\n"+ assert _ids(_extract(tmp_path, {"c.ts": src})) == {("consumer", "socket::/feed")}+++_EVENT_USES = "use Illuminate\\Broadcasting\\PrivateChannel;\nuse Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast;\n"+++def _event(body: str, name: str = "OrderShipped") -> str:+ return (+ f"<?php\n\nnamespace App\\Events;\n\n{_EVENT_USES}\n"+ f"class {name} implements ShouldBroadcast\n{{\n{body}\n}}\n"+ )+++_ON_ORDER = (+ " public function broadcastOn(): array\n"+ " {\n return [new PrivateChannel('orders.'.$this->order->id)];\n }\n"+)+++class TestLaravelBroadcasting:+ def test_an_event_class_is_broadcast_under_its_class_name(self, tmp_path: Path) -> None:+ rows = _extract(tmp_path, {"app/Events/OrderShipped.php": _event(_ON_ORDER)})+ assert _ids(rows) == {+ ("provider", "socket::private-orders.{param}#App\\Events\\OrderShipped")+ }+ assert rows[0].meta == {+ "scope": "private-orders.{param}",+ "event": "App\\Events\\OrderShipped",+ "transport": "pusher",+ }++ def test_broadcast_as_renames_the_event(self, tmp_path: Path) -> None:+ body = _ON_ORDER + " public function broadcastAs(): string { return 'order.shipped'; }\n"+ rows = _extract(tmp_path, {"app/Events/OrderShipped.php": _event(body)})+ assert _ids(rows) == {("provider", "socket::private-orders.{param}#order.shipped")}++ @pytest.mark.parametrize(+ ("listen", "event"),+ [+ ("Echo.private(`orders.${id}`).listen('OrderShipped', f)", "App\\Events\\OrderShipped"),+ ("window.Echo.private('orders.' + id).listen('.order.shipped', f)", "order.shipped"),+ ("useEcho(`orders.${id}`, 'OrderShipped', f)", "App\\Events\\OrderShipped"),+ ("useEcho(`orders.${id}`, ['.order.shipped', 'Other'], f)", "order.shipped"),+ ],+ )+ def test_echo_listeners(self, tmp_path: Path, listen: str, event: str) -> None:+ rows = _extract(tmp_path, {"app.ts": f"import {{ useEcho }} from '@laravel/echo-react';\n{listen};\n"})+ assert ("consumer", f"socket::private-orders.{{param}}#{event}") in _ids(rows)++ def test_presence_and_public_channels(self, tmp_path: Path) -> None:+ src = "Echo.join('room.1').listen('.moved', f);\nEcho.channel('news').listen('.posted', g);\n"+ assert _ids(_extract(tmp_path, {"a.js": src})) == {+ ("consumer", "socket::presence-room.1#moved"),+ ("consumer", "socket::news#posted"),+ }++ def test_the_event_links_to_its_listener(self, tmp_path: Path) -> None:+ server = _extract(tmp_path, {"app/Events/OrderShipped.php": _event(_ON_ORDER)}, "api")+ client = _extract(+ tmp_path, {"a.ts": "Echo.private(`orders.${order.id}`).listen('OrderShipped', f);\n"}, "web"+ )+ links = match_contracts(server + client)+ assert [(lk.provider_repo, lk.consumer_repo) for lk in links] == [("api", "web")]++ def test_an_escaped_fully_qualified_echo_name(self, tmp_path: Path) -> None:+ src = "Echo.private(`orders.${id}`).listen('.App\\\\Events\\\\OrderShipped', f);\n"+ assert _ids(_extract(tmp_path, {"a.ts": src})) == {+ ("consumer", "socket::private-orders.{param}#App\\Events\\OrderShipped")+ }++ def test_a_notification_is_not_an_event(self, tmp_path: Path) -> None:+ src = _event(_ON_ORDER, "OrderShippedNotice").replace(+ "implements ShouldBroadcast", "extends Notification"+ )+ assert _extract(tmp_path, {"app/Notifications/N.php": src}) == []++ def test_anonymous_broadcast(self, tmp_path: Path) -> None:+ src = "<?php\nBroadcast::private('orders.'.$id)->as('OrderPlaced')->with($o)->send();\n"+ assert _ids(_extract(tmp_path, {"S.php": src})) == {+ ("provider", "socket::private-orders.{param}#OrderPlaced")+ }+++class TestPusher:+ def test_trigger_and_subscribe(self, tmp_path: Path) -> None:+ php = "<?php\nuse Pusher\\Pusher;\n$pusher->trigger('private-feed', 'item.added', $data);\n"+ js = (+ "import Pusher from 'pusher-js';\n"+ "const channel = pusher.subscribe('private-feed');\n"+ "channel.bind('item.added', f);\nmychannel.bind('other', g);\n"+ )+ provider = _extract(tmp_path, {"P.php": php}, "api")+ consumer = _extract(tmp_path, {"c.ts": js}, "web")+ assert _ids(provider) == {("provider", "socket::private-feed#item.added")}+ assert _ids(consumer) == {("consumer", "socket::private-feed#item.added")}++ def test_a_reused_variable_keeps_each_subscriptions_events(self, tmp_path: Path) -> None:+ js = (+ "import Pusher from 'pusher-js';\n"+ "function a() { const channel = pusher.subscribe('orders'); channel.bind('Shipped', f); }\n"+ "function b() { const channel = pusher.subscribe('users'); channel.bind('Joined', g); }\n"+ )+ assert _ids(_extract(tmp_path, {"c.ts": js})) == {+ ("consumer", "socket::orders#Shipped"),+ ("consumer", "socket::users#Joined"),+ }++ def test_a_chained_bind(self, tmp_path: Path) -> None:+ js = "import Pusher from 'pusher-js';\npusher.subscribe('feed').bind('added', f);\n"+ assert _ids(_extract(tmp_path, {"c.ts": js})) == {("consumer", "socket::feed#added")}diff --git a/tests/unit/workspace/test_strings.py b/tests/unit/workspace/test_strings.pyindex 73c75f2a1..543120f19 100644--- a/tests/unit/workspace/test_strings.py+++ b/tests/unit/workspace/test_strings.py@@ -10,7 +10,9 @@ from repowise.core.workspace.extractors.strings import (PYTHON_SYNTAX,Arg,resolve_argument,+ resolve_string,select_argument,+ string_constants,syntax_for_suffix,)@@ -49,6 +51,72 @@ class TestResolveArgument:got = resolve_argument(["['queue' => 'jobs']"], Arg(keys=("queue",)), PHP_SYNTAX, {})assert got == (["jobs"], False)+ def test_normalize_runs_before_the_hole_check(self) -> None:+ got = resolve_argument(+ ["`${base}/orders`"], Arg(pos=0), JS_SYNTAX, {}, lambda v: v.rpartition("/")[2]+ )+ assert got == (["orders"], False)++ def test_normalize_may_refuse(self) -> None:+ assert resolve_argument(["'x'"], Arg(pos=0), JS_SYNTAX, {}, lambda v: None) == ([], True)+++def _js(src: str, expr: str) -> str | None:+ return resolve_string(expr, JS_SYNTAX, string_constants(src, JS_SYNTAX))+++class TestJsConstants:+ def test_a_const_folds(self) -> None:+ assert _js("export const QUEUE = 'orders';\n", "QUEUE") == "orders"++ def test_as_const_and_a_trailing_comment_are_not_the_value(self) -> None:+ assert _js("const Q = 'orders' as const; // the queue\n", "Q") == "orders"++ def test_a_typed_const_folds(self) -> None:+ assert _js("const Q: string = 'orders';\n", "Q") == "orders"++ def test_let_and_var_are_not_folded(self) -> None:+ src = "let A = 'a';\nvar B = 'b';\nA = 'c';\n"+ assert _js(src, "A") is None+ assert _js(src, "B") is None++ def test_a_const_declared_twice_is_refused(self) -> None:+ assert _js("const Q = 'a';\nfunction f() { const Q = 'b'; }\n", "Q") is None++ def test_a_const_built_by_concatenation(self) -> None:+ assert _js("const BASE = '/api';\nconst URL = BASE + '/users';\n", "URL") == "/api/users"++ def test_object_members_fold(self) -> None:+ src = "export const QUEUES = {\n ticketSold: 'ticket.sold',\n 'guest-in': \"guest.in\",\n} as const;\n"+ assert _js(src, "QUEUES.ticketSold") == "ticket.sold"+ assert string_constants(src, JS_SYNTAX)["QUEUES.guest-in"] == '"guest.in"'++ def test_nested_object_members_fold(self) -> None:+ src = "const Q = Object.freeze({ orders: { created: 'orders.created' } });\n"+ assert _js(src, "Q.orders.created") == "orders.created"++ def test_enum_members_fold(self) -> None:+ src = "export enum Queue { Sold = 'ticket.sold', Plain }\n"+ assert _js(src, "Queue.Sold") == "ticket.sold"+ assert _js(src, "Queue.Plain") is None++ def test_a_comment_between_members_is_skipped(self) -> None:+ src = "const Q = {\n a: 'x', // first\n /* second */ b: 'y',\n};\n"+ assert (_js(src, "Q.a"), _js(src, "Q.b")) == ("x", "y")++ def test_a_member_that_is_not_a_string_is_refused(self) -> None:+ assert _js("const Q = { n: 5, f: () => 'x' };\n", "Q.n") is None++ def test_an_example_in_a_comment_is_not_a_binding(self) -> None:+ assert _js("// const Q = 'a';\n", "Q") is None+++class TestPhpConstants:+ def test_a_class_constant_folds_through_self(self) -> None:+ constants = string_constants("class A { const QUEUE = 'jobs'; }", PHP_SYNTAX)+ assert resolve_string("self::QUEUE", PHP_SYNTAX, constants) == "jobs"+ assert resolve_string("static::QUEUE", PHP_SYNTAX, constants) == "jobs"+@pytest.mark.parametrize(("suffix", "expected"),diff --git a/tests/unit/workspace/test_topic_dialects.py b/tests/unit/workspace/test_topic_dialects.pyindex 2a8058916..a54ad395d 100644--- a/tests/unit/workspace/test_topic_dialects.py+++ b/tests/unit/workspace/test_topic_dialects.py@@ -16,6 +16,10 @@ def _extract(tmp_path: Path, rel: str, content: str, alias: str = "svc"):return TopicExtractor().extract(tmp_path, alias)+# amqplib's `publish` and `consume` are read only in a file importing it.+_AMQP = "import amqp from 'amqplib';\n"++def _one(contracts, role: str):rows = [c for c in contracts if c.role == role]assert len(rows) == 1, rows@@ -109,27 +113,26 @@ class TestRabbitMq:assert c.meta["kind"] == "queue"def test_publish_carries_exchange_and_routing_key(self, tmp_path: Path) -> None:- c = _one(- _extract(tmp_path, "pub.ts", "channel.publish('orders', 'order.created', body);"),- "provider",- )+ src = _AMQP + "channel.publish('orders', 'order.created', body);"+ c = _one(_extract(tmp_path, "pub.ts", src), "provider")assert c.contract_id == "topic::orders"assert c.meta["kind"] == "exchange"assert c.meta["routing_key"] == "order.created"def test_publish_to_the_default_exchange_names_the_queue(self, tmp_path: Path) -> None:- c = _one(_extract(tmp_path, "pub.ts", "channel.publish('', 'jobs', body);"), "provider")+ src = _AMQP + "channel.publish('', 'jobs', body);"+ c = _one(_extract(tmp_path, "pub.ts", src), "provider")assert c.contract_id == "topic::jobs"assert c.meta["kind"] == "queue"assert "routing_key" not in c.metadef test_two_routing_keys_on_one_exchange_are_two_rows(self, tmp_path: Path) -> None:- src = "channel.publish('orders', 'a', b);\nchannel.publish('orders', 'b', b);\n"+ src = _AMQP + "channel.publish('orders', 'a', b);\nchannel.publish('orders', 'b', b);\n"keys = sorted(c.meta["routing_key"] for c in _extract(tmp_path, "pub.ts", src))assert keys == ["a", "b"]def test_repeated_identical_call_is_one_row(self, tmp_path: Path) -> None:- src = "channel.consume('jobs', a);\nchannel.consume('jobs', b);\n"+ src = _AMQP + "channel.consume('jobs', a);\nchannel.consume('jobs', b);\n"assert len(_extract(tmp_path, "w.js", src)) == 1def test_bind_queue_is_a_binding_consumer_of_the_exchange(self, tmp_path: Path) -> None:@@ -208,7 +211,60 @@ class TestRabbitMq:],)def test_a_name_not_settled_in_the_file_is_refused(self, tmp_path: Path, call: str) -> None:- assert _extract(tmp_path, "w.js", call) == []+ assert _extract(tmp_path, "w.js", _AMQP + call) == []++ def test_publish_and_consume_need_the_amqplib_import(self, tmp_path: Path) -> None:+ src = "channel.publish('orders', 'k', b);\nchannel.consume('jobs', h);\n"+ assert _extract(tmp_path, "w.ts", src) == []++ def test_any_channel_name_is_read_in_an_amqplib_file(self, tmp_path: Path) -> None:+ src = _AMQP + "await this.ch.consume('jobs', h);\n"+ assert _one(_extract(tmp_path, "w.ts", src), "consumer").contract_id == "topic::jobs"++ def test_send_to_queue_needs_no_import(self, tmp_path: Path) -> None:+ src = "currentChannel().sendToQueue('jobs', body);\n"+ assert _one(_extract(tmp_path, "w.ts", src), "provider").contract_id == "topic::jobs"++ def test_an_object_member_constant_folds(self, tmp_path: Path) -> None:+ src = (+ _AMQP+ + "export const QUEUES = { ticketSold: 'ticket.sold' } as const;\n"+ + "channel.consume(QUEUES.ticketSold, h);\n"+ )+ assert _one(_extract(tmp_path, "w.ts", src), "consumer").contract_id == "topic::ticket.sold"+++class TestPhpAmqplib:+ _USE = "<?php\nuse PhpAmqpLib\\Message\\AMQPMessage;\n"++ def test_publish_to_an_exchange(self, tmp_path: Path) -> None:+ src = self._USE + "$channel->basic_publish($msg, 'orders', 'order.created');\n"+ c = _one(_extract(tmp_path, "Pub.php", src), "provider")+ assert (c.contract_id, c.meta["kind"], c.meta["routing_key"]) == (+ "topic::orders",+ "exchange",+ "order.created",+ )++ def test_publish_to_the_default_exchange_names_the_queue(self, tmp_path: Path) -> None:+ src = self._USE + "$channel->basic_publish($msg, '', 'jobs');\n"+ c = _one(_extract(tmp_path, "Pub.php", src), "provider")+ assert (c.contract_id, c.meta["kind"]) == ("topic::jobs", "queue")++ def test_consume_and_bind(self, tmp_path: Path) -> None:+ src = (+ self._USE+ + "$channel->queue_bind('audit', 'orders', 'order.*');\n"+ + "$channel->basic_consume('audit', '', false, true, false, false, $cb);\n"+ )+ rows = _extract(tmp_path, "Work.php", src)+ assert {(c.contract_id, c.meta["kind"]) for c in rows} == {+ ("topic::orders", "binding"),+ ("topic::audit", "queue"),+ }++ def test_nothing_without_the_library(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "X.php", "<?php\n$x->basic_publish($m, 'orders');\n") == []class TestNats:@@ -235,3 +291,166 @@ class TestNats:def test_an_unrelated_receiver_is_not_nats(self, tmp_path: Path) -> None:assert _extract(tmp_path, "x.ts", "store.subscribe('state', h);") == []++ def test_bare_sub_is_not_a_nats_receiver(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "x.ts", "sub.subscribe('events.created', h);") == []++ @pytest.mark.parametrize("subject", ["events.*", "events.>"])+ def test_a_wildcard_subscription_is_a_pattern(self, tmp_path: Path, subject: str) -> None:+ c = _one(_extract(tmp_path, "sub.go", f'nc.Subscribe("{subject}", h)\n'), "consumer")+ assert c.meta["pattern"] == "nats"++ def test_a_plain_subject_is_not_a_pattern(self, tmp_path: Path) -> None:+ c = _one(_extract(tmp_path, "sub.go", 'nc.Subscribe("events.created", h)\n'), "consumer")+ assert "pattern" not in c.meta+++class TestKafkaPattern:+ def test_topic_pattern_is_a_regex_subscription(self, tmp_path: Path) -> None:+ src = '@KafkaListener(topicPattern = "orders\\\\..*")\nvoid f() {}'+ c = _one(_extract(tmp_path, "C.java", src), "consumer")+ assert c.meta["pattern"] == "regex"+ assert c.meta["topic"] == "orders\\..*" # the Java escape read as the regex it spells++ def test_a_topics_listener_is_not_a_pattern(self, tmp_path: Path) -> None:+ c = _one(_extract(tmp_path, "C.java", '@KafkaListener(topics = "a.*")'), "consumer")+ assert "pattern" not in c.meta+++class TestBullMq:+ _IMPORT = "import { Queue, Worker } from 'bullmq';\n"++ def test_queue_and_worker(self, tmp_path: Path) -> None:+ src = self._IMPORT + "const q = new Queue('emails');\nnew Worker<Job>('emails', process);\n"+ rows = _extract(tmp_path, "q.ts", src)+ assert {(c.role, c.contract_id, c.meta["kind"]) for c in rows} == {+ ("provider", "topic::emails", "queue"),+ ("consumer", "topic::emails", "queue"),+ }++ def test_a_queue_class_of_another_library_is_not_bullmq(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "q.ts", "const q = new Queue('emails');\n") == []++ def test_nestjs_processor_and_inject_queue(self, tmp_path: Path) -> None:+ src = (+ "import { Processor, InjectQueue } from '@nestjs/bullmq';\n"+ "@Processor('audio')\nclass AudioProcessor {}\n"+ "constructor(@InjectQueue('audio') private q: Queue) {}\n"+ )+ rows = _extract(tmp_path, "audio.ts", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("consumer", "topic::audio"),+ ("provider", "topic::audio"),+ }++ def test_a_flow_names_its_queue(self, tmp_path: Path) -> None:+ src = (+ self._IMPORT+ + "const flow = new FlowProducer();\n"+ + "flow.add({ name: 'j', queueName: 'renders' });\n"+ )+ assert _one(_extract(tmp_path, "f.ts", src), "provider").contract_id == "topic::renders"+++class TestAws:+ def test_sqs_queue_url_names_its_last_segment(self, tmp_path: Path) -> None:+ src = (+ "const URL = 'https://sqs.eu-west-1.amazonaws.com/123456789012/orders';\n"+ "await sqs.send(new SendMessageCommand({ QueueUrl: URL, MessageBody: b }));\n"+ "await sqs.send(new ReceiveMessageCommand({ QueueUrl: `${base}/orders` }));\n"+ )+ rows = _extract(tmp_path, "q.ts", src)+ assert {(c.role, c.contract_id, c.meta["broker"]) for c in rows} == {+ ("provider", "topic::orders", "sqs"),+ ("consumer", "topic::orders", "sqs"),+ }++ def test_a_queue_url_from_the_environment_is_refused(self, tmp_path: Path) -> None:+ src = "new SendMessageCommand({ QueueUrl: process.env.QUEUE_URL, MessageBody: b });\n"+ assert _extract(tmp_path, "q.ts", src) == []++ def test_sns_topic_arn_names_its_last_field(self, tmp_path: Path) -> None:+ src = "new PublishCommand({ TopicArn: 'arn:aws:sns:eu-west-1:123:orders', Message: m });\n"+ c = _one(_extract(tmp_path, "p.ts", src), "provider")+ assert (c.contract_id, c.meta["broker"], c.meta["kind"]) == ("topic::orders", "sns", "topic")++ def test_boto3_keywords(self, tmp_path: Path) -> None:+ src = "sqs.send_message(QueueUrl='https://sqs.x/1/jobs', MessageBody='x')\n"+ assert _one(_extract(tmp_path, "p.py", src), "provider").contract_id == "topic::jobs"++ def test_send_message_without_a_queue_url_is_not_sqs(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "bot.ts", "bot.sendMessage(chatId, 'hello');\n") == []+++class TestRedis:+ _IMPORT = "import Redis from 'ioredis';\n"++ def test_publish_subscribe(self, tmp_path: Path) -> None:+ src = self._IMPORT + "pub.publish('scores', x);\nsub.subscribe('scores');\n"+ rows = _extract(tmp_path, "r.ts", src)+ assert {(c.role, c.contract_id, c.meta["broker"], c.meta["kind"]) for c in rows} == {+ ("provider", "topic::scores", "redis", "channel"),+ ("consumer", "topic::scores", "redis", "channel"),+ }++ def test_psubscribe_is_a_glob_pattern(self, tmp_path: Path) -> None:+ src = self._IMPORT + "sub.psubscribe('scores.*');\n"+ assert _one(_extract(tmp_path, "r.ts", src), "consumer").meta["pattern"] == "glob"++ def test_an_rxjs_subscribe_is_not_a_channel(self, tmp_path: Path) -> None:+ src = self._IMPORT + "obs$.subscribe((v) => log(v));\nstore.subscribe(handler);\n"+ assert _extract(tmp_path, "r.ts", src) == []++ def test_nothing_without_a_redis_client(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "r.ts", "emitter.publish('scores', x);\n") == []++ def test_a_redis_client_named_client_is_redis_not_nats(self, tmp_path: Path) -> None:+ src = "import { createClient } from 'redis';\nclient.publish('scores', x);\n"+ assert _one(_extract(tmp_path, "r.ts", src), "provider").meta["broker"] == "redis"++ def test_laravel_facade(self, tmp_path: Path) -> None:+ src = "<?php\nRedis::publish('scores', $x);\nRedis::subscribe(['scores', 'ranks'], $cb);\n"+ rows = _extract(tmp_path, "R.php", src)+ assert sorted((c.role, c.contract_id) for c in rows) == [+ ("consumer", "topic::ranks"),+ ("consumer", "topic::scores"),+ ("provider", "topic::scores"),+ ]+++class TestNestMicroservices:+ _IMPORT = "import { EventPattern, MessagePattern, ClientProxy } from '@nestjs/microservices';\n"++ def test_handlers(self, tmp_path: Path) -> None:+ src = self._IMPORT + "@EventPattern('ticket.sold')\nf() {}\n@MessagePattern('sum')\ng() {}\n"+ rows = _extract(tmp_path, "c.ts", src)+ assert {(c.role, c.contract_id, c.meta["broker"]) for c in rows} == {+ ("consumer", "topic::ticket.sold", "nestjs"),+ ("consumer", "topic::sum", "nestjs"),+ }++ def test_a_client_proxy_emits_under_any_name(self, tmp_path: Path) -> None:+ src = (+ self._IMPORT+ + "constructor(@Inject('BILLING') private readonly billing: ClientProxy) {}\n"+ + "this.billing.emit('ticket.sold', t);\n"+ + "res.send('ok');\n"+ )+ c = _one(_extract(tmp_path, "s.ts", src), "provider")+ assert (c.contract_id, c.symbol_name) == (+ "topic::ticket.sold",+ "ClientProxy.emit('ticket.sold')",+ )++ def test_an_object_pattern_is_named_as_nest_serializes_it(self, tmp_path: Path) -> None:+ src = (+ self._IMPORT+ + "@MessagePattern({ role: 'math', cmd: 'sum' })\nf() {}\n"+ + "client: ClientProxy;\nthis.client.send({ cmd: 'sum', role: 'math' }, [1, 2]);\n"+ )+ rows = _extract(tmp_path, "m.ts", src)+ assert {c.contract_id for c in rows} == {'topic::{"cmd":"sum","role":"math"}'}+ assert {c.role for c in rows} == {"consumer", "provider"}++ def test_handlers_need_the_microservices_import(self, tmp_path: Path) -> None:+ assert _extract(tmp_path, "c.ts", "@EventPattern('x')\nf() {}\n") == []diff --git a/tests/unit/workspace/test_topic_matching.py b/tests/unit/workspace/test_topic_matching.pyindex a7404e827..bab3b9cf5 100644--- a/tests/unit/workspace/test_topic_matching.py+++ b/tests/unit/workspace/test_topic_matching.py@@ -7,7 +7,7 @@ import pytestfrom repowise.core.workspace.contracts import Contract, ContractLinkfrom repowise.core.workspace.diagnostics import build_diagnosticsfrom repowise.core.workspace.matching import match_contracts-from repowise.core.workspace.matching.topic import routing_matches+from repowise.core.workspace.matching.topic import pattern_matches, routing_matchesdef _topic(repo: str, role: str, name: str, file: str, **meta) -> Contract:@@ -178,3 +178,121 @@ class TestDiagnosticsReadTheConsumerId:assert ContractLink.from_dict(link.to_dict()).consumer_contract_id == "topic::audit"plain = ContractLink.from_dict({**link.to_dict(), "consumer_contract_id": None})assert "consumer_contract_id" not in plain.to_dict()+++class TestPatternMatches:+ @pytest.mark.parametrize(+ ("syntax", "pattern", "name", "expected"),+ [+ ("nats", "orders.*", "orders.created", True),+ ("nats", "orders.*", "orders.created.v2", False),+ ("nats", "orders.>", "orders.created.v2", True),+ ("nats", "orders.>", "orders", False),+ ("nats", "*.created", "orders.created", True),+ ("glob", "orders.*", "orders.created.v2", True),+ ("glob", "orders.?", "orders.a", True),+ ("glob", "Orders.*", "orders.a", True),+ ("regex", "orders\\..*", "orders.created", True),+ ("regex", "orders\\..*", "ordersXcreated", False),+ ("regex", "[unclosed", "orders", False),+ ("unknown", "*", "orders", False),+ ],+ )+ def test_semantics(self, syntax: str, pattern: str, name: str, expected: bool) -> None:+ assert pattern_matches(syntax, pattern, name) is expected+++class TestPatternSubscriptions:+ def _subscriber(self, pattern: str, syntax: str = "nats") -> Contract:+ return _topic("audit", "consumer", pattern, "sub.go", kind="subject", pattern=syntax)++ def test_a_pattern_links_every_publisher_it_matches(self) -> None:+ contracts = [+ _topic("orders", "provider", "orders.created", "a.go", kind="subject"),+ _topic("orders", "provider", "orders.deleted", "b.go", kind="subject"),+ _topic("billing", "provider", "invoices.created", "c.go", kind="subject"),+ self._subscriber("orders.*"),+ ]+ links = match_contracts(contracts)+ # Each link names the topic it carries; the subscription is the consumer's id.+ assert sorted((lk.contract_id, lk.provider_file) for lk in links) == [+ ("topic::orders.created", "a.go"),+ ("topic::orders.deleted", "b.go"),+ ]+ assert {lk.consumer_contract_id for lk in links} == {"topic::orders.*"}++ def test_two_topics_from_one_file_are_two_links(self) -> None:+ contracts = [+ _topic("orders", "provider", "orders.created", "pub.go", kind="subject"),+ _topic("orders", "provider", "orders.deleted", "pub.go", kind="subject"),+ self._subscriber("orders.*"),+ ]+ assert len(match_contracts(contracts)) == 2++ @pytest.mark.parametrize(("pattern", "syntax"), [(">", "nats"), ("*", "glob"), (".*", "regex")])+ def test_a_pattern_of_wildcards_alone_links_nothing(self, pattern: str, syntax: str) -> None:+ contracts = [+ _topic("orders", "provider", "orders.created", "a.go", kind="subject"),+ self._subscriber(pattern, syntax),+ ]+ assert match_contracts(contracts) == []++ def test_a_pattern_reaches_only_its_own_broker(self) -> None:+ kafka = _topic("orders", "provider", "orders.created", "a.ts", kind="topic")+ kafka.meta["broker"] = "kafka"+ nats = self._subscriber("orders.*")+ nats.meta["broker"] = "nats"+ assert match_contracts([kafka, nats]) == []+++ def test_a_pattern_in_its_own_service_is_not_linked(self) -> None:+ contracts = [+ _topic("audit", "provider", "orders.created", "a.go", kind="subject"),+ self._subscriber("orders.*"),+ ]+ assert match_contracts(contracts) == []+++def _on(broker: str, role: str, repo: str, name: str = "emails", **meta) -> Contract:+ c = _topic(repo, role, name, f"{repo}.src", kind="queue", **meta)+ c.meta["broker"] = broker+ return c+++class TestTransports:+ @pytest.mark.parametrize(+ ("provider", "consumer", "linked"),+ [+ ("rabbitmq", "rabbitmq", True),+ ("kafka", "rabbitmq", False),+ ("sns", "sqs", False),+ ("laravel", "rabbitmq", True),+ ("rabbitmq", "laravel", True),+ ("nestjs", "kafka", True),+ ("laravel", "bullmq", False),+ ("redis", "bullmq", False),+ ("bullmq", "bullmq", True),+ ],+ )+ def test_which_brokers_meet(self, provider: str, consumer: str, linked: bool) -> None:+ links = match_contracts([_on(provider, "provider", "a"), _on(consumer, "consumer", "b")])+ assert bool(links) is linked++ def test_two_laravel_apps_meet_only_on_one_job_class(self) -> None:+ same = [+ _on("laravel", "provider", "web", job="App\\Jobs\\Send"),+ _on("laravel", "consumer", "worker", job="App\\Jobs\\Send"),+ ]+ other = [+ _on("laravel", "provider", "web", job="App\\Jobs\\Send"),+ _on("laravel", "consumer", "worker", job="App\\Jobs\\Other"),+ ]+ assert len(match_contracts(same)) == 1+ assert match_contracts(other) == []++ def test_a_name_that_only_looks_like_a_pattern_is_exact(self) -> None:+ contracts = [+ _topic("orders", "provider", "orders.created", "a.go", kind="subject"),+ _topic("audit", "consumer", "orders.*", "sub.go", kind="subject"),+ ]+ assert match_contracts(contracts) == []