fix(typescript): keep import types out of runtime dependencies
Recognize type-only import contexts without dropping real runtime imports. Invalidate stale AST cache entries and cover normalized generics, file suffixes, and source offsets. Fixes #4992.
Co-Authored-By: Codex <noreply@openai.com>
(cherry picked from commit 42b117e8b8)
This commit is contained in:
1 parent
7fc5312e91
commit
69954b537d
4 files changed
+107
-7
No files matched your search
+24
-3
@@ -40,6 +40,7 @@ from graphify.rcfile import (
|
||||
get_language_overrides,
|
||||
set_language_overrides,
|
||||
)
|
||||
from graphify.extractors.engine import _js_import_is_type_only
|
||||
from graphify.extractors.base import ( # noqa: F401
|
||||
_LANGUAGE_BUILTIN_GLOBALS,
|
||||
_PYTHON_BUILTIN_NAMES,
|
||||
@@ -2338,16 +2339,21 @@ def extract_js(path: Path) -> dict:
|
||||
source = _read_source_bytes(path)
|
||||
working = _normalize_ts_export_type_star(source) or source
|
||||
normalized = _normalize_ts_import_types(working, tsx=suffix == ".tsx")
|
||||
if normalized is not None:
|
||||
type_only_import_offsets.update(
|
||||
match.start() for match in _TS_IMPORT_CALL_RE.finditer(working)
|
||||
if normalized[match.start():match.start() + 6] != b'import'
|
||||
)
|
||||
working = normalized if normalized is not None else working
|
||||
before_annotations = working
|
||||
normalized = _normalize_ts_tag_and_import_annotations(
|
||||
before_annotations, tsx=suffix == ".tsx"
|
||||
)
|
||||
if normalized is not None:
|
||||
type_only_import_offsets = {
|
||||
type_only_import_offsets.update(
|
||||
match.start() for match in _TS_QUALIFIED_IMPORT_TYPE_RE.finditer(before_annotations)
|
||||
if normalized[match.start():match.start() + 6] != b'import'
|
||||
}
|
||||
)
|
||||
working = normalized if normalized is not None else working
|
||||
source_override = working if working is not source else None
|
||||
except OSError:
|
||||
@@ -2392,6 +2398,21 @@ def _rescue_js_dynamic_imports(
|
||||
if not _re.search(r"(?<!\w)import\s*\(", src): # cheap bail — most files have none
|
||||
return
|
||||
type_only_positions: set[int] = set()
|
||||
if effective_suffix(path).lower() in (".ts", ".tsx", ".mts", ".cts"):
|
||||
from tree_sitter import Language, Parser
|
||||
import tree_sitter_typescript as ts_typescript
|
||||
|
||||
raw_source = _read_source_bytes(path, warn=False)
|
||||
factory = (ts_typescript.language_tsx if effective_suffix(path).lower() == ".tsx"
|
||||
else ts_typescript.language_typescript)
|
||||
root = Parser(Language(factory())).parse(raw_source).root_node
|
||||
type_only_import_offsets = set(type_only_import_offsets or ())
|
||||
type_only_import_offsets.update(
|
||||
match.start() for match in _TS_IMPORT_CALL_RE.finditer(raw_source)
|
||||
if _js_import_is_type_only(
|
||||
root.descendant_for_byte_range(match.start(), match.start() + 1)
|
||||
)
|
||||
)
|
||||
if type_only_import_offsets:
|
||||
# The AST uses UTF-8 bytes with original line endings, whereas the
|
||||
# rescue pass reads text with universal-newline translation. Map
|
||||
@@ -2448,7 +2469,7 @@ def _rescue_js_dynamic_imports(
|
||||
r"""(?<!\w)import\s*\(\s*(?:'([^'\n]+)'|"([^"\n]+)"|`([^`$\n]+)`)\s*\)""",
|
||||
src,
|
||||
):
|
||||
# A repaired TypeScript import-type is not an executable import().
|
||||
# TypeScript import types are not executable import() calls.
|
||||
# Regex offsets are characters, while tree-sitter offsets are bytes.
|
||||
if m.start() in type_only_positions:
|
||||
continue
|
||||
|
||||
@@ -3062,6 +3062,19 @@ def _find_body(node, config: LanguageConfig):
|
||||
return child
|
||||
return None
|
||||
|
||||
|
||||
def _js_import_is_type_only(node) -> bool:
|
||||
"""Recognize unambiguous TypeScript type contexts around an import call."""
|
||||
while node is not None:
|
||||
if node.type in {"type_annotation", "type_alias_declaration", "type_query",
|
||||
"interface_declaration", "constraint", "default_type"}:
|
||||
return True
|
||||
if node.type in {"statement_block", "program"}:
|
||||
break
|
||||
node = node.parent
|
||||
return False
|
||||
|
||||
|
||||
def _dynamic_import_js(node, source: bytes, caller_nid: str, str_path: str, edges: list,
|
||||
seen_dyn_pairs: set) -> bool:
|
||||
"""Detect dynamic import() calls in JS/TS and emit imports_from edges.
|
||||
@@ -3085,6 +3098,8 @@ def _dynamic_import_js(node, source: bytes, caller_nid: str, str_path: str, edge
|
||||
return False
|
||||
if _read_text(func_node, source) != "import":
|
||||
return False
|
||||
if _js_import_is_type_only(node):
|
||||
return True
|
||||
|
||||
# Extract the module path from the arguments
|
||||
args = node.child_by_field_name("arguments")
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""TypeScript import types must not become runtime dependencies (#4992)."""
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract_js
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".ts", ".tsx", ".mts", ".cts"])
|
||||
@pytest.mark.parametrize("source", [
|
||||
"export function accept(page: import('@playwright/test').Page): void {}",
|
||||
"function f(): import('@playwright/test').Page { throw 1; }",
|
||||
"type Page = import('@playwright/test').Page;",
|
||||
"type Module = typeof import('@playwright/test');",
|
||||
"interface Options { page: import('@playwright/test').Page }",
|
||||
"function f<T extends import('@playwright/test').Page>() {}",
|
||||
"function f<T = import('@playwright/test').Page>() {}",
|
||||
"function f() { const page: import('@playwright/test').Page = undefined; }",
|
||||
"f<import('@playwright/test').Page>();\nfunction after() {}",
|
||||
"f<typeof import('@playwright/test')>();\nfunction after() {}",
|
||||
])
|
||||
def test_type_import_does_not_emit_runtime_edge_or_package_path(tmp_path, suffix, source):
|
||||
path = tmp_path / f"example{suffix}"
|
||||
path.write_text(source, encoding="utf-8")
|
||||
|
||||
result = extract_js(path)
|
||||
|
||||
assert "error" not in result
|
||||
assert not any(edge["relation"] == "dynamic_import" or edge.get("deferred")
|
||||
for edge in result["edges"])
|
||||
assert not any(node.get("source_file") == "@playwright/test"
|
||||
for node in result["nodes"])
|
||||
if "function after" in source:
|
||||
assert any(node["label"] == "after()" for node in result["nodes"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".ts", ".tsx", ".mts", ".cts"])
|
||||
@pytest.mark.parametrize("prefix", ["", "// caf\u00e9\r\n", "\ufeff// caf\u00e9\r\n"])
|
||||
def test_runtime_import_survives_type_import_of_same_package(tmp_path, suffix, prefix):
|
||||
path = tmp_path / f"example{suffix}"
|
||||
source = (prefix
|
||||
+ "export function load(page: import('@playwright/test').Page) {\r\n"
|
||||
+ " return import('@playwright/test');\r\n"
|
||||
+ "}\r\n")
|
||||
path.write_bytes(source.encode("utf-8"))
|
||||
|
||||
result = extract_js(path)
|
||||
|
||||
assert "error" not in result
|
||||
runtime_edges = [edge for edge in result["edges"]
|
||||
if edge["relation"] == "dynamic_import" or edge.get("deferred")]
|
||||
assert runtime_edges
|
||||
assert any(edge.get("deferred") and edge.get("source_location")
|
||||
== ("L2" if not prefix else "L3") for edge in runtime_edges)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".js", ".ts", ".tsx"])
|
||||
def test_runtime_comparison_import_is_not_a_type_import(tmp_path, suffix):
|
||||
path = tmp_path / f"example{suffix}"
|
||||
path.write_text('const x = a < b, import("runtime") > (d);\n', encoding="utf-8")
|
||||
|
||||
result = extract_js(path)
|
||||
|
||||
assert "error" not in result
|
||||
assert any(edge["relation"] == "dynamic_import" or edge.get("deferred")
|
||||
for edge in result["edges"])
|
||||
@@ -61,7 +61,7 @@ def test_ts_call_typeof_import_keeps_subsequent_declarations(tmp_path: Path, cap
|
||||
assert "before()" in labels
|
||||
assert "after()" in labels
|
||||
assert "AfterClass" in labels
|
||||
assert "mod" in labels
|
||||
assert "mod" not in labels # An import type is not a runtime module dependency.
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ def test_ts_call_import_member_type_keeps_subsequent_declarations(tmp_path: Path
|
||||
assert "before()" in labels
|
||||
assert "after()" in labels
|
||||
assert "AfterClass" in labels
|
||||
assert "mod" in labels
|
||||
assert "mod" not in labels
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def test_tsx_call_typeof_import_keeps_subsequent_declarations(tmp_path: Path, ca
|
||||
assert "after()" in labels
|
||||
assert "AfterWidget" in labels
|
||||
assert "Comp()" in labels
|
||||
assert "mod" in labels
|
||||
assert "mod" not in labels
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ def test_ts_multiline_import_type_arguments(tmp_path: Path, capsys):
|
||||
})
|
||||
labels = _labels(r)
|
||||
assert "after()" in labels
|
||||
assert "mod" in labels
|
||||
assert "mod" not in labels
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user