From 9e87a5f87832af3b89d8167d9125426ca7e59191 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 22:04:22 +0000 Subject: [PATCH 1/7] TypeScript umbrella members keep the workspace paths rewrite A discovered umbrella set SCIP_TS_PATHS=0, a line copied from the SCIP_TS_PROJECTS branch. scip_ts_paths.py writes its paths into the tsconfig.json of every named workspace package that has one. A member referenced by its directory is indexed through that file, and a named config that extends it inherits the paths; in an unbuilt pnpm or yarn workspace they are what resolve imports between members. Without them a member's import of another resolves to nothing and its call and type edges are lost. The new harness test reads the member's tsconfig.json as the indexer sees it: the import's paths entry is there, and the file is restored afterwards. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_typescript_delta.sh | 5 +- .../test_run_typescript_delta_umbrella.py | 60 ++++++++++++++++++- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 2353888518d..7df305967c1 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -48,10 +48,11 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then # umbrella root tsconfig: index member projects instead of loading the root. - # One path per line (a member directory may contain a space). + # One path per line (a member directory may contain a space). SCIP_TS_PATHS + # stays as configured: the rewrite lands in each member's tsconfig.json, and + # in an unbuilt workspace it is what resolves imports between members. mapfile -t PROJECTS <<<"$discovered" WORKSPACES="" - SCIP_TS_PATHS=0 fi # Ownership uses the full discovered set even when a delta indexes a subset, # so a root-level tsconfig cannot keep documents a more specific member owns. diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 1890760170b..e8ec0a56d72 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -7,6 +7,7 @@ import os import subprocess from pathlib import Path +from typing import Any _SCRIPT = ( Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_typescript_delta.sh" @@ -18,13 +19,19 @@ for a in "$@"; do printf '\\t%s' "$a"; done printf '\\n' } >>"$CALLS" +# The member tsconfig the indexer reads, one line per target. +for a in "$@"; do + if [[ -f "$a/tsconfig.json" ]]; then + printf '%s\\t%s\\n' "$a" "$(tr -d '\\n' <"$a/tsconfig.json")" >>"$CALLS.tsconfig" + fi +done while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done """ _FAKE_PYTHON = """#!/usr/bin/env bash -# Forward discover/filter/merge to the real helpers; stub only the converter. +# Forward discover/filter/merge/paths to the real helpers; stub only the converter. case "${1-}" in - *scip_ts_projects.py|*scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; + *scip_ts_projects.py|*scip_merge_indexes.py|*scip_ts_paths.py) exec "$REAL_PYTHON" "$@" ;; esac { printf 'convert' @@ -67,6 +74,7 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: bin_dir.mkdir(exist_ok=True) calls = tmp_path / "calls" calls.unlink(missing_ok=True) + Path(f"{calls}.tsconfig").unlink(missing_ok=True) for name, body in (("scip-typescript", _FAKE_SCIP), ("python", _FAKE_PYTHON)): dest = bin_dir / name dest.write_text(body) @@ -84,6 +92,7 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: } # Don't leak a parent SCIP_TS_PROJECTS into the test. env.pop("SCIP_TS_PROJECTS", None) + env.pop("SCIP_TS_PATHS", None) subprocess.run( ["bash", str(_SCRIPT), str(repo), base, head], env=env, @@ -114,6 +123,53 @@ def _targets(runs: list[list[str]]) -> list[str]: return out +def _indexed_tsconfigs(tmp_path: Path) -> dict[str, dict[str, Any]]: + """The tsconfig.json each member had when the indexer ran, by target.""" + out = {} + for line in (tmp_path / "calls.tsconfig").read_text().splitlines(): + target, text = line.split("\t", 1) + out[target] = json.loads(text) + return out + + +def test_umbrella_workspace_members_resolve_unbuilt_packages(tmp_path: Path) -> None: + """An umbrella over an unbuilt workspace keeps the dist-export paths rewrite. + + `@x/lib` exports `dist/`, which exists only after a build. Each member is + indexed through its own tsconfig, so the rewrite must reach that tsconfig + or `app`'s import of `@x/lib` resolves to nothing and its edges are lost. + """ + repo = tmp_path / "repo" + files = { + "pnpm-workspace.yaml": 'packages:\n - "packages/*"\n', + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "packages/app/package.json": json.dumps({"name": "@x/app"}), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": 'import { b } from "@x/lib";\nexport const a = b;\n', + "packages/lib/package.json": json.dumps( + {"name": "@x/lib", "exports": {".": "./dist/index.js"}} + ), + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/index.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + app = _indexed_tsconfigs(tmp_path)["packages/app"] + assert app["compilerOptions"]["paths"] == {"@x/lib": ["../lib/src/index.ts"]} + # The rewrite is undone once the pass ends. + assert json.loads((repo / "packages/app/tsconfig.json").read_text()) == {"include": ["src"]} + + def test_umbrella_root_is_indexed_as_member_projects(tmp_path: Path) -> None: repo = _repo(tmp_path) head = _git(repo, "rev-parse", "HEAD") From 700bc0a2b7b139c802c31d8debf385a43a416895 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:14:03 +0000 Subject: [PATCH 2/7] The TypeScript paths rewrite keeps the aliases a tsconfig inherits A paths or baseUrl written into a tsconfig replaces the one its extends chain sets. An app that extends a base with its own aliases lost them once the rewrite reached umbrella members: its import of such an alias failed with TS2307 and the call edges through it were dropped. scip_ts_paths.py now follows the extends chain, keeps the paths in effect, and writes only the workspace entries beside them, relative to the baseUrl in effect. It no longer sets a baseUrl. Inherited entries with no baseUrl are rebased to the package's directory. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_ts_paths.py | 149 +++++++++++++++--- .../test_run_typescript_delta_umbrella.py | 54 +++++++ tests/unit/test_scip_ts_paths.py | 34 ++++ 3 files changed, 214 insertions(+), 23 deletions(-) diff --git a/scripts/scip_harness/scip_ts_paths.py b/scripts/scip_harness/scip_ts_paths.py index d1cb787017b..202bc0722e7 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -13,7 +13,10 @@ SOURCE file the build target came from (`dist/` → `src/`, `.js` → `.ts` / `.tsx`, an existing file wins), and writes them into the consumer packages' `tsconfig.json` — a backup `tsconfig.json.scip-bak` sits beside each, and -`--restore` puts the originals back. Run it before `scip-typescript index` +`--restore` puts the originals back. A `paths` written into a tsconfig +replaces the one its `extends` chain set, so the aliases in effect are +carried over, and the added entries are written against the `baseUrl` in +effect, which is left as it is. Run it before `scip-typescript index` on a checkout that has no build output; skip it on a built checkout. python scip_ts_paths.py [--restore] [--dry-run] @@ -27,6 +30,7 @@ import re import sys from pathlib import Path +from typing import Any _BUILD_DIRS = ("dist", "build", "lib", "out", "esm", "cjs") _SRC_EXTS = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") @@ -121,9 +125,19 @@ def _expand_pattern(pkg_dir: Path, key: str, target: str) -> list[tuple[str, str return out -def paths_for(consumer_dir: Path, packages: list[tuple[str, Path, dict]]) -> dict[str, list[str]]: +def _relative(path: Path, base: Path, dotted: bool) -> str: + """`path` relative to `base`; `dotted` writes the leading `./` that a + `paths` entry needs when no `baseUrl` is in effect.""" + rel = os.path.relpath(path, base).replace(os.sep, "/") + return "./" + rel if dotted and not rel.startswith("../") and rel != ".." else rel + + +def paths_for( + consumer_dir: Path, packages: list[tuple[str, Path, dict]], base_url: Path | None = None +) -> dict[str, list[str]]: """{specifier: [relative source path]} for every exported subpath of - every OTHER workspace package, relative to the consumer's tsconfig.""" + every OTHER workspace package, relative to the `baseUrl` in effect, or + to the consumer's tsconfig when there is none.""" paths: dict[str, list[str]] = {} for name, pkg_dir, data in packages: if pkg_dir == consumer_dir: @@ -153,10 +167,107 @@ def paths_for(consumer_dir: Path, packages: list[tuple[str, Path, dict]]) -> dic if src is None: continue spec = name if key == "." else name + key[1:] - paths[spec] = [os.path.relpath(src, consumer_dir).replace(os.sep, "/")] + paths[spec] = [_relative(src, base_url or consumer_dir, base_url is None)] return paths +def _config_text(path: Path) -> str: + """A tsconfig as the project wrote it: the backup of one this script + has patched, else the file itself.""" + backup = path.with_name(path.name + ".scip-bak") + return (backup if backup.is_file() else path).read_text(encoding="utf-8") + + +def _parse_tsconfig(text: str) -> dict[str, Any] | None: + # tsconfig allows comments and trailing commas; strip them for json + # (outside string literals: `"@/*"` is a path pattern, not a comment) + stripped = re.sub( + r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', + lambda m: m.group(1) or "", + text, + flags=re.S, + ) + stripped = re.sub(r",(\s*[}\]])", r"\1", stripped) + try: + cfg = json.loads(stripped) + except ValueError: + return None + return cfg if isinstance(cfg, dict) else None + + +def _extends_target(spec: str, from_dir: Path) -> Path | None: + """The file an `extends` entry names, looked up as TypeScript does: a + path from the extending config, or a config under `node_modules`.""" + if spec.startswith((".", "/")): + bases = [from_dir / spec] + else: + bases = [d / "node_modules" / spec for d in (from_dir, *from_dir.parents)] + for base in bases: + for cand in (base, base.with_name(base.name + ".json"), base / "tsconfig.json"): + if cand.is_file(): + return cand + return None + + +def _from_config(value: str, cfg_dir: Path, leaf_dir: Path) -> Path: + """A relative option value as a directory: from the config that wrote + it, or from the extending config for `${configDir}`.""" + if value.startswith("${configDir}"): + return Path(os.path.normpath(leaf_dir / value[len("${configDir}") :].lstrip("/"))) + return Path(os.path.normpath(cfg_dir / value)) + + +def effective_options( + cfg: dict[str, Any], cfg_dir: Path, leaf_dir: Path, depth: int = 0 +) -> tuple[dict[str, Any] | None, Path, Path | None]: + """(`paths`, the directory its entries resolve from without a `baseUrl`, + the `baseUrl` directory) in effect for a tsconfig. Each option comes from + the last config in the `extends` chain that sets it, whole.""" + paths: dict[str, Any] | None = None + paths_dir, base_url = cfg_dir, None + ext = cfg.get("extends") + specs = [ext] if isinstance(ext, str) else ext if isinstance(ext, list) else [] + for spec in specs if depth < 32 else []: # a cycle of extends ends here + target = _extends_target(spec, cfg_dir) if isinstance(spec, str) else None + try: + parent = _parse_tsconfig(_config_text(target)) if target else None + except OSError: + parent = None + if target is None or parent is None: + continue + p, p_dir, b = effective_options(parent, target.parent, leaf_dir, depth + 1) + if p is not None: + paths, paths_dir = p, p_dir + if b is not None: + base_url = b + co = cfg.get("compilerOptions") + if isinstance(co, dict): + if isinstance(co.get("paths"), dict): + paths, paths_dir = co["paths"], cfg_dir + if isinstance(co.get("baseUrl"), str): + base_url = _from_config(co["baseUrl"], cfg_dir, leaf_dir) + return paths, paths_dir, base_url + + +def _rebased(paths: dict[str, Any], from_dir: Path, to_dir: Path) -> dict[str, Any]: + """Inherited `paths` entries, which resolve from the config that wrote + them when no `baseUrl` is set, rewritten to resolve from `to_dir`.""" + if from_dir == to_dir: + return dict(paths) + out: dict[str, Any] = {} + for key, targets in paths.items(): + if not isinstance(targets, list): + out[key] = targets + continue + out[key] = [ + _relative(Path(os.path.normpath(from_dir / t)), to_dir, True) + if isinstance(t, str) and not t.startswith("${configDir}") and not os.path.isabs(t) + else t + for t in targets + ] + return out + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("checkout") @@ -176,28 +287,20 @@ def main() -> int: continue if not tsconfig.exists(): continue - paths = paths_for(pkg_dir, packages) - if not paths: - continue - text = tsconfig.read_text(encoding="utf-8") - # tsconfig allows comments and trailing commas; strip them for json - # (outside string literals: `"@/*"` is a path pattern, not a comment) - stripped = re.sub( - r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', - lambda m: m.group(1) or "", - text, - flags=re.S, - ) - stripped = re.sub(r",(\s*[}\]])", r"\1", stripped) - try: - cfg = json.loads(stripped) - except ValueError: + text = _config_text(tsconfig) + cfg = _parse_tsconfig(text) + if cfg is None: print(f"skip {tsconfig}: not parseable", file=sys.stderr) continue + existing, existing_dir, base_url = effective_options(cfg, pkg_dir, pkg_dir) + paths = paths_for(pkg_dir, packages, base_url) + if not paths: + continue + if existing and base_url is None: + existing = _rebased(existing, existing_dir, pkg_dir) co = cfg.setdefault("compilerOptions", {}) - existing = co.get("paths") or {} - co["paths"] = {**paths, **existing} # a package's own aliases win - co.setdefault("baseUrl", ".") + # the aliases already in effect win; the baseUrl in effect stays + co["paths"] = {**paths, **(existing or {})} if args.dry_run: print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") continue diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index e8ec0a56d72..8be75926352 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -511,3 +511,57 @@ def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: log = _run(tmp_path, repo, base, head) assert _runs(log) == [] assert not (tmp_path / "delta.json").exists() + + +def test_umbrella_member_keeps_aliases_inherited_from_a_base_tsconfig(tmp_path: Path) -> None: + """The rewrite adds workspace paths to the aliases a member inherits. + + `app` extends a base whose `baseUrl` and `paths` map `@local/internal`. + A `paths` written into `app` replaces the inherited one, so the rewrite + must carry the inherited aliases over and must not replace the inherited + `baseUrl`, against which the added paths are written. + """ + repo = tmp_path / "repo" + files = { + "pnpm-workspace.yaml": 'packages:\n - "packages/*"\n', + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "tsconfig.base.json": json.dumps( + { + "compilerOptions": { + "baseUrl": ".", + "paths": {"@local/internal": ["internal/index.ts"]}, + } + } + ), + "internal/index.ts": "export const i = 1;\n", + "packages/app/package.json": json.dumps({"name": "@x/app"}), + "packages/app/tsconfig.json": json.dumps( + {"extends": "../../tsconfig.base.json", "include": ["src"]} + ), + "packages/app/src/a.ts": ( + 'import { b } from "@x/lib";\nimport { i } from "@local/internal";\n' + "export const a = b + i;\n" + ), + "packages/lib/package.json": json.dumps( + {"name": "@x/lib", "exports": {".": "./dist/index.js"}} + ), + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/index.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + _run(tmp_path, repo, "--full", head) + options = _indexed_tsconfigs(tmp_path)["packages/app"]["compilerOptions"] + assert options["paths"] == { + "@x/lib": ["packages/lib/src/index.ts"], + "@local/internal": ["internal/index.ts"], + } + assert "baseUrl" not in options diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index bfaa571026a..c901162fb64 100644 --- a/tests/unit/test_scip_ts_paths.py +++ b/tests/unit/test_scip_ts_paths.py @@ -99,3 +99,37 @@ def test_patch_then_restore_puts_every_tsconfig_back(tmp_path: Path) -> None: assert "restored 1 tsconfig(s)" in _run(tmp_path, "--restore") assert tsconfig.read_bytes() == original assert not (tmp_path / "web" / "tsconfig.json.scip-bak").exists() + + +def test_patch_keeps_inherited_paths_and_their_base(tmp_path: Path) -> None: + _workspace(tmp_path) + (tmp_path / "internal").mkdir() + (tmp_path / "internal" / "index.ts").write_text("export const i = 1;\n") + # No baseUrl: the base's paths resolve from the base's own directory. + (tmp_path / "tsconfig.base.json").write_text( + json.dumps({"compilerOptions": {"paths": {"@local/internal": ["./internal/index.ts"]}}}) + ) + (tmp_path / "web" / "tsconfig.json").write_text( + json.dumps({"extends": "../tsconfig.base.json"}) + ) + # A baseUrl the package sets itself: the added paths are written against it. + api = tmp_path / "api" + api.mkdir() + (api / "package.json").write_text(json.dumps({"name": "api"})) + (api / "tsconfig.json").write_text( + json.dumps({"compilerOptions": {"baseUrl": "src", "paths": {"~/*": ["*"]}}}) + ) + + _run(tmp_path) + web = json.loads((tmp_path / "web" / "tsconfig.json").read_text())["compilerOptions"] + assert web == { + "paths": { + "@acme/shared": ["../packages/shared/src/index.ts"], + "@local/internal": ["../internal/index.ts"], + } + } + api_options = json.loads((api / "tsconfig.json").read_text())["compilerOptions"] + assert api_options == { + "baseUrl": "src", + "paths": {"@acme/shared": ["../../packages/shared/src/index.ts"], "~/*": ["*"]}, + } From 5f11ff284336a01e541d559bea74378e065b1fcf Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:41:40 +0000 Subject: [PATCH 3/7] The paths rewrite stops an extends cycle and leaves a package it cannot read unpatched A cycle through array extends made the walk exponential: the depth cap bounded a chain, not the branching. The walk now keeps the configs it has entered and skips one it meets again, as TypeScript's resolution stack does. A base tsconfig with a byte order mark did not parse, so its paths were replaced by the written ones. The BOM is stripped before parsing. An extends entry that cannot be resolved or parsed, such as a package that names its config through exports, now leaves that package's tsconfig unpatched and says so, instead of writing a paths over aliases the script cannot see. The ${configDir} template is matched in any case, as TypeScript does, and the backup is a byte copy, so --restore gives back a CRLF tsconfig as it was. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_ts_paths.py | 49 +++++++++++---- tests/unit/test_scip_ts_paths.py | 91 ++++++++++++++++++++++++++- 2 files changed, 125 insertions(+), 15 deletions(-) diff --git a/scripts/scip_harness/scip_ts_paths.py b/scripts/scip_harness/scip_ts_paths.py index 202bc0722e7..b0b292c3c3e 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -35,6 +35,7 @@ _BUILD_DIRS = ("dist", "build", "lib", "out", "esm", "cjs") _SRC_EXTS = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") _CONDITIONS = ("types", "import", "module", "default", "require", "node") +_CONFIG_DIR = "${configdir}" def _pick(target): @@ -179,6 +180,8 @@ def _config_text(path: Path) -> str: def _parse_tsconfig(text: str) -> dict[str, Any] | None: + # TypeScript reads a file without its byte order mark, which json rejects + text = text.removeprefix("\ufeff") # tsconfig allows comments and trailing commas; strip them for json # (outside string literals: `"@/*"` is a path pattern, not a comment) stripped = re.sub( @@ -196,8 +199,9 @@ def _parse_tsconfig(text: str) -> dict[str, Any] | None: def _extends_target(spec: str, from_dir: Path) -> Path | None: - """The file an `extends` entry names, looked up as TypeScript does: a - path from the extending config, or a config under `node_modules`.""" + """The file an `extends` entry names: a path from the extending config, + or a config under `node_modules` found by its path. A package that names + its config through `exports` or a `tsconfig` field is not resolved.""" if spec.startswith((".", "/")): bases = [from_dir / spec] else: @@ -209,33 +213,48 @@ def _extends_target(spec: str, from_dir: Path) -> Path | None: return None +def _has_config_dir(value: str) -> bool: + """TypeScript matches the `${configDir}` template in any case.""" + return value[: len(_CONFIG_DIR)].lower() == _CONFIG_DIR + + def _from_config(value: str, cfg_dir: Path, leaf_dir: Path) -> Path: """A relative option value as a directory: from the config that wrote it, or from the extending config for `${configDir}`.""" - if value.startswith("${configDir}"): - return Path(os.path.normpath(leaf_dir / value[len("${configDir}") :].lstrip("/"))) + if _has_config_dir(value): + return Path(os.path.normpath(leaf_dir / value[len(_CONFIG_DIR) :].lstrip("/"))) return Path(os.path.normpath(cfg_dir / value)) +class ExtendsNotFollowed(Exception): + """An `extends` entry that cannot be resolved or parsed: the options it + would give are unknown, so a `paths` written over them could replace + aliases this script cannot see.""" + + def effective_options( - cfg: dict[str, Any], cfg_dir: Path, leaf_dir: Path, depth: int = 0 + cfg: dict[str, Any], cfg_dir: Path, leaf_dir: Path, seen: frozenset[Path] = frozenset() ) -> tuple[dict[str, Any] | None, Path, Path | None]: """(`paths`, the directory its entries resolve from without a `baseUrl`, the `baseUrl` directory) in effect for a tsconfig. Each option comes from - the last config in the `extends` chain that sets it, whole.""" + the last config in the `extends` chain that sets it, whole. `seen` holds + the configs being walked: one met again is skipped, as TypeScript's + resolution stack does (TS18000). Raises `ExtendsNotFollowed`.""" paths: dict[str, Any] | None = None paths_dir, base_url = cfg_dir, None ext = cfg.get("extends") specs = [ext] if isinstance(ext, str) else ext if isinstance(ext, list) else [] - for spec in specs if depth < 32 else []: # a cycle of extends ends here + for spec in specs: target = _extends_target(spec, cfg_dir) if isinstance(spec, str) else None + if target is not None and target.resolve() in seen: + continue try: parent = _parse_tsconfig(_config_text(target)) if target else None except OSError: parent = None if target is None or parent is None: - continue - p, p_dir, b = effective_options(parent, target.parent, leaf_dir, depth + 1) + raise ExtendsNotFollowed(str(spec)) + p, p_dir, b = effective_options(parent, target.parent, leaf_dir, seen | {target.resolve()}) if p is not None: paths, paths_dir = p, p_dir if b is not None: @@ -261,7 +280,7 @@ def _rebased(paths: dict[str, Any], from_dir: Path, to_dir: Path) -> dict[str, A continue out[key] = [ _relative(Path(os.path.normpath(from_dir / t)), to_dir, True) - if isinstance(t, str) and not t.startswith("${configDir}") and not os.path.isabs(t) + if isinstance(t, str) and not _has_config_dir(t) and not os.path.isabs(t) else t for t in targets ] @@ -292,7 +311,13 @@ def main() -> int: if cfg is None: print(f"skip {tsconfig}: not parseable", file=sys.stderr) continue - existing, existing_dir, base_url = effective_options(cfg, pkg_dir, pkg_dir) + try: + existing, existing_dir, base_url = effective_options( + cfg, pkg_dir, pkg_dir, frozenset({tsconfig.resolve()}) + ) + except ExtendsNotFollowed as err: + print(f"skip {tsconfig}: extends not followed ({err})", file=sys.stderr) + continue paths = paths_for(pkg_dir, packages, base_url) if not paths: continue @@ -305,7 +330,7 @@ def main() -> int: print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") continue if not backup.exists(): - backup.write_text(text, encoding="utf-8") + backup.write_bytes(tsconfig.read_bytes()) tsconfig.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8") changed += 1 print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index c901162fb64..fe05c6139e5 100644 --- a/tests/unit/test_scip_ts_paths.py +++ b/tests/unit/test_scip_ts_paths.py @@ -71,14 +71,18 @@ def test_the_converter_maps_packages_through_the_shared_list(tmp_path: Path) -> assert conv.ts_package_dirs(None) == {} and conv.ts_package_dirs(tmp_path / "no") == {} -def _run(root: Path, *flags: str) -> str: - out = subprocess.run( +def _proc(root: Path, *flags: str, timeout: float | None = None): + return subprocess.run( [sys.executable, str(_HARNESS / "scip_ts_paths.py"), str(root), *flags], capture_output=True, text=True, check=True, + timeout=timeout, ) - return out.stdout + + +def _run(root: Path, *flags: str) -> str: + return _proc(root, *flags).stdout def test_patch_then_restore_puts_every_tsconfig_back(tmp_path: Path) -> None: @@ -133,3 +137,84 @@ def test_patch_keeps_inherited_paths_and_their_base(tmp_path: Path) -> None: "baseUrl": "src", "paths": {"@acme/shared": ["../../packages/shared/src/index.ts"], "~/*": ["*"]}, } + + +def test_a_cycle_through_array_extends_ends_where_typescript_stops_it(tmp_path: Path) -> None: + _workspace(tmp_path) + for name, others in (("a", ["b", "c"]), ("b", ["a", "c"]), ("c", ["a", "b"])): + (tmp_path / f"{name}.json").write_text( + json.dumps({"extends": [f"./{o}.json" for o in others]}) + ) + (tmp_path / "web" / "tsconfig.json").write_text(json.dumps({"extends": "../a.json"})) + + # the walk keeps the configs it has entered, as TypeScript's resolution + # stack does (TS18000); a depth cap alone is exponential over arrays + assert "patched 1 tsconfig(s)" in _proc(tmp_path, timeout=20).stdout + + +def test_a_base_with_a_byte_order_mark_still_gives_its_paths(tmp_path: Path) -> None: + _workspace(tmp_path) + (tmp_path / "internal").mkdir() + (tmp_path / "internal" / "index.ts").write_text("export const i = 1;\n") + (tmp_path / "tsconfig.base.json").write_bytes( + b"\xef\xbb\xbf" + + json.dumps( + {"compilerOptions": {"paths": {"@local/internal": ["./internal/index.ts"]}}} + ).encode() + ) + (tmp_path / "web" / "tsconfig.json").write_text( + json.dumps({"extends": "../tsconfig.base.json"}) + ) + + _run(tmp_path) + web = json.loads((tmp_path / "web" / "tsconfig.json").read_text())["compilerOptions"] + assert web["paths"]["@local/internal"] == ["../internal/index.ts"] + assert "@acme/shared" in web["paths"] + + +def test_an_extends_that_cannot_be_followed_leaves_the_package_unpatched(tmp_path: Path) -> None: + _workspace(tmp_path) + web = tmp_path / "web" / "tsconfig.json" + web.write_text(json.dumps({"extends": "@co/tsconfig/base"})) + bad = tmp_path / "bad" + bad.mkdir() + (bad / "package.json").write_text(json.dumps({"name": "bad"})) + (bad / "tsconfig.json").write_text(json.dumps({"extends": "../broken.json"})) + (tmp_path / "broken.json").write_text("{ not json") + original = web.read_bytes() + + out = _proc(tmp_path) + assert web.read_bytes() == original + assert not (tmp_path / "web" / "tsconfig.json.scip-bak").exists() + assert not (bad / "tsconfig.json.scip-bak").exists() + assert "extends not followed" in out.stderr + assert "patched 0 tsconfig(s)" in out.stdout + + +def test_config_dir_is_matched_in_any_case(tmp_path: Path) -> None: + _workspace(tmp_path) + (tmp_path / "tsconfig.base.json").write_text( + json.dumps({"compilerOptions": {"paths": {"@l/*": ["${ConfigDir}/internal/*"]}}}) + ) + (tmp_path / "web" / "tsconfig.json").write_text( + json.dumps( + {"extends": "../tsconfig.base.json", "compilerOptions": {"baseUrl": "${CONFIGDIR}/src"}} + ) + ) + + _run(tmp_path) + web = json.loads((tmp_path / "web" / "tsconfig.json").read_text())["compilerOptions"] + assert web["paths"]["@acme/shared"] == ["../../packages/shared/src/index.ts"] + assert web["paths"]["@l/*"] == ["${ConfigDir}/internal/*"] + + +def test_restore_gives_back_the_bytes_of_a_crlf_tsconfig(tmp_path: Path) -> None: + _workspace(tmp_path) + tsconfig = tmp_path / "web" / "tsconfig.json" + tsconfig.write_bytes(b'{\r\n "compilerOptions": {"strict": true}\r\n}\r\n') + original = tsconfig.read_bytes() + + _run(tmp_path) + assert (tmp_path / "web" / "tsconfig.json.scip-bak").read_bytes() == original + _run(tmp_path, "--restore") + assert tsconfig.read_bytes() == original From 3c08380a32f0455fcd556e794ced2946a761ee97 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:55:12 +0000 Subject: [PATCH 4/7] The paths rewrite leaves a specifier to the alias in effect that matches it TypeScript takes an exact paths key before any pattern (matchPatternOrExact), so an added @pkg/feature took the import from a configured @pkg/* and resolved it to another file. A workspace entry is added only when no key in effect matches its specifier: the same key, or a single-star pattern whose prefix and suffix fit around it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_ts_paths.py | 27 ++++++++++- tests/unit/test_scip_ts_paths.py | 67 +++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_ts_paths.py b/scripts/scip_harness/scip_ts_paths.py index b0b292c3c3e..d1f9bf06fd4 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -16,7 +16,8 @@ `--restore` puts the originals back. A `paths` written into a tsconfig replaces the one its `extends` chain set, so the aliases in effect are carried over, and the added entries are written against the `baseUrl` in -effect, which is left as it is. Run it before `scip-typescript index` +effect, which is left as it is. An entry is left out when an alias in effect +already matches its specifier. Run it before `scip-typescript index` on a checkout that has no build output; skip it on a built checkout. python scip_ts_paths.py [--restore] [--dry-run] @@ -29,6 +30,7 @@ import os import re import sys +from collections.abc import Iterable from pathlib import Path from typing import Any @@ -287,6 +289,27 @@ def _rebased(paths: dict[str, Any], from_dir: Path, to_dir: Path) -> dict[str, A return out +def _matched(spec: str, keys: Iterable[str]) -> bool: + """Whether a `paths` key already takes `spec`: the key itself, or a + pattern with one `*` whose prefix and suffix fit around it. TypeScript + tries an exact key first and then the matching pattern with the longest + prefix (`matchPatternOrExact`), so an added exact key would take the + specifier from any of them. A key with two stars matches nothing.""" + for key in keys: + prefix, star, suffix = key.partition("*") + if not star: + if key == spec: + return True + elif ( + "*" not in suffix + and len(spec) >= len(prefix) + len(suffix) + and spec.startswith(prefix) + and spec.endswith(suffix) + ): + return True + return False + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("checkout") @@ -319,6 +342,8 @@ def main() -> int: print(f"skip {tsconfig}: extends not followed ({err})", file=sys.stderr) continue paths = paths_for(pkg_dir, packages, base_url) + # a specifier an alias in effect matches keeps that alias + paths = {k: v for k, v in paths.items() if not _matched(k, existing or {})} if not paths: continue if existing and base_url is None: diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index fe05c6139e5..df604f83358 100644 --- a/tests/unit/test_scip_ts_paths.py +++ b/tests/unit/test_scip_ts_paths.py @@ -218,3 +218,70 @@ def test_restore_gives_back_the_bytes_of_a_crlf_tsconfig(tmp_path: Path) -> None assert (tmp_path / "web" / "tsconfig.json.scip-bak").read_bytes() == original _run(tmp_path, "--restore") assert tsconfig.read_bytes() == original + + +def _kit(root: Path, web_paths: dict[str, list[str]]) -> Path: + """A workspace package with a root and a subpath export, and a consumer + whose own tsconfig sets `web_paths`.""" + _workspace(root) + kit = root / "packages" / "kit" + (kit / "src").mkdir(parents=True) + (kit / "src" / "index.ts").write_text("export const kit = 1;\n") + (kit / "src" / "feature.ts").write_text("export const feature = 1;\n") + (kit / "package.json").write_text( + json.dumps( + { + "name": "@acme/kit", + "exports": {".": "./dist/index.js", "./feature": "./dist/feature.js"}, + } + ) + ) + web = root / "web" / "tsconfig.json" + web.write_text(json.dumps({"compilerOptions": {"paths": web_paths}})) + return web + + +def test_alias_in_effect_keeps_a_subpath_its_wildcard_matches(tmp_path: Path) -> None: + # TypeScript tries an exact key before any pattern (matchPatternOrExact), + # so an added `@acme/kit/feature` would take the import from `@acme/kit/*` + web = _kit(tmp_path, {"@acme/kit/*": ["./local/*.ts"]}) + + _run(tmp_path) + paths = json.loads(web.read_text())["compilerOptions"]["paths"] + assert paths == { + "@acme/shared": ["../packages/shared/src/index.ts"], + "@acme/kit": ["../packages/kit/src/index.ts"], + "@acme/kit/*": ["./local/*.ts"], + } + + +def test_alias_in_effect_that_does_not_match_leaves_the_subpath_added(tmp_path: Path) -> None: + # neither pattern fits around `@acme/kit/feature`: one prefix differs, + # the other suffix does, and a key with two stars matches nothing + configured = { + "@acme/other/*": ["./other/*"], + "@acme/kit/*/x": ["./x/*"], + "@acme/*/*": ["./two/*"], + } + web = _kit(tmp_path, configured) + + _run(tmp_path) + paths = json.loads(web.read_text())["compilerOptions"]["paths"] + assert paths == { + "@acme/shared": ["../packages/shared/src/index.ts"], + "@acme/kit": ["../packages/kit/src/index.ts"], + "@acme/kit/feature": ["../packages/kit/src/feature.ts"], + **configured, + } + + +def test_alias_in_effect_keeps_its_exact_key(tmp_path: Path) -> None: + web = _kit(tmp_path, {"@acme/kit/feature": ["./local/feature.ts"]}) + + assert "+2 paths" in _run(tmp_path) + paths = json.loads(web.read_text())["compilerOptions"]["paths"] + assert paths == { + "@acme/shared": ["../packages/shared/src/index.ts"], + "@acme/kit": ["../packages/kit/src/index.ts"], + "@acme/kit/feature": ["./local/feature.ts"], + } From 85e5b5a589d559e4310d19dc5d8c1691215d329c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:09:46 +0000 Subject: [PATCH 5/7] The paths rewrite patches the config each umbrella member is indexed through An umbrella may reference a member by its config file, such as packages/app/tsconfig.build.json, but the rewrite patched only each package's tsconfig.json. The harness now passes the configs it gives the indexer to scip_ts_paths.py with --config, and restores those same files. Each config is computed from the configs as the project wrote them, so a named config that extends a rewritten tsconfig.json gets the same entries in either order, and never the entries added for that parent. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_typescript_delta.sh | 32 ++++-- scripts/scip_harness/scip_ts_paths.py | 105 +++++++++++------- .../test_run_typescript_delta_umbrella.py | 53 +++++++++ tests/unit/test_scip_ts_paths.py | 84 ++++++++++++++ 4 files changed, 227 insertions(+), 47 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 0b1b3720d5f..4ffa6256de8 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -49,8 +49,8 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then # umbrella root tsconfig: index member projects instead of loading the root. # One path per line (a member directory may contain a space). SCIP_TS_PATHS - # stays as configured: the rewrite lands in each member's tsconfig.json, and - # in an unbuilt workspace it is what resolves imports between members. + # stays as configured: the rewrite lands in the config each member is indexed + # through, and in an unbuilt workspace it resolves imports between members. mapfile -t PROJECTS <<<"$discovered" WORKSPACES="" fi @@ -104,21 +104,28 @@ PYEOF fi fi +# paths_rewrite [tsconfig...]: scip_ts_paths.py over the given configs, or +# over every workspace package's tsconfig.json when none is given; the same +# files are restored on exit. +paths_rewrite() { + local args=("$CHECKOUT") cfg + for cfg in "$@"; do args+=(--config "$cfg"); done + "$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "${args[@]}" >&2 + # shellcheck disable=SC2016 # $PYTHON and $HARNESS_DIR expand when the exit hook runs + on_exit '"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" '"$(printf '%q ' "${args[@]}")"'--restore >/dev/null 2>&1' +} + # index_workspace: scip-typescript over the checkout into $WORK/index.scip. # Everything it writes into the tree (the tsconfig paths, a named project's # tsconfig.scip.json and package.json stub) is undone on exit. index_workspace() { - local targets=() proj - if [[ "$SCIP_TS_PATHS" == "1" ]]; then - "$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "$CHECKOUT" >&2 - # shellcheck disable=SC2016 # expanded when the exit hook runs - on_exit '"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "$CHECKOUT" --restore >/dev/null 2>&1' - fi + local targets=() configs=() proj for proj in "${PROJECTS[@]}"; do proj=${proj%/} # An umbrella reference may name a tsconfig file (e.g. tsconfig.build.json). if [[ -f "$proj" ]]; then targets+=("$proj") + configs+=("$proj") continue fi [[ -d "$proj" ]] || { @@ -127,6 +134,7 @@ index_workspace() { } if [[ -f "$proj/tsconfig.json" ]]; then targets+=("$proj") + configs+=("$proj/tsconfig.json") continue fi on_exit "rm -f $(printf %q "$proj/tsconfig.scip.json")" @@ -142,6 +150,14 @@ JSONEOF fi targets+=("$proj/tsconfig.scip.json") done + if [[ "$SCIP_TS_PATHS" == "1" ]]; then + # A member list rewrites exactly the configs the indexer is given. + if [[ ${#ALL_PROJECTS[@]} -eq 0 ]]; then + paths_rewrite + elif [[ ${#configs[@]} -gt 0 ]]; then + paths_rewrite "${configs[@]}" + fi + fi local ws=() [[ -n "$WORKSPACES" ]] && ws=("$WORKSPACES") # One indexer process per member: scip-typescript walks every target in a diff --git a/scripts/scip_harness/scip_ts_paths.py b/scripts/scip_harness/scip_ts_paths.py index d1f9bf06fd4..595660189b0 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -12,15 +12,19 @@ package's `exports` (and `main` / `types`), mapping each specifier to the SOURCE file the build target came from (`dist/` → `src/`, `.js` → `.ts` / `.tsx`, an existing file wins), and writes them into the consumer packages' -`tsconfig.json` — a backup `tsconfig.json.scip-bak` sits beside each, and -`--restore` puts the originals back. A `paths` written into a tsconfig +`tsconfig.json`, or into the files `--config` names, which are the configs +the indexer is given — a backup `.scip-bak` sits beside each, and +`--restore` with the same arguments puts the originals back. Each config is +computed from the configs as the project wrote them, so one that extends a +config rewritten in the same pass gets the same entries in either order, and +never the entries added for that parent. A `paths` written into a tsconfig replaces the one its `extends` chain set, so the aliases in effect are carried over, and the added entries are written against the `baseUrl` in effect, which is left as it is. An entry is left out when an alias in effect already matches its specifier. Run it before `scip-typescript index` on a checkout that has no build output; skip it on a built checkout. - python scip_ts_paths.py [--restore] [--dry-run] + python scip_ts_paths.py [--config ]... [--restore] [--dry-run] """ from __future__ import annotations @@ -310,55 +314,78 @@ def _matched(spec: str, keys: Iterable[str]) -> bool: return False +def _owner(cfg_dir: Path, packages: list[tuple[str, Path, dict[str, Any]]]) -> Path | None: + """The directory of the innermost workspace package holding a config.""" + holders = [d for _n, d, _ in packages if cfg_dir == d or d in cfg_dir.parents] + return max(holders, key=lambda d: len(d.parts), default=None) + + +def _patch( + tsconfig: Path, root: Path, packages: list[tuple[str, Path, dict[str, Any]]], dry: bool +) -> bool: + """Write the workspace entries into one tsconfig; whether it changed.""" + cfg_dir = tsconfig.parent + cfg = _parse_tsconfig(_config_text(tsconfig)) + if cfg is None: + print(f"skip {tsconfig}: not parseable", file=sys.stderr) + return False + try: + existing, existing_dir, base_url = effective_options( + cfg, cfg_dir, cfg_dir, frozenset({tsconfig.resolve()}) + ) + except ExtendsNotFollowed as err: + print(f"skip {tsconfig}: extends not followed ({err})", file=sys.stderr) + return False + owner = _owner(cfg_dir, packages) + paths = paths_for(cfg_dir, [p for p in packages if p[1] != owner], base_url) + # a specifier an alias in effect matches keeps that alias + paths = {k: v for k, v in paths.items() if not _matched(k, existing or {})} + if not paths: + return False + if existing and base_url is None: + existing = _rebased(existing, existing_dir, cfg_dir) + co = cfg.setdefault("compilerOptions", {}) + # the aliases already in effect win; the baseUrl in effect stays + co["paths"] = {**paths, **(existing or {})} + rel = os.path.relpath(tsconfig, root).replace(os.sep, "/") + print(f"{rel}: +{len(paths)} paths") + if dry: + return False + backup = tsconfig.with_name(tsconfig.name + ".scip-bak") + if not backup.exists(): + backup.write_bytes(tsconfig.read_bytes()) + tsconfig.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8") + return True + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("checkout") + ap.add_argument( + "--config", + action="append", + default=[], + help="a tsconfig to patch, relative to the checkout (repeatable); " + "default: every workspace package's tsconfig.json", + ) ap.add_argument("--restore", action="store_true") ap.add_argument("--dry-run", action="store_true") args = ap.parse_args() root = Path(args.checkout).resolve() packages = workspace_packages(root) + if args.config: + configs = list(dict.fromkeys(Path(os.path.normpath(root / c)) for c in args.config)) + else: + configs = [pkg_dir / "tsconfig.json" for _n, pkg_dir, _d in packages] changed = 0 - for _name, pkg_dir, _data in packages: - tsconfig = pkg_dir / "tsconfig.json" - backup = pkg_dir / "tsconfig.json.scip-bak" + for tsconfig in configs: + backup = tsconfig.with_name(tsconfig.name + ".scip-bak") if args.restore: if backup.exists(): backup.replace(tsconfig) changed += 1 - continue - if not tsconfig.exists(): - continue - text = _config_text(tsconfig) - cfg = _parse_tsconfig(text) - if cfg is None: - print(f"skip {tsconfig}: not parseable", file=sys.stderr) - continue - try: - existing, existing_dir, base_url = effective_options( - cfg, pkg_dir, pkg_dir, frozenset({tsconfig.resolve()}) - ) - except ExtendsNotFollowed as err: - print(f"skip {tsconfig}: extends not followed ({err})", file=sys.stderr) - continue - paths = paths_for(pkg_dir, packages, base_url) - # a specifier an alias in effect matches keeps that alias - paths = {k: v for k, v in paths.items() if not _matched(k, existing or {})} - if not paths: - continue - if existing and base_url is None: - existing = _rebased(existing, existing_dir, pkg_dir) - co = cfg.setdefault("compilerOptions", {}) - # the aliases already in effect win; the baseUrl in effect stays - co["paths"] = {**paths, **(existing or {})} - if args.dry_run: - print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") - continue - if not backup.exists(): - backup.write_bytes(tsconfig.read_bytes()) - tsconfig.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8") - changed += 1 - print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") + elif tsconfig.exists(): + changed += _patch(tsconfig, root, packages, args.dry_run) print(f"{'restored' if args.restore else 'patched'} {changed} tsconfig(s)") return 0 diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index b1e975259c7..f97c5db355f 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -23,6 +23,11 @@ for a in "$@"; do if [[ -f "$a/tsconfig.json" ]]; then printf '%s\\t%s\\n' "$a" "$(tr -d '\\n' <"$a/tsconfig.json")" >>"$CALLS.tsconfig" + elif [[ "$a" == *.json && -f "$a" ]]; then + # A member named by its config file, and the package tsconfig.json beside it. + for c in "$a" "${a%/*}/tsconfig.json"; do + [[ -f "$c" ]] && printf '%s\\t%s\\n' "$c" "$(tr -d '\\n' <"$c")" >>"$CALLS.tsconfig" + done fi done while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done @@ -585,3 +590,51 @@ def test_umbrella_member_keeps_aliases_inherited_from_a_base_tsconfig(tmp_path: "@local/internal": ["internal/index.ts"], } assert "baseUrl" not in options + + +def test_umbrella_member_named_by_its_config_file_gets_the_paths(tmp_path: Path) -> None: + """An umbrella reference to `packages/app/tsconfig.build.json` is indexed + through that file, so the rewrite must land there, not in the package's + `tsconfig.json`, and the restore must undo that same file.""" + repo = tmp_path / "repo" + build = {"compilerOptions": {"strict": True}, "include": ["src"]} + files = { + "pnpm-workspace.yaml": 'packages:\n - "packages/*"\n', + "tsconfig.json": json.dumps( + { + "files": [], + "references": [ + {"path": "packages/app/tsconfig.build.json"}, + {"path": "packages/lib"}, + ], + } + ), + "packages/app/package.json": json.dumps({"name": "@x/app"}), + # not referenced by the umbrella, so not the config the indexer reads + "packages/app/tsconfig.json": json.dumps({"include": ["src", "test"]}), + "packages/app/tsconfig.build.json": json.dumps(build), + "packages/app/src/a.ts": 'import { b } from "@x/lib";\nexport const a = b;\n', + "packages/lib/package.json": json.dumps( + {"name": "@x/lib", "exports": {".": "./dist/index.js"}} + ), + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/index.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/app/tsconfig.build.json", "packages/lib"] + indexed = _indexed_tsconfigs(tmp_path) + assert indexed["packages/app/tsconfig.build.json"]["compilerOptions"] == { + "strict": True, + "paths": {"@x/lib": ["../lib/src/index.ts"]}, + } + assert indexed["packages/app/tsconfig.json"] == {"include": ["src", "test"]} + # Every file the rewrite touched is back, and no backup is left behind. + assert _git(repo, "status", "--porcelain", "--ignored", "--untracked-files=all") == "" diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index df604f83358..64a47161fbe 100644 --- a/tests/unit/test_scip_ts_paths.py +++ b/tests/unit/test_scip_ts_paths.py @@ -285,3 +285,87 @@ def test_alias_in_effect_keeps_its_exact_key(tmp_path: Path) -> None: "@acme/kit": ["../packages/kit/src/index.ts"], "@acme/kit/feature": ["./local/feature.ts"], } + + +def test_a_named_config_is_patched_and_restored_alone(tmp_path: Path) -> None: + """`--config` names the files the indexer reads; only those change.""" + _workspace(tmp_path) + web = tmp_path / "web" + build = web / "tsconfig.build.json" + build.write_bytes(b'{"compilerOptions": {"strict": true},\r\n "include": ["src"]}\r\n') + original = build.read_bytes() + beside = (web / "tsconfig.json").read_bytes() + + out = _run(tmp_path, "--config", "web/tsconfig.build.json") + assert "web/tsconfig.build.json: +1 paths" in out and "patched 1 tsconfig(s)" in out + cfg = json.loads(build.read_text()) + assert cfg["compilerOptions"]["paths"] == {"@acme/shared": ["../packages/shared/src/index.ts"]} + assert (web / "tsconfig.json").read_bytes() == beside + assert not (web / "tsconfig.json.scip-bak").exists() + + assert "restored 1" in _run(tmp_path, "--config", "web/tsconfig.build.json", "--restore") + assert build.read_bytes() == original + assert sorted(p.name for p in web.iterdir()) == [ + "package.json", + "tsconfig.build.json", + "tsconfig.json", + ] + + +def _chained(root: Path) -> list[str]: + """`web/tsconfig.build.json` extends `web/tsconfig.json`, and a config + in `@acme/shared` extends `web/tsconfig.json` from another package; all + three are selected.""" + _workspace(root) + web = root / "web" + (web / "src").mkdir() + (web / "src" / "index.ts").write_text("export const w = 1;\n") + (web / "package.json").write_text( + json.dumps({"name": "web", "exports": {".": "./dist/index.js"}}) + ) + (web / "tsconfig.json").write_text( + json.dumps({"compilerOptions": {"paths": {"@local/*": ["./local/*"]}}}) + ) + (web / "tsconfig.build.json").write_text(json.dumps({"extends": "./tsconfig.json"})) + shared = root / "packages" / "shared" + (shared / "tsconfig.build.json").write_text(json.dumps({"extends": "../../web/tsconfig.json"})) + return ["web/tsconfig.json", "web/tsconfig.build.json", "packages/shared/tsconfig.build.json"] + + +def _options(path: Path) -> dict: + return json.loads(path.read_text())["compilerOptions"] + + +def test_a_named_config_over_a_rewritten_tsconfig_reads_what_the_project_wrote( + tmp_path: Path, +) -> None: + """A selected config is computed from the configs as the project wrote + them: one that extends a rewritten `tsconfig.json` carries that file's + own aliases and its own workspace entries, never the entries added for + the parent, and the result is the same in either order.""" + results = [] + for order in (1, -1): + root = tmp_path / f"order{order}" + root.mkdir() + selected = _chained(root) + originals = {rel: (root / rel).read_bytes() for rel in selected} + flags = [arg for rel in selected[::order] for arg in ("--config", rel)] + assert "patched 3 tsconfig(s)" in _run(root, *flags) + results.append({rel: _options(root / rel) for rel in selected}) + _run(root, *flags, "--restore") + assert {rel: (root / rel).read_bytes() for rel in selected} == originals + assert not list(root.rglob("*.scip-bak")) + assert results[0] == results[1] + got = results[0] + assert got["web/tsconfig.json"]["paths"] == { + "@acme/shared": ["../packages/shared/src/index.ts"], + "@local/*": ["./local/*"], + } + # Same package: the same entries as its parent, each once. + assert got["web/tsconfig.build.json"]["paths"] == got["web/tsconfig.json"]["paths"] + # Another package: `web` is added for it, the parent's `@acme/shared` + # (this package's own name) is not, and the alias resolves from `web`. + assert got["packages/shared/tsconfig.build.json"]["paths"] == { + "web": ["../../web/src/index.ts"], + "@local/*": ["../../web/local/*"], + } From 790d12c727809a1eea7eea5cb6f1523373f2ae8a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:52:24 +0000 Subject: [PATCH 6/7] The paths rewrite includes the generated tsconfig.scip.json A member directory with no tsconfig.json is indexed through the tsconfig.scip.json the harness writes, but that file was not in the --config list, so a sibling exporting unbuilt dist files had no alias in the config the indexer read. Add it to the list. The restore puts the generated bytes back and the exit hook removes the file, so the tree is clean afterwards. Assisted-by: Claude Code Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_typescript_delta.sh | 1 + .../test_run_typescript_delta_umbrella.py | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 4ffa6256de8..45cdc8a45af 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -149,6 +149,7 @@ JSONEOF printf '{"name": "scip-%s", "version": "0.0.0", "private": true}\n' "${proj//\//-}" >"$proj/package.json" fi targets+=("$proj/tsconfig.scip.json") + configs+=("$proj/tsconfig.scip.json") done if [[ "$SCIP_TS_PATHS" == "1" ]]; then # A member list rewrites exactly the configs the indexer is given. diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index ef0651d0213..a680ebc60d1 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -640,6 +640,42 @@ def test_umbrella_member_named_by_its_config_file_gets_the_paths(tmp_path: Path) assert _git(repo, "status", "--porcelain", "--ignored", "--untracked-files=all") == "" +def test_umbrella_member_without_a_tsconfig_gets_the_paths_in_its_generated_one( + tmp_path: Path, +) -> None: + """A member directory with no `tsconfig.json` is indexed through the + `tsconfig.scip.json` the harness writes, so the rewrite must reach that + file too, and the file must be gone again afterwards.""" + repo = tmp_path / "repo" + files = { + "pnpm-workspace.yaml": 'packages:\n - "packages/*"\n', + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "packages/app/package.json": json.dumps({"name": "@x/app"}), + "packages/app/src/a.ts": 'import { b } from "@x/lib";\nexport const a = b;\n', + "packages/lib/package.json": json.dumps( + {"name": "@x/lib", "exports": {".": "./dist/index.js"}} + ), + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/index.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/app/tsconfig.scip.json", "packages/lib"] + generated = _indexed_tsconfigs(tmp_path)["packages/app/tsconfig.scip.json"] + assert generated["compilerOptions"]["paths"] == {"@x/lib": ["../lib/src/index.ts"]} + # The generated config and its backup are gone, and the tree is as committed. + assert _git(repo, "status", "--porcelain", "--ignored", "--untracked-files=all") == "" + + def _commit_tree_files(repo: Path, parent: str, files: dict[bytes, bytes]) -> str: """Commit `files` on top of `parent` with Git plumbing and return the new sha. From fb9b3c8a0c9e00e06cc24e9859cf35885338be3d Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 08:53:58 +0000 Subject: [PATCH 7/7] Strip tsconfig trailing commas outside strings The trailing-comma substitution also ran inside quoted values, so an alias such as "./file,].ts" lost its comma and the rewritten config carried the changed path. Match a quoted string first and keep it, as the comment pass before it does. Assisted-by: Claude Code Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_ts_paths.py | 6 +++++- tests/unit/test_scip_ts_paths.py | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_ts_paths.py b/scripts/scip_harness/scip_ts_paths.py index 595660189b0..f6f2eecb1da 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -196,7 +196,11 @@ def _parse_tsconfig(text: str) -> dict[str, Any] | None: text, flags=re.S, ) - stripped = re.sub(r",(\s*[}\]])", r"\1", stripped) + stripped = re.sub( + r'("(?:\\.|[^"\\])*")|,(?=\s*[}\]])', + lambda m: m.group(1) or "", + stripped, + ) try: cfg = json.loads(stripped) except ValueError: diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index 64a47161fbe..1ffe9f74f72 100644 --- a/tests/unit/test_scip_ts_paths.py +++ b/tests/unit/test_scip_ts_paths.py @@ -369,3 +369,11 @@ def test_a_named_config_over_a_rewritten_tsconfig_reads_what_the_project_wrote( "web": ["../../web/src/index.ts"], "@local/*": ["../../web/local/*"], } + + +def test_trailing_comma_strip_leaves_a_quoted_value_alone() -> None: + cfg = _load("scip_ts_paths")._parse_tsconfig( + '{"compilerOptions": {"paths": {"@local": ["./file,].ts",],},},}' + ) + assert cfg is not None + assert cfg["compilerOptions"]["paths"] == {"@local": ["./file,].ts"]}