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(ts-workspace): split ts_workspace into a package with a workspace probe class (#4017)
Raghav Chamadiya82d114b94fe9
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.pydeleted file mode 100644index 378668716..000000000--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py+++ /dev/null@@ -1,1356 +0,0 @@-"""npm/yarn/pnpm workspace package resolution for TypeScript imports.--Reads the root ``package.json``'s ``workspaces`` field (string list or-``{"packages": [...]}`` form) and ``pnpm-workspace.yaml``'s ``packages``-list, expands glob patterns, and reads each sibling package's ``name``-field. The resulting ``{pkg_name: dir_posix}`` map lets the TS resolver-turn ``import x from "@myorg/foo"`` into the correct intra-repo file-rather than an ``external:`` node.--Both manifests are consulted because they are not interchangeable: pnpm-does not read the ``workspaces`` field at all, so a pnpm monorepo-declares its members only in ``pnpm-workspace.yaml``.--Subpath imports (``@myorg/foo/bar/baz``) honour Node.js ``"exports"``-subpath patterns when the workspace's ``package.json`` declares them:-- "exports": {- ".": "./src/index.ts",- "./util": "./src/util.ts",- "./graph/*": "./src/graph/*.tsx",- "./modules/*": { "import": "./src/modules/*.ts" }- }--Conditional values (``{"import": ..., "default": ..., ...}``) are-flattened to the first plausible source target. Packages without an-``exports`` field fall back to the legacy ``<pkg>/<subpath>`` probe so-"plain" monorepo layouts keep working.-"""--from __future__ import annotations--import contextlib-import json-import posixpath-import re-import subprocess-from collections.abc import Container-from dataclasses import dataclass, field-from pathlib import Path-from typing import TYPE_CHECKING, Any--from .pnpm_workspace import read_pnpm_workspace_patterns--if TYPE_CHECKING:- from .context import ResolverContext---# ----------------------------------------------------------------------------# Single pruned filesystem scan-# ----------------------------------------------------------------------------# The mdx / vitest-config / package.json finders below all need to locate-# files by name across the repo. Doing that with per-finder ``rglob`` calls-# walked the ENTIRE tree (including node_modules, virtualenvs, .git) once-# per pattern — 12+ full walks, measured at ~6 min on a medium repo with a-# checked-in .venv. One ``os.walk`` with directory pruning, memoized on the-# resolver context, replaces all of them.-#-# The prune list is deliberately narrow: vendored/derived trees that can-# never contain *our* manifests or docs. ``.github`` and other dot-dirs that-# may hold real package.json files (custom actions) are NOT pruned wholesale.-_SCAN_PRUNE_DIRS: frozenset[str] = frozenset({- "node_modules",- ".git",- ".hg",- ".svn",- ".venv",- "venv",- ".tox",- "__pycache__",- ".repowise",- ".repowise.prebench-bak",- ".next",- ".nuxt",- ".turbo",- ".cache",- ".parcel-cache",- ".yarn",- ".pnpm-store",-})--_VITEST_CONFIG_NAMES: frozenset[str] = frozenset({- "vitest.config.ts", "vitest.config.js", "vitest.config.mts",- "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",- "vite.config.ts", "vite.config.js", "vite.config.mts",- "vite.config.mjs",-})---@dataclass-class _RepoFileScan:- """File locations gathered by the single pruned walk."""-- mdx_files: list[Path] = field(default_factory=list)- vitest_configs: list[Path] = field(default_factory=list)- package_jsons: list[Path] = field(default_factory=list)- plugin_jsons: list[Path] = field(default_factory=list)---def _scan_repo_files(repo_path: Path, *, prune_nested_git: bool = True) -> _RepoFileScan:- """One pruned walk collecting every finder's target files.-- Uses the shared :func:`repowise.core.fs_walk.walk_repo` (nested-git- pruning, cycle guard) with this module's deliberately-narrow prune set.- """- from repowise.core.fs_walk import walk_repo-- scan = _RepoFileScan()- for dirpath, _dirnames, filenames in walk_repo(- repo_path, prune_dirs=_SCAN_PRUNE_DIRS, prune_nested_git=prune_nested_git- ):- for fname in filenames:- if fname.endswith(".mdx"):- scan.mdx_files.append(Path(dirpath) / fname)- elif fname in _VITEST_CONFIG_NAMES:- scan.vitest_configs.append(Path(dirpath) / fname)- elif fname == "package.json":- scan.package_jsons.append(Path(dirpath) / fname)- elif fname == "plugin.json":- scan.plugin_jsons.append(Path(dirpath) / fname)- return scan---def _get_repo_scan(ctx: ResolverContext) -> _RepoFileScan:- """Memoized accessor — one walk per resolver context."""- cached = getattr(ctx, "_ts_repo_file_scan", None)- if cached is not None:- return cached- scan = (- _scan_repo_files(ctx.repo_path, prune_nested_git=ctx.prune_nested_git)- if ctx.repo_path is not None- else _RepoFileScan()- )- ctx._ts_repo_file_scan = scan # type: ignore[attr-defined]- return scan---def _parsed_package_jsons(ctx: ResolverContext) -> list[tuple[str, dict]]:- """``(repo-relative dir, data)`` for every readable ``package.json`` object.-- Memoized per resolver context, so every finder shares one parse. The- base is ``ctx.repo_path`` as given, not ``.resolve()``d: the shared scan- walks that same path, and a different base would drop every manifest.- """- cached = getattr(ctx, "_ts_parsed_package_jsons", None)- if cached is not None:- return cached- parsed: list[tuple[str, dict]] = []- for pkg_file in _get_repo_scan(ctx).package_jsons:- # node_modules manifests are already pruned by the shared scan.- try:- pkg_dir = pkg_file.parent.relative_to(ctx.repo_path).as_posix()- data = json.loads(pkg_file.read_text(encoding="utf-8", errors="ignore"))- except (ValueError, OSError, json.JSONDecodeError):- continue- if isinstance(data, dict):- parsed.append((pkg_dir, data))- ctx._ts_parsed_package_jsons = parsed # type: ignore[attr-defined]- return parsed---# Order in which we collapse Node "conditional exports" objects down to-# a single target. Source-pointing conditions come first so a TS-aware-# static analyser sees the original ``.ts`` file rather than a built-# artefact, then ESM/default, with CJS last.-_CONDITION_PRIORITY: tuple[str, ...] = (- "source",- "import",- "default",- "node",- "require",- "types",- "browser",-)---def _flatten_export_value(value: Any) -> str | None:- """Collapse a Node ``exports`` entry to a single relative target string.-- Returns ``None`` for blocked entries (``null``) or shapes we can't- handle. Recursively unwraps nested condition objects and arrays.- """- if isinstance(value, str):- return value- if isinstance(value, dict):- for cond in _CONDITION_PRIORITY:- inner = value.get(cond)- if inner is None:- continue- flat = _flatten_export_value(inner)- if flat:- return flat- return None- if isinstance(value, list):- for item in value:- flat = _flatten_export_value(item)- if flat:- return flat- return None---def _ordered_export_targets(value: Any) -> tuple[str, ...]:- """Every target a Node ``exports`` entry can mean, best first.-- The head is exactly what :func:`_flatten_export_value` chose, so a package- whose ranked condition names a file the repository contains binds the file- it always bound. The tail is every other leaf, ranked conditions before- unranked ones, and is reached only when the head names nothing indexed.-- The tail has to exist because a package may publish its sources under a- condition no fixed list can name — zod uses ``@zod/source`` — while every- condition this module ranks names build output a source checkout does not- contain, leaving the whole package unresolvable.- """- ordered: list[str] = []- head = _flatten_export_value(value)- if head is not None:- ordered.append(head)-- def walk(node: Any) -> None:- if isinstance(node, str):- if node not in ordered:- ordered.append(node)- elif isinstance(node, list):- for item in node:- walk(item)- elif isinstance(node, dict):- for cond in _CONDITION_PRIORITY:- if cond in node:- walk(node[cond])- for cond, inner in node.items():- if cond not in _CONDITION_PRIORITY:- walk(inner)-- walk(value)- return tuple(ordered)---_DECLARATION_SUFFIXES: tuple[str, ...] = (".d.ts", ".d.mts", ".d.cts")---def _build_exports_map(pkg_data: dict) -> dict[str, tuple[str, ...]]:- """Return ``{exports_key: (target, ...)}`` for a workspace package.-- ``exports`` may be a single string (shorthand for ``{".": <str>}``)- or a subpath dict. Keys that don't start with ``.`` are dropped (the- Node spec disallows mixing main-entry shorthand with subpath maps).- """- raw = pkg_data.get("exports")- if raw is None:- return {}- if isinstance(raw, str):- return {".": (raw,)}- if not isinstance(raw, dict):- return {}- out: dict[str, tuple[str, ...]] = {}- for key, value in raw.items():- if not isinstance(key, str) or not key.startswith("."):- continue- # A key whose ranked walk yields nothing is dropped, exactly as before.- # Keeping it on the strength of a spare candidate alone would let that- # candidate answer in the exports step, ahead of the fallbacks that- # answer for such a key today — a moved binding rather than a new one.- if _flatten_export_value(value) is None:- continue- out[key] = _ordered_export_targets(value)- return out---def _match_export_key(- subpath: str, exports_map: dict[str, tuple[str, ...]]-) -> tuple[str, ...] | None:- """Resolve a subpath against an ``exports`` map.-- ``subpath`` is the part of the import specifier after the package- name, with no leading slash (``""`` for the bare package, ``"lib/x"``- for ``@org/pkg/lib/x``). Exact keys win over wildcard patterns; among- wildcards the longest static prefix wins (Node spec). Returns the- matched key's candidate targets in priority order.- """- key = "." if subpath == "" else "./" + subpath- if key in exports_map:- return exports_map[key]- best_targets: tuple[str, ...] | None = None- best_prefix_len = -1- for pattern, targets in exports_map.items():- if "*" not in pattern:- continue- prefix, _, suffix = pattern.partition("*")- if not key.startswith(prefix):- continue- if suffix and not key.endswith(suffix):- continue- captured = (- key[len(prefix) : len(key) - len(suffix)]- if suffix- else key[len(prefix) :]- )- if len(prefix) > best_prefix_len:- # Beyond the head, a candidate carrying no ``*`` is dropped: the- # same fixed file would otherwise answer every distinct subpath- # under this key, quietly collapsing them onto one another.- kept = targets[:1] + tuple(t for t in targets[1:] if "*" in t)- best_targets = tuple(- t.replace("*", captured, 1) if "*" in t else t for t in kept- )- best_prefix_len = len(prefix)- return best_targets---def read_workspaces_field(pkg_data: dict) -> list[str]:- ws = pkg_data.get("workspaces")- if isinstance(ws, list):- return [str(p) for p in ws if isinstance(p, str)]- if isinstance(ws, dict):- packages = ws.get("packages")- if isinstance(packages, list):- return [str(p) for p in packages if isinstance(p, str)]- return []---def build_workspace_map(repo_path: Path | None) -> dict[str, str]:- """Return ``{package_name: dir_posix}`` for every workspace package.-- Empty dict when neither ``package.json``'s ``workspaces`` field nor- ``pnpm-workspace.yaml`` declares any members.- """- return {name: info["dir"] for name, info in build_workspace_info(repo_path).items()}---@dataclass(frozen=True)-class _WorkspaceDeclaration:- """Which globs govern a repo's workspace, and whether the root is a member."""-- includes: tuple[str, ...]- excludes: tuple[str, ...]- include_root: bool-- @property- def is_empty(self) -> bool:- return not self.includes and not self.include_root---def _read_workspace_declaration(repo_path: Path) -> _WorkspaceDeclaration:- """Resolve the governing manifest into member globs.-- pnpm keeps its member globs in ``pnpm-workspace.yaml`` and does not read- ``package.json``'s ``workspaces`` field at all, so the two manifests are- not interchangeable and must not be merged: unioning them would register a- member pnpm never installs, turning a registry dependency into a fake- intra-repo edge. When the pnpm manifest is present it is authoritative.- """- pnpm = read_pnpm_workspace_patterns(repo_path)- if pnpm is not None:- includes, excludes = pnpm- # "The root package is always included, even when custom location- # wildcards are used" — pnpm's ``packages`` setting. So a root-only- # workspace (no ``packages`` key) still has exactly one member.- return _WorkspaceDeclaration(tuple(includes), tuple(excludes), include_root=True)-- root_pkg = repo_path / "package.json"- if not root_pkg.is_file():- return _WorkspaceDeclaration((), (), include_root=False)- try:- data = json.loads(root_pkg.read_text(encoding="utf-8", errors="ignore"))- except Exception:- return _WorkspaceDeclaration((), (), include_root=False)- if not isinstance(data, dict):- return _WorkspaceDeclaration((), (), include_root=False)- return _WorkspaceDeclaration(- tuple(read_workspaces_field(data)), (), include_root=False- )---def _expand_member_dirs(repo_path: Path, declared: _WorkspaceDeclaration) -> list[Path]:- """Expand member globs to directories, minus the negated ones.-- Negated entries are expanded with the SAME globber as the includes and- subtracted, rather than matched with a second pattern language. ``pathspec``- was the obvious candidate and is wrong here: it implements git-ignore- semantics, under which a slashless ``foo`` matches at any depth and a- directory match swallows its descendants, so ``!foo`` and ``!packages/*``- would silently drop members pnpm keeps. ``Path.glob`` anchors at the repo- root and honours single-segment ``*``, which is what fast-glob (pnpm's- matcher) does for these forms.-- The root, when it is a member, is never subject to the negated patterns.-- Both loops tolerate a pattern ``Path.glob`` refuses: the strings come from- a hand-written manifest, and an absolute entry raises ``NotImplementedError``- while an empty one raises ``ValueError``. A bad entry drops itself rather- than the whole workspace, which is how every other manifest read in this- module already behaves.- """- excluded: set[Path] = set()- for pattern in declared.excludes:- with contextlib.suppress(NotImplementedError, ValueError):- excluded.update(p for p in repo_path.glob(pattern) if p.is_dir())-- dirs: list[Path] = [repo_path] if declared.include_root else []- for pattern in declared.includes:- with contextlib.suppress(NotImplementedError, ValueError):- globbed = [repo_path] if pattern == "." else repo_path.glob(pattern)- dirs.extend(p for p in globbed if p.is_dir() and p not in excluded)- return dirs---def build_workspace_info(repo_path: Path | None) -> dict[str, dict[str, Any]]:- """Return ``{pkg_name: {"dir": <posix>, "exports": {...}, "main": str|None}}``.-- A richer counterpart to :func:`build_workspace_map` that also carries- the workspace package's ``exports`` subpath map (Node.js spec) plus- ``main``/``module`` entry-point hints. Lets the resolver translate- sub-path imports through the package's own resolution rules instead- of probing ``<pkg>/<subpath>`` blindly.- """- if repo_path is None or not repo_path.is_dir():- return {}- declared = _read_workspace_declaration(repo_path)- if declared.is_empty:- return {}-- result: dict[str, dict[str, Any]] = {}- for ws_dir in _expand_member_dirs(repo_path, declared):- try:- rel = ws_dir.relative_to(repo_path).as_posix()- except ValueError:- continue- ws_pkg = ws_dir / "package.json"- if not ws_pkg.is_file():- continue- try:- ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))- except Exception:- continue- if not isinstance(ws_data, dict):- continue- name = ws_data.get("name")- if not isinstance(name, str) or not name:- continue- result[name] = {- "dir": rel,- "exports": _build_exports_map(ws_data),- "main": ws_data.get("module") if isinstance(ws_data.get("module"), str)- else (ws_data.get("main") if isinstance(ws_data.get("main"), str) else None),- }- return result---def get_or_build_workspace_info(ctx: ResolverContext) -> dict[str, dict[str, Any]]:- cached = getattr(ctx, "_ts_workspace_info", None)- if cached is not None:- return cached- info = build_workspace_info(ctx.repo_path)- ctx._ts_workspace_info = info # type: ignore[attr-defined]- return info---_PROBE_EXTENSIONS: tuple[str, ...] = (- ".ts",- ".tsx",- ".mts",- ".cts",- ".js",- ".jsx",- ".mjs",- ".cjs",-)---def _normalize_repo_rel(base: str) -> str:- """Collapse a joined repo-relative path so it can match ``path_set``.-- Callers build candidates as ``f"{pkg_dir}/{sub}"``, and the workspace- ROOT's dir is ``"."`` (pnpm always includes the root; npm/yarn repos may- list ``"."`` explicitly). That join yields ``"./src/index.ts"``, which- never equals the repo-relative ``"src/index.ts"`` a path set holds — so- without this every root-package import silently failed to resolve.-- A trailing slash survives: one caller uses the result as a ``startswith``- prefix, where dropping it would let ``src/locales`` also match- ``src/locales-old``.-- A path that collapses ENTIRELY to the root (``"./"`` — the root package's- ``"."`` joined with an empty subpath) normalizes to ``""``, not ``"./"``:- ``posixpath.normpath("./")`` is ``"."``, and re-appending the slash would- leave a prefix no repo-relative path starts with. That case is reachable- from ``_expand_exports_wildcard`` whenever a root package's wildcard- target sits at the repo root (``{"./*": "./*.ts"}``) rather than under a- subdirectory, and it silently dropped every match.- """- if not (base.startswith("./") or "/./" in base):- return base- normalized = posixpath.normpath(base)- if normalized == ".":- return ""- return f"{normalized}/" if base.endswith("/") and not normalized.endswith("/") else normalized---def _probe_path(base: str, path_set: set[str]) -> str | None:- """Locate a concrete file for ``base`` (a repo-relative path stem).-- Tries the path as-is first (handles targets that already carry an- extension, e.g. ``"./src/graph/sigma-canvas.tsx"`` from an exports- pattern). Then probes common TS/JS extensions and ``index.*``- children so directory-shaped specifiers resolve to a barrel file.- """- base = _normalize_repo_rel(base)- if base in path_set:- return base- for ext in _PROBE_EXTENSIONS:- cand = base + ext- if cand in path_set:- return cand- for ext in _PROBE_EXTENSIONS:- cand = f"{base}/index{ext}"- if cand in path_set:- return cand- return None---def _read_sub_package_manifest(repo_path: Path, sub_dir_posix: str) -> dict[str, Any] | None:- """Read and parse ``<repo_path>/<sub_dir_posix>/package.json``, or None.-- Same read/parse tolerance as :func:`build_workspace_info`'s manifest- read. No ``name`` field is required here: the caller already knows the- subpath that names this package, since that subpath is how it got here.- """- manifest = repo_path / sub_dir_posix / "package.json"- if not manifest.is_file():- return None- try:- data = json.loads(manifest.read_text(encoding="utf-8", errors="ignore"))- except Exception:- return None- return data if isinstance(data, dict) else None---def _resolve_nested_subpackage(dir_posix: str, sub: str, ctx: ResolverContext) -> str | None:- """Resolve ``sub`` as a sub-package nested inside a workspace member.-- Some packages ship sub-packages inside their own tree without being- separate workspace members (solid's ``packages/solid/web``, ``store``,- etc.), each with its own ``package.json`` and entry point, resolved- relative to itself rather than under the outer package's ``src``/``lib``/- ``dist`` roots. Mirrors the bare-package resolution above (exports- field, then ``index``, then ``main``/``module``, then a source-root- ``index``), rooted one level deeper at ``<dir_posix>/<sub>``.-- Reached only after every probe on the outer package has already failed,- so this can only turn an unresolved import into a real file -- it never- competes with a specifier that already resolves.- """- if ctx.repo_path is None:- return None- sub_dir = f"{dir_posix}/{sub}"- sub_pkg_data = _read_sub_package_manifest(ctx.repo_path, sub_dir)- if sub_pkg_data is None:- return None-- exports_map = _build_exports_map(sub_pkg_data)- targets = _match_export_key("", exports_map) if exports_map else None- for target in targets or ():- if target.endswith(_DECLARATION_SUFFIXES):- continue- cand = _probe_path(f"{sub_dir}/{target.lstrip('./')}", ctx.path_set)- if cand is not None:- return cand-- cand = _probe_path(f"{sub_dir}/index", ctx.path_set)- if cand is not None:- return cand- main = (- sub_pkg_data.get("module")- if isinstance(sub_pkg_data.get("module"), str)- else (sub_pkg_data.get("main") if isinstance(sub_pkg_data.get("main"), str) else None)- )- if isinstance(main, str):- cand = _probe_path(f"{sub_dir}/{main.lstrip('./')}", ctx.path_set)- if cand is not None:- return cand- for source_root in ("src", "lib"):- cand = _probe_path(f"{sub_dir}/{source_root}/index", ctx.path_set)- if cand is not None:- return cand- return None---def resolve_via_workspaces(module_path: str, ctx: ResolverContext) -> str | None:- """Resolve a bare specifier (``@scope/pkg`` or ``@scope/pkg/sub/file``)- against the workspace map. Honours each workspace's ``exports``- subpath map (Node.js spec) before falling back to a ``<pkg>/<subpath>``- probe so plain monorepo layouts without ``exports`` keep working.- Returns a repo-relative path or None.- """- info = get_or_build_workspace_info(ctx)- if not info:- return None-- # Match the longest package-name prefix. ``@scope/pkg/sub/x`` should bind- # ``@scope/pkg`` and resolve ``sub/x`` under that workspace's dir.- best_name: str | None = None- for name in info:- if (module_path == name or module_path.startswith(name + "/")) and (- best_name is None or len(name) > len(best_name)- ):- best_name = name- if best_name is None:- return None-- pkg = info[best_name]- dir_posix: str = pkg["dir"]- exports_map: dict[str, tuple[str, ...]] = pkg["exports"]- sub = module_path[len(best_name) :].lstrip("/")-- targets = _match_export_key(sub, exports_map) if exports_map else None-- def probe_target(target: str) -> str | None:- # Targets are package-relative ("./src/lib/foo.ts"). Strip the- # leading "./" and join with the package dir to get a repo path.- return _probe_path(f"{dir_posix}/{target.lstrip('./')}", ctx.path_set)-- def spare_export_target() -> str | None:- """A candidate past the ranked one, for when nothing else answered.-- Kept behind every pre-existing probe so this can only fill a specifier- that resolved to nothing: a package naming its sources under a- condition no fixed list ranks is unreachable otherwise, but reordering- would move imports that already bind, which is a different change.-- A declaration file is never taken here. It carries no bodies, so- binding one as an entry resolves every call through it to a signature- — worse than the external node it would replace, which claims nothing.- """- for target in (targets or ())[1:]:- if target.endswith(_DECLARATION_SUFFIXES):- continue- resolved = probe_target(target)- if resolved is not None:- return resolved- return None-- def built_export_source() -> str | None:- # Last, so it only fills a specifier nothing else bound: every- # candidate names build output absent from the checkout.- checked_in = get_checked_in_builds(ctx)- for target in targets or ():- resolved = _built_source(dir_posix, target, ctx.path_set, checked_in)- if resolved is not None:- return resolved- return None-- # 1) ``exports`` field — the package's authoritative subpath map.- if targets:- resolved = probe_target(targets[0])- if resolved is not None:- return resolved-- # 2) Bare-package fallback — no ``exports[.]`` entry: try index.*,- # then ``main``/``module`` from package.json, then the entries a- # package publishing only from a build directory leaves reachable.- if not sub:- cand = _probe_path(f"{dir_posix}/index", ctx.path_set)- if cand is not None:- return cand- main = pkg.get("main")- if isinstance(main, str):- cand = _probe_path(f"{dir_posix}/{main.lstrip('./')}", ctx.path_set)- if cand is not None:- return cand- cand = spare_export_target()- if cand is not None:- return cand- for source_root in ("src", "lib"):- cand = _probe_path(f"{dir_posix}/{source_root}/index", ctx.path_set)- if cand is not None:- return cand- return built_export_source()-- # 3) Subpath fallback — packages without ``exports`` (plain monorepo- # layouts): try ``<pkg>/<sub>`` directly, then under common source- # roots (``src``, ``lib``, ``dist``) so the resolver still finds- # files in packages that publish from a build directory.- direct = _probe_path(f"{dir_posix}/{sub}", ctx.path_set)- if direct is not None:- return direct- for src_root in ("src", "lib", "dist"):- cand = _probe_path(f"{dir_posix}/{src_root}/{sub}", ctx.path_set)- if cand is not None:- return cand- cand = spare_export_target() or built_export_source()- if cand is not None:- return cand-- # 4) Nested sub-package fallback — ``sub`` may itself be a package with- # its own ``package.json``, not a path under the outer package's layout.- return _resolve_nested_subpackage(dir_posix, sub, ctx)---# ----------------------------------------------------------------------------# TsWorkspaceIndex — aggregated workspace view consumed by the dead-code-# analyzer (exports-wildcard entry points), the resolver, and any future-# pass that needs to know "what does the workspace publish?".-# ------------------------------------------------------------------------------@dataclass-class TsWorkspaceIndex:- """Aggregated TypeScript/JavaScript workspace metadata.-- ``packages`` mirrors :func:`build_workspace_info` — kept here so a- single object carries every workspace fact the rest of the pipeline- needs. ``exports_entry_paths`` is the set of repo-relative source- files that any workspace package's ``package.json`` ``exports`` map- resolves to (including wildcards expanded against ``ctx.path_set``).- These files are *the* public surface of the monorepo — flagging them- as unreachable just because nothing inside the repo imports them is- a false positive, since downstream consumers reach them via the- package boundary the analyzer can't observe.- """-- packages: dict[str, dict[str, Any]] = field(default_factory=dict)- exports_entry_paths: set[str] = field(default_factory=set)- # Files any ``package.json`` in the repo (workspace member or not) names as- # where the package starts: ``bin``, ``main``/``module``, ``exports["."]``.- manifest_entry_paths: set[str] = field(default_factory=set)---def _expand_exports_wildcard(- target: str, exports_pattern: str, pkg_dir: str, path_set: set[str]-) -> set[str]:- """Return every concrete source file matching a wildcard exports target.-- ``exports_pattern`` is the key like ``"./locales/*"``; ``target`` is- the right-hand side like ``"./src/locales/*.ts"``. The function- interprets ``*`` as ``[^/]*`` (single path segment, Node spec) and- enumerates ``path_set`` entries under ``pkg_dir`` that match the- expanded prefix/suffix.- """- if "*" not in target:- # Non-wildcard target — just probe the concrete path.- stripped = target.lstrip("./")- resolved = _probe_path(f"{pkg_dir}/{stripped}", path_set)- return {resolved} if resolved is not None else set()- # Decompose ``./src/locales/*.ts`` into prefix=``src/locales/`` and- # suffix=``.ts``. The Node spec only allows one ``*`` per pattern.- stripped = target.lstrip("./")- prefix, _, suffix = stripped.partition("*")- # Normalized because this is a startswith probe rather than a _probe_path- # lookup — a root package's ``"."`` dir would otherwise make every- # candidate fail the prefix test.- base_prefix = _normalize_repo_rel(f"{pkg_dir}/{prefix}")- matches: set[str] = set()- for candidate in path_set:- if not candidate.startswith(base_prefix):- continue- if suffix and not candidate.endswith(suffix):- continue- # Node.js package exports spec explicitly allows the `*` wildcard- # to match any string including `/` (directory boundaries).- # We previously incorrectly rejected paths spanning directories.- matches.add(candidate)- return matches---# Build output a package.json may point at, and the source extensions tsc-# compiles to it. Only the unambiguous ``X.js``/``X.d.ts`` ← ``X.ts`` shape is-# mapped. Shortcut: the build dir is the conventional one, not the tsconfig-# ``outDir``/``rootDir``; reading those means a JSONC ``extends`` walk.-_BUILD_OUTPUT_JS = re.compile(r"^(?:dist|build|lib|out)/(.+?)(?:\.[mc]?js|\.d\.[mc]?ts)$")-_BUILD_SOURCE_EXTENSIONS: tuple[str, ...] = (".ts", ".tsx", ".mts", ".js")---def _manifest_targets(pkg_data: dict) -> tuple[list[str], tuple[str, ...]]:- """``(start targets, exports["."] targets)`` one ``package.json`` names.-- Start targets are every ``bin`` target (string or map), ``main`` and- ``module``; the export targets come best first, declaration files skipped.- """- bin_ = pkg_data.get("bin")- bins = bin_.values() if isinstance(bin_, dict) else (bin_,)- starts = [- t for t in (*bins, pkg_data.get("main"), pkg_data.get("module")) if isinstance(t, str)- ]- exports = pkg_data.get("exports")- # A conditions-only object (``{"import": ..., "require": ...}``) is ``"."``.- if isinstance(exports, dict) and any(str(k).startswith(".") for k in exports):- exports = exports.get(".")- ordered = _ordered_export_targets(exports) if exports is not None else ()- return starts, tuple(t for t in ordered if not t.endswith(_DECLARATION_SUFFIXES))---def _built_output(pkg_dir: str, target: str) -> tuple[str, re.Match[str]] | None:- """``(repo-relative path, match)`` when *target* names build output inside the repo."""- rel = target.removeprefix("./")- built = _BUILD_OUTPUT_JS.match(rel)- if built is None:- return None- path = _normalize_repo_rel(f"{pkg_dir}/{rel}")- # ``..`` in a manifest must not send the on-disk check outside the repo.- if path == ".." or path.startswith("../"):- return None- return path, built---def _named_build_outputs(manifests: list[tuple[str, dict]]) -> set[str]:- """Every in-repo build-output path the manifests' targets name, subpath exports included."""- named: set[str] = set()- for pkg_dir, data in manifests:- starts, exports = _manifest_targets(data)- subpaths = (t for targets in _build_exports_map(data).values() for t in targets)- for target in (*starts, *exports, *subpaths):- built = _built_output(pkg_dir, target)- if built is not None:- named.add(built[0])- return named---def checked_in_builds(- repo_path: Path | None, manifests: list[tuple[str, dict]], path_set: set[str]-) -> frozenset[str]:- """Build outputs the manifests name that exist on disk and are not gitignored.-- A committed build is part of the checkout; a gitignored local build is- not. One ``git check-ignore --stdin`` call answers for the whole repo, so- nested ``.gitignore`` files count; outside a git work tree (or without- git) every existing file counts as checked in.- """- if repo_path is None:- return frozenset()- return _git_checked_in(repo_path, _named_build_outputs(manifests) - path_set)---def _git_checked_in(repo_path: Path, paths: set[str]) -> frozenset[str]:- """The *paths* that exist on disk and are not gitignored, in one git call."""- on_disk = {path for path in paths if (repo_path / path).is_file()}- if not on_disk:- return frozenset()- try:- verdict = subprocess.run(- ["git", "-C", str(repo_path), "check-ignore", "-z", "--stdin"],- # Bytes, NUL-separated: a text-mode pipe on Windows writes CRLF,- # and git would read each path with a trailing CR.- input="\0".join(sorted(on_disk)).encode("utf-8") + b"\0",- capture_output=True,- timeout=30,- )- # Exit 1 = none ignored; 128 = not a work tree (nothing is ignored).- out = verdict.stdout.decode("utf-8", errors="replace") if verdict.returncode == 0 else ""- ignored = set(filter(None, out.split("\0")))- except (OSError, subprocess.SubprocessError):- ignored = set()- return frozenset(on_disk - ignored)---@dataclass-class _CheckedInBuilds:- """``path in self``: is this build output part of the checkout?-- Seeded with the manifest-named outputs the batched check found checked in;- any other path (a wildcard export's concrete output) is asked on first use,- which costs a git call only when that file exists on disk.- """-- repo_path: Path | None- verdict: dict[str, bool]-- def __contains__(self, path: object) -> bool:- if not isinstance(path, str):- return False- if path not in self.verdict:- self.verdict[path] = self.repo_path is not None and bool(- _git_checked_in(self.repo_path, {path})- )- return self.verdict[path]---def get_checked_in_builds(ctx: ResolverContext) -> _CheckedInBuilds:- """Memoized per resolver context, shared by the entry index and the resolver."""- cached = getattr(ctx, "_ts_checked_in_builds", None)- if cached is not None:- return cached- checked = checked_in_builds(ctx.repo_path, _parsed_package_jsons(ctx), ctx.path_set)- builds = _CheckedInBuilds(ctx.repo_path, dict.fromkeys(checked, True))- ctx._ts_checked_in_builds = builds # type: ignore[attr-defined]- return builds---def _built_source(- pkg_dir: str, target: str, path_set: set[str], checked_in: Container[str]-) -> str | None:- """The source a build-output *target* was compiled from, when that output is not checked in.-- ``dist|build|lib|out/X.(m|c)js`` (or ``X.d.(m|c)ts``) maps to- ``src/X.(ts|tsx|mts|js)``. A committed build is the file itself, and- remapping it would name a file the package does not run. Exact hits only,- so an ambiguous source never stands in for the build.- """- built = _built_output(pkg_dir, target)- if built is None:- return None- base = _normalize_repo_rel(f"{pkg_dir}/src/{built[1].group(1)}")- hit = next((base + ext for ext in _BUILD_SOURCE_EXTENSIONS if base + ext in path_set), None)- return hit if hit is not None and built[0] not in checked_in else None---def probe_manifest_target(- pkg_dir: str, target: str, path_set: set[str], checked_in: Container[str]-) -> str | None:- """The indexed file a ``package.json`` target names, reading built output as its source.-- *checked_in* comes from :func:`checked_in_builds` / :func:`get_checked_in_builds`.- """- if target.endswith(_DECLARATION_SUFFIXES):- return None # a declaration never starts a package, committed or not- hit = _probe_path(f"{pkg_dir}/{target.removeprefix('./')}", path_set)- return hit if hit is not None else _built_source(pkg_dir, target, path_set, checked_in)---def manifest_entry_paths(- pkg_dir: str, pkg_data: dict, path_set: set[str], checked_in: Container[str] = frozenset()-) -> set[str]:- """Files one ``package.json`` declares as where it starts.-- Every ``bin`` target (string or map), ``main`` and ``module``, and the- first ``exports["."]`` target that resolves. Declaration files are skipped.- """- starts, exports = _manifest_targets(pkg_data)- found = {- hit- for t in starts- if (hit := probe_manifest_target(pkg_dir, t, path_set, checked_in)) is not None- }- for target in exports:- hit = probe_manifest_target(pkg_dir, target, path_set, checked_in)- if hit is not None:- found.add(hit)- break- return found---def build_ts_workspace_index(ctx: ResolverContext) -> TsWorkspaceIndex:- """Build the workspace index for *ctx*.-- Idempotent — safe to call multiple times. Reads the workspace- metadata via :func:`build_workspace_info` and resolves every- ``exports`` target (concrete and wildcard) against ``ctx.path_set``- so a file's reachability through the package boundary is observable- to downstream passes.- """- packages = get_or_build_workspace_info(ctx)- entries: set[str] = set()- path_set = ctx.path_set- for _name, pkg in packages.items():- dir_posix: str = pkg["dir"]- exports_map: dict[str, tuple[str, ...]] = pkg.get("exports") or {}- for pattern, targets in exports_map.items():- # The ranked target only. The spare candidates exist to bind an- # import the resolver would otherwise drop; letting them widen the- # published-entry set would suppress dead-code findings instead,- # which is a different change and is not what was measured here.- entries.update(- _expand_exports_wildcard(targets[0], pattern, dir_posix, path_set)- )- # ``main``/``module`` shorthand — package's primary entry.- main = pkg.get("main")- if isinstance(main, str):- resolved = _probe_path(f"{dir_posix}/{main.lstrip('./')}", path_set)- if resolved is not None:- entries.add(resolved)- checked_in = get_checked_in_builds(ctx)- declared: set[str] = set()- for pkg_dir, data in _parsed_package_jsons(ctx):- declared |= manifest_entry_paths(pkg_dir, data, path_set, checked_in)- return TsWorkspaceIndex(- packages=packages, exports_entry_paths=entries, manifest_entry_paths=declared- )---def get_or_build_ts_index(ctx: ResolverContext) -> TsWorkspaceIndex:- """Memoized accessor — builds the index once per resolver context."""- cached = getattr(ctx, "_ts_workspace_index", None)- if cached is not None:- return cached- index = build_ts_workspace_index(ctx)- ctx._ts_workspace_index = index # type: ignore[attr-defined]- return index---# ----------------------------------------------------------------------------# MDX import scan + vitest config scan — entry-point sources the static-# graph never observes through the TS/JS parser path.-# -----------------------------------------------------------------------------_MDX_IMPORT_RE = re.compile(- r"""import\s+- (?:type\s+)?- (?:\{[^}]*\}|\*\s+as\s+\w+|\w+(?:\s*,\s*\{[^}]*\})?)- \s+from\s+['"]([^'"]+)['"]""",- re.VERBOSE,-)--_VITEST_INCLUDE_RE = re.compile(- r"""include\s*:\s*\[\s*((?:['"][^'"]+['"]\s*,?\s*)+)\]""",- re.MULTILINE,-)-_VITEST_STRING_RE = re.compile(r"""['"]([^'"]+)['"]""")---def find_mdx_import_targets(ctx: ResolverContext) -> set[str]:- """Return repo-relative paths reached only via ``import`` in MDX/MD files.-- React-component libraries published as documentation (``.mdx`` files- that embed live TSX components) hide their consumers from the static- TS parser because nothing in this repo parses MDX. The regex below- is intentionally narrow: ``import … from '...'``. Anything fancier- (JSX-in-MDX components, MDX-specific shorthand) falls out and gets- treated as no-edge — better than a parser dependency.- """- if ctx.repo_path is None:- return set()- from .typescript import resolve_ts_js_import-- targets: set[str] = set()- for mdx in _get_repo_scan(ctx).mdx_files:- try:- text = mdx.read_text(encoding="utf-8", errors="ignore")- except Exception:- continue- try:- rel = mdx.relative_to(ctx.repo_path).as_posix()- except ValueError:- continue- for match in _MDX_IMPORT_RE.finditer(text):- spec = match.group(1)- # Pre-normalise relative specifiers so ``../foo`` resolves- # against ``ctx.path_set`` — the underlying TS resolver- # leaves ``..`` segments unflattened and relies on the- # parser layer to do this, which doesn't run for MDX.- if spec.startswith("."):- import os as _os- joined = _os.path.normpath(_os.path.join(_os.path.dirname(rel), spec))- joined = joined.replace("\\", "/")- # Re-express as a relative spec rooted at the repo so- # ``resolve_ts_js_import`` treats it as relative.- spec_for_resolve = "./" + joined- resolved = resolve_ts_js_import(spec_for_resolve, "_root_.mdx", ctx)- else:- resolved = resolve_ts_js_import(spec, rel, ctx)- if resolved is None:- continue- if resolved.startswith("external:"):- continue- targets.add(resolved)- return targets---def _vitest_glob_to_regex(glob: str) -> re.Pattern[str]:- """Translate a vitest/minimatch glob into a regex matching repo paths.-- ``**`` matches zero-or-more path segments (including empty); a single- ``*`` matches one path segment (no ``/``); ``?`` matches a single- non-``/`` char. Anything else is escaped. Python's ``fnmatch`` treats- ``*`` as "any chars including ``/``", which collapses ``foo/**/x``- into a too-strict regex that misses ``foo/x`` — hence this- bespoke translator.- """- out: list[str] = ["^"]- i = 0- while i < len(glob):- c = glob[i]- if c == "*":- if i + 1 < len(glob) and glob[i + 1] == "*":- # ``**`` — zero or more path segments. Consume optional- # trailing ``/`` so ``foo/**/bar`` matches ``foo/bar``.- i += 2- if i < len(glob) and glob[i] == "/":- out.append("(?:.*/)?")- i += 1- else:- out.append(".*")- else:- out.append("[^/]*")- i += 1- elif c == "?":- out.append("[^/]")- i += 1- elif c in ".+()|^$[]{}\\":- out.append("\\" + c)- i += 1- else:- out.append(c)- i += 1- out.append("$")- return re.compile("".join(out))---def find_vitest_include_targets(ctx: ResolverContext) -> set[str]:- """Return repo-relative source files matching vitest ``include`` globs.-- Belt-and-suspenders alongside the ``*.test.*`` never-flag pattern —- catches custom test layouts like ``runtime-tests/**`` that escape- the filename convention.- """- if ctx.repo_path is None:- return set()-- targets: set[str] = set()- for cfg in _get_repo_scan(ctx).vitest_configs:- try:- text = cfg.read_text(encoding="utf-8", errors="ignore")- except Exception:- continue- cfg_dir = cfg.parent- for inc_match in _VITEST_INCLUDE_RE.finditer(text):- for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):- glob_pat = str_match.group(1)- # Resolve glob relative to the config file's directory.- base = (cfg_dir / glob_pat).as_posix()- try:- rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()- except ValueError:- continue- regex = _vitest_glob_to_regex(rel_glob)- for candidate in ctx.path_set:- if regex.match(candidate):- targets.add(candidate)- return targets---# ----------------------------------------------------------------------------# Grafana plugin entry detection-# -----------------------------------------------------------------------------_GRAFANA_ENTRY_EXTS: tuple[str, ...] = (- ".ts", ".tsx", ".js", ".jsx",-)---def find_grafana_plugin_targets(ctx: ResolverContext) -> set[str]:- """Return repo-relative paths for Grafana plugin module entry points.-- Grafana plugins are loaded by convention: Grafana reads ``plugin.json``- and loads ``module.ts`` / ``module.tsx`` / ``module.js`` / ``module.jsx``- located in the same directory or in a sibling ``src/`` directory.- """- if ctx.repo_path is None:- return set()-- targets: set[str] = set()- for plugin_file in _get_repo_scan(ctx).plugin_jsons:- try:- rel_dir = plugin_file.parent.relative_to(ctx.repo_path).as_posix()- except ValueError:- continue-- dir_prefix = "" if rel_dir == "." else f"{rel_dir}/"- candidate_prefixes = (dir_prefix, f"{dir_prefix}src/")-- for prefix in candidate_prefixes:- for ext in _GRAFANA_ENTRY_EXTS:- candidate = f"{prefix}module{ext}"- if candidate in ctx.path_set:- targets.add(candidate)-- return targets---# ----------------------------------------------------------------------------# npm-script entry detection-# -----------------------------------------------------------------------------# Source-file extensions a script might point at directly. Includes the-# ``.mts``/``.cts`` family because hono/zod benchmarks favour them.-_NPM_SCRIPT_SOURCE_EXTS: tuple[str, ...] = (- ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts",-)--# Runner tokens that take a single source path as their first non-flag-# positional. Detection is positional rather than name-based so we don't-# have to track shell-syntax quirks (``--`` separators, env-var prefixes,-# multi-command ``&&`` chains).-_NPM_SCRIPT_RUNNERS: frozenset[str] = frozenset({- "tsx", "ts-node", "ts-node-esm", "vite-node", "swc-node",- "node", "deno", "bun",- "esbuild", "rollup", "vite", "webpack",-})--# Sub-package names that conventionally hold ad-hoc / experimental-# scripts — bench harnesses, tree-shaking experiments, examples, demos.-# Their source files are typically passed as CLI arguments at runtime-# (``rollup -c --input X.ts``, ``tsx index.ts <file>``) rather than-# imported by anything in the static graph. Treating them as entry-# points matches how a human reads the repo: maintained code, not dead.-_EXPERIMENT_DIR_NAMES: frozenset[str] = frozenset({- "bench", "benches", "benchmark", "benchmarks",- "treeshake", "treeshaking",- "example", "examples",- "demo", "demos",- "sample", "samples",- "playground", "playgrounds",- "scratch",- # ``scripts/`` is conventionally ad-hoc tooling invoked via npm- # commands or pre/post-commit hooks — never imported by application- # code, but always maintained. Treat the whole dir as live.- "scripts",-})---def _iter_script_tokens(script: str) -> list[str]:- """Split a script command on whitespace and shell separators.-- Strips quotes off individual tokens but does NOT honour shell quoting- (``"a b"`` becomes two tokens) — matches Node's npm script semantics- where commands are passed to ``sh -c`` and we only care about token- *shape*, not faithful argv reconstruction.- """- # Replace shell chain operators with spaces so each chunk parses.- cleaned = re.sub(r"&&|\|\||;|\|", " ", script)- return [tok.strip("'\"") for tok in cleaned.split() if tok.strip("'\"")]---def find_npm_script_entry_targets(ctx: ResolverContext) -> set[str]:- """Return repo-relative source files referenced by ``package.json`` scripts.-- Hono's ``benchmarks/{jsx,routers,query-param}/**`` and zod's- ``packages/{bench,treeshake,tsc}/**`` are invoked as ``tsx <path>`` /- ``bun run <path>`` / ``rollup -c <path>`` from their package's- ``scripts.*`` — never imported by the main entry graph, so they read- as ``in_degree==0`` despite being live, maintained code. This scan- surfaces those paths as entry points.-- Also picks up quoted glob arguments (prettier / eslint / format-check- style ``"src/**/*.ts"``) so files only ever consumed by build tooling- aren't flagged dead — they're maintained code, just not application- code.- """- if ctx.repo_path is None:- return set()-- path_set = ctx.path_set- targets: set[str] = set()-- # Build a quick "directory → files under it" index lazily by scanning- # ``path_set`` once. Cheap: a few thousand strings at most.- dirs_in_repo: dict[str, list[str]] = {}- for p in path_set:- idx = 0- while True:- slash = p.find("/", idx)- if slash == -1:- break- dirs_in_repo.setdefault(p[:slash], []).append(p)- idx = slash + 1-- for pkg_rel, data in _parsed_package_jsons(ctx):- scripts = data.get("scripts") or {}- if not isinstance(scripts, dict):- continue- pkg_prefix = "" if pkg_rel in ("", ".") else f"{pkg_rel}/"-- # Experimental sub-package convention: ``packages/bench``,- # ``packages/treeshake``, ``examples/`` style directories invoke- # their source files via runtime-supplied CLI arguments- # (``rollup --input``, ``import.meta.resolve``) that no static- # scan can resolve. The presence of an ``experimental`` directory- # name + a ``package.json`` is the human-meaningful "this is a- # maintained script bag" signal — mark every source file under- # it as an entry. Honour ``"private": true`` *or* the directory- # name match; the conventional names are the load-bearing signal.- pkg_dir_name = posixpath.basename(pkg_rel).lower()- if pkg_dir_name in _EXPERIMENT_DIR_NAMES:- dir_files = dirs_in_repo.get(pkg_rel) if pkg_rel else None- if dir_files:- for f in dir_files:- if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):- targets.add(f)-- for command in scripts.values():- if not isinstance(command, str):- continue- tokens = _iter_script_tokens(command)- for token in tokens:- if not token or token.startswith("-"):- continue- # Source file with a known extension — try resolving as a- # path relative to the package directory. Glob meta-chars- # are handled by the next branch.- lower = token.lower()- if (- any(lower.endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS)- and "*" not in token- and "?" not in token- ):- candidate = (pkg_prefix + token).lstrip("./")- candidate = re.sub(r"\\", "/", candidate)- # Normalise ``a/./b`` and ``a/../b`` segments.- parts: list[str] = []- for seg in candidate.split("/"):- if seg in ("", "."):- continue- if seg == "..":- if parts:- parts.pop()- continue- parts.append(seg)- norm = "/".join(parts)- if norm in path_set:- targets.add(norm)- continue- # Glob argument (prettier / eslint / format scope) — only- # expand when the token has a glob meta-character and- # contains a slash, so plain runner names like ``tsc`` and- # plain flags don't get misinterpreted.- if ("*" in token or "?" in token) and "/" in token:- rel_glob = (pkg_prefix + token).lstrip("./")- # Strip stray leading ``./`` left over from npm conv.- if rel_glob.startswith("./"):- rel_glob = rel_glob[2:]- try:- regex = _vitest_glob_to_regex(rel_glob)- except re.error:- continue- for candidate in path_set:- if regex.match(candidate):- targets.add(candidate)- continue- # Bare directory token (``eslint src runtime-tests build``)- # — mark every source file inside as live. Constrained to- # directories that actually exist in ``path_set`` to avoid- # treating arbitrary identifiers (``run``, ``--``) as dirs.- if "/" not in token and token in (- "src", "lib", "app", "test", "tests", "scripts",- "benchmarks", "perf-measures", "runtime-tests", "build",- "examples",- ):- dir_rel = pkg_prefix + token- files = dirs_in_repo.get(dir_rel.rstrip("/"))- if files:- for f in files:- if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):- targets.add(f)-- # Catch experimental sub-directories nested inside a package — e.g.- # ``packages/tsc/bench/*.ts``, ``examples/*/index.ts`` — where the- # parent ``package.json`` doesn't itself match the experimental- # convention but a descendant directory does. We only scan dirs that- # already appear in ``dirs_in_repo`` (i.e., that hold source files),- # so the pass is bounded by what's in ``path_set``.- for dir_rel, files in dirs_in_repo.items():- last_seg = dir_rel.rsplit("/", 1)[-1].lower()- if last_seg not in _EXPERIMENT_DIR_NAMES:- continue- for f in files:- if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):- targets.add(f)- return targetsdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/__init__.pynew file mode 100644index 000000000..b888c0a7d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/__init__.py@@ -0,0 +1,97 @@+"""npm/yarn/pnpm workspace package resolution for TypeScript imports.++Maps each workspace package name to its directory so ``import x from+"@myorg/foo"`` binds the intra-repo file instead of an ``external:`` node.+Subpath imports honour the package's Node ``exports`` map, falling back to a+``<pkg>/<subpath>`` probe for plain monorepo layouts.++Every submodule name is re-exported here. Patch a name where it is looked up:+a patch on this package does not reach lookups inside the submodules.+"""++# ruff: noqa: F401++from __future__ import annotations++import contextlib+import json+import posixpath+import re+import subprocess+from collections.abc import Container+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, Any++from ..pnpm_workspace import read_pnpm_workspace_patterns+from .builds import (+ _BUILD_OUTPUT_JS,+ _BUILD_SOURCE_EXTENSIONS,+ _built_output,+ _built_source,+ _CheckedInBuilds,+ _git_checked_in,+ _manifest_targets,+ _named_build_outputs,+ checked_in_builds,+ get_checked_in_builds,+ manifest_entry_paths,+ probe_manifest_target,+)+from .exports import (+ _CONDITION_PRIORITY,+ _DECLARATION_SUFFIXES,+ _build_exports_map,+ _flatten_export_value,+ _match_export_key,+ _ordered_export_targets,+)+from .index import (+ TsWorkspaceIndex,+ _expand_exports_wildcard,+ build_ts_workspace_index,+ get_or_build_ts_index,+)+from .members import (+ _expand_member_dirs,+ _read_workspace_declaration,+ _WorkspaceDeclaration,+ build_workspace_info,+ build_workspace_map,+ get_or_build_workspace_info,+ read_workspaces_field,+)+from .paths import (+ _PROBE_EXTENSIONS,+ _normalize_repo_rel,+ _probe_path,+)+from .resolve import (+ _read_sub_package_manifest,+ _resolve_nested_subpackage,+ _WorkspaceProbe,+ resolve_via_workspaces,+)+from .scan import (+ _SCAN_PRUNE_DIRS,+ _VITEST_CONFIG_NAMES,+ _get_repo_scan,+ _parsed_package_jsons,+ _RepoFileScan,+ _scan_repo_files,+)+from .tool_configs import (+ _EXPERIMENT_DIR_NAMES,+ _GRAFANA_ENTRY_EXTS,+ _MDX_IMPORT_RE,+ _NPM_SCRIPT_RUNNERS,+ _NPM_SCRIPT_SOURCE_EXTS,+ _VITEST_INCLUDE_RE,+ _VITEST_STRING_RE,+ _iter_script_tokens,+ _vitest_glob_to_regex,+ find_grafana_plugin_targets,+ find_mdx_import_targets,+ find_npm_script_entry_targets,+ find_vitest_include_targets,+)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/builds.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/builds.pynew file mode 100644index 000000000..c941aa3dc--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/builds.py@@ -0,0 +1,168 @@+"""Build output named by ``package.json`` and the sources it was compiled from.++Only the unambiguous ``X.js``/``X.d.ts`` from ``src/X.ts`` shape is mapped, under+the conventional build dirs rather than tsconfig ``outDir`` (that needs a JSONC+``extends`` walk). A committed build is the file itself and is never remapped.+"""++from __future__ import annotations++import re+import subprocess+from collections.abc import Container+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING++from .exports import _DECLARATION_SUFFIXES, _build_exports_map, _ordered_export_targets+from .paths import _normalize_repo_rel, _probe_path+from .scan import _parsed_package_jsons++if TYPE_CHECKING:+ from ..context import ResolverContext+++_BUILD_OUTPUT_JS = re.compile(r"^(?:dist|build|lib|out)/(.+?)(?:\.[mc]?js|\.d\.[mc]?ts)$")+_BUILD_SOURCE_EXTENSIONS: tuple[str, ...] = (".ts", ".tsx", ".mts", ".js")+++def _manifest_targets(pkg_data: dict) -> tuple[list[str], tuple[str, ...]]:+ """``(bin/main/module targets, exports["."] targets best first, declarations skipped)``."""+ bin_ = pkg_data.get("bin")+ bins = bin_.values() if isinstance(bin_, dict) else (bin_,)+ starts = [+ t for t in (*bins, pkg_data.get("main"), pkg_data.get("module")) if isinstance(t, str)+ ]+ exports = pkg_data.get("exports")+ # A conditions-only object (``{"import": ..., "require": ...}``) is ``"."``.+ if isinstance(exports, dict) and any(str(k).startswith(".") for k in exports):+ exports = exports.get(".")+ ordered = _ordered_export_targets(exports) if exports is not None else ()+ return starts, tuple(t for t in ordered if not t.endswith(_DECLARATION_SUFFIXES))+++def _built_output(pkg_dir: str, target: str) -> tuple[str, re.Match[str]] | None:+ """``(repo-relative path, match)`` when *target* names build output inside the repo."""+ rel = target.removeprefix("./")+ built = _BUILD_OUTPUT_JS.match(rel)+ if built is None:+ return None+ path = _normalize_repo_rel(f"{pkg_dir}/{rel}")+ # ``..`` in a manifest must not send the on-disk check outside the repo.+ if path == ".." or path.startswith("../"):+ return None+ return path, built+++def _named_build_outputs(manifests: list[tuple[str, dict]]) -> set[str]:+ """Every in-repo build-output path the manifests' targets name, subpath exports included."""+ named: set[str] = set()+ for pkg_dir, data in manifests:+ starts, exports = _manifest_targets(data)+ subpaths = (t for targets in _build_exports_map(data).values() for t in targets)+ for target in (*starts, *exports, *subpaths):+ built = _built_output(pkg_dir, target)+ if built is not None:+ named.add(built[0])+ return named+++def checked_in_builds(+ repo_path: Path | None, manifests: list[tuple[str, dict]], path_set: set[str]+) -> frozenset[str]:+ """Build outputs the manifests name that exist on disk and are not gitignored.++ Outside a git work tree every existing file counts as checked in.+ """+ if repo_path is None:+ return frozenset()+ return _git_checked_in(repo_path, _named_build_outputs(manifests) - path_set)+++def _git_checked_in(repo_path: Path, paths: set[str]) -> frozenset[str]:+ """The *paths* that exist on disk and are not gitignored, in one git call."""+ on_disk = {path for path in paths if (repo_path / path).is_file()}+ if not on_disk:+ return frozenset()+ try:+ verdict = subprocess.run(+ ["git", "-C", str(repo_path), "check-ignore", "-z", "--stdin"],+ # Bytes: a text-mode pipe on Windows writes CRLF into each path.+ input="\0".join(sorted(on_disk)).encode("utf-8") + b"\0",+ capture_output=True,+ timeout=30,+ )+ # Exit 1 = none ignored; 128 = not a work tree (nothing is ignored).+ out = verdict.stdout.decode("utf-8", errors="replace") if verdict.returncode == 0 else ""+ ignored = set(filter(None, out.split("\0")))+ except (OSError, subprocess.SubprocessError):+ ignored = set()+ return frozenset(on_disk - ignored)+++@dataclass+class _CheckedInBuilds:+ """``path in self``: is this build output checked in? Unseeded paths are asked on first use."""++ repo_path: Path | None+ verdict: dict[str, bool]++ def __contains__(self, path: object) -> bool:+ if not isinstance(path, str):+ return False+ if path not in self.verdict:+ self.verdict[path] = self.repo_path is not None and bool(+ _git_checked_in(self.repo_path, {path})+ )+ return self.verdict[path]+++def get_checked_in_builds(ctx: ResolverContext) -> _CheckedInBuilds:+ """Memoized per resolver context, shared by the entry index and the resolver."""+ cached = getattr(ctx, "_ts_checked_in_builds", None)+ if cached is not None:+ return cached+ checked = checked_in_builds(ctx.repo_path, _parsed_package_jsons(ctx), ctx.path_set)+ builds = _CheckedInBuilds(ctx.repo_path, dict.fromkeys(checked, True))+ ctx._ts_checked_in_builds = builds # type: ignore[attr-defined]+ return builds+++def _built_source(+ pkg_dir: str, target: str, path_set: set[str], checked_in: Container[str]+) -> str | None:+ """The source a build-output *target* was compiled from, when that output is not checked in."""+ built = _built_output(pkg_dir, target)+ if built is None:+ return None+ base = _normalize_repo_rel(f"{pkg_dir}/src/{built[1].group(1)}")+ hit = next((base + ext for ext in _BUILD_SOURCE_EXTENSIONS if base + ext in path_set), None)+ return hit if hit is not None and built[0] not in checked_in else None+++def probe_manifest_target(+ pkg_dir: str, target: str, path_set: set[str], checked_in: Container[str]+) -> str | None:+ """The indexed file a ``package.json`` target names, reading built output as its source."""+ if target.endswith(_DECLARATION_SUFFIXES):+ return None # a declaration never starts a package, committed or not+ hit = _probe_path(f"{pkg_dir}/{target.removeprefix('./')}", path_set)+ return hit if hit is not None else _built_source(pkg_dir, target, path_set, checked_in)+++def manifest_entry_paths(+ pkg_dir: str, pkg_data: dict, path_set: set[str], checked_in: Container[str] = frozenset()+) -> set[str]:+ """Files one ``package.json`` starts at: bin/main/module and the first resolving ``exports["."]``."""+ starts, exports = _manifest_targets(pkg_data)+ found = {+ hit+ for t in starts+ if (hit := probe_manifest_target(pkg_dir, t, path_set, checked_in)) is not None+ }+ for target in exports:+ hit = probe_manifest_target(pkg_dir, target, path_set, checked_in)+ if hit is not None:+ found.add(hit)+ break+ return founddiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/exports.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/exports.pynew file mode 100644index 000000000..ff2ce72f6--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/exports.py@@ -0,0 +1,126 @@+"""Node ``exports`` maps: flattening condition objects and matching subpaths."""++from __future__ import annotations++from typing import Any++# Condition collapse order: source first (the ``.ts`` file, not a build), then ESM/default, CJS last.+_CONDITION_PRIORITY: tuple[str, ...] = (+ "source",+ "import",+ "default",+ "node",+ "require",+ "types",+ "browser",+)+++def _flatten_export_value(value: Any) -> str | None:+ """Collapse a Node ``exports`` entry to one target; ``None`` when blocked or unhandled."""+ if isinstance(value, str):+ return value+ if isinstance(value, dict):+ for cond in _CONDITION_PRIORITY:+ inner = value.get(cond)+ if inner is None:+ continue+ flat = _flatten_export_value(inner)+ if flat:+ return flat+ return None+ if isinstance(value, list):+ for item in value:+ flat = _flatten_export_value(item)+ if flat:+ return flat+ return None+++def _ordered_export_targets(value: Any) -> tuple[str, ...]:+ """Every target a Node ``exports`` entry can mean, best first.++ The head is :func:`_flatten_export_value`'s choice. The tail (every other+ leaf, ranked conditions first) covers sources published under a condition+ no fixed list names, such as ``@zod/source``.+ """+ ordered: list[str] = []+ head = _flatten_export_value(value)+ if head is not None:+ ordered.append(head)++ def walk(node: Any) -> None:+ if isinstance(node, str):+ if node not in ordered:+ ordered.append(node)+ elif isinstance(node, list):+ for item in node:+ walk(item)+ elif isinstance(node, dict):+ for cond in _CONDITION_PRIORITY:+ if cond in node:+ walk(node[cond])+ for cond, inner in node.items():+ if cond not in _CONDITION_PRIORITY:+ walk(inner)++ walk(value)+ return tuple(ordered)+++_DECLARATION_SUFFIXES: tuple[str, ...] = (".d.ts", ".d.mts", ".d.cts")+++def _build_exports_map(pkg_data: dict) -> dict[str, tuple[str, ...]]:+ """``{exports_key: (target, ...)}``; a string ``exports`` is ``"."``, keys not starting with ``.`` drop."""+ raw = pkg_data.get("exports")+ if raw is None:+ return {}+ if isinstance(raw, str):+ return {".": (raw,)}+ if not isinstance(raw, dict):+ return {}+ out: dict[str, tuple[str, ...]] = {}+ for key, value in raw.items():+ if not isinstance(key, str) or not key.startswith("."):+ continue+ # A spare candidate alone must not keep a key: it would answer ahead of the fallbacks.+ if _flatten_export_value(value) is None:+ continue+ out[key] = _ordered_export_targets(value)+ return out+++def _match_export_key(+ subpath: str, exports_map: dict[str, tuple[str, ...]]+) -> tuple[str, ...] | None:+ """The candidate targets for *subpath* (``""`` = bare package), best first.++ Exact keys win over wildcards; among wildcards the longest static prefix wins.+ """+ key = "." if subpath == "" else "./" + subpath+ if key in exports_map:+ return exports_map[key]+ best_targets: tuple[str, ...] | None = None+ best_prefix_len = -1+ for pattern, targets in exports_map.items():+ if "*" not in pattern:+ continue+ prefix, _, suffix = pattern.partition("*")+ if not key.startswith(prefix):+ continue+ if suffix and not key.endswith(suffix):+ continue+ captured = (+ key[len(prefix) : len(key) - len(suffix)]+ if suffix+ else key[len(prefix) :]+ )+ if len(prefix) > best_prefix_len:+ # Past the head, a ``*``-less candidate would answer every subpath alike.+ kept = targets[:1] + tuple(t for t in targets[1:] if "*" in t)+ best_targets = tuple(+ t.replace("*", captured, 1) if "*" in t else t for t in kept+ )+ best_prefix_len = len(prefix)+ return best_targetsdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/index.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/index.pynew file mode 100644index 000000000..be6c59ca3--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/index.py@@ -0,0 +1,88 @@+"""``TsWorkspaceIndex``: the files a workspace publishes as entry points."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any++from .builds import get_checked_in_builds, manifest_entry_paths+from .members import get_or_build_workspace_info+from .paths import _normalize_repo_rel, _probe_path+from .scan import _parsed_package_jsons++if TYPE_CHECKING:+ from ..context import ResolverContext+++@dataclass+class TsWorkspaceIndex:+ """Aggregated TypeScript/JavaScript workspace metadata.++ ``exports_entry_paths`` are the files workspace ``exports`` maps publish:+ consumers outside the repo reach them, so they are never unreachable.+ """++ packages: dict[str, dict[str, Any]] = field(default_factory=dict)+ exports_entry_paths: set[str] = field(default_factory=set)+ # Start files any ``package.json`` names, workspace member or not.+ manifest_entry_paths: set[str] = field(default_factory=set)+++def _expand_exports_wildcard(+ target: str, exports_pattern: str, pkg_dir: str, path_set: set[str]+) -> set[str]:+ """Every indexed file an ``exports`` target (``"./src/locales/*.ts"``) matches."""+ if "*" not in target:+ stripped = target.lstrip("./")+ resolved = _probe_path(f"{pkg_dir}/{stripped}", path_set)+ return {resolved} if resolved is not None else set()+ # The Node spec allows one ``*`` per pattern.+ stripped = target.lstrip("./")+ prefix, _, suffix = stripped.partition("*")+ base_prefix = _normalize_repo_rel(f"{pkg_dir}/{prefix}")+ matches: set[str] = set()+ for candidate in path_set:+ if not candidate.startswith(base_prefix):+ continue+ if suffix and not candidate.endswith(suffix):+ continue+ # Per the Node spec ``*`` may span ``/``.+ matches.add(candidate)+ return matches+++def build_ts_workspace_index(ctx: ResolverContext) -> TsWorkspaceIndex:+ """Build the workspace index for *ctx*; idempotent."""+ packages = get_or_build_workspace_info(ctx)+ entries: set[str] = set()+ path_set = ctx.path_set+ for _name, pkg in packages.items():+ dir_posix: str = pkg["dir"]+ exports_map: dict[str, tuple[str, ...]] = pkg.get("exports") or {}+ for pattern, targets in exports_map.items():+ # The ranked target only: spare candidates must not widen the published set.+ entries.update(+ _expand_exports_wildcard(targets[0], pattern, dir_posix, path_set)+ )+ main = pkg.get("main")+ if isinstance(main, str):+ resolved = _probe_path(f"{dir_posix}/{main.lstrip('./')}", path_set)+ if resolved is not None:+ entries.add(resolved)+ checked_in = get_checked_in_builds(ctx)+ declared: set[str] = set()+ for pkg_dir, data in _parsed_package_jsons(ctx):+ declared |= manifest_entry_paths(pkg_dir, data, path_set, checked_in)+ return TsWorkspaceIndex(+ packages=packages, exports_entry_paths=entries, manifest_entry_paths=declared+ )+++def get_or_build_ts_index(ctx: ResolverContext) -> TsWorkspaceIndex:+ """Memoized per resolver context."""+ cached = getattr(ctx, "_ts_workspace_index", None)+ if cached is not None:+ return cached+ index = build_ts_workspace_index(ctx)+ ctx._ts_workspace_index = index # type: ignore[attr-defined]+ return indexdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/members.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/members.pynew file mode 100644index 000000000..ec0c0a574--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/members.py@@ -0,0 +1,144 @@+"""Workspace member discovery from ``package.json`` and ``pnpm-workspace.yaml``.++pnpm does not read ``package.json``'s ``workspaces`` field, so when+``pnpm-workspace.yaml`` exists it alone governs membership: merging the two+would register members pnpm never installs as fake intra-repo edges.+"""++from __future__ import annotations++import contextlib+import json+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING, Any++from ..pnpm_workspace import read_pnpm_workspace_patterns+from .exports import _build_exports_map++if TYPE_CHECKING:+ from ..context import ResolverContext+++def read_workspaces_field(pkg_data: dict) -> list[str]:+ ws = pkg_data.get("workspaces")+ if isinstance(ws, list):+ return [str(p) for p in ws if isinstance(p, str)]+ if isinstance(ws, dict):+ packages = ws.get("packages")+ if isinstance(packages, list):+ return [str(p) for p in packages if isinstance(p, str)]+ return []+++def _entry_hint(pkg_data: dict) -> str | None:+ """``module`` when it is a string, else ``main`` when it is, else None."""+ module = pkg_data.get("module")+ if isinstance(module, str):+ return module+ main = pkg_data.get("main")+ return main if isinstance(main, str) else None+++def build_workspace_map(repo_path: Path | None) -> dict[str, str]:+ """Return ``{package_name: dir_posix}`` for every workspace package."""+ return {name: info["dir"] for name, info in build_workspace_info(repo_path).items()}+++@dataclass(frozen=True)+class _WorkspaceDeclaration:+ """Which globs govern a repo's workspace, and whether the root is a member."""++ includes: tuple[str, ...]+ excludes: tuple[str, ...]+ include_root: bool++ @property+ def is_empty(self) -> bool:+ return not self.includes and not self.include_root+++def _read_workspace_declaration(repo_path: Path) -> _WorkspaceDeclaration:+ """Resolve the governing manifest into member globs."""+ pnpm = read_pnpm_workspace_patterns(repo_path)+ if pnpm is not None:+ includes, excludes = pnpm+ # pnpm always includes the root package, even with no ``packages`` key.+ return _WorkspaceDeclaration(tuple(includes), tuple(excludes), include_root=True)++ root_pkg = repo_path / "package.json"+ if not root_pkg.is_file():+ return _WorkspaceDeclaration((), (), include_root=False)+ try:+ data = json.loads(root_pkg.read_text(encoding="utf-8", errors="ignore"))+ except Exception:+ return _WorkspaceDeclaration((), (), include_root=False)+ if not isinstance(data, dict):+ return _WorkspaceDeclaration((), (), include_root=False)+ return _WorkspaceDeclaration(+ tuple(read_workspaces_field(data)), (), include_root=False+ )+++def _expand_member_dirs(repo_path: Path, declared: _WorkspaceDeclaration) -> list[Path]:+ """Expand member globs to directories, minus the negated ones.++ Negations use the same ``Path.glob`` as the includes, which anchors at the+ root like pnpm's matcher; git-ignore semantics would drop members pnpm+ keeps. The root member is never negated. A pattern ``Path.glob`` refuses+ (absolute or empty) drops only itself.+ """+ excluded: set[Path] = set()+ for pattern in declared.excludes:+ with contextlib.suppress(NotImplementedError, ValueError):+ excluded.update(p for p in repo_path.glob(pattern) if p.is_dir())++ dirs: list[Path] = [repo_path] if declared.include_root else []+ for pattern in declared.includes:+ with contextlib.suppress(NotImplementedError, ValueError):+ globbed = [repo_path] if pattern == "." else repo_path.glob(pattern)+ dirs.extend(p for p in globbed if p.is_dir() and p not in excluded)+ return dirs+++def build_workspace_info(repo_path: Path | None) -> dict[str, dict[str, Any]]:+ """Return ``{pkg_name: {"dir": <posix>, "exports": {...}, "main": str|None}}``."""+ if repo_path is None or not repo_path.is_dir():+ return {}+ declared = _read_workspace_declaration(repo_path)+ if declared.is_empty:+ return {}++ result: dict[str, dict[str, Any]] = {}+ for ws_dir in _expand_member_dirs(repo_path, declared):+ try:+ rel = ws_dir.relative_to(repo_path).as_posix()+ except ValueError:+ continue+ ws_pkg = ws_dir / "package.json"+ if not ws_pkg.is_file():+ continue+ try:+ ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))+ except Exception:+ continue+ if not isinstance(ws_data, dict):+ continue+ name = ws_data.get("name")+ if not isinstance(name, str) or not name:+ continue+ result[name] = {+ "dir": rel,+ "exports": _build_exports_map(ws_data),+ "main": _entry_hint(ws_data),+ }+ return result+++def get_or_build_workspace_info(ctx: ResolverContext) -> dict[str, dict[str, Any]]:+ cached = getattr(ctx, "_ts_workspace_info", None)+ if cached is not None:+ return cached+ info = build_workspace_info(ctx.repo_path)+ ctx._ts_workspace_info = info # type: ignore[attr-defined]+ return infodiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/paths.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/paths.pynew file mode 100644index 000000000..168a988b6--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/paths.py@@ -0,0 +1,47 @@+"""Repo-relative path probing for workspace targets."""++from __future__ import annotations++import posixpath++_PROBE_EXTENSIONS: tuple[str, ...] = (+ ".ts",+ ".tsx",+ ".mts",+ ".cts",+ ".js",+ ".jsx",+ ".mjs",+ ".cjs",+)+++def _normalize_repo_rel(base: str) -> str:+ """Collapse a joined repo-relative path so it can match ``path_set``.++ The root package's dir is ``"."``, so joins yield ``"./src/x.ts"``. A+ trailing slash survives (callers use the result as a ``startswith``+ prefix), and a path that is the root itself becomes ``""``.+ """+ if not (base.startswith("./") or "/./" in base):+ return base+ normalized = posixpath.normpath(base)+ if normalized == ".":+ return ""+ return f"{normalized}/" if base.endswith("/") and not normalized.endswith("/") else normalized+++def _probe_path(base: str, path_set: set[str]) -> str | None:+ """The file for path stem ``base``: as-is, then with a TS/JS extension, then ``index.*``."""+ base = _normalize_repo_rel(base)+ if base in path_set:+ return base+ for ext in _PROBE_EXTENSIONS:+ cand = base + ext+ if cand in path_set:+ return cand+ for ext in _PROBE_EXTENSIONS:+ cand = f"{base}/index{ext}"+ if cand in path_set:+ return cand+ return Nonediff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/resolve.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/resolve.pynew file mode 100644index 000000000..43e49478a--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/resolve.py@@ -0,0 +1,190 @@+"""Bare specifier resolution against the workspace map.++Each ladder keeps its historical order. Steps added later (spare export+candidates, built-output sources, nested sub-packages) sit behind every older+probe, so they only fill a specifier that resolved to nothing.+"""++from __future__ import annotations++import json+from collections.abc import Callable+from pathlib import Path+from typing import TYPE_CHECKING, Any++from .builds import _built_source, get_checked_in_builds+from .exports import _DECLARATION_SUFFIXES, _build_exports_map, _match_export_key+from .members import _entry_hint, get_or_build_workspace_info+from .paths import _probe_path++if TYPE_CHECKING:+ from ..context import ResolverContext+++def _read_sub_package_manifest(repo_path: Path, sub_dir_posix: str) -> dict[str, Any] | None:+ """Parse ``<repo_path>/<sub_dir_posix>/package.json``, or None; no ``name`` required."""+ manifest = repo_path / sub_dir_posix / "package.json"+ if not manifest.is_file():+ return None+ try:+ data = json.loads(manifest.read_text(encoding="utf-8", errors="ignore"))+ except Exception:+ return None+ return data if isinstance(data, dict) else None+++def _resolve_nested_subpackage(dir_posix: str, sub: str, ctx: ResolverContext) -> str | None:+ """Resolve ``sub`` as a sub-package with its own ``package.json`` (solid's ``web``, ``store``).++ Same order as the bare-package ladder, rooted at ``<dir_posix>/<sub>``.+ """+ if ctx.repo_path is None:+ return None+ sub_dir = f"{dir_posix}/{sub}"+ sub_pkg_data = _read_sub_package_manifest(ctx.repo_path, sub_dir)+ if sub_pkg_data is None:+ return None++ exports_map = _build_exports_map(sub_pkg_data)+ targets = _match_export_key("", exports_map) if exports_map else None+ for target in targets or ():+ if target.endswith(_DECLARATION_SUFFIXES):+ continue+ cand = _probe_path(f"{sub_dir}/{target.lstrip('./')}", ctx.path_set)+ if cand is not None:+ return cand++ cand = _probe_path(f"{sub_dir}/index", ctx.path_set)+ if cand is not None:+ return cand+ main = _entry_hint(sub_pkg_data)+ if isinstance(main, str):+ cand = _probe_path(f"{sub_dir}/{main.lstrip('./')}", ctx.path_set)+ if cand is not None:+ return cand+ for source_root in ("src", "lib"):+ cand = _probe_path(f"{sub_dir}/{source_root}/index", ctx.path_set)+ if cand is not None:+ return cand+ return None+++def _match_workspace_name(module_path: str, info: dict[str, dict[str, Any]]) -> str | None:+ """The longest workspace package name *module_path* is, or sits under."""+ best_name: str | None = None+ for name in info:+ if (module_path == name or module_path.startswith(name + "/")) and (+ best_name is None or len(name) > len(best_name)+ ):+ best_name = name+ return best_name+++def _first_found(steps: tuple[Callable[[], str | None], ...]) -> str | None:+ """The first file a step finds, running the steps in order."""+ for step in steps:+ found = step()+ if found is not None:+ return found+ return None+++class _WorkspaceProbe:+ """The probes for one specifier against the workspace package it names."""++ __slots__ = ("ctx", "dir_posix", "pkg", "sub", "targets")++ def __init__(self, pkg: dict[str, Any], sub: str, ctx: ResolverContext) -> None:+ self.ctx = ctx+ self.pkg = pkg+ self.dir_posix: str = pkg["dir"]+ self.sub = sub+ exports_map: dict[str, tuple[str, ...]] = pkg["exports"]+ self.targets = _match_export_key(sub, exports_map) if exports_map else None++ def resolve(self) -> str | None:+ # The ``exports`` map is authoritative.+ if self.targets:+ resolved = self.probe_target(self.targets[0])+ if resolved is not None:+ return resolved+ if not self.sub:+ # Bare package with no ``exports["."]`` hit.+ return _first_found((+ self.index_entry,+ self.main_entry,+ self.spare_export_target,+ self.source_root_index,+ self.built_export_source,+ ))+ # Subpath under a plain layout, then build output, then a nested sub-package.+ return _first_found((+ self.direct_subpath,+ self.source_root_subpath,+ self.spare_export_target,+ self.built_export_source,+ self.nested_subpackage,+ ))++ def probe(self, rel: str) -> str | None:+ return _probe_path(f"{self.dir_posix}/{rel}", self.ctx.path_set)++ def probe_target(self, target: str) -> str | None:+ return self.probe(target.lstrip("./"))++ def index_entry(self) -> str | None:+ return self.probe("index")++ def main_entry(self) -> str | None:+ main = self.pkg.get("main")+ return self.probe(main.lstrip("./")) if isinstance(main, str) else None++ def source_root_index(self) -> str | None:+ for source_root in ("src", "lib"):+ cand = self.probe(f"{source_root}/index")+ if cand is not None:+ return cand+ return None++ def direct_subpath(self) -> str | None:+ return self.probe(self.sub)++ def source_root_subpath(self) -> str | None:+ for src_root in ("src", "lib", "dist"):+ cand = self.probe(f"{src_root}/{self.sub}")+ if cand is not None:+ return cand+ return None++ def spare_export_target(self) -> str | None:+ """A candidate past the ranked one; never a declaration file, which has no bodies."""+ for target in (self.targets or ())[1:]:+ if target.endswith(_DECLARATION_SUFFIXES):+ continue+ resolved = self.probe_target(target)+ if resolved is not None:+ return resolved+ return None++ def built_export_source(self) -> str | None:+ checked_in = get_checked_in_builds(self.ctx)+ for target in self.targets or ():+ resolved = _built_source(self.dir_posix, target, self.ctx.path_set, checked_in)+ if resolved is not None:+ return resolved+ return None++ def nested_subpackage(self) -> str | None:+ return _resolve_nested_subpackage(self.dir_posix, self.sub, self.ctx)+++def resolve_via_workspaces(module_path: str, ctx: ResolverContext) -> str | None:+ """Resolve ``@scope/pkg`` or ``@scope/pkg/sub/file`` to a repo-relative path, or None."""+ info = get_or_build_workspace_info(ctx)+ if not info:+ return None+ best_name = _match_workspace_name(module_path, info)+ if best_name is None:+ return None+ sub = module_path[len(best_name) :].lstrip("/")+ return _WorkspaceProbe(info[best_name], sub, ctx).resolve()diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/scan.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/scan.pynew file mode 100644index 000000000..b5a110f74--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/scan.py@@ -0,0 +1,110 @@+"""One pruned filesystem walk, memoized per resolver context, shared by every finder.++A per-finder ``rglob`` walked the whole tree (node_modules, virtualenvs, .git)+once per pattern. The prune list stays narrow: only vendored or derived trees+that never hold our manifests; dot-dirs like ``.github`` may hold real ones.+"""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from ..context import ResolverContext+++_SCAN_PRUNE_DIRS: frozenset[str] = frozenset({+ "node_modules",+ ".git",+ ".hg",+ ".svn",+ ".venv",+ "venv",+ ".tox",+ "__pycache__",+ ".repowise",+ ".repowise.prebench-bak",+ ".next",+ ".nuxt",+ ".turbo",+ ".cache",+ ".parcel-cache",+ ".yarn",+ ".pnpm-store",+})++_VITEST_CONFIG_NAMES: frozenset[str] = frozenset({+ "vitest.config.ts", "vitest.config.js", "vitest.config.mts",+ "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",+ "vite.config.ts", "vite.config.js", "vite.config.mts",+ "vite.config.mjs",+})+++@dataclass+class _RepoFileScan:+ """File locations gathered by the single pruned walk."""++ mdx_files: list[Path] = field(default_factory=list)+ vitest_configs: list[Path] = field(default_factory=list)+ package_jsons: list[Path] = field(default_factory=list)+ plugin_jsons: list[Path] = field(default_factory=list)+++def _scan_repo_files(repo_path: Path, *, prune_nested_git: bool = True) -> _RepoFileScan:+ """One pruned walk collecting every finder's target files."""+ from repowise.core.fs_walk import walk_repo++ scan = _RepoFileScan()+ for dirpath, _dirnames, filenames in walk_repo(+ repo_path, prune_dirs=_SCAN_PRUNE_DIRS, prune_nested_git=prune_nested_git+ ):+ for fname in filenames:+ if fname.endswith(".mdx"):+ scan.mdx_files.append(Path(dirpath) / fname)+ elif fname in _VITEST_CONFIG_NAMES:+ scan.vitest_configs.append(Path(dirpath) / fname)+ elif fname == "package.json":+ scan.package_jsons.append(Path(dirpath) / fname)+ elif fname == "plugin.json":+ scan.plugin_jsons.append(Path(dirpath) / fname)+ return scan+++def _get_repo_scan(ctx: ResolverContext) -> _RepoFileScan:+ """Memoized accessor — one walk per resolver context."""+ cached = getattr(ctx, "_ts_repo_file_scan", None)+ if cached is not None:+ return cached+ scan = (+ _scan_repo_files(ctx.repo_path, prune_nested_git=ctx.prune_nested_git)+ if ctx.repo_path is not None+ else _RepoFileScan()+ )+ ctx._ts_repo_file_scan = scan # type: ignore[attr-defined]+ return scan+++def _parsed_package_jsons(ctx: ResolverContext) -> list[tuple[str, dict]]:+ """``(repo-relative dir, data)`` for every readable ``package.json`` object, memoized.++ The base is ``ctx.repo_path`` as given, not resolved: the scan walks that+ same path, and a different base would drop every manifest.+ """+ cached = getattr(ctx, "_ts_parsed_package_jsons", None)+ if cached is not None:+ return cached+ parsed: list[tuple[str, dict]] = []+ for pkg_file in _get_repo_scan(ctx).package_jsons:+ try:+ pkg_dir = pkg_file.parent.relative_to(ctx.repo_path).as_posix()+ data = json.loads(pkg_file.read_text(encoding="utf-8", errors="ignore"))+ except (ValueError, OSError, json.JSONDecodeError):+ continue+ if isinstance(data, dict):+ parsed.append((pkg_dir, data))+ ctx._ts_parsed_package_jsons = parsed # type: ignore[attr-defined]+ return parseddiff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/tool_configs.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/tool_configs.pynew file mode 100644index 000000000..6bcdd5b36--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace/tool_configs.py@@ -0,0 +1,326 @@+"""Entry points named by tool configs: MDX imports, vitest globs, Grafana plugins, npm scripts.++The static TS/JS graph never sees these consumers, so without them the files+they reach would read as unreachable.+"""++from __future__ import annotations++import posixpath+import re+from collections.abc import Iterable, Iterator+from pathlib import Path+from typing import TYPE_CHECKING++from .scan import _get_repo_scan, _parsed_package_jsons++if TYPE_CHECKING:+ from ..context import ResolverContext+++_MDX_IMPORT_RE = re.compile(+ r"""import\s++ (?:type\s+)?+ (?:\{[^}]*\}|\*\s+as\s+\w+|\w+(?:\s*,\s*\{[^}]*\})?)+ \s+from\s+['"]([^'"]+)['"]""",+ re.VERBOSE,+)++_VITEST_INCLUDE_RE = re.compile(+ r"""include\s*:\s*\[\s*((?:['"][^'"]+['"]\s*,?\s*)+)\]""",+ re.MULTILINE,+)+_VITEST_STRING_RE = re.compile(r"""['"]([^'"]+)['"]""")+++def find_mdx_import_targets(ctx: ResolverContext) -> set[str]:+ """Return repo-relative paths reached via ``import … from '...'`` in MDX files.++ The regex is deliberately narrow; anything fancier is no edge rather than a parser dependency.+ """+ if ctx.repo_path is None:+ return set()+ from ..typescript import resolve_ts_js_import++ targets: set[str] = set()+ for mdx in _get_repo_scan(ctx).mdx_files:+ try:+ text = mdx.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ try:+ rel = mdx.relative_to(ctx.repo_path).as_posix()+ except ValueError:+ continue+ for match in _MDX_IMPORT_RE.finditer(text):+ spec = match.group(1)+ # The TS resolver leaves ``..`` unflattened, so flatten it here.+ if spec.startswith("."):+ import os as _os+ joined = _os.path.normpath(_os.path.join(_os.path.dirname(rel), spec))+ joined = joined.replace("\\", "/")+ spec_for_resolve = "./" + joined+ resolved = resolve_ts_js_import(spec_for_resolve, "_root_.mdx", ctx)+ else:+ resolved = resolve_ts_js_import(spec, rel, ctx)+ if resolved is None:+ continue+ if resolved.startswith("external:"):+ continue+ targets.add(resolved)+ return targets+++def _vitest_glob_to_regex(glob: str) -> re.Pattern[str]:+ """Translate a vitest/minimatch glob into a regex matching repo paths.++ ``**`` is zero or more segments, ``*`` one segment, ``?`` one non-``/``+ char; ``fnmatch`` would make ``foo/**/x`` miss ``foo/x``.+ """+ out: list[str] = ["^"]+ i = 0+ while i < len(glob):+ c = glob[i]+ if c == "*":+ if i + 1 < len(glob) and glob[i + 1] == "*":+ # Consume a trailing ``/`` so ``foo/**/bar`` matches ``foo/bar``.+ i += 2+ if i < len(glob) and glob[i] == "/":+ out.append("(?:.*/)?")+ i += 1+ else:+ out.append(".*")+ else:+ out.append("[^/]*")+ i += 1+ elif c == "?":+ out.append("[^/]")+ i += 1+ elif c in ".+()|^$[]{}\\":+ out.append("\\" + c)+ i += 1+ else:+ out.append(c)+ i += 1+ out.append("$")+ return re.compile("".join(out))+++def _glob_matches(regex: re.Pattern[str], path_set: set[str]) -> set[str]:+ return {candidate for candidate in path_set if regex.match(candidate)}+++def _vitest_include_globs(text: str) -> Iterator[str]:+ """Every string inside a vitest config's ``include: [...]`` lists."""+ for inc_match in _VITEST_INCLUDE_RE.finditer(text):+ for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):+ yield str_match.group(1)+++def _vitest_glob_targets(cfg_dir: Path, glob_pat: str, ctx: ResolverContext) -> set[str]:+ base = (cfg_dir / glob_pat).as_posix()+ try:+ rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()+ except ValueError:+ return set()+ return _glob_matches(_vitest_glob_to_regex(rel_glob), ctx.path_set)+++def find_vitest_include_targets(ctx: ResolverContext) -> set[str]:+ """Return repo-relative source files matching vitest ``include`` globs."""+ if ctx.repo_path is None:+ return set()++ targets: set[str] = set()+ for cfg in _get_repo_scan(ctx).vitest_configs:+ try:+ text = cfg.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ for glob_pat in _vitest_include_globs(text):+ targets |= _vitest_glob_targets(cfg.parent, glob_pat, ctx)+ return targets+++_GRAFANA_ENTRY_EXTS: tuple[str, ...] = (+ ".ts", ".tsx", ".js", ".jsx",+)+++def find_grafana_plugin_targets(ctx: ResolverContext) -> set[str]:+ """Grafana plugin entries: ``module.*`` beside ``plugin.json`` or in its ``src/``."""+ if ctx.repo_path is None:+ return set()++ targets: set[str] = set()+ for plugin_file in _get_repo_scan(ctx).plugin_jsons:+ try:+ rel_dir = plugin_file.parent.relative_to(ctx.repo_path).as_posix()+ except ValueError:+ continue++ dir_prefix = "" if rel_dir == "." else f"{rel_dir}/"+ candidate_prefixes = (dir_prefix, f"{dir_prefix}src/")++ for prefix in candidate_prefixes:+ for ext in _GRAFANA_ENTRY_EXTS:+ candidate = f"{prefix}module{ext}"+ if candidate in ctx.path_set:+ targets.add(candidate)++ return targets+++_NPM_SCRIPT_SOURCE_EXTS: tuple[str, ...] = (+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts",+)++_NPM_SCRIPT_RUNNERS: frozenset[str] = frozenset({+ "tsx", "ts-node", "ts-node-esm", "vite-node", "swc-node",+ "node", "deno", "bun",+ "esbuild", "rollup", "vite", "webpack",+})++# Directories of maintained scripts run with runtime CLI arguments (benches, examples, demos).+_EXPERIMENT_DIR_NAMES: frozenset[str] = frozenset({+ "bench", "benches", "benchmark", "benchmarks",+ "treeshake", "treeshaking",+ "example", "examples",+ "demo", "demos",+ "sample", "samples",+ "playground", "playgrounds",+ "scratch",+ "scripts",+})+++def _iter_script_tokens(script: str) -> list[str]:+ """Split a script command on whitespace and shell separators; quotes are stripped, not honoured."""+ cleaned = re.sub(r"&&|\|\||;|\|", " ", script)+ return [tok.strip("'\"") for tok in cleaned.split() if tok.strip("'\"")]+++# Bare directory tokens (``eslint src runtime-tests build``).+_SCRIPT_DIR_TOKENS: frozenset[str] = frozenset({+ "src", "lib", "app", "test", "tests", "scripts",+ "benchmarks", "perf-measures", "runtime-tests", "build",+ "examples",+})+++def _is_script_source(path: str) -> bool:+ return path.lower().endswith(_NPM_SCRIPT_SOURCE_EXTS)+++def _source_files(files: list[str] | None) -> Iterator[str]:+ return (f for f in files or () if _is_script_source(f))+++def _dirs_in_repo(path_set: set[str]) -> dict[str, list[str]]:+ """``{directory: files anywhere under it}`` for every directory in *path_set*."""+ dirs_in_repo: dict[str, list[str]] = {}+ for p in path_set:+ idx = 0+ while True:+ slash = p.find("/", idx)+ if slash == -1:+ break+ dirs_in_repo.setdefault(p[:slash], []).append(p)+ idx = slash + 1+ return dirs_in_repo+++def _normalize_script_path(candidate: str) -> str:+ """Normalise ``a/./b`` and ``a/../b`` segments."""+ parts: list[str] = []+ for seg in candidate.split("/"):+ if seg in ("", "."):+ continue+ if seg == "..":+ if parts:+ parts.pop()+ continue+ parts.append(seg)+ return "/".join(parts)+++def _source_token_targets(token: str, pkg_prefix: str, path_set: set[str]) -> tuple[str, ...]:+ candidate = (pkg_prefix + token).lstrip("./")+ candidate = re.sub(r"\\", "/", candidate)+ norm = _normalize_script_path(candidate)+ return (norm,) if norm in path_set else ()+++def _glob_token_targets(token: str, pkg_prefix: str, path_set: set[str]) -> set[str]:+ rel_glob = (pkg_prefix + token).lstrip("./")+ if rel_glob.startswith("./"):+ rel_glob = rel_glob[2:]+ try:+ regex = _vitest_glob_to_regex(rel_glob)+ except re.error:+ return set()+ return _glob_matches(regex, path_set)+++def _script_token_targets(+ token: str, pkg_prefix: str, dirs_in_repo: dict[str, list[str]], path_set: set[str]+) -> Iterable[str]:+ """Source files one script token names, or nothing."""+ if not token or token.startswith("-"):+ return ()+ has_glob = "*" in token or "?" in token+ if _is_script_source(token) and not has_glob:+ return _source_token_targets(token, pkg_prefix, path_set)+ # A glob needs a slash, so runner names and flags are never expanded.+ if has_glob and "/" in token:+ return _glob_token_targets(token, pkg_prefix, path_set)+ if "/" not in token and token in _SCRIPT_DIR_TOKENS:+ return _source_files(dirs_in_repo.get((pkg_prefix + token).rstrip("/")))+ return ()+++def _package_script_targets(+ pkg_rel: str, data: dict, dirs_in_repo: dict[str, list[str]], path_set: set[str]+) -> set[str]:+ """Source files one ``package.json``'s ``scripts`` reach."""+ scripts = data.get("scripts") or {}+ if not isinstance(scripts, dict):+ return set()+ pkg_prefix = "" if pkg_rel in ("", ".") else f"{pkg_rel}/"+ targets: set[str] = set()++ if posixpath.basename(pkg_rel).lower() in _EXPERIMENT_DIR_NAMES:+ targets.update(_source_files(dirs_in_repo.get(pkg_rel) if pkg_rel else None))++ for command in scripts.values():+ if not isinstance(command, str):+ continue+ for token in _iter_script_tokens(command):+ targets.update(_script_token_targets(token, pkg_prefix, dirs_in_repo, path_set))+ return targets+++def _experiment_dir_targets(dirs_in_repo: dict[str, list[str]]) -> Iterator[str]:+ for dir_rel, files in dirs_in_repo.items():+ if dir_rel.rsplit("/", 1)[-1].lower() in _EXPERIMENT_DIR_NAMES:+ yield from _source_files(files)+++def find_npm_script_entry_targets(ctx: ResolverContext) -> set[str]:+ """Return repo-relative source files ``package.json`` scripts reach.++ Covers source paths (``tsx bench/x.ts``), glob arguments (``"src/**/*.ts"``),+ bare directory tokens, and every source file under an experiment directory.+ """+ if ctx.repo_path is None:+ return set()++ path_set = ctx.path_set+ dirs_in_repo = _dirs_in_repo(path_set)+ targets: set[str] = set()+ for pkg_rel, data in _parsed_package_jsons(ctx):+ targets |= _package_script_targets(pkg_rel, data, dirs_in_repo, path_set)++ # Experiment directories nested anywhere, with or without their own package.json.+ targets.update(_experiment_dir_targets(dirs_in_repo))+ return targets