diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 0b0fa745574..45cdc8a45af 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 the config each member is indexed + # through, and in an unbuilt workspace it 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. @@ -103,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" ]] || { @@ -126,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")" @@ -140,7 +149,16 @@ 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. + 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 d1cb787017b..f6f2eecb1da 100755 --- a/scripts/scip_harness/scip_ts_paths.py +++ b/scripts/scip_harness/scip_ts_paths.py @@ -12,11 +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. Run it before `scip-typescript index` +`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 @@ -26,11 +34,14 @@ import os import re import sys +from collections.abc import Iterable 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") _CONDITIONS = ("types", "import", "module", "default", "require", "node") +_CONFIG_DIR = "${configdir}" def _pick(target): @@ -121,9 +132,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,59 +174,222 @@ 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: + # 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( + r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', + lambda m: m.group(1) or "", + text, + flags=re.S, + ) + stripped = re.sub( + r'("(?:\\.|[^"\\])*")|,(?=\s*[}\]])', + lambda m: m.group(1) or "", + 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: 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: + 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 _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 _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, 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. `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: + 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: + 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: + 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 _has_config_dir(t) and not os.path.isabs(t) + else t + for t in targets + ] + 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 _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 - 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: - print(f"skip {tsconfig}: not parseable", file=sys.stderr) - continue - co = cfg.setdefault("compilerOptions", {}) - existing = co.get("paths") or {} - co["paths"] = {**paths, **existing} # a package's own aliases win - co.setdefault("baseUrl", ".") - if args.dry_run: - print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths") - continue - if not backup.exists(): - backup.write_text(text, encoding="utf-8") - 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 809c2987ebf..a680ebc60d1 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,24 @@ 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" + 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 """ _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 +79,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 +97,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 +128,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") @@ -477,6 +538,144 @@ def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: 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 + + +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") == "" + + +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. diff --git a/tests/unit/test_scip_ts_paths.py b/tests/unit/test_scip_ts_paths.py index bfaa571026a..1ffe9f74f72 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: @@ -99,3 +103,277 @@ 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"], "~/*": ["*"]}, + } + + +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 + + +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"], + } + + +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/*"], + } + + +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"]}