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(lwc): link Lightning Web Component imports, templates and exposed bundles, and reach Apex from @salesforce/apex (#4411)
Raghav Chamadiya82baa4a34296
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 70f3450b5..debab26ec 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1002,6 +1002,14 @@ both settles a name two files declare and refuses a class that merely shadows aframework widget. A class reached through an `export` barrel is missed, whichcosts an edge rather than inventing one.+### Lightning Web Components++Inside an `lwc/<name>/` bundle, `c/<name>` imports resolve to that bundle's+main module and `@salesforce/apex/Cls.method` imports to the Apex method.+Templates link to child components by tag and to their own class's members by+`{binding}`, `@wire` binds its Apex method, and an exposed bundle is an entry+point. A name two sfdx projects declare goes to the nearer one; a tie gets no edge.+### Known gaps per language- **Template dialects are invisible.** Django/Jinja, Go templates, ERB,diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 234003433..39e2d5652 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -167,7 +167,7 @@ reported as unreachable.| C# | ASP.NET (attribute and minimal API), EF Core, gRPC-dotnet, host-builder extensions, CommunityToolkit MVVM || Go | net/http, gin, echo, chi, gRPC server registration || Rust | Axum, Actix |-| JS / TS / Svelte | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit / Astro, tRPC, Express / NestJS, Angular |+| JS / TS / Svelte | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit / Astro, tRPC, Express / NestJS, Angular, Lightning Web Components || C++ | GoogleTest, Catch2, Boost.Test, doctest, Google Benchmark, libFuzzer || PHP | Laravel, TYPO3 || Dart | Flutter route tables, `runApp()` and widget trees |diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.pyindex d9bccc099..36f5dcb4d 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom tree_sitter import Nodefrom ...models import NamedBinding+from ...resolvers.lwc import apex_specifierfrom ..helpers import node_text@@ -33,6 +34,17 @@ def _extract_require_bindings(return _module_pattern_bindings(name_node, src)+def _apex_method(stmt_node: Node, src: str) -> str | None:+ """``m`` for ``import x from '@salesforce/apex/[ns.]Cls.m'``, else None.++ Salesforce's default export of that module is the Apex method itself, so+ the binding publishes the method's name rather than ``default``.+ """+ source = stmt_node.child_by_field_name("source")+ spec = apex_specifier(node_text(source, src).strip("'\"`")) if source is not None else None+ return spec[2] if spec is not None else None++def _bound_at(local_node: Node, exported: str | None, src: str, *, module_alias: bool = False) -> NamedBinding:@@ -187,9 +199,12 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[Nfor sub in child.children:if sub.type == "identifier":local = node_text(sub, src)- names.append(local)+ method = _apex_method(stmt_node, src)+ names.append(method or local)bindings.append(- NamedBinding(local_name=local, exported_name="default", source_file=None)+ NamedBinding(+ local_name=local, exported_name=method or "default", source_file=None+ ))elif sub.type == "named_imports":for spec in sub.children:diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex e7dde83e5..b16ff3ca3 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -40,6 +40,7 @@ from . import (hono,jakarta,laravel,+ lwc,micronaut,next_app,pytest_edges,@@ -87,6 +88,7 @@ _HANDLERS: list[FrameworkHandler] = [*flutter.HANDLERS,*express.HANDLERS,*angular.HANDLERS,+ *lwc.HANDLERS,*next_app.HANDLERS,*hono.HANDLERS,*remix.HANDLERS,diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py b/packages/core/src/repowise/core/ingestion/framework_edges/lwc.pynew file mode 100644index 000000000..bf7fbc29a--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py@@ -0,0 +1,240 @@+"""Lightning Web Components: template tags, template bindings and exposed bundles.++* ``<c-child-name>`` in a template: a file edge to the child bundle's main module.+* ``{handleClick}`` in a template: a ``framework_binds`` edge to that class member.+* ``<isExposed>true</isExposed>`` in ``.js-meta.xml``: the main module is an entry+ point anchored to ``framework:lwc``; its ``configurationEditor`` gets a file edge.++Tags are read from raw text because the HTML grammar splits them at ``_``.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..framework_facts import LWC+from ..resolvers.lwc import (+ apex_specifier,+ lwc_bundle_dir,+ lwc_bundles,+ lwc_namespaces,+ lwc_tag_index,+ nearest,+)+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ add_symbol_edge,+ anchor_edge,+ source_text,+)++if TYPE_CHECKING:+ import networkx as nx++ from ..resolvers import ResolverContext++_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)+# `<ns-rest`: the namespace ends at the first hyphen.+_TAG_RE = re.compile(r"<([A-Za-z][A-Za-z0-9]*)-([A-Za-z0-9_-]+)")+# `{name}` / `{name.field}`: the leading identifier is a member of the class.+_BINDING_RE = re.compile(r"\{\s*([A-Za-z_$][\w$]*)")+_WIRE_RE = re.compile(r"@wire\s*\(\s*([A-Za-z_$][\w$]*)")+# Targets are ignored unless the bundle is exposed.+_EXPOSED_RE = re.compile(r"<isExposed>\s*true\s*</isExposed>", re.IGNORECASE)+# `for:item="x"`, `for:index="i"`, `iterator:it={...}`: template-local names.+_LOOP_VAR_RE = re.compile(r"""for:(?:item|index)\s*=\s*["']([A-Za-z_$][\w$]*)|iterator:([A-Za-z_$][\w$]*)""")+# A `<template ...>` open tag or a `</template>` close tag (loops live on templates).+# Quoted attribute values may hold `>`; `<template-x>` is a custom element, not a template.+_TEMPLATE_TAG_RE = re.compile(+ r"""<template(?=[\s>/])(?:[^>"']|"[^"]*"|'[^']*')*>|</template\s*>""", re.IGNORECASE+)+# A Flow screen component's property editor, named by tag in its targetConfig.+_EDITOR_RE = re.compile(r"""configurationEditor\s*=\s*["']([A-Za-z][A-Za-z0-9]*)-([A-Za-z0-9_-]+)["']""")+++def _members(parsed: Any) -> dict[str, str]:+ """Method and accessor name -> symbol id for the module's top-level classes."""+ classes = {s.name for s in parsed.symbols if s.kind == "class" and not s.parent_name}+ return {+ s.name: s.id+ for s in parsed.symbols+ if s.kind == "method" and s.parent_name in classes+ }+++def _tag_target(ns: str, body: str, referrer: str, ctx: ResolverContext) -> str | None:+ """The main module a ``<ns-body>`` tag written in *referrer* instantiates, or None.++ HTML tag names are case-insensitive; kebab names are lowercase, so is the lookup.+ """+ if ns.lower() not in lwc_namespaces(ctx):+ return None+ name = lwc_tag_index(ctx).get(body.lower())+ target = nearest(lwc_bundles(ctx)[name], referrer) if name is not None else None+ # A component's own tag (recursion) says nothing about who reaches it.+ if target is None or lwc_bundle_dir(target) == lwc_bundle_dir(referrer):+ return None+ return target+++def _loop_scopes(text: str) -> list[tuple[int, int, frozenset[str]]]:+ """``(start, end, names)`` per loop template: the span where its variables are visible.++ The span runs from the end of the ``<template for:each ...>`` open tag to+ its matching ``</template>``, nested templates balanced on a stack. An+ unclosed one runs to the end of the text.+ """+ scopes: list[tuple[int, int, frozenset[str]]] = []+ stack: list[tuple[int, frozenset[str]]] = []+ for m in _TEMPLATE_TAG_RE.finditer(text):+ if m.group().startswith("</"):+ if stack:+ start, names = stack.pop()+ scopes.append((start, m.start(), names))+ continue+ names = frozenset(a or b for a, b in _LOOP_VAR_RE.findall(m.group()))+ stack.append((m.end(), names))+ scopes.extend((start, len(text), names) for start, names in stack)+ return [scope for scope in scopes if scope[2]]+++def _binding_edges(graph: nx.DiGraph, template: str, text: str, main: Any) -> int:+ """``{member}`` in *template* -> that method or getter of the bundle's class.++ A binding inside a loop that declares the same name (``for:item``,+ ``for:index``, ``iterator:``) reads the loop variable, not the member.+ """+ members = _members(main)+ scopes = _loop_scopes(text)+ names = {+ m.group(1)+ for m in _BINDING_RE.finditer(text)+ if m.group(1) in members+ and not any(s <= m.start() < e and m.group(1) in local for s, e, local in scopes)+ }+ module_sym = f"{template}::__module__"+ return sum(add_symbol_edge(graph, module_sym, members[n]) for n in names)+++def _template_edges(graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext) -> int:+ bundles = lwc_bundles(ctx)+ source_map = getattr(ctx, "source_map", None) or {}+ count = 0+ for path in sorted(parsed_files):+ bundle_dir = lwc_bundle_dir(path) if path.endswith(".html") else None+ if bundle_dir is None:+ continue+ text = _COMMENT_RE.sub(" ", source_text(path, parsed_files[path], source_map))+ for m in _TAG_RE.finditer(text):+ target = _tag_target(m.group(1), m.group(2), path, ctx)+ if target is not None:+ count += _add_edge_if_new(graph, path, target)+ own = bundle_dir.rpartition("/")[2]+ main = next((p for p in bundles.get(own, ()) if lwc_bundle_dir(p) == bundle_dir), None)+ if main in parsed_files:+ count += _binding_edges(graph, path, text, parsed_files[main])+ return count+++def _apex_method(apex: Any, cls: str, method: str) -> str | None:+ """The id of *cls*.*method* in a parsed Apex file, matched case-insensitively.++ Ceiling: a local lookup; use a shared case-insensitive Apex index once one exists.+ """+ cls, method = cls.lower(), method.lower()+ found = [+ s+ for s in apex.symbols+ if s.kind == "method" and s.name.lower() == method and (s.parent_name or "").lower() == cls+ ]+ # Only an @AuraEnabled method is callable from LWC, which settles an overload.+ aura = [s for s in found if any(d.lower().startswith("@auraenabled") for d in s.decorators)]+ ids = {s.id for s in (aura or found)}+ return ids.pop() if len(ids) == 1 else None+++def _apex_bindings(parsed: Any, parsed_files: dict[str, Any]) -> dict[str, str]:+ """Local name -> Apex method id for each ``@salesforce/apex`` import that resolved."""+ bound: dict[str, str] = {}+ for imp in parsed.imports:+ spec = apex_specifier(imp.module_path)+ apex = parsed_files.get(imp.resolved_file or "")+ if spec is None or apex is None:+ continue+ target = _apex_method(apex, spec[1], spec[2])+ if target is not None:+ bound.update((b.local_name, target) for b in imp.bindings if b.local_name)+ return bound+++def _wire_edges(graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext) -> int:+ """``@wire(getThings, ...)`` with an Apex import binding -> that Apex method.++ The edge starts at the ``wire(...)`` call's caller: the class for a field,+ the method for a handler.+ """+ source_map = getattr(ctx, "source_map", None) or {}+ count = 0+ for path, parsed in parsed_files.items():+ if lwc_bundle_dir(path) is None:+ continue+ text = source_text(path, parsed, source_map)+ bound = _apex_bindings(parsed, parsed_files) if "@wire" in text else None+ if not bound:+ continue+ callers = {c.line: c.caller_symbol_id for c in parsed.calls if c.target_name == "wire"}+ for m in _WIRE_RE.finditer(text):+ caller = callers.get(text.count("\n", 0, m.start()) + 1)+ target = bound.get(m.group(1))+ if caller is not None and target is not None:+ count += add_symbol_edge(graph, caller, target)+ return count+++def _exposure_edges(graph: nx.DiGraph, ctx: ResolverContext) -> int:+ if ctx.repo_path is None:+ return 0+ count = 0+ for name, mains in lwc_bundles(ctx).items():+ for main in mains:+ meta = f"{main.rpartition('/')[0]}/{name}.js-meta.xml"+ try:+ text = (ctx.repo_path / meta).read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ continue+ text = _COMMENT_RE.sub(" ", text)+ for m in _EDITOR_RE.finditer(text):+ editor = _tag_target(m.group(1), m.group(2), main, ctx)+ if editor is not None:+ count += _add_edge_if_new(graph, main, editor)+ if not _EXPOSED_RE.search(text):+ continue+ count += anchor_edge(graph, LWC, main)+ node = graph.nodes.get(main)+ if node is not None:+ node["is_entry_point"] = True+ return count+++class _LwcHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return bool(lwc_bundles(dctx.ctx))++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return (+ _template_edges(graph, parsed_files, ctx)+ + _wire_edges(graph, parsed_files, ctx)+ + _exposure_edges(graph, ctx)+ )+++HANDLERS: list[FrameworkHandler] = [_LwcHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_facts.py b/packages/core/src/repowise/core/ingestion/framework_facts.pyindex 9910c1f21..c9b440eee 100644--- a/packages/core/src/repowise/core/ingestion/framework_facts.py+++ b/packages/core/src/repowise/core/ingestion/framework_facts.py@@ -129,6 +129,9 @@ ANDROID = FrameworkFacts(name="Android", anchor="framework:android")ANGULAR = FrameworkFacts(name="Angular", anchor="framework:angular")+#: The Lightning runtime that places the LWC bundles a ``.js-meta.xml`` exposes.+LWC = FrameworkFacts(name="Lightning Web Components", anchor="framework:lwc")+#: Workspace config naming what an Angular build loads: Angular CLI's#: ``angular.json`` and an Nx project's ``project.json``.ANGULAR_WORKSPACE_FILES = frozenset({"angular.json", "project.json"})diff --git a/packages/core/src/repowise/core/ingestion/resolvers/lwc.py b/packages/core/src/repowise/core/ingestion/resolvers/lwc.pynew file mode 100644index 000000000..85afff82b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/lwc.py@@ -0,0 +1,168 @@+"""Lightning Web Components: bundle names, module specifiers and template tags.++An LWC bundle is ``.../lwc/<name>/`` with main module ``<name>.js`` (or ``.ts``).+JS imports reach it as ``c/<name>`` (or the sfdx namespace), templates as+``<c-kebab-name>``, looked up in a reverse index of ``kebab(name)`` because+camelCase cannot be recovered from a tag. ``@salesforce/apex/[ns.]Cls.method``+resolves to the Apex class file. A name two bundles declare goes to the one+sharing the longest directory prefix with the referrer; a tie resolves nothing.+"""++from __future__ import annotations++import json+import re+from typing import TYPE_CHECKING++from ...test_paths import is_test_related_path++if TYPE_CHECKING:+ from .context import ResolverContext++APEX_MODULE_PREFIXES = ("@salesforce/apex/", "@salesforce/apexContinuation/")+_SPECIFIER_RE = re.compile(r"([A-Za-z]\w*)/([A-Za-z]\w*)")+_UPPER_RE = re.compile(r"[A-Z]")+++def kebab(name: str) -> str:+ """The template tag body for bundle *name*: ``fooBar2Baz`` -> ``foo-bar2-baz``."""+ return _UPPER_RE.sub(lambda m: "-" + m.group().lower(), name)+++def lwc_bundle_dir(path: str) -> str | None:+ """``.../lwc/<name>`` for any file inside a bundle (tests included), else None."""+ parts = path.split("/")+ for i in range(len(parts) - 2, 0, -1):+ if parts[i - 1] == "lwc":+ return "/".join(parts[: i + 1])+ return None+++def lwc_bundles(ctx: ResolverContext) -> dict[str, tuple[str, ...]]:+ """Bundle name -> main module paths, built once per context."""+ cached = getattr(ctx, "_lwc_bundles", None)+ if cached is not None:+ return cached+ found: dict[str, list[str]] = {}+ for path in ctx.sorted_paths:+ parts = path.split("/")+ if len(parts) < 3 or parts[-3] != "lwc":+ continue+ name = parts[-2]+ if parts[-1] in (f"{name}.js", f"{name}.ts"):+ found.setdefault(name, []).append(path)+ bundles = {name: tuple(paths) for name, paths in found.items()}+ ctx._lwc_bundles = bundles # type: ignore[attr-defined]+ return bundles+++def lwc_tag_index(ctx: ResolverContext) -> dict[str, str]:+ """``kebab(name)`` -> bundle name. Distinct legal names never share a kebab form."""+ cached = getattr(ctx, "_lwc_tag_index", None)+ if cached is None:+ cached = {kebab(name): name for name in lwc_bundles(ctx)}+ ctx._lwc_tag_index = cached # type: ignore[attr-defined]+ return cached+++def lwc_namespaces(ctx: ResolverContext) -> frozenset[str]:+ """``c`` plus every sfdx ``namespace`` the repository declares for itself, lowercased."""+ cached = getattr(ctx, "_lwc_namespaces", None)+ if cached is not None:+ return cached+ names = {"c"}+ if ctx.repo_path is not None:+ manifests = {p for p in ctx.path_set if p.rpartition("/")[2] == "sfdx-project.json"}+ manifests.add("sfdx-project.json")+ for rel in sorted(manifests):+ try:+ text = (ctx.repo_path / rel).read_text(encoding="utf-8-sig")+ namespace = json.loads(text).get("namespace")+ except (OSError, ValueError, AttributeError):+ continue+ if isinstance(namespace, str) and namespace.strip():+ names.add(namespace.strip().lower())+ result = frozenset(names)+ ctx._lwc_namespaces = result # type: ignore[attr-defined]+ return result+++def nearest(candidates: tuple[str, ...], referrer: str) -> str | None:+ """The candidate sharing the most leading directories with *referrer*; None on a tie."""+ if len(candidates) == 1:+ return candidates[0]+ ref = referrer.split("/")++ def shared(path: str) -> int:+ n = 0+ for a, b in zip(path.split("/"), ref, strict=False):+ if a != b:+ break+ n += 1+ return n++ scored = sorted(((shared(c), c) for c in candidates), reverse=True)+ if scored[0][0] == scored[1][0]:+ return None+ return scored[0][1]+++def _apex_classes(ctx: ResolverContext) -> dict[str, tuple[str, ...]]:+ """Lowercased Apex class name -> ``.cls`` paths (Apex names are case-insensitive).++ Ceiling: a local index; use a shared case-insensitive Apex index once one exists.+ """+ cached = getattr(ctx, "_lwc_apex_classes", None)+ if cached is None:+ found: dict[str, list[str]] = {}+ for path in ctx.sorted_paths:+ if path[-4:].lower() == ".cls":+ stem = path.rpartition("/")[2][:-4].lower()+ found.setdefault(stem, []).append(path)+ cached = {name: tuple(paths) for name, paths in found.items()}+ ctx._lwc_apex_classes = cached # type: ignore[attr-defined]+ return cached+++def apex_specifier(module_path: str) -> tuple[str | None, str, str] | None:+ """``(ns, Cls, method)`` for ``@salesforce/apex/[ns.]Cls.method``, else None.++ The one place the specifier is taken apart: the resolver, the import+ binding and the ``@wire`` edges all read it here.+ """+ prefix = next((p for p in APEX_MODULE_PREFIXES if module_path.startswith(p)), None)+ if prefix is None:+ return None+ parts = module_path[len(prefix) :].split(".")+ if len(parts) not in (2, 3) or not all(parts):+ return None+ return (parts[0] if len(parts) == 3 else None, parts[-2], parts[-1])+++def _resolve_apex_module(+ spec: tuple[str | None, str, str], importer_path: str, ctx: ResolverContext+) -> str | None:+ """The class file; another package's namespace stays external."""+ ns, cls, _ = spec+ if ns is not None and ns.lower() not in lwc_namespaces(ctx):+ return None+ candidates = _apex_classes(ctx).get(cls.lower())+ return nearest(candidates, importer_path) if candidates else None+++def resolve_lwc_module(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """A module inside an LWC bundle: ``c/fooBar`` -> that bundle's main module,+ ``@salesforce/apex/Cls.method`` -> the Apex class file. Other Salesforce+ modules (schema, labels, ``lightning/*``) are not files here and stay external.+ """+ if module_path.startswith(APEX_MODULE_PREFIXES):+ spec = apex_specifier(module_path)+ # Jest only mocks Apex, so a test's import is no use of the class.+ if spec is None or is_test_related_path(importer_path, "javascript"):+ return None+ return _resolve_apex_module(spec, importer_path, ctx)+ m = _SPECIFIER_RE.fullmatch(module_path)+ if m is None or m.group(1).lower() not in lwc_namespaces(ctx):+ return None+ candidates = lwc_bundles(ctx).get(m.group(2))+ return nearest(candidates, importer_path) if candidates else Nonediff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.pyindex 6f22c8fb6..13e472fc5 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py@@ -7,6 +7,7 @@ from collections.abc import Iterablefrom pathlib import Pathfrom .context import ResolverContext+from .lwc import lwc_bundle_dir, resolve_lwc_modulefrom .subpath_imports import resolve_subpath_importfrom .svelte_kit import resolve_lib_aliasfrom .ts_workspace import resolve_via_workspaces@@ -93,6 +94,12 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverContreturn candidatereturn None+ # LWC ``c/fooBar``, only from inside an ``lwc/<bundle>/`` folder.+ if lwc_bundle_dir(importer_path) is not None:+ lwc_resolved = resolve_lwc_module(module_path, importer_path, ctx)+ if lwc_resolved is not None:+ return lwc_resolved+# Node.js subpath imports (``#lib/...`` via package.json "imports").subpath_resolved = resolve_subpath_import(module_path, importer_path, ctx)if subpath_resolved is not None:diff --git a/tests/unit/ingestion/test_lwc_framework_edges.py b/tests/unit/ingestion/test_lwc_framework_edges.pynew file mode 100644index 000000000..efc81669e--- /dev/null+++ b/tests/unit/ingestion/test_lwc_framework_edges.py@@ -0,0 +1,247 @@+"""Lightning Web Components: module specifiers, template tags and bindings, exposed bundles.++The end-to-end cases go through traverse -> parse -> graph -> framework edges+-> dead code, the path a real index takes.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.resolvers.lwc import kebab, lwc_bundle_dir, nearest++_LWC = "force-app/main/default/lwc"+_EXPOSED = "<LightningComponentBundle><isExposed>true</isExposed></LightningComponentBundle>\n"+# A target counts for nothing while the bundle is not exposed.+_HIDDEN = (+ "<LightningComponentBundle><isExposed>false</isExposed>"+ "<targets><target>lightning__Tab</target></targets></LightningComponentBundle>\n"+)++_APP = {+ "sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "acme"}\n',+ f"{_LWC}/parent/parent.js": (+ "import { LightningElement } from 'lwc';\n"+ "import { reduceErrors } from 'c/ldsUtils';\n"+ "import getThings from '@salesforce/apex/ThingController.getThings';\n"+ "import NAME from '@salesforce/schema/Account.Name';\n"+ "export default class Parent extends LightningElement {\n"+ " get label() { return reduceErrors([]); }\n"+ " handleClick() { return getThings(); }\n"+ " notInTemplate() { return NAME; }\n"+ " get row() { return null; }\n"+ "}\n"+ ),+ f"{_LWC}/parent/parent.html": (+ "<template>\n"+ " <!-- <c-orphan></c-orphan> -->\n"+ " <lightning-button label={label} onclick={handleClick}></lightning-button>\n"+ " <c-child-comp record-id={recordId}></c-child-comp>\n"+ " <acme-fsc_flow-combobox></acme-fsc_flow-combobox>\n"+ " <c-rd2-entry-form></c-rd2-entry-form>\n"+ " <other-child-comp></other-child-comp>\n"+ " <c-parent></c-parent>\n"+ ' <template for:each={label} for:item="row"><p key={row.id}>{row.name}</p></template>\n'+ "</template>\n"+ ),+ f"{_LWC}/parent/parent.js-meta.xml": _EXPOSED.replace(+ "</LightningComponentBundle>",+ '<targetConfigs><targetConfig targets="lightning__FlowScreen"'+ ' configurationEditor="c-parent-C-P-E"/></targetConfigs></LightningComponentBundle>',+ ),+ f"{_LWC}/parentCPE/parentCPE.js": (+ "import { LightningElement } from 'lwc';\n"+ "export default class ParentCPE extends LightningElement {}\n"+ ),+ f"{_LWC}/parent/__tests__/parent.test.js": (+ "import { createElement } from 'lwc';\nimport Parent from 'c/parent';\n"+ "import getThings from '@salesforce/apex/ThingController.getThings';\n"+ "it('renders', () => { createElement('c-parent', { is: Parent }); });\n"+ ),+ f"{_LWC}/childComp/childComp.js": (+ "import { LightningElement, api, wire } from 'lwc';\n"+ "import getThings from '@salesforce/apex/acme.thingController.getThings';\n"+ "export default class ChildComp extends LightningElement {\n"+ " @api recordId;\n"+ " @wire(getThings) things;\n"+ "}\n"+ ),+ f"{_LWC}/fsc_flowCombobox/fsc_flowCombobox.js": (+ "import { LightningElement } from 'lwc';\n"+ "export default class FlowCombobox extends LightningElement {}\n"+ ),+ f"{_LWC}/rd2EntryForm/rd2EntryForm.js": (+ "import { LightningElement } from 'lwc';\n"+ "export default class Rd2EntryForm extends LightningElement {}\n"+ ),+ "force-app/main/default/classes/ThingController.cls": (+ "public with sharing class ThingController {\n"+ " @AuraEnabled(cacheable=true)\n"+ " public static List<String> getThings() { return getThings(1); }\n"+ " private static List<String> getThings(Integer n) { return new List<String>(); }\n"+ "}\n"+ ),+ f"{_LWC}/ldsUtils/ldsUtils.js": "export function reduceErrors(errors) { return errors; }\n",+ f"{_LWC}/orphan/orphan.js": (+ "import { LightningElement } from 'lwc';\n"+ "export default class Orphan extends LightningElement {}\n"+ ),+ f"{_LWC}/orphan/orphan.js-meta.xml": _HIDDEN,+}+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _graph(repo: Path) -> tuple[object, set[tuple[str, str]]]:+ builder = GraphBuilder(repo)+ parser = ASTParser()+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(repo).traverse():+ src = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, src))+ source_map[fi.path] = src+ builder.set_source_map(source_map)+ builder.build()+ builder.add_framework_edges([])+ report = DeadCodeAnalyzer(+ builder.graph(), {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=repo+ ).analyze({"detect_unused_internals": True})+ dead = {(f.kind.value, f.file_path) for f in report.findings}+ return builder.graph(), dead+++def test_kebab_keeps_digits_attached_and_underscores_literal() -> None:+ assert kebab("accountList") == "account-list"+ assert kebab("rd2EntryForm") == "rd2-entry-form"+ assert kebab("fsc_flowCombobox") == "fsc_flow-combobox"+++def test_an_apex_import_binding_publishes_the_method_name(tmp_path: Path) -> None:+ repo = _write(tmp_path, {f"{_LWC}/a/a.js": (+ "import fetchThings from '@salesforce/apex/ns.ThingController.getThings';\n"+ "import other from './helper';\n"+ )}) # fmt: skip+ (fi,) = FileTraverser(repo).traverse()+ parsed = ASTParser().parse_file(fi, Path(fi.abs_path).read_bytes())+ apex, plain = parsed.imports+ assert apex.imported_names == ["getThings"]+ assert [(b.local_name, b.exported_name) for b in apex.bindings] == [("fetchThings", "getThings")]+ assert [(b.local_name, b.exported_name) for b in plain.bindings] == [("other", "default")]+++def test_bundle_dir_covers_tests_and_ignores_the_lwc_root() -> None:+ assert lwc_bundle_dir(f"{_LWC}/a/__tests__/a.test.js") == f"{_LWC}/a"+ assert lwc_bundle_dir(f"{_LWC}/a/a.html") == f"{_LWC}/a"+ assert lwc_bundle_dir(f"{_LWC}/jsconfig.json") is None+ assert lwc_bundle_dir("src/app.js") is None+++def test_nearest_prefers_the_referrer_s_project_and_refuses_a_tie() -> None:+ a, b = "p1/lwc/x/x.js", "p2/lwc/x/x.js"+ assert nearest((a, b), "p1/lwc/y/y.js") == a+ assert nearest((a, b), "p3/lwc/y/y.js") is None+++def test_lwc_bundles_are_linked_bound_and_anchored(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ parent_js, parent_html = f"{_LWC}/parent/parent.js", f"{_LWC}/parent/parent.html"++ # c/ldsUtils from a bundle, c/parent from a jest test.+ assert graph.has_edge(parent_js, f"{_LWC}/ldsUtils/ldsUtils.js")+ assert graph.has_edge(f"{_LWC}/parent/__tests__/parent.test.js", parent_js)+ # @salesforce/apex: the class file, the imperative call and the @wire binding+ # reach the method (namespace and class case-insensitive). A jest test only+ # mocks Apex, so its import stays external.+ cls = "force-app/main/default/classes/ThingController.cls"+ method = f"{cls}::ThingController::getThings#0"+ assert graph.has_edge(parent_js, cls)+ call = graph.get_edge_data(f"{parent_js}::Parent::handleClick", method)+ assert (call["edge_type"], call["resolution_origin"]) == ("calls", "import_scoped")+ child_cls = f"{_LWC}/childComp/childComp.js::ChildComp"+ assert graph.get_edge_data(child_cls, method)["edge_type"] == "framework_binds"+ assert not graph.has_edge(f"{_LWC}/parent/__tests__/parent.test.js", cls)+ # Platform modules stay external.+ assert graph.has_edge(parent_js, "external:@salesforce/schema/Account.Name")++ # Tags: kebab, digits, underscores, the sfdx namespace; not other namespaces,+ # comments or the component's own tag.+ tag_targets = {t for _, t in graph.out_edges(parent_html) if not t.startswith(parent_html)}+ assert tag_targets == {+ f"{_LWC}/childComp/childComp.js",+ f"{_LWC}/fsc_flowCombobox/fsc_flowCombobox.js",+ f"{_LWC}/rd2EntryForm/rd2EntryForm.js",+ }++ # Bindings reach the getter and the handler, as framework_binds, and nothing else.+ module = f"{parent_html}::__module__"+ binds = {t for _, t, d in graph.out_edges(module, data=True) if d["edge_type"] == "framework_binds"}+ assert binds == {f"{parent_js}::Parent::label", f"{parent_js}::Parent::handleClick"}++ # The Flow property editor its meta names, matched case-insensitively.+ assert graph.has_edge(parent_js, f"{_LWC}/parentCPE/parentCPE.js")++ # Exposure anchors the bundle; an unexposed bundle nothing names stays dead.+ assert graph.has_edge("framework:lwc", parent_js)+ assert graph.nodes[parent_js]["is_entry_point"] is True+ unreachable = {path for kind, path in dead if kind == "unreachable_file"}+ assert f"{_LWC}/orphan/orphan.js" in unreachable+ assert not unreachable & {+ parent_js,+ f"{_LWC}/childComp/childComp.js",+ f"{_LWC}/ldsUtils/ldsUtils.js",+ f"{_LWC}/parentCPE/parentCPE.js",+ }+++def test_a_loop_variable_shadows_a_member_only_inside_its_loop(tmp_path: Path) -> None:+ js = f"{_LWC}/list/list.js"+ files = {+ js: (+ "import { LightningElement } from 'lwc';\n"+ "export default class List extends LightningElement {\n"+ " get item() { return 1; }\n get child() { return 2; }\n"+ " get it() { return 3; }\n get rows() { return []; }\n get idx() { return 4; }\n"+ "}\n"+ ),+ f"{_LWC}/list/list.html": (+ "<template>\n"+ " <p>{item}</p>\n"+ ' <template for:each={rows} for:item="item">\n'+ " <p key={item.id}>{item.name}</p>\n"+ ' <template for:each={item.kids} for:item="child">{child} {item.x}</template>\n'+ " {child.name}\n"+ " </template>\n"+ " <template iterator:it={rows}>{it.value}</template>\n"+ ' <template for:each={rows} for:item="r" for:index="idx">{idx}</template>\n'+ " {idx}\n"+ "</template>\n"+ ),+ }+ graph, _ = _graph(_write(tmp_path, files))+ module = f"{_LWC}/list/list.html::__module__"+ binds = {t.rpartition("::")[2] for _, t, d in graph.out_edges(module, data=True)+ if d["edge_type"] == "framework_binds"} # fmt: skip+ # `item` before the loop and `rows` in the loop's own tag read the members;+ # `child` after the inner loop closes and `idx` after its loop read the members+ # too; `it` occurs only inside its loop.+ assert binds == {"item", "rows", "child", "idx"}+++def test_a_name_shared_by_two_projects_resolves_within_the_importer_s(tmp_path: Path) -> None:+ files = {}+ for project in ("one", "two"):+ root = f"{project}/force-app/main/default/lwc"+ files[f"{root}/dup/dup.js"] = "export const x = 1;\n"+ files[f"{root}/user/user.js"] = "import { x } from 'c/dup';\nexport default x;\n"+ graph, _ = _graph(_write(tmp_path, files))+ for project in ("one", "two"):+ root = f"{project}/force-app/main/default/lwc"+ assert graph.has_edge(f"{root}/user/user.js", f"{root}/dup/dup.js")