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
refactor(core): move the TS/JS perf marker hooks into their own module (#2599)
Raghav Chamadiyaebb3a77877db
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.pyindex 4e83cf66a..33e216aff 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py@@ -1,9 +1,7 @@"""TypeScript / JavaScript ``PerfDialect``.-Extracted verbatim from the original ``_ts_sink_kind`` (``io_boundaries.py``)-and the TS branches of the walker (``_has_async_modifier`` and the-``_TS_STRING_KINDS`` string-concat predicate). One instance serves both-``typescript`` / ``tsx`` and ``javascript`` / ``jsx`` (identical call grammar).+One instance serves ``typescript`` / ``tsx`` and ``javascript`` / ``jsx``, which+share a call grammar."""from __future__ import annotations@@ -12,8 +10,8 @@ import refrom typing import TYPE_CHECKING, ClassVarfrom ..loop_facts import BatchForm-from .base import BasePerfDialectfrom .python import HTTP_VERBS+from .ts_js_markers import TsJsMarkerHooks, first_named_child, identifier_nameif TYPE_CHECKING:from tree_sitter import Node@@ -71,27 +69,117 @@ TS_SINK_METHODS: frozenset[str] = (_TS_STRING_KINDS: frozenset[str] = frozenset({"string", "template_string"})_TS_AUG_ASSIGN_KINDS: frozenset[str] = frozenset({"augmented_assignment_expression"})-# Heavy client/connection classes that should be hoisted, not re-``new``-ed each-# iteration. Distinctive names only (``Client`` / ``Pool`` collide with worker-# pools and unrelated SDKs, so they are deliberately excluded for precision).-_TS_RESOURCE_CTORS: frozenset[str] = frozenset(- {- "PrismaClient",- "MongoClient",- "Sequelize",- "DataSource",- "Redis",- "IORedis",- }+# A function/lambda scope: the boundary for the reaching-assignment walk and the+# "not a loop exit" skip for break/return/throw inside a nested closure (a+# callback's own ``return`` doesn't exit the loop).+_FN_KINDS: frozenset[str] = frozenset(+ {"function_declaration", "function_expression", "arrow_function", "method_definition"})+# The prisma point calls a loop can batch, and the bulk call each becomes.+_PRISMA_BULK_FORMS: dict[str, str] = {+ "findUnique": "findMany",+ "findFirst": "findMany",+ "delete": "deleteMany",+}+# A concurrency limiter, named by convention (``limit`` / ``this.sem``), or by the# method async-mutex (``runExclusive``) and bottleneck (``schedule``) run work through._LIMITER_NAME_RE = re.compile(r"(?i)(sem|semaphore|limiter|limit|mutex)$")_LIMITER_METHODS: frozenset[str] = frozenset({"runExclusive", "schedule"})+_ASSIGNMENT_FIELDS: dict[str, tuple[str, str]] = {+ "variable_declarator": ("name", "value"),+ "assignment_expression": ("left", "right"),+}+++def _enclosing_scope(loop: Node) -> Node:+ """The function around *loop*, else the loop's own parent."""+ scope = loop.parent+ while scope is not None and scope.type not in _FN_KINDS:+ scope = scope.parent+ return scope or loop.parent or loop+++def _unwrap(node: Node) -> Node:+ """Peel await / parens: ``(await x()).y`` needs both hops stripped to+ reach the call ``x()`` itself."""+ cur = node+ while cur.type in ("await_expression", "parenthesized_expression"):+ inner = first_named_child(cur)+ if inner is None:+ return cur+ cur = inner+ return cur+++def _callee_object(call: Node) -> Node | None:+ """``x`` in ``x.method(...)``."""+ fn = call.child_by_field_name("function")+ return fn.child_by_field_name("object") if fn is not None else None+++def _pair_key_is(node: Node, key: bytes) -> bool:+ return node.type == "pair" and (node.child_by_field_name("key") or node).text == key-class TsJsPerfDialect(BasePerfDialect):++def _option_value(call: Node, key: bytes) -> Node | None:+ """The value under *key* in the call's leading ``{ ... }`` options argument."""+ args = call.child_by_field_name("arguments")+ options = first_named_child(args) if args is not None else None+ if options is None or options.type != "object":+ return None+ return next(+ (pair.child_by_field_name("value") for pair in options.children if _pair_key_is(pair, key)),+ None,+ )+++def _is_data_projection(node: Node) -> bool:+ """``response.data``: the body of whatever *response* resolves to."""+ prop = node.child_by_field_name("property")+ return node.type == "member_expression" and prop is not None and prop.text == b"data"+++def _slice_is_bounded(call: Node) -> bool:+ """``.slice(a, N)`` where N is an integer literal or an ALL_CAPS named+ constant — a constant-width read, not the whole collection."""+ args = call.child_by_field_name("arguments")+ named = [c for c in args.children if c.is_named] if args is not None else []+ if len(named) != 2:+ return False+ end = named[1]+ if end.type == "number":+ return True+ name = identifier_name(end)+ return name is not None and name.isupper()+++def _sole_where_pair(call: Node) -> tuple[Node, Node] | None:+ """``(key, value)`` of a ``where`` object that filters on exactly one field."""+ where = _option_value(call, b"where")+ if where is None or where.type != "object":+ return None+ pairs = [c for c in where.children if c.type == "pair"]+ if len(pairs) != 1:+ return None+ key, value = pairs[0].child_by_field_name("key"), pairs[0].child_by_field_name("value")+ return (key, value) if key is not None and value is not None else None+++def _assigned_value(node: Node, name: bytes) -> Node | None:+ """The value *node* binds to the bare identifier *name*, if it is such a binding."""+ fields = _ASSIGNMENT_FIELDS.get(node.type)+ if fields is None:+ return None+ target, value = (node.child_by_field_name(field) for field in fields)+ if target is None or target.type != "identifier" or target.text != name:+ return None+ return value+++class TsJsPerfDialect(TsJsMarkerHooks):language = "typescript"markers = frozenset({@@ -130,13 +218,9 @@ class TsJsPerfDialect(BasePerfDialect):return Nonedef is_constant_loop(self, node: Node) -> bool:- """True if a ``for...of`` / ``for...in`` iterates a compile-time-constant- bound: an inline **array literal** (``for (const p of ["/a", "/b"])`` —- the author enumerated a fixed set, so there is no data-dependent N+1- blow-up) or an **ALL_CAPS** named constant (``for (const f of- DREAMS_FILENAMES)``). Mirrors the Python dialect's literal-collection- skip. C-style ``for (;;)`` / ``while`` / ``do`` are cursors — never- constant here (they are pagination / polling)."""+ """True if a ``for...of`` / ``for...in`` walks a fixed set: an inline array+ literal or an ALL_CAPS named constant, so no data-dependent N+1. C-style+ ``for (;;)`` / ``while`` / ``do`` are cursors and never constant."""if node.type not in self._ITERATION_LOOP_KINDS:return Falseright = node.child_by_field_name("right")@@ -144,11 +228,8 @@ class TsJsPerfDialect(BasePerfDialect):return Falseif right.type == "array":return True- if right.type == "identifier" and right.text is not None:- name = right.text.decode("utf-8", "replace")- if name.isupper() and len(name) > 1:- return True- return False+ name = identifier_name(right)+ return name is not None and name.isupper() and len(name) > 1def sink_kind(self,@@ -164,177 +245,19 @@ class TsJsPerfDialect(BasePerfDialect):return "network"root_kind = io_names.get(root)if root_kind is not None:- # A call on an imported I/O package (``axios.get`` / ``db.query``) is- # a sink only when it is a known round-trip verb or is awaited — NOT- # a sync helper (``axios.isCancel`` / ``axios.create``) or a query- # builder (``.where()`` / ``.select()``), which over-fired before- # this gate.+ # A call on an imported I/O package is a sink only as a round-trip+ # verb or when awaited, never a sync helper or a query builder.if method in TS_SINK_METHODS or awaited:return root_kindreturn None- # Distinctive prisma-client verbs, but only as a MEMBER call. A prisma- # query is always reached through the client (``prisma.user.aggregate``),- # so a bare ``aggregate(xs)`` / ``groupBy(xs)`` / ``upsert(x)`` is an- # ordinary local function and was being reported as a database round- # trip -- an N+1 finding on pure arithmetic, in code with no database.+ # Prisma verbs count only as member calls: a query goes through the client+ # (``prisma.user.aggregate``), so a bare ``aggregate(xs)`` is a local function.if is_attribute and method in PRISMA_METHODS:return "db"if method in TS_FS_METHODS: # distinctive sync-fs verbsreturn "filesystem"return None- def loop_call_marker(- self, root: str, method: str, node: Node, list_names: frozenset[str]- ) -> str | None:- # ``arr.includes(x)`` where ``arr`` is a known array -> O(n) membership.- if method == "includes" and root in list_names:- return "membership_test_against_list_in_loop"- # ``JSON.parse(JSON.stringify(x))`` deep-clone in a loop is the canonical- # waste (use ``structuredClone``). Gate: a BARE ``JSON.parse`` /- # ``JSON.stringify`` per iteration was 0% precision (30/30 were- # format-conversion loops serializing a DISTINCT payload each pass —- # necessary work, not waste), so the marker is restricted to the- # deep-clone idiom, which is unconditionally hoistable.- if root == "JSON" and method == "parse" and self._arg_is_json_stringify(node):- return "json_parse_in_loop"- return None-- @staticmethod- def _arg_is_json_stringify(node: Node) -> bool:- """True if the call's first argument is itself a ``JSON.stringify(...)``- call — the ``JSON.parse(JSON.stringify(x))`` deep-clone idiom."""- args = node.child_by_field_name("arguments")- if args is None:- return False- first = next((c for c in args.children if c.is_named), None)- if first is None or first.type != "call_expression":- return False- fn = first.child_by_field_name("function")- return (- fn is not None- and fn.text is not None- and fn.text.decode("utf-8", "replace") == "JSON.stringify"- )-- def bare_call_marker(self, root: str, method: str, node: Node) -> str | None:- # ``arr.reduce((acc, x) => [...acc, x], [])`` rebuilds the accumulator- # every step -> O(n^2). The ``.reduce`` IS the loop, so this fires at any- # depth. Precision-first: only when the callback spreads its OWN- # accumulator param into a fresh array / object literal.- if method != "reduce":- return None- args = node.child_by_field_name("arguments")- if args is None:- return None- cb = next((c for c in args.children if c.is_named), None)- if cb is None or cb.type not in ("arrow_function", "function", "function_expression"):- return None- acc = self._first_param_name(cb)- body = cb.child_by_field_name("body")- if acc is None or body is None:- return None- return "array_spread_in_reduce" if self._spreads_name_in_collection(body, acc) else None-- @staticmethod- def _first_param_name(cb: Node) -> str | None:- """First parameter identifier of an arrow/function (the reduce accumulator)."""- params = cb.child_by_field_name("parameters")- if params is not None:- for c in params.children:- ident = c if c.type == "identifier" else c.child_by_field_name("pattern")- if ident is not None and ident.type == "identifier" and ident.text is not None:- return ident.text.decode("utf-8", "replace")- return None- # ``x => …`` single unparenthesized param.- first = next((c for c in cb.children if c.is_named), None)- if first is not None and first.type == "identifier" and first.text is not None:- return first.text.decode("utf-8", "replace")- return None-- @staticmethod- def _params_contain(fn: Node, name: str) -> bool:- """True if any parameter of ``fn`` binds ``name`` (a shadow of an outer- accumulator). Handles both parenthesized parameter lists and the single- unparenthesized ``x => …`` form."""- params = fn.child_by_field_name("parameters")- if params is not None:- for c in params.children:- ident = c if c.type == "identifier" else c.child_by_field_name("pattern")- if (- ident is not None- and ident.type == "identifier"- and ident.text is not None- and ident.text.decode("utf-8", "replace") == name- ):- return True- return False- first = next((c for c in fn.children if c.is_named), None)- return (- first is not None- and first.type == "identifier"- and first.text is not None- and first.text.decode("utf-8", "replace") == name- )-- _FN_LITERAL_KINDS: frozenset[str] = frozenset(- {"arrow_function", "function", "function_expression"}- )-- @staticmethod- def _spreads_name_in_collection(body: Node, name: str) -> bool:- """True if *body* spreads ``name`` into an array / object literal- (``[...name, x]`` / ``{...name}``) — the O(n^2) accumulator rebuild.-- Stops at a nested arrow/function that re-binds ``name`` as its own- parameter: a spread of ``name`` inside such a scope targets THAT binding- (e.g. an inner ``reduce`` with its own ``acc``), not the outer- accumulator, so it must not be attributed to the outer reduce.- """- stack: list[Node] = [body]- while stack:- n = stack.pop()- if (- n != body- and n.type in TsJsPerfDialect._FN_LITERAL_KINDS- and TsJsPerfDialect._params_contain(n, name)- ):- continue- if (- n.type == "spread_element"- and n.parent is not None- and n.parent.type- in (- "array",- "object",- )- ):- arg = next((c for c in n.children if c.is_named), None)- if (- arg is not None- and arg.type == "identifier"- and arg.text is not None- and arg.text.decode("utf-8", "replace") == name- ):- return True- stack.extend(n.children)- return False-- def loop_stmt_marker(self, node: Node, list_names: frozenset[str]) -> str | None:- # ``new PrismaClient(...)`` etc. is a ``new_expression`` (not a- # ``call_expression``), so it arrives here rather than via the call path.- if node.type != "new_expression":- return None- ctor = self._constructor_name(node)- return "resource_construction_in_loop" if ctor in _TS_RESOURCE_CTORS else None-- @staticmethod- def _constructor_name(node: Node) -> str | None:- """Rightmost identifier of a ``new X()`` / ``new pkg.X()`` constructor."""- ctor = node.child_by_field_name("constructor")- if ctor is None or ctor.text is None:- return None- return ctor.text.decode("utf-8", "replace").split(".")[-1]-# -- chunked-loop detection ------------------------------------------------def is_chunked_loop(self, node: Node) -> bool:@@ -354,13 +277,6 @@ class TsJsPerfDialect(BasePerfDialect):# -- promotion facts (perf/loop_facts.py) ----------------------------------- #: Filesystem listing calls whose result count scales with data on disk.- #: A function/lambda scope: the boundary for the reaching-assignment walk- #: (below it) and the "not a loop exit" skip for break/return/throw inside- #: a nested closure (a callback's own ``return`` doesn't exit the loop).- _FN_KINDS: frozenset[str] = frozenset(- {"function_declaration", "function_expression", "arrow_function", "method_definition"}- )sequence_appends = frozenset({"push", "unshift", "splice"})await_kind = "await_expression"key_hops: ClassVar[dict[str, str]] = {@@ -383,19 +299,6 @@ class TsJsPerfDialect(BasePerfDialect):{"break_statement", "continue_statement", "return_statement", "throw_statement"})scope_kinds = _FN_KINDS- _PRISMA_BATCH_METHODS: frozenset[str] = frozenset({"findUnique", "findFirst", "delete"})-- @staticmethod- def _unwrap(node: Node) -> Node:- """Peel await / parens: ``(await x()).y`` needs both hops stripped to- reach the call ``x()`` itself."""- cur = node- while cur.type in ("await_expression", "parenthesized_expression"):- inner = next((c for c in cur.children if c.is_named), None)- if inner is None:- return cur- cur = inner- return curdef _magnitude_of_expr(self, expr: Node | None, probe: SinkProbe, depth: int = 0@@ -403,67 +306,40 @@ class TsJsPerfDialect(BasePerfDialect):"""Whether *expr* is provably a growing / bounded source, else None."""if expr is None or depth > 4:return None- node = self._unwrap(expr)+ node = _unwrap(expr)+ if node.type == "call_expression":+ return self._call_magnitude(node, probe, depth)if node.type == "binary_expression" and any(c.type in ("||", "??") for c in node.children):# ``(await q).data ?? []``: the fallback is empty, the read is not.- return self._grows(self._magnitude_of_expr(node.child_by_field_name("left"), probe, depth + 1))- if node.type == "call_expression":- method = self.callee_method_name(node) or ""- if method == "slice":- return "bounded" if self._slice_is_bounded(node) else None- if probe(node) in ("db", "network"):- # A read capped in the query (``take: n``) is as large as its cap.- capped = any(- n.type == "pair" and (n.child_by_field_name("key") or n).text == b"take"- for n in self._walk(node)- )- return None if capped else "grows_with_data"- if method == "json":- # ``fetch(url).json()`` / ``(await sink()).json()`` — a- # projection of whatever the receiver resolves to.- fn = node.child_by_field_name("function")- obj = fn.child_by_field_name("object") if fn is not None else None- return self._grows(self._magnitude_of_expr(obj, probe, depth + 1))+ inner = node.child_by_field_name("left")+ elif _is_data_projection(node):+ inner = node.child_by_field_name("object")+ else:return None- if node.type == "member_expression":- prop = node.child_by_field_name("property")- if prop is not None and prop.text == b"data":- inner = self._magnitude_of_expr(node.child_by_field_name("object"), probe, depth + 1)- return self._grows(inner)+ return self._grows(self._magnitude_of_expr(inner, probe, depth + 1))++ def _call_magnitude(self, call: Node, probe: SinkProbe, depth: int) -> LoopMagnitude | None:+ method = self.callee_method_name(call) or ""+ if method == "slice":+ return "bounded" if _slice_is_bounded(call) else None+ if probe(call) in ("db", "network"):+ # A read capped in the query (``take: n``) is as large as its cap.+ capped = any(_pair_key_is(n, b"take") for n in self._walk(call))+ return None if capped else "grows_with_data"+ if method == "json":+ # ``fetch(url).json()`` / ``(await sink()).json()`` — a+ # projection of whatever the receiver resolves to.+ return self._grows(self._magnitude_of_expr(_callee_object(call), probe, depth + 1))return None- @staticmethod- def _slice_is_bounded(node: Node) -> bool:- """``.slice(a, N)`` where N is an integer literal or an ALL_CAPS named- constant — a constant-width read, not the whole collection."""- args = node.child_by_field_name("arguments")- named = [c for c in args.children if c.is_named] if args is not None else []- if len(named) != 2:- return False- end = named[1]- if end.type == "number":- return True- return end.type == "identifier" and bool(end.text) and end.text.decode(- "utf-8", "replace"- ).isupper()-def _reaching_assignment(self, loop: Node, name: bytes) -> Node | None:"""The value of the last ``name = ...`` before *loop* in its function."""- scope = loop.parent- while scope is not None and scope.type not in self._FN_KINDS:- scope = scope.parentlast: tuple[int, Node] | None = None- for node in self._walk(scope or loop.parent or loop, prune=self._FN_KINDS):+ for node in self._walk(_enclosing_scope(loop), prune=_FN_KINDS):if node.end_byte > loop.start_byte:continue- if node.type == "variable_declarator":- target, value = node.child_by_field_name("name"), node.child_by_field_name("value")- elif node.type == "assignment_expression":- target, value = node.child_by_field_name("left"), node.child_by_field_name("right")- else:- continue- named = target is not None and target.type == "identifier" and target.text == name- if named and value is not None and (last is None or node.start_byte > last[0]):+ value = _assigned_value(node, name)+ if value is not None and (last is None or node.start_byte > last[0]):last = (node.start_byte, value)return last[1] if last is not None else None@@ -472,7 +348,7 @@ class TsJsPerfDialect(BasePerfDialect):return Noneright = loop.child_by_field_name("right")magnitude = self._magnitude_of_expr(right, probe)- if magnitude is None and right is not None and right.type == "identifier" and right.text:+ if magnitude is None and right is not None and identifier_name(right):return self._magnitude_of_expr(self._reaching_assignment(loop, right.text), probe)return magnitude@@ -530,87 +406,68 @@ class TsJsPerfDialect(BasePerfDialect):def batch_form(self, sink: Node, loop: Node, probe: SinkProbe) -> BatchForm | None:"""Prisma ``m.findUnique/findFirst/delete({ where: { f: key } })`` -> its bulk form."""- target = loop.child_by_field_name("left")- fn = sink.child_by_field_name("function")- if (- not self.is_iteration_loop(loop)- or target is None- or target.type != "identifier"- or fn is None- or fn.type != "member_expression"- ):- return None- receiver, method = fn.child_by_field_name("object"), self.callee_method_name(sink)- if receiver is None or method not in self._PRISMA_BATCH_METHODS:+ element = self._loop_element(loop)+ point_call = self._prisma_point_call(sink)+ if element is None or point_call is None:return None+ receiver, method = point_callbody = self.loop_body(loop) or loop- iterable = self.loop_iterable_name(loop)- for node in self._walk(body):- if (- node.type == "call_expression"- and self.callee_root_name(node) == iterable- and self.callee_method_name(node) in self.sequence_appends- ):- return None # a worklist: its keys are not known before the loop- refs = [n for n in self._walk(sink) if n.type == "identifier" and n.text == target.text]- field = self._where_key(sink, refs[0]) if len(refs) == 1 else None+ if self._appends_to_iterable(loop, body):+ return None # a worklist: its keys are not known before the loop+ field = self._where_key(sink, element)if field is None or self._reads_loop_local(sink, body):return Nonetext = (receiver.text or b"").decode()- only_io = self._only_io_in_body(sink, body, probe)- if method == "delete":- # Batched, a delete also removes rows a skipped iteration would have left.- return BatchForm(- f"{text}.deleteMany({{ where: {{ {field}: {{ in: keys }} }} }})",- only_io and self._unconditional(sink, body),- )return BatchForm(- f"{text}.findMany({{ where: {{ {field}: {{ in: keys }} }} }})",- only_io and method == "findUnique" and not self._builds_in_order(body),+ f"{text}.{_PRISMA_BULK_FORMS[method]}({{ where: {{ {field}: {{ in: keys }} }} }})",+ self._batch_equivalent(sink, body, probe),)- def _where_key(self, sink: Node, ref: Node) -> str | None:- """The field of a one-field ``where`` whose value is the loop element *ref*."""- args = sink.child_by_field_name("arguments")- options = next((c for c in args.children if c.is_named), None) if args else None- if options is None or options.type != "object":+ def _loop_element(self, loop: Node) -> Node | None:+ """The identifier a ``for...of`` / ``for...in`` binds each element to."""+ target = loop.child_by_field_name("left")+ if not self.is_iteration_loop(loop) or identifier_name(target) is None:return None- where = next(- (- pair.child_by_field_name("value")- for pair in options.children- if pair.type == "pair" and (pair.child_by_field_name("key") or pair).text == b"where"- ),- None,- )- pairs = [c for c in where.children if c.type == "pair"] if where is not None else []- if where is None or where.type != "object" or len(pairs) != 1:+ return target++ def _prisma_point_call(self, sink: Node) -> tuple[Node, str] | None:+ """``(receiver, method)`` of a ``m.findUnique/findFirst/delete(...)`` member call."""+ fn = sink.child_by_field_name("function")+ if fn is None or fn.type != "member_expression":return None- key, value = pairs[0].child_by_field_name("key"), pairs[0].child_by_field_name("value")- if key is None or value is None or not self._is_key_of(value, ref):+ receiver, method = fn.child_by_field_name("object"), self.callee_method_name(sink)+ if receiver is None or method not in _PRISMA_BULK_FORMS:+ return None+ return receiver, method++ def _appends_to_iterable(self, loop: Node, body: Node) -> bool:+ """The body pushes onto the collection the loop walks."""+ iterable = self.loop_iterable_name(loop)+ return any(+ node.type == "call_expression"+ and self.callee_root_name(node) == iterable+ and self.callee_method_name(node) in self.sequence_appends+ for node in self._walk(body)+ )++ def _where_key(self, sink: Node, element: Node) -> str | None:+ """The field of a one-field ``where`` whose value is the loop *element*,+ when the sink names that element exactly once."""+ refs = [n for n in self._walk(sink) if n.type == "identifier" and n.text == element.text]+ pair = _sole_where_pair(sink)+ if len(refs) != 1 or pair is None or not self._is_key_of(pair[1], refs[0]):return None- return (key.text or b"").decode() or None-- def list_bound_names(self, root: Node) -> frozenset[str]:- """Names bound to an array literal (``const arr = [...]``)."""- names: set[str] = set()- stack: list[Node] = [root]- while stack:- n = stack.pop()- if n.type == "variable_declarator":- name = n.child_by_field_name("name")- value = n.child_by_field_name("value")- if (- name is not None- and name.type == "identifier"- and name.text is not None- and value is not None- and value.type == "array"- ):- names.add(name.text.decode("utf-8", "replace"))- for c in n.children:- stack.append(c)- return frozenset(names)+ return (pair[0].text or b"").decode() or None++ def _batch_equivalent(self, sink: Node, body: Node, probe: SinkProbe) -> bool:+ """Whether the bulk call does exactly what the loop's per-row calls did."""+ if not self._only_io_in_body(sink, body, probe):+ return False+ method = self.callee_method_name(sink)+ if method == "delete":+ # Batched, a delete also removes rows a skipped iteration would have left.+ return self._unconditional(sink, body)+ return method == "findUnique" and not self._builds_in_order(body)DIALECT = TsJsPerfDialect()diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.pynew file mode 100644index 000000000..7e19742e9--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py@@ -0,0 +1,161 @@+"""The TS/JS anti-pattern marker hooks: list membership, deep-clone, spread-in-reduce,+and client construction inside a loop."""++from __future__ import annotations++from collections.abc import Iterator+from typing import TYPE_CHECKING++from .base import BasePerfDialect++if TYPE_CHECKING:+ from tree_sitter import Node++# Heavy client/connection classes that should be hoisted, not re-``new``-ed each+# iteration. Distinctive names only (``Client`` / ``Pool`` collide with worker+# pools and unrelated SDKs, so they are deliberately excluded for precision).+_TS_RESOURCE_CTORS: frozenset[str] = frozenset(+ {+ "PrismaClient",+ "MongoClient",+ "Sequelize",+ "DataSource",+ "Redis",+ "IORedis",+ }+)++_FN_LITERAL_KINDS: frozenset[str] = frozenset({"arrow_function", "function", "function_expression"})+++# -- TS/JS syntax helpers (shared with ts_js.py) -------------------------------+++def node_text(node: Node | None) -> str | None:+ """*node*'s source text, or None when there is no node or no text."""+ if node is None or node.text is None:+ return None+ return node.text.decode("utf-8", "replace")+++def identifier_name(node: Node | None) -> str | None:+ """The name *node* spells when it is a bare identifier."""+ return node_text(node) if node is not None and node.type == "identifier" else None+++def first_named_child(node: Node) -> Node | None:+ return next((c for c in node.children if c.is_named), None)+++# -- marker predicates ---------------------------------------------------------+++def _param_names(fn: Node) -> Iterator[str]:+ """Names of an arrow/function's identifier parameters, in order.++ A destructured parameter binds no single name and is skipped.+ """+ params = fn.child_by_field_name("parameters")+ if params is None:+ # ``x => …`` single unparenthesized param.+ candidates = [first_named_child(fn)]+ else:+ candidates = [+ c if c.type == "identifier" else c.child_by_field_name("pattern")+ for c in params.children+ ]+ for candidate in candidates:+ name = identifier_name(candidate)+ if name is not None:+ yield name+++def _is_json_deep_clone(call: Node) -> bool:+ """True if the call's first argument is itself a ``JSON.stringify(...)`` call."""+ args = call.child_by_field_name("arguments")+ first = first_named_child(args) if args is not None else None+ if first is None or first.type != "call_expression":+ return False+ return node_text(first.child_by_field_name("function")) == "JSON.stringify"+++def _reduce_spreads_accumulator(call: Node) -> bool:+ """A ``reduce`` whose callback spreads its OWN accumulator param into a fresh+ array / object literal."""+ args = call.child_by_field_name("arguments")+ cb = first_named_child(args) if args is not None else None+ if cb is None or cb.type not in _FN_LITERAL_KINDS:+ return False+ acc = next(_param_names(cb), None)+ body = cb.child_by_field_name("body")+ return acc is not None and body is not None and _spreads_name_in_collection(body, acc)+++def _spreads_name_in_collection(body: Node, name: str) -> bool:+ """True if *body* spreads ``name`` into an array / object literal.++ A nested arrow/function that re-binds ``name`` as a parameter (an inner+ ``reduce`` with its own ``acc``) is skipped: its spreads target that binding.+ """+ stack: list[Node] = [body]+ while stack:+ n = stack.pop()+ if n != body and n.type in _FN_LITERAL_KINDS and name in _param_names(n):+ continue+ if _is_collection_spread_of(n, name):+ return True+ stack.extend(n.children)+ return False+++def _is_collection_spread_of(node: Node, name: str) -> bool:+ """``[...name]`` / ``{...name}``."""+ parent = node.parent+ if node.type != "spread_element" or parent is None or parent.type not in ("array", "object"):+ return False+ return identifier_name(first_named_child(node)) == name+++class TsJsMarkerHooks(BasePerfDialect):+ def loop_call_marker(+ self, root: str, method: str, node: Node, list_names: frozenset[str]+ ) -> str | None:+ # ``arr.includes(x)`` where ``arr`` is a known array -> O(n) membership.+ if method == "includes" and root in list_names:+ return "membership_test_against_list_in_loop"+ # Only the ``JSON.parse(JSON.stringify(x))`` deep clone: a bare parse or+ # stringify per iteration converts a distinct payload each pass, which is+ # necessary work.+ if root == "JSON" and method == "parse" and _is_json_deep_clone(node):+ return "json_parse_in_loop"+ return None++ def bare_call_marker(self, root: str, method: str, node: Node) -> str | None:+ # ``arr.reduce((acc, x) => [...acc, x], [])`` rebuilds the accumulator every+ # step (O(n^2)). The ``.reduce`` is the loop, so this fires at any depth.+ if method == "reduce" and _reduce_spreads_accumulator(node):+ return "array_spread_in_reduce"+ return None++ def loop_stmt_marker(self, node: Node, list_names: frozenset[str]) -> str | None:+ # ``new PrismaClient(...)`` etc. is a ``new_expression`` (not a+ # ``call_expression``), so it arrives here rather than via the call path.+ if node.type != "new_expression":+ return None+ # Rightmost identifier of a ``new X()`` / ``new pkg.X()`` constructor.+ ctor = node_text(node.child_by_field_name("constructor"))+ if ctor is not None and ctor.split(".")[-1] in _TS_RESOURCE_CTORS:+ return "resource_construction_in_loop"+ return None++ def list_bound_names(self, root: Node) -> frozenset[str]:+ """Names bound to an array literal (``const arr = [...]``)."""+ names: set[str] = set()+ for n in self._walk(root):+ if n.type != "variable_declarator":+ continue+ name = identifier_name(n.child_by_field_name("name"))+ value = n.child_by_field_name("value")+ if name is not None and value is not None and value.type == "array":+ names.add(name)+ return frozenset(names)