From 26c670b9d56fbaccf777a450b31b1b6129ef4138 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:35:43 -0500 Subject: [PATCH 1/4] feat(findings): copied-type-cast flags a cast onto a same-name copy of the value's type Co-Authored-By: Claude Opus 5.5 --- docs/CODE_MAP.md | 1 + .../services/findings/copied_type_casts.mjs | 104 +++++++++++++ .../services/findings/copied_type_casts.py | 139 ++++++++++++++++++ server/app/services/findings/runner.py | 6 +- server/app/services/findings/tools.py | 2 +- server/tests/test_copied_type_casts.py | 69 +++++++++ site/src/Reference.tsx | 1 + site/src/docs/pages/findings.md | 2 +- skills/srcly-code-quality/SKILL.md | 1 + 9 files changed, 321 insertions(+), 4 deletions(-) create mode 100644 server/app/services/findings/copied_type_casts.mjs create mode 100644 server/app/services/findings/copied_type_casts.py create mode 100644 server/tests/test_copied_type_casts.py diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index 4f83bcaf..1fb7d25e 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -86,6 +86,7 @@ Browser | Solid rule `solid-returned-cleanup` (a function returned from `onMount`/`createEffect`, which Solid ignores) on files that import `solid-js` | `server/app/services/findings/solid.py` | | Await-in-loop rule (`await-in-loop`, `[db]` rank when the loop walks an awaited `prisma.*`/`findMany` result); skips pagination/retry/chain loops, `tx.*` in transactions, `Promise.all` chunks, sleeps and tests | `server/app/services/findings/async_loops.py` | | Duplicate-type rule (`duplicate-type`): a non-exported top-level object type (`type X = {…}` or `interface`) whose name another non-test file exports, when at least 3 of its fields, and at least half, match that type by name and declared type text; tests and `.d.ts` skipped | `server/app/services/findings/duplicate_types.py` (`object_types`, `find_copies`, `DuplicateTypeTool`); test `server/tests/test_duplicate_types.py` | +| Copied-type cast rule (`copied-type-cast`): a cast (`x as T`, payloads of `Promise<…>` compared) whose operand type and `T` are different named declarations with one name, one of them the project's own; runs `copied_type_casts.mjs` with the project's `typescript` per tsc config; anonymous types, lib-vs-lib, tests and portable snapshots skipped | `server/app/services/findings/copied_type_casts.py` (`plan`, `CopiedTypeCastTool`, `parse_output`) and `copied_type_casts.mjs`; test `server/tests/test_copied_type_casts.py` | | Rule-pack runner: a project's ast-grep YAML rules in `.srcly/rules/` (`ast-grep scan --json=stream`, binary from `SRCLY_AST_GREP`, `node_modules/.bin`, or PATH; missing → N/A); starter rules in `docs/rule-packs/` | `server/app/services/findings/astgrep.py` (`plan`, `AstGrepTool`, `parse_output`) | | `srcly findings [path] --rule `: every finding as `path:line rule message` with a count per rule (`--format json`); a count is N/A with the reason when a checker that could report the rule failed or checked no file (srcly tools and ast-grep declare `Tool.rules`; `typescript.unscheduled` lists configured checks that were not planned) | `server/app/services/findings/listing.py` (`build`, `render`, `run`); CLI in `server/app/run.py`; test `server/tests/test_findings_listing.py` | | `srcly fix`: findings carry `fix` (byte edits or a file delete); diff by default, `--write` applies, deletes only with `--rule unreachable-file`; fixers are `reachability.py` (drop `export`, delete file) and `solid.py` (`onCleanup`) | `server/app/services/findings/fixes.py` (`plan`, `diff`, `run`); CLI in `server/app/run.py`; proof in `server/tests/test_fixes.py` (real `tsc` before and after) | diff --git a/server/app/services/findings/copied_type_casts.mjs b/server/app/services/findings/copied_type_casts.mjs new file mode 100644 index 00000000..f756969b --- /dev/null +++ b/server/app/services/findings/copied_type_casts.mjs @@ -0,0 +1,104 @@ +// srcly's `copied-type-cast` checker: one tsconfig's casts onto a same-name copy of the operand's type. +// Run by copied_type_casts.py: node copied_type_casts.mjs +// It loads the project's own `typescript` (resolved from the tsconfig), so the +// checker sees the project the way its tsc does. Prints one JSON object. +import { createRequire } from "node:module"; +import path from "node:path"; + +const [configPath, scopeDir] = process.argv.slice(2); +let ts; +try { + ts = createRequire(path.resolve(configPath))("typescript"); +} catch { + console.log(JSON.stringify({ error: "the project has no `typescript` package" })); + process.exit(0); +} + +const configError = []; +const config = ts.getParsedCommandLineOfConfigFile(configPath, {}, { + ...ts.sys, + onUnRecoverableConfigFileDiagnostic: (d) => configError.push(ts.flattenDiagnosticMessageText(d.messageText, " ")), +}); +if (!config || configError.length) { + console.log(JSON.stringify({ error: configError[0] ?? "unreadable tsconfig" })); + process.exit(0); +} +const program = ts.createProgram({ + rootNames: config.fileNames, + options: { ...config.options, noEmit: true }, + projectReferences: config.projectReferences, +}); +const checker = program.getTypeChecker(); +const scope = path.resolve(scopeDir) + path.sep; +const inNodeModules = (file) => file.split(/[\\/]/).includes("node_modules"); +const isProjectFile = (sf) => + !sf.isDeclarationFile && !inNodeModules(sf.fileName) && path.resolve(sf.fileName).startsWith(scope); +// A declaration the project wrote, as opposed to one from a library or lib.d.ts. +const isOwn = (sf) => + !program.isSourceFileDefaultLibrary(sf) && !program.isSourceFileFromExternalLibrary(sf) && !inNodeModules(sf.fileName); + +function unwrapPromise(type) { + if (type.getSymbol()?.getName() !== "Promise") return null; + const args = checker.getTypeArguments(type); + return args?.length === 1 ? args[0] : null; +} + +// The named declaration behind a type: its alias (`type X = …`) or its +// class/interface/enum symbol. Anonymous object types (`__type`, `__object`) +// have no name to share and are left out. +function named(type) { + const sym = type.aliasSymbol ?? type.getSymbol(); + const decl = sym?.declarations?.[0]; + if (!sym || !decl || sym.getName().startsWith("__")) return null; + const sf = decl.getSourceFile(); + return { + sym, + name: sym.getName(), + file: path.resolve(sf.fileName), + line: sf.getLineAndCharacterOfPosition(decl.getStart(sf)).line + 1, + own: isOwn(sf), + }; +} + +const files = []; +const casts = []; +for (const sf of program.getSourceFiles()) { + if (!isProjectFile(sf)) continue; + files.push(path.resolve(sf.fileName)); + const visit = (node) => { + if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) { + const typeNode = node.type; + const isConst = ts.isTypeReferenceNode(typeNode) && typeNode.typeName.getText(sf) === "const"; + if (!isConst) check(sf, node); + } + ts.forEachChild(node, visit); + }; + visit(sf); +} + +function check(sf, node) { + let src = checker.getTypeAtLocation(node.expression); + let tgt = checker.getTypeFromTypeNode(node.type); + // `fetchDoc(id) as Promise`: the copy hides in the payload. + const ps = unwrapPromise(src), pt = unwrapPromise(tgt); + if (ps && pt) [src, tgt] = [ps, pt]; + const a = named(src), b = named(tgt); + if (!a || !b || a.name !== b.name || a.sym === b.sym) return; + if (a.file === b.file && a.line === b.line) return; + // Two library declarations (DOM's and Node's `ReadableStream`) are not the project's copy. + if (!a.own && !b.own) return; + const start = sf.getLineAndCharacterOfPosition(node.getStart(sf)); + const end = sf.getLineAndCharacterOfPosition(node.getEnd()); + casts.push({ + file: path.resolve(sf.fileName), + line: start.line + 1, + endLine: end.line + 1, + column: start.character + 1, + text: node.getText(sf).replace(/\s+/g, " ").slice(0, 80), + name: a.name, + source: { file: a.file, line: a.line }, + target: { file: b.file, line: b.line }, + }); +} + +console.log(JSON.stringify({ files, casts })); diff --git a/server/app/services/findings/copied_type_casts.py b/server/app/services/findings/copied_type_casts.py new file mode 100644 index 00000000..91bd0088 --- /dev/null +++ b/server/app/services/findings/copied_type_casts.py @@ -0,0 +1,139 @@ +"""srcly's ``copied-type-cast`` rule: a cast onto a same-name copy of the operand's type. + +``fetchDoc(id) as Promise`` where ``fetchDoc`` returns the +``DocDetail`` from ``docs.queries.ts`` and the file casts it to its own +``DocDetail``. The two types share a name but are two declarations, and the +cast is what keeps tsc from comparing them. ``duplicate-type`` finds the copied +declaration by its fields; this rule finds the cast that hides it, so it also +catches copies of a library type (``t.status as ChatThreadStatus`` onto a local +copy of Prisma's enum) and copies whose fields have drifted. + +A cast (``x as T`` or ``x``, not ``as const``) is reported when: + +- the operand's type and ``T`` are both named types (a type alias, interface, + class or enum) with the same name; for ``Promise as Promise`` the + payloads ``A`` and ``B`` are compared; +- they are different symbols, so not one declaration seen twice or one + interface merged across files; +- at least one of the two is declared in the project, not in a library or + ``lib.d.ts`` (DOM's and Node's ``ReadableStream`` are not the project's copy). + +Anonymous object types (``as { x: number }``) have no name and are left out. +The rule needs the type checker, so it runs a small Node script +(``copied_type_casts.mjs``) with the project's own ``typescript`` once per +tsconfig, for projects that install ``typescript``. Test files and ``.d.ts`` +files are skipped. It is not run for portable (compare) snapshots. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Optional + +from app.services.deps.common import is_test_path +from app.services.findings import typescript +from app.services.findings.model import Finding, rel_label +from app.services.findings.tools import MissingTool, Tool, ToolFailed, find_up, first_line, run_process, timeout_for + +SCRIPT = Path(__file__).with_name("copied_type_casts.mjs") +RULE = "copied-type-cast" + + +def _where(file: str, line: int, root: Path) -> str: + """A declaration as ``path:line``: relative to the root, or from the package for a library.""" + path = Path(file) + try: + return f"{path.relative_to(root).as_posix()}:{line}" + except ValueError: + pass + parts = path.parts + if "node_modules" in parts: + last = len(parts) - 1 - parts[::-1].index("node_modules") + return f"{'/'.join(parts[last + 1:])}:{line}" + return f"{path.name}:{line}" + + +def parse_output(stdout: str, root: Path, tool_id: str) -> tuple[list[Finding], list[str]]: + try: + data = json.loads(stdout) + except json.JSONDecodeError as exc: + raise ToolFailed(f"unreadable JSON output ({exc.msg})") from exc + if data.get("error"): + raise ToolFailed(str(data["error"])) + + def keep(file: str) -> bool: + try: + rel = Path(file).relative_to(root).as_posix() + except ValueError: + return False + return not is_test_path(rel) + + files = [f for f in data.get("files", []) if keep(f)] + findings = [] + for cast in data.get("casts", []): + if not keep(cast["file"]): + continue + name, src, tgt = cast["name"], cast["source"], cast["target"] + findings.append( + Finding( + path=cast["file"], + line=cast["line"], + end_line=cast["endLine"], + column=cast["column"], + rule=RULE, + message=( + f"`{cast['text']}` casts the `{name}` from {_where(src['file'], src['line'], root)} " + f"to a different `{name}`, declared in {_where(tgt['file'], tgt['line'], root)}. " + f"The cast keeps tsc from comparing the two copies. Keep one declaration, import it, " + f"and drop the cast." + ), + severity="warning", + tool=tool_id, + ) + ) + return findings, files + + +class CopiedTypeCastTool(Tool): + rules = (RULE,) + + def __init__(self, root: Path, config: Path, node: str, label_base: Path) -> None: + name = rel_label(config, label_base) + super().__init__( + id=f"srcly-casts:{name}", + tool="srcly-casts", + label=f"srcly copied-type casts ({name})", + source="srcly defaults", + root=root, + extensions=typescript.TS_EXTENSIONS, + timeout=timeout_for("srcly-casts"), + signature_paths=(config, SCRIPT), + ) + self.config = config + self.node = node + + def check(self): + root = self.root.resolve() + out = run_process([self.node, str(SCRIPT), str(self.config), str(root)], self.config.parent, self.timeout) + if out.returncode != 0: + raise ToolFailed(first_line(out.stderr or out.stdout) or f"exit code {out.returncode}") + return parse_output(out.stdout, root, self.id) + + +def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: + """One run per tsconfig (as many as ``tsc`` gets) whose project has a ``typescript`` package; none otherwise.""" + from app.services.dataflow.availability import locate_node + + configs = [ + config + for config in typescript.tsconfigs(root, stop)[: typescript.MAX_TSC_PROJECTS] + if find_up(config.parent, "node_modules/typescript/package.json") + ] + if not configs: + return [] + node = locate_node() + if node is None: + return [MissingTool("srcly-casts", "srcly-casts", "srcly copied-type casts", root, typescript.TS_EXTENSIONS, "no Node on PATH (set SRCLY_NODE)")] + label_base = stop or root + return [CopiedTypeCastTool(root, config, node, label_base) for config in configs] diff --git a/server/app/services/findings/runner.py b/server/app/services/findings/runner.py index 6ecf2cbc..30bc8e58 100644 --- a/server/app/services/findings/runner.py +++ b/server/app/services/findings/runner.py @@ -13,7 +13,7 @@ from pathlib import Path from typing import Optional, Sequence -from app.services.findings import astgrep, async_loops, builtin_ts, duplicate_types, reachability, ruff, solid, typescript +from app.services.findings import astgrep, async_loops, builtin_ts, copied_type_casts, duplicate_types, reachability, ruff, solid, typescript from app.services.findings.model import Finding, FindingsResult, ToolRun from app.services.findings.tools import Tool, run @@ -36,7 +36,8 @@ def plan_tools(root: Path, *, portable: bool = False, stop: Optional[Path] = Non - srcly's reachability check over the whole TS import graph, and its Solid rules on every file that imports ``solid-js``, and its await-in-loop rule on every non-test JS/TS file, and its duplicate-type - rule over every non-test TS file; + rule over every non-test TS file, and its copied-type-cast rule (a + type-checked Node script) per project tsconfig; - the project's ast-grep rule pack in ``.srcly/rules/``, when it has one. """ root = root.resolve() @@ -54,6 +55,7 @@ def plan_tools(root: Path, *, portable: bool = False, stop: Optional[Path] = Non solid.SolidTool(root), async_loops.AwaitInLoopTool(root), duplicate_types.DuplicateTypeTool(root), + *([] if portable else copied_type_casts.plan(root, stop)), ] diff --git a/server/app/services/findings/tools.py b/server/app/services/findings/tools.py index 0ad608ac..071a8317 100644 --- a/server/app/services/findings/tools.py +++ b/server/app/services/findings/tools.py @@ -31,7 +31,7 @@ def _env_timeout(name: str, default: float) -> float: # Generous: these run in the background, never in front of the treemap. # ``SRCLY_FINDINGS_TIMEOUT`` overrides every tool's limit. -DEFAULT_TIMEOUTS = {"tsc": 120.0, "eslint": 120.0, "ruff": 60.0, "srcly-ts": 60.0, "srcly-reach": 60.0, "srcly-solid": 60.0, "srcly-async": 60.0, "srcly-dup-types": 60.0, "ast-grep": 60.0} +DEFAULT_TIMEOUTS = {"tsc": 120.0, "eslint": 120.0, "ruff": 60.0, "srcly-ts": 60.0, "srcly-reach": 60.0, "srcly-solid": 60.0, "srcly-async": 60.0, "srcly-dup-types": 60.0, "srcly-casts": 120.0, "ast-grep": 60.0} def timeout_for(tool: str) -> float: diff --git a/server/tests/test_copied_type_casts.py b/server/tests/test_copied_type_casts.py new file mode 100644 index 00000000..0fbb17e3 --- /dev/null +++ b/server/tests/test_copied_type_casts.py @@ -0,0 +1,69 @@ +"""``copied-type-cast`` on a small project, through the real TypeScript checker. Skips without Node or engine/node_modules.""" + +import shutil +from pathlib import Path + +import pytest + +from app.services.dataflow.availability import ENGINE_DIR +from app.services.findings import copied_type_casts +from app.services.findings.tools import run + +TS = ENGINE_DIR / "node_modules" / "typescript" +pytestmark = pytest.mark.skipif(shutil.which("node") is None or not TS.is_dir(), reason="needs Node and engine/node_modules") + + +def write(root: Path, rel: str, text: str) -> None: + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text, encoding="utf-8") + + +def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_path: Path): + root = tmp_path.resolve() + (root / "node_modules").mkdir() + (root / "node_modules" / "typescript").symlink_to(TS.resolve()) + write(root, "tsconfig.json", '{ "compilerOptions": { "strict": true, "noEmit": true, "lib": ["es2022", "dom"] }, "include": ["src"] }\n') + write( + root, + "src/api.ts", + "export type Doc = { id: string; title: string };\n" + 'export type Status = "open" | "done";\n' + "export declare function fetchDoc(id: string): Promise;\n" + "export declare function status(): Status;\n", + ) + write( + root, + "src/view.ts", + 'import { fetchDoc, status, type Doc as Shared } from "./api";\n' + "type Doc = { id: string; title: string; extra?: number };\n" + 'type Status = "open" | "done";\n' + # True: the payload of the promise is a same-name copy, and so is the union alias. + 'export const a = fetchDoc("1") as Promise;\n' + "export const b = status() as Status;\n" + # False: the same declaration under another local name, an anonymous shape, `as const`, a lib type. + 'export const c = fetchDoc("1") as Promise;\n' + "export const d = ({ id: \"1\" }) as { id: string };\n" + 'export const e = ["x"] as const;\n' + "export const f = new Blob().stream() as ReadableStream;\n", + ) + # Tests are skipped. + write(root, "src/view.test.ts", 'import { status } from "./api";\ntype Status = "open" | "done";\nexport const t = status() as Status;\n') + + tools = copied_type_casts.plan(root) + assert [t.id for t in tools] == ["srcly-casts:tsconfig.json"] + result, findings = run(tools[0]) + assert result.status == "ok", result.reason + assert sorted(Path(f).relative_to(root).as_posix() for f in result.files) == ["src/api.ts", "src/view.ts"] + got = {(Path(f.path).relative_to(root).as_posix(), f.line): f.message for f in findings} + assert list(got) == [("src/view.ts", 4), ("src/view.ts", 5)] + assert got[("src/view.ts", 4)].startswith( + '`fetchDoc("1") as Promise` casts the `Doc` from src/api.ts:1 to a different `Doc`, declared in src/view.ts:2.' + ) + assert "`Status` from src/api.ts:2" in got[("src/view.ts", 5)] + + +def test_a_project_without_typescript_gets_no_run(tmp_path: Path): + write(tmp_path, "tsconfig.json", "{}\n") + write(tmp_path, "src/a.ts", "export const a = 1 as number;\n") + assert copied_type_casts.plan(tmp_path) == [] diff --git a/site/src/Reference.tsx b/site/src/Reference.tsx index ad1cc14f..116f63dd 100644 --- a/site/src/Reference.tsx +++ b/site/src/Reference.tsx @@ -45,6 +45,7 @@ const checkers: [string, string][] = [ ['srcly reachability', 'Unreachable files and unused exports, walking imports from detected entries'], ['srcly Solid rules, await-in-loop', 'Solid cleanups returned from onMount or createEffect, and await inside a loop'], ['srcly duplicate types', 'A local object type that copies a type another file exports (fields matched by name and type)'], + ['srcly copied-type casts', 'A cast onto a type with the same name as the operand\'s type but another declaration (type-checked, per tsconfig)'], ['ast-grep', 'Your own YAML rules in .srcly/rules/'], ]; diff --git a/site/src/docs/pages/findings.md b/site/src/docs/pages/findings.md index f354be93..7f805a55 100644 --- a/site/src/docs/pages/findings.md +++ b/site/src/docs/pages/findings.md @@ -16,7 +16,7 @@ Srcly selects checks based on the files and tools it finds. Checks run independe | ast-grep rules | `.srcly/rules/` files exist and ast-grep is available | The optional binary or rule run is unavailable. | | Data-flow rules (`impossible-defense`, `repeated-fork`, `context-relay`, `broad-prop-bundle`) | You pass `--dataflow` to `report` or `compare`, and Node 18+ is available | The engine is missing, the root is not TypeScript, or the run failed. The reason is in `report.md`. | -The exact checks vary by project. Srcly runs `tsc` per detected TypeScript project, expands solution configurations, runs ESLint when configured, and runs Ruff for Python. Its built-in TS checks include selected patterns such as explicit `any`, suppression directives without a reason, and non-null assertion chains when project tools do not cover those files. It also reports selected reachability, Solid, and await-in-loop signals, and `duplicate-type`: a local object type that copies a type another file exports, so a change to the exported type does not reach the copy. Optional ast-grep YAML rules can add project-specific checks. See [Configuration](../configuration/) for setup. +The exact checks vary by project. Srcly runs `tsc` per detected TypeScript project, expands solution configurations, runs ESLint when configured, and runs Ruff for Python. Its built-in TS checks include selected patterns such as explicit `any`, suppression directives without a reason, and non-null assertion chains when project tools do not cover those files. It also reports selected reachability, Solid, and await-in-loop signals, and `duplicate-type`: a local object type that copies a type another file exports, so a change to the exported type does not reach the copy, and `copied-type-cast`: a cast such as `fetchDoc(id) as Promise` onto a type with the same name as the value's type but another declaration, which keeps tsc from comparing the two copies (it runs the project's own TypeScript checker once per `tsc` project). Optional ast-grep YAML rules can add project-specific checks. See [Configuration](../configuration/) for setup. ## Read a finding diff --git a/skills/srcly-code-quality/SKILL.md b/skills/srcly-code-quality/SKILL.md index 4533a08c..1ec03090 100644 --- a/skills/srcly-code-quality/SKILL.md +++ b/skills/srcly-code-quality/SKILL.md @@ -94,6 +94,7 @@ Progress, version banners and cache warnings go to stderr, so stdout stays parse - TSX render branching, prop count, inline handlers, and nesting: UI complexity and test-surface risk. - `any` usage and TS ignore directives: type-safety debt. - `duplicate-type`: a local type copies one another file exports. Run `srcly refs `, move the callers to the exported type, delete the copy and any casts that hid it, all in one change. Compare `srcly findings . --rule duplicate-type` before and after. +- `copied-type-cast`: a cast onto a same-name copy of the value's type (`fetchDoc(id) as Promise`, `t.status as RunStatus` onto a local copy of a Prisma enum). Import the one declaration, delete the copy, drop the cast; tsc then checks the two sides. Fix it together with any `duplicate-type` hit on the same name. - Import coupling and dependency graph density: dependency-boundary review targets. - TODOs in complex files: maintenance markers worth validating. - Low comment density only matters when paired with complexity, public API behavior, or non-obvious domain logic. From adfc6719a355567f54d73a2e1a6cd3ba7da6589f Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:47:31 -0500 Subject: [PATCH 2/4] fix(findings): copied-type-cast reads N/A for broken or skipped configs, resolves enum members, checks one-file roots Co-Authored-By: Claude Opus 5.5 --- .../services/findings/copied_type_casts.mjs | 26 +++-- .../services/findings/copied_type_casts.py | 95 +++++++++++++++---- server/app/services/findings/listing.py | 15 ++- server/tests/test_copied_type_casts.py | 86 +++++++++++++---- 4 files changed, 174 insertions(+), 48 deletions(-) diff --git a/server/app/services/findings/copied_type_casts.mjs b/server/app/services/findings/copied_type_casts.mjs index f756969b..5e96adc7 100644 --- a/server/app/services/findings/copied_type_casts.mjs +++ b/server/app/services/findings/copied_type_casts.mjs @@ -19,8 +19,12 @@ const config = ts.getParsedCommandLineOfConfigFile(configPath, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: (d) => configError.push(ts.flattenDiagnosticMessageText(d.messageText, " ")), }); +// A broken config (a missing `extends` base) changes what the checker sees: N/A, not a clean 0. +// TS18003 (no inputs) is an empty project, which checks nothing. +const fatal = config?.errors.find((d) => d.code !== 18003); +if (fatal) configError.push(ts.flattenDiagnosticMessageText(fatal.messageText, " ")); if (!config || configError.length) { - console.log(JSON.stringify({ error: configError[0] ?? "unreadable tsconfig" })); + console.log(JSON.stringify({ error: `tsconfig: ${configError[0] ?? "unreadable"}` })); process.exit(0); } const program = ts.createProgram({ @@ -29,10 +33,12 @@ const program = ts.createProgram({ projectReferences: config.projectReferences, }); const checker = program.getTypeChecker(); -const scope = path.resolve(scopeDir) + path.sep; +// The scan root: a folder, or one file. +const scope = path.resolve(scopeDir); +const inScope = (file) => file === scope || file.startsWith(scope + path.sep); const inNodeModules = (file) => file.split(/[\\/]/).includes("node_modules"); const isProjectFile = (sf) => - !sf.isDeclarationFile && !inNodeModules(sf.fileName) && path.resolve(sf.fileName).startsWith(scope); + !sf.isDeclarationFile && !inNodeModules(sf.fileName) && inScope(path.resolve(sf.fileName)); // A declaration the project wrote, as opposed to one from a library or lib.d.ts. const isOwn = (sf) => !program.isSourceFileDefaultLibrary(sf) && !program.isSourceFileFromExternalLibrary(sf) && !inNodeModules(sf.fileName); @@ -43,13 +49,19 @@ function unwrapPromise(type) { return args?.length === 1 ? args[0] : null; } +// Only these declare a type with a name another file can copy. +const NAMED = ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum; + // The named declaration behind a type: its alias (`type X = …`) or its -// class/interface/enum symbol. Anonymous object types (`__type`, `__object`) -// have no name to share and are left out. +// class/interface/enum symbol. An enum member (`Status.Ready`, or the one +// member of a one-member enum) stands for its enum. Anonymous object types, +// type parameters and anything else are left out. function named(type) { - const sym = type.aliasSymbol ?? type.getSymbol(); + if (type.flags & ts.TypeFlags.TypeParameter) return null; + let sym = type.aliasSymbol ?? type.getSymbol(); + if (sym && sym.flags & ts.SymbolFlags.EnumMember) sym = sym.parent; const decl = sym?.declarations?.[0]; - if (!sym || !decl || sym.getName().startsWith("__")) return null; + if (!sym || !decl || !(sym.flags & NAMED)) return null; const sf = decl.getSourceFile(); return { sym, diff --git a/server/app/services/findings/copied_type_casts.py b/server/app/services/findings/copied_type_casts.py index 91bd0088..c7dac9e6 100644 --- a/server/app/services/findings/copied_type_casts.py +++ b/server/app/services/findings/copied_type_casts.py @@ -27,14 +27,16 @@ class or enum) with the same name; for ``Promise as Promise`` the from __future__ import annotations +import hashlib import json +import os from pathlib import Path from typing import Optional from app.services.deps.common import is_test_path from app.services.findings import typescript from app.services.findings.model import Finding, rel_label -from app.services.findings.tools import MissingTool, Tool, ToolFailed, find_up, first_line, run_process, timeout_for +from app.services.findings.tools import _PRUNED_DIRS, Tool, ToolFailed, find_up, first_line, run_process, timeout_for SCRIPT = Path(__file__).with_name("copied_type_casts.mjs") RULE = "copied-type-cast" @@ -54,20 +56,26 @@ def _where(file: str, line: int, root: Path) -> str: return f"{path.name}:{line}" -def parse_output(stdout: str, root: Path, tool_id: str) -> tuple[list[Finding], list[str]]: +def _base(root: Path) -> Path: + return root if root.is_dir() else root.parent + + +def parse_output(stdout: str, root: Path, tool_id: str, display: Optional[Path] = None) -> tuple[list[Finding], list[str]]: + """The script's JSON as findings. Declarations show relative to ``display`` (the tsconfig's folder).""" try: data = json.loads(stdout) except json.JSONDecodeError as exc: raise ToolFailed(f"unreadable JSON output ({exc.msg})") from exc if data.get("error"): raise ToolFailed(str(data["error"])) + base = _base(root) + shown = display or base def keep(file: str) -> bool: - try: - rel = Path(file).relative_to(root).as_posix() - except ValueError: + path = Path(file) + if path != root and root not in path.parents: return False - return not is_test_path(rel) + return not is_test_path(path.relative_to(base).as_posix()) files = [f for f in data.get("files", []) if keep(f)] findings = [] @@ -83,8 +91,8 @@ def keep(file: str) -> bool: column=cast["column"], rule=RULE, message=( - f"`{cast['text']}` casts the `{name}` from {_where(src['file'], src['line'], root)} " - f"to a different `{name}`, declared in {_where(tgt['file'], tgt['line'], root)}. " + f"`{cast['text']}` casts the `{name}` from {_where(src['file'], src['line'], shown)} " + f"to a different `{name}`, declared in {_where(tgt['file'], tgt['line'], shown)}. " f"The cast keeps tsc from comparing the two copies. Keep one declaration, import it, " f"and drop the cast." ), @@ -95,6 +103,28 @@ def keep(file: str) -> bool: return findings, files +_INPUTS = typescript.TS_EXTENSIONS + (".json",) + + +def project_inputs(directory: Path) -> str: + """A digest of the TS and JSON files under a tsconfig's folder (path, size, mtime). + + The checker reads files outside the scanned folder (a sibling's exported + type), so the scan's own fingerprint cannot tell when a cached result is stale. + """ + digest = hashlib.sha256() + for dirpath, dirnames, filenames in os.walk(directory): + dirnames[:] = sorted(d for d in dirnames if d not in _PRUNED_DIRS and not d.startswith(".")) + for name in sorted(filenames): + if name.endswith(_INPUTS): + try: + st = os.stat(os.path.join(dirpath, name)) + except OSError: + continue + digest.update(f"{dirpath}/{name}:{st.st_size}:{st.st_mtime_ns}\n".encode()) + return digest.hexdigest()[:16] + + class CopiedTypeCastTool(Tool): rules = (RULE,) @@ -113,27 +143,50 @@ def __init__(self, root: Path, config: Path, node: str, label_base: Path) -> Non self.config = config self.node = node + def signature(self) -> str: + return f"{super().signature()}|inputs={project_inputs(self.config.parent)}" + def check(self): root = self.root.resolve() out = run_process([self.node, str(SCRIPT), str(self.config), str(root)], self.config.parent, self.timeout) if out.returncode != 0: raise ToolFailed(first_line(out.stderr or out.stdout) or f"exit code {out.returncode}") - return parse_output(out.stdout, root, self.id) + return parse_output(out.stdout, root, self.id, self.config.parent) -def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: - """One run per tsconfig (as many as ``tsc`` gets) whose project has a ``typescript`` package; none otherwise.""" +def _configs(root: Path, stop: Optional[Path]) -> list[tuple[Path, str]]: + """Every tsconfig for ``root``, with why the rule cannot check it (empty when it can).""" from app.services.dataflow.availability import locate_node - configs = [ - config - for config in typescript.tsconfigs(root, stop)[: typescript.MAX_TSC_PROJECTS] - if find_up(config.parent, "node_modules/typescript/package.json") - ] - if not configs: - return [] node = locate_node() - if node is None: - return [MissingTool("srcly-casts", "srcly-casts", "srcly copied-type casts", root, typescript.TS_EXTENSIONS, "no Node on PATH (set SRCLY_NODE)")] + out = [] + for index, config in enumerate(typescript.tsconfigs(root, stop)): + why = "" + if index >= typescript.MAX_TSC_PROJECTS: + why = f"over the limit of {typescript.MAX_TSC_PROJECTS} projects" + elif not find_up(config.parent, "node_modules/typescript/package.json"): + why = "no node_modules/typescript" + elif node is None: + why = "no Node on PATH (set SRCLY_NODE)" + out.append((config, why)) + return out + + +def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: + """One run per tsconfig the rule can check, as many as ``tsc`` gets.""" + from app.services.dataflow.availability import locate_node + label_base = stop or root - return [CopiedTypeCastTool(root, config, node, label_base) for config in configs] + configs = [config for config, why in _configs(root, stop) if not why] + node = locate_node() if configs else None + return [CopiedTypeCastTool(root, config, node, label_base) for config in configs] if node else [] + + +def unscheduled(root: Path, stop: Optional[Path] = None) -> list[tuple[str, str, str]]: + """Configs ``plan`` leaves out: (tool, label, reason). ``srcly findings`` reads the rule's count as N/A for them.""" + label_base = stop or root + return [ + ("srcly-casts", f"srcly copied-type casts ({rel_label(config, label_base)})", why) + for config, why in _configs(root, stop) + if why + ] diff --git a/server/app/services/findings/listing.py b/server/app/services/findings/listing.py index 621f79e5..aca31e61 100644 --- a/server/app/services/findings/listing.py +++ b/server/app/services/findings/listing.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import Optional, Sequence -from app.services.findings import typescript +from app.services.findings import copied_type_casts, typescript from app.services.findings.model import FindingsResult, ToolRun from app.services.findings.runner import collect, plan_tools from app.services.findings.tools import Tool @@ -22,6 +22,9 @@ Skipped = Sequence[tuple[str, str, str]] """Configured checks that were not planned: (tool, label, reason).""" +SKIPPED_RULES = {"srcly-casts": (copied_type_casts.RULE,)} +"""The rules a skipped srcly checker would have reported.""" + def _family(rule: str) -> str: """The project tool that names rules this way.""" @@ -42,11 +45,14 @@ def _blockers( checkers, left_out, name = list(tools), list(skipped), "checker" if rule is not None: owners = [t for t in tools if rule in t.rules] + skipped_owners = [s for s in skipped if rule in SKIPPED_RULES.get(s[0], ())] # An ast-grep id is the project's choice, so it may also be an eslint rule's name. shared = all(t.tool == "ast-grep" for t in owners) - family = _family(rule) if not owners else "eslint" if shared else None + family = None if owners or skipped_owners else _family(rule) + if owners and shared: + family = "eslint" checkers = [t for t in tools if t in owners or t.tool == family or t.id in reporters] - left_out = [s for s in skipped if s[0] == family] + left_out = [s for s in skipped if s[0] == family or s in skipped_owners] name = " or ".join(t.label for t in owners) or f"{family} run" why = [runs[t.id].reason for t in checkers if not runs[t.id].ok] why += [f"{label} not run: {reason}" for _, label, reason in left_out] @@ -140,5 +146,6 @@ def run(root: Path, rules: Sequence[str] = (), fmt: str = "md", refresh: bool = stop = find_repo_root(root if root.is_dir() else root.parent) tools = plan_tools(root, stop=stop) result = collect(root, fingerprint=cache.fingerprint(root), tools=tools, use_cache=not refresh) - payload = build(root, result, tools, rules, typescript.unscheduled(root, stop)) + skipped = typescript.unscheduled(root, stop) + copied_type_casts.unscheduled(root, stop) + payload = build(root, result, tools, rules, skipped) return json.dumps(payload, indent=2) if fmt == "json" else render(payload) diff --git a/server/tests/test_copied_type_casts.py b/server/tests/test_copied_type_casts.py index 0fbb17e3..dd42839f 100644 --- a/server/tests/test_copied_type_casts.py +++ b/server/tests/test_copied_type_casts.py @@ -1,12 +1,14 @@ """``copied-type-cast`` on a small project, through the real TypeScript checker. Skips without Node or engine/node_modules.""" +import os import shutil from pathlib import Path import pytest from app.services.dataflow.availability import ENGINE_DIR -from app.services.findings import copied_type_casts +from app.services.findings import copied_type_casts, listing +from app.services.findings.model import FindingsResult from app.services.findings.tools import run TS = ENGINE_DIR / "node_modules" / "typescript" @@ -19,18 +21,33 @@ def write(root: Path, rel: str, text: str) -> None: p.write_text(text, encoding="utf-8") -def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_path: Path): - root = tmp_path.resolve() - (root / "node_modules").mkdir() +def project(root: Path, config: str = '{ "compilerOptions": { "strict": true, "lib": ["es2022", "dom"] }, "include": ["src"] }\n') -> Path: + root = root.resolve() + (root / "node_modules").mkdir(parents=True) (root / "node_modules" / "typescript").symlink_to(TS.resolve()) - write(root, "tsconfig.json", '{ "compilerOptions": { "strict": true, "noEmit": true, "lib": ["es2022", "dom"] }, "include": ["src"] }\n') + write(root, "tsconfig.json", config) + return root + + +def findings_of(root: Path, scan: Path | None = None): + tools = copied_type_casts.plan(scan or root) + assert [t.id for t in tools] == ["srcly-casts:tsconfig.json"] + result, findings = run(tools[0]) + return result, {(Path(f.path).relative_to(root).as_posix(), f.line): f.message for f in findings} + + +def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_path: Path): + root = project(tmp_path) write( root, "src/api.ts", "export type Doc = { id: string; title: string };\n" 'export type Status = "open" | "done";\n' "export declare function fetchDoc(id: string): Promise;\n" - "export declare function status(): Status;\n", + "export declare function status(): Status;\n" + "export enum Level { Low, High }\n" + "export enum Only { Unknown }\n" + "export declare const level: Level;\n", ) write( root, @@ -45,25 +62,62 @@ def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_pa 'export const c = fetchDoc("1") as Promise;\n' "export const d = ({ id: \"1\" }) as { id: string };\n" 'export const e = ["x"] as const;\n' - "export const f = new Blob().stream() as ReadableStream;\n", + "export const f = new Blob().stream() as ReadableStream;\n" + # True: a narrowed enum value still stands for its enum. + 'import { Level as ApiLevel, Only, level } from "./api";\n' + "enum Level { Low, High }\n" + "export const g = (level === ApiLevel.Low ? level : ApiLevel.Low) as Level;\n" + "export const h = ApiLevel.Low as Level;\n" + # False: a one-member enum's value is not a type named after the member; type parameters are not copies. + "type Unknown = { u: 1 };\n" + "export const i = Only.Unknown as Unknown;\n" + "export function j(x: T) { return (y: T) => x as T; }\n", ) # Tests are skipped. write(root, "src/view.test.ts", 'import { status } from "./api";\ntype Status = "open" | "done";\nexport const t = status() as Status;\n') - tools = copied_type_casts.plan(root) - assert [t.id for t in tools] == ["srcly-casts:tsconfig.json"] - result, findings = run(tools[0]) + result, got = findings_of(root) assert result.status == "ok", result.reason assert sorted(Path(f).relative_to(root).as_posix() for f in result.files) == ["src/api.ts", "src/view.ts"] - got = {(Path(f.path).relative_to(root).as_posix(), f.line): f.message for f in findings} - assert list(got) == [("src/view.ts", 4), ("src/view.ts", 5)] + assert list(got) == [("src/view.ts", 4), ("src/view.ts", 5), ("src/view.ts", 12), ("src/view.ts", 13)] assert got[("src/view.ts", 4)].startswith( '`fetchDoc("1") as Promise` casts the `Doc` from src/api.ts:1 to a different `Doc`, declared in src/view.ts:2.' ) assert "`Status` from src/api.ts:2" in got[("src/view.ts", 5)] -def test_a_project_without_typescript_gets_no_run(tmp_path: Path): - write(tmp_path, "tsconfig.json", "{}\n") - write(tmp_path, "src/a.ts", "export const a = 1 as number;\n") - assert copied_type_casts.plan(tmp_path) == [] +def test_one_file_as_the_root_is_checked_and_a_change_outside_it_is_a_new_signature(tmp_path: Path): + root = project(tmp_path) + write(root, "src/api.ts", "export type Doc = { id: string };\nexport declare const doc: Doc;\n") + write(root, "src/ui/view.ts", 'import { doc } from "../api";\ntype Doc = { id: string };\nexport const a = doc as Doc;\n') + view = root / "src/ui/view.ts" + result, got = findings_of(root, view) + assert [Path(f).relative_to(root).as_posix() for f in result.files] == ["src/ui/view.ts"] + assert list(got) == [("src/ui/view.ts", 3)] + assert "`Doc` from src/api.ts:1" in got[("src/ui/view.ts", 3)] + # The checker reads api.ts, outside the scanned folder, so it is part of the cache signature. + tool = copied_type_casts.plan(root / "src/ui")[0] + before = tool.signature() + write(root, "src/api.ts", "export type ApiDoc = { id: string };\nexport declare const doc: ApiDoc;\n") + os.utime(root / "src/api.ts", ns=(1, 1)) + assert tool.signature() != before + + +def test_a_broken_tsconfig_is_na_not_zero(tmp_path: Path): + root = project(tmp_path, '{ "extends": "./missing-base.json", "include": ["src"] }\n') + write(root, "src/a.ts", "export const a = 1 as number;\n") + result, got = findings_of(root) + assert result.status == "na" and "missing-base.json" in result.reason + + +def test_configs_it_cannot_check_make_the_rule_na(tmp_path: Path): + root = tmp_path.resolve() + for name in "abcdefg": + write(root, f"{name}/tsconfig.json", "{}\n") + assert copied_type_casts.plan(root) == [] + skipped = copied_type_casts.unscheduled(root) + assert skipped[0] == ("srcly-casts", "srcly copied-type casts (a/tsconfig.json)", "no node_modules/typescript") + assert skipped[-1][2] == "over the limit of 6 projects" + got = listing.build(root, FindingsResult(root=str(root), status="ok"), [], ["copied-type-cast"], skipped) + assert got["rules"][0]["count"] is None + assert "srcly copied-type casts (g/tsconfig.json) not run: over the limit of 6 projects" in got["rules"][0]["reason"] From 7770d396a17583952844046722a362a75c25d199 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:57:26 -0500 Subject: [PATCH 3/4] fix(findings): copied-type-cast reads the written target name, follows project references to sources, dedupes across tsconfigs Co-Authored-By: Claude Opus 5.5 --- .../services/findings/copied_type_casts.mjs | 37 ++++++++++++++----- .../services/findings/copied_type_casts.py | 20 +++++++--- server/app/services/findings/jobs.py | 11 ++++-- server/app/services/findings/runner.py | 8 ++++ server/tests/test_copied_type_casts.py | 37 +++++++++++++++++-- 5 files changed, 91 insertions(+), 22 deletions(-) diff --git a/server/app/services/findings/copied_type_casts.mjs b/server/app/services/findings/copied_type_casts.mjs index 5e96adc7..9d24c403 100644 --- a/server/app/services/findings/copied_type_casts.mjs +++ b/server/app/services/findings/copied_type_casts.mjs @@ -27,11 +27,12 @@ if (!config || configError.length) { console.log(JSON.stringify({ error: `tsconfig: ${configError[0] ?? "unreadable"}` })); process.exit(0); } -const program = ts.createProgram({ - rootNames: config.fileNames, - options: { ...config.options, noEmit: true }, - projectReferences: config.projectReferences, -}); +const options = { ...config.options, noEmit: true }; +const host = ts.createCompilerHost(options); +// Read a project reference's sources, as editors do, not its built `.d.ts`: +// an unbuilt reference (TS6305) would otherwise leave its types unresolved and read as a clean 0. +host.useSourceOfProjectReferenceRedirect = () => true; +const program = ts.createProgram({ rootNames: config.fileNames, options, projectReferences: config.projectReferences, host }); const checker = program.getTypeChecker(); // The scan root: a folder, or one file. const scope = path.resolve(scopeDir); @@ -58,7 +59,19 @@ const NAMED = ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFla // type parameters and anything else are left out. function named(type) { if (type.flags & ts.TypeFlags.TypeParameter) return null; - let sym = type.aliasSymbol ?? type.getSymbol(); + return declared(type.aliasSymbol ?? type.getSymbol()); +} + +// The cast's target as written: `as Other` names `Other` even when +// `type Other = Doc` folds to `Doc` in the checker. Imports resolve to what they bind. +function written(typeNode) { + if (!ts.isTypeReferenceNode(typeNode)) return null; + let sym = checker.getSymbolAtLocation(typeNode.typeName); + if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym); + return declared(sym); +} + +function declared(sym) { if (sym && sym.flags & ts.SymbolFlags.EnumMember) sym = sym.parent; const decl = sym?.declarations?.[0]; if (!sym || !decl || !(sym.flags & NAMED)) return null; @@ -91,12 +104,18 @@ for (const sf of program.getSourceFiles()) { function check(sf, node) { let src = checker.getTypeAtLocation(node.expression); let tgt = checker.getTypeFromTypeNode(node.type); + let tgtNode = node.type; // `fetchDoc(id) as Promise`: the copy hides in the payload. const ps = unwrapPromise(src), pt = unwrapPromise(tgt); - if (ps && pt) [src, tgt] = [ps, pt]; - const a = named(src), b = named(tgt); + if (ps && pt) { + [src, tgt] = [ps, pt]; + const args = ts.isTypeReferenceNode(tgtNode) ? tgtNode.typeArguments : undefined; + tgtNode = args?.length === 1 ? args[0] : null; + } + const a = named(src), b = (tgtNode && written(tgtNode)) ?? named(tgt); if (!a || !b || a.name !== b.name || a.sym === b.sym) return; - if (a.file === b.file && a.line === b.line) return; + // One declaration reached as a merged and an unmerged symbol (a global augmentation) is not a copy. + if (a.sym.declarations.some((d) => b.sym.declarations.includes(d))) return; // Two library declarations (DOM's and Node's `ReadableStream`) are not the project's copy. if (!a.own && !b.own) return; const start = sf.getLineAndCharacterOfPosition(node.getStart(sf)); diff --git a/server/app/services/findings/copied_type_casts.py b/server/app/services/findings/copied_type_casts.py index c7dac9e6..f4bc122d 100644 --- a/server/app/services/findings/copied_type_casts.py +++ b/server/app/services/findings/copied_type_casts.py @@ -60,21 +60,26 @@ def _base(root: Path) -> Path: return root if root.is_dir() else root.parent -def parse_output(stdout: str, root: Path, tool_id: str, display: Optional[Path] = None) -> tuple[list[Finding], list[str]]: - """The script's JSON as findings. Declarations show relative to ``display`` (the tsconfig's folder).""" +def parse_output(stdout: str, root: Path, tool_id: str, project: Optional[Path] = None) -> tuple[list[Finding], list[str]]: + """The script's JSON as findings. + + ``project`` (the repository root) is the one base for test classification + and shown paths, so a scan of one file judges it like a scan of its + folder, and two tsconfigs that check one cast give one message. + """ try: data = json.loads(stdout) except json.JSONDecodeError as exc: raise ToolFailed(f"unreadable JSON output ({exc.msg})") from exc if data.get("error"): raise ToolFailed(str(data["error"])) - base = _base(root) - shown = display or base + shown = project if project is not None and project.is_dir() else _base(root) def keep(file: str) -> bool: path = Path(file) if path != root and root not in path.parents: return False + base = shown if shown in path.parents else _base(root) return not is_test_path(path.relative_to(base).as_posix()) files = [f for f in data.get("files", []) if keep(f)] @@ -142,16 +147,19 @@ def __init__(self, root: Path, config: Path, node: str, label_base: Path) -> Non ) self.config = config self.node = node + self.project = label_base def signature(self) -> str: - return f"{super().signature()}|inputs={project_inputs(self.config.parent)}" + # The checker can read any file in the repository (a workspace package, `../shared`). + inputs = self.project if self.project.is_dir() else self.config.parent + return f"{super().signature()}|inputs={project_inputs(inputs)}" def check(self): root = self.root.resolve() out = run_process([self.node, str(SCRIPT), str(self.config), str(root)], self.config.parent, self.timeout) if out.returncode != 0: raise ToolFailed(first_line(out.stderr or out.stdout) or f"exit code {out.returncode}") - return parse_output(out.stdout, root, self.id, self.config.parent) + return parse_output(out.stdout, root, self.id, self.project) def _configs(root: Path, stop: Optional[Path]) -> list[tuple[Path, str]]: diff --git a/server/app/services/findings/jobs.py b/server/app/services/findings/jobs.py index 22c623a6..30704fc6 100644 --- a/server/app/services/findings/jobs.py +++ b/server/app/services/findings/jobs.py @@ -19,9 +19,11 @@ class FindingsJob: - def __init__(self, root: Path, fingerprint: Optional[str]) -> None: + def __init__(self, root: Path, fingerprint: Optional[str], signature: str = "") -> None: self.root = root self.fingerprint = fingerprint + self.signature = signature + """The planned tools' signatures: a checker can read files outside ``root``.""" self._result: Optional[FindingsResult] = None self._done = threading.Event() @@ -54,13 +56,14 @@ def __init__(self) -> None: self._lock = threading.Lock() def start(self, root: Path, fingerprint: Optional[str]) -> FindingsJob: - """The job for ``root`` at ``fingerprint``, started if new.""" + """The job for ``root`` at ``fingerprint`` and the same tool signatures, started if new.""" root = root.resolve() + signature = runner.tools_signature(root) if fingerprint is not None else "" with self._lock: for job in reversed(self._jobs): - if job.root == root and job.fingerprint == fingerprint and fingerprint is not None: + if job.root == root and job.fingerprint == fingerprint and fingerprint is not None and job.signature == signature: return job - job = FindingsJob(root, fingerprint) + job = FindingsJob(root, fingerprint, signature) self._jobs.append(job) del self._jobs[:-MAX_JOBS] threading.Thread(target=job.run, name="srcly-findings-job", daemon=True).start() diff --git a/server/app/services/findings/runner.py b/server/app/services/findings/runner.py index 30bc8e58..2475c65f 100644 --- a/server/app/services/findings/runner.py +++ b/server/app/services/findings/runner.py @@ -164,6 +164,14 @@ def clear_memory(self) -> None: findings_cache = FindingsCache() +def tools_signature(root: Path) -> str: + """The signatures of the tools ``collect`` would plan for ``root``; empty when planning fails.""" + try: + return "\n".join(sorted(t.signature() for t in plan_tools(root))) + except Exception: # noqa: BLE001 - the job reports a planning failure itself + return "" + + def cache_key(root: Path, fingerprint: str, tools: Sequence[Tool], portable: bool) -> str: signatures = "\n".join(sorted(t.signature() for t in tools)) raw = f"format={FINDINGS_FORMAT};{root.resolve()};{fingerprint};{portable};{signatures}" diff --git a/server/tests/test_copied_type_casts.py b/server/tests/test_copied_type_casts.py index dd42839f..d647e4af 100644 --- a/server/tests/test_copied_type_casts.py +++ b/server/tests/test_copied_type_casts.py @@ -9,6 +9,7 @@ from app.services.dataflow.availability import ENGINE_DIR from app.services.findings import copied_type_casts, listing from app.services.findings.model import FindingsResult +from app.services.findings.runner import run_tools from app.services.findings.tools import run TS = ENGINE_DIR / "node_modules" / "typescript" @@ -30,7 +31,7 @@ def project(root: Path, config: str = '{ "compilerOptions": { "strict": true, "l def findings_of(root: Path, scan: Path | None = None): - tools = copied_type_casts.plan(scan or root) + tools = copied_type_casts.plan(scan or root, root) assert [t.id for t in tools] == ["srcly-casts:tsconfig.json"] result, findings = run(tools[0]) return result, {(Path(f.path).relative_to(root).as_posix(), f.line): f.message for f in findings} @@ -71,8 +72,13 @@ def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_pa # False: a one-member enum's value is not a type named after the member; type parameters are not copies. "type Unknown = { u: 1 };\n" "export const i = Only.Unknown as Unknown;\n" - "export function j(x: T) { return (y: T) => x as T; }\n", + "export function j(x: T) { return (y: T) => x as T; }\n" + # False: an alias with another name is not a same-name copy, even though the checker folds it to `Doc`. + "type Other = Shared;\n" + 'export const k = fetchDoc("1") as Promise;\n', ) + # Tests are skipped, also when the scan is that one file. + write(root, "src/tests/case.ts", 'import { status } from "../api";\ntype Status = "open" | "done";\nexport const t = status() as Status;\n') # Tests are skipped. write(root, "src/view.test.ts", 'import { status } from "./api";\ntype Status = "open" | "done";\nexport const t = status() as Status;\n') @@ -84,6 +90,31 @@ def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_pa '`fetchDoc("1") as Promise` casts the `Doc` from src/api.ts:1 to a different `Doc`, declared in src/view.ts:2.' ) assert "`Status` from src/api.ts:2" in got[("src/view.ts", 5)] + _, one = findings_of(root, root / "src/tests/case.ts") + assert one == {} + + +def test_two_configs_that_check_one_cast_report_it_once(tmp_path: Path): + root = project(tmp_path, '{ "include": ["pkg"] }\n') + write(root, "pkg/tsconfig.json", "{}\n") + write(root, "pkg/api.ts", "export type Doc = { id: string };\nexport declare const doc: Doc;\n") + write(root, "pkg/view.ts", 'import { doc } from "./api";\ntype Doc = { id: string };\nexport const a = doc as Doc;\n') + tools = copied_type_casts.plan(root) + assert [t.id for t in tools] == ["srcly-casts:pkg/tsconfig.json", "srcly-casts:tsconfig.json"] + result = run_tools(root, tools) + assert [(f.line, f.rule) for f in result.findings] == [(3, "copied-type-cast")] + assert "from pkg/api.ts:1" in result.findings[0].message + + +def test_an_unbuilt_project_reference_is_read_from_its_sources(tmp_path: Path): + root = project(tmp_path, '{ "files": ["app/view.ts"], "references": [{ "path": "./lib" }], "compilerOptions": { "strict": true } }\n') + write(root, "lib/tsconfig.json", '{ "compilerOptions": { "composite": true, "outDir": "out" }, "include": ["*.ts"] }\n') + write(root, "lib/api.ts", "export type Doc = { id: string };\nexport declare const doc: Doc;\n") + write(root, "app/view.ts", 'import { doc } from "../lib/api";\ntype Doc = { id: string };\nexport const a = doc as Doc;\n') + tool = next(t for t in copied_type_casts.plan(root) if t.id == "srcly-casts:tsconfig.json") + result, findings = run(tool) + assert result.status == "ok", result.reason + assert [(Path(f.path).relative_to(root).as_posix(), f.line) for f in findings] == [("app/view.ts", 3)] def test_one_file_as_the_root_is_checked_and_a_change_outside_it_is_a_new_signature(tmp_path: Path): @@ -96,7 +127,7 @@ def test_one_file_as_the_root_is_checked_and_a_change_outside_it_is_a_new_signat assert list(got) == [("src/ui/view.ts", 3)] assert "`Doc` from src/api.ts:1" in got[("src/ui/view.ts", 3)] # The checker reads api.ts, outside the scanned folder, so it is part of the cache signature. - tool = copied_type_casts.plan(root / "src/ui")[0] + tool = copied_type_casts.plan(root / "src/ui", root)[0] before = tool.signature() write(root, "src/api.ts", "export type ApiDoc = { id: string };\nexport declare const doc: ApiDoc;\n") os.utime(root / "src/api.ts", ns=(1, 1)) From e13882c0b5489796eadd33eefe10246221e57935 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 01:07:36 -0500 Subject: [PATCH 4/4] fix(findings): copied-type-cast unwraps only Promise itself, strips parentheses, forces source redirects, sees symlinked files as one Co-Authored-By: Claude Opus 5.5 --- .../services/findings/copied_type_casts.mjs | 26 +++++++++++++++++-- server/tests/test_copied_type_casts.py | 8 ++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/server/app/services/findings/copied_type_casts.mjs b/server/app/services/findings/copied_type_casts.mjs index 9d24c403..886d9412 100644 --- a/server/app/services/findings/copied_type_casts.mjs +++ b/server/app/services/findings/copied_type_casts.mjs @@ -3,8 +3,17 @@ // It loads the project's own `typescript` (resolved from the tsconfig), so the // checker sees the project the way its tsc does. Prints one JSON object. import { createRequire } from "node:module"; +import fs from "node:fs"; import path from "node:path"; +const realpath = (file) => { + try { + return fs.realpathSync(file); + } catch { + return path.resolve(file); + } +}; + const [configPath, scopeDir] = process.argv.slice(2); let ts; try { @@ -27,7 +36,7 @@ if (!config || configError.length) { console.log(JSON.stringify({ error: `tsconfig: ${configError[0] ?? "unreadable"}` })); process.exit(0); } -const options = { ...config.options, noEmit: true }; +const options = { ...config.options, noEmit: true, disableSourceOfProjectReferenceRedirect: false }; const host = ts.createCompilerHost(options); // Read a project reference's sources, as editors do, not its built `.d.ts`: // an unbuilt reference (TS6305) would otherwise leave its types unresolved and read as a clean 0. @@ -50,6 +59,11 @@ function unwrapPromise(type) { return args?.length === 1 ? args[0] : null; } +const isLibPromise = (sym) => + sym?.getName() === "Promise" && + !!sym.declarations?.length && + sym.declarations.every((d) => program.isSourceFileDefaultLibrary(d.getSourceFile())); + // Only these declare a type with a name another file can copy. const NAMED = ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum; @@ -65,6 +79,7 @@ function named(type) { // The cast's target as written: `as Other` names `Other` even when // `type Other = Doc` folds to `Doc` in the checker. Imports resolve to what they bind. function written(typeNode) { + while (ts.isParenthesizedTypeNode(typeNode)) typeNode = typeNode.type; if (!ts.isTypeReferenceNode(typeNode)) return null; let sym = checker.getSymbolAtLocation(typeNode.typeName); if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym); @@ -80,6 +95,7 @@ function declared(sym) { sym, name: sym.getName(), file: path.resolve(sf.fileName), + real: realpath(sf.fileName), line: sf.getLineAndCharacterOfPosition(decl.getStart(sf)).line + 1, own: isOwn(sf), }; @@ -109,13 +125,19 @@ function check(sf, node) { const ps = unwrapPromise(src), pt = unwrapPromise(tgt); if (ps && pt) { [src, tgt] = [ps, pt]; + // The written argument is the payload only for `Promise` itself; an alias such as + // `Wrapped = Promise<{ data: T }>` may wrap or replace it, so the checker's payload decides. + while (ts.isParenthesizedTypeNode(tgtNode)) tgtNode = tgtNode.type; + const isPromise = ts.isTypeReferenceNode(tgtNode) && isLibPromise(checker.getSymbolAtLocation(tgtNode.typeName)); const args = ts.isTypeReferenceNode(tgtNode) ? tgtNode.typeArguments : undefined; - tgtNode = args?.length === 1 ? args[0] : null; + tgtNode = isPromise && args?.length === 1 ? args[0] : null; } const a = named(src), b = (tgtNode && written(tgtNode)) ?? named(tgt); if (!a || !b || a.name !== b.name || a.sym === b.sym) return; // One declaration reached as a merged and an unmerged symbol (a global augmentation) is not a copy. if (a.sym.declarations.some((d) => b.sym.declarations.includes(d))) return; + // One file loaded twice (`preserveSymlinks`, a workspace link and a relative path) is one declaration. + if (a.real === b.real && a.line === b.line) return; // Two library declarations (DOM's and Node's `ReadableStream`) are not the project's copy. if (!a.own && !b.own) return; const start = sf.getLineAndCharacterOfPosition(node.getStart(sf)); diff --git a/server/tests/test_copied_type_casts.py b/server/tests/test_copied_type_casts.py index d647e4af..49e31d5e 100644 --- a/server/tests/test_copied_type_casts.py +++ b/server/tests/test_copied_type_casts.py @@ -75,7 +75,11 @@ def test_a_cast_onto_a_same_name_copy_is_reported_and_other_casts_are_not(tmp_pa "export function j(x: T) { return (y: T) => x as T; }\n" # False: an alias with another name is not a same-name copy, even though the checker folds it to `Doc`. "type Other = Shared;\n" - 'export const k = fetchDoc("1") as Promise;\n', + 'export const k = fetchDoc("1") as Promise;\n' + 'export const l = fetchDoc("1") as (Promise<(Other)>);\n' + # False: an alias that wraps its argument; the payload is anonymous, not `Doc`. + "type Wrapped = Promise<{ data: T }>;\n" + 'export const m = fetchDoc("1") as unknown as Promise as Wrapped;\n', ) # Tests are skipped, also when the scan is that one file. write(root, "src/tests/case.ts", 'import { status } from "../api";\ntype Status = "open" | "done";\nexport const t = status() as Status;\n') @@ -107,7 +111,7 @@ def test_two_configs_that_check_one_cast_report_it_once(tmp_path: Path): def test_an_unbuilt_project_reference_is_read_from_its_sources(tmp_path: Path): - root = project(tmp_path, '{ "files": ["app/view.ts"], "references": [{ "path": "./lib" }], "compilerOptions": { "strict": true } }\n') + root = project(tmp_path, '{ "files": ["app/view.ts"], "references": [{ "path": "./lib" }], "compilerOptions": { "strict": true, "disableSourceOfProjectReferenceRedirect": true } }\n') write(root, "lib/tsconfig.json", '{ "compilerOptions": { "composite": true, "outDir": "out" }, "include": ["*.ts"] }\n') write(root, "lib/api.ts", "export type Doc = { id: string };\nexport declare const doc: Doc;\n") write(root, "app/view.ts", 'import { doc } from "../lib/api";\ntype Doc = { id: string };\nexport const a = doc as Doc;\n')