Skip to content

Commit 28938a4

Browse files
nothariharansafishamsi
authored andcommitted
feat(extract): add EJS (.ejs) template extractor (#3811)
EJS views sat in CODE_EXTENSIONS with no extractor, so an Express/Node app's templates were counted as code and contributed nothing (the #1689 warning). A .ejs file is HTML with <% %> scriptlets and inline <script> blocks, so feeding the whole file to the JS grammar made it one top-level ERROR. Add extract_ejs: mask the template down to its JS regions (code-tag and <script> bodies), parse them with the TS grammar, and add the two relationships no JS grammar can see - dynamic import('./X') and the EJS <%- include('partial') %> composition edge, resolved to the real partial file. Wire .ejs into the dispatch, the jsts language family, the JS resolve/cache sets, and the hook source extensions. (cherry picked from commit 3824cda)
1 parent 4de6ed1 commit 28938a4

5 files changed

Lines changed: 403 additions & 5 deletions

File tree

‎graphify/cli.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
}
7070
}, ensure_ascii=False, separators=(",", ":")) + "\n"
7171
_HOOK_SOURCE_EXTS = (
72-
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.go',
72+
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.ejs', '.go',
7373
'.rs', '.java', '.rb', '.c', '.h', '.cpp', '.hpp', '.cc', '.cs', '.kt',
7474
'.swift', '.php', '.scala', '.lua', '.ps1', '.psm1', '.psd1', # #4271: PowerShell sources are graphable too
7575
'.sh', '.md', '.rst', '.txt', '.mdx',

‎graphify/extract.py‎

Lines changed: 172 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2734,6 +2734,176 @@ def extract_astro(path: Path) -> dict:
27342734
return result
27352735

27362736

2737+
# EJS spells a tag `<%` (code), `<%_` (code, whitespace-slurp), `<%=`/`<%-`
2738+
# (escaped/unescaped output) or `<%#` (comment); `<%%` is an escaped literal
2739+
# `<%`. Only the code bodies and inline `<script>` bodies are JS statements a
2740+
# grammar can read — markup and output expressions are not, so a `.ejs` file fed
2741+
# whole to the JS grammar is one top-level ERROR that loses every symbol (the
2742+
# `.svelte` lesson of #3928).
2743+
_EJS_SCRIPT_TAG_RE = _HTML_SCRIPT_TAG_RE
2744+
_EJS_INCLUDE_RE = re.compile(
2745+
r"""<%(?:_|[-=])?\s*include\s*\(\s*['"]([^'"]+)['"]"""
2746+
)
2747+
2748+
2749+
def _ejs_mask_non_script(src: str) -> str:
2750+
"""Blank an EJS template down to the JavaScript a parser can read.
2751+
2752+
Keeps the bodies of code tags (``<% %>`` / ``<%_ %>``) and of JS ``<script>``
2753+
blocks; markup, ``<%# %>`` comments and ``<%= %>``/``<%- %>`` output
2754+
expressions become spaces, with ``\\r``/``\\n`` preserved so AST line
2755+
numbers and byte offsets still match the original file. An output tag inside
2756+
a ``<script>`` body is replaced by a length-preserving ``0`` so the
2757+
surrounding statement still parses (``const x = <%- data %>;``).
2758+
"""
2759+
n = len(src)
2760+
keep = bytearray(n) # 1 where the character is JS we want to parse
2761+
neutralize = bytearray(n) # 1 inside an output tag that sits in kept JS
2762+
2763+
for m in _EJS_SCRIPT_TAG_RE.finditer(src):
2764+
if _NON_JS_SCRIPT_TYPE_RE.search(m.group(1)):
2765+
continue
2766+
for p in range(m.start(2), m.end(2)):
2767+
keep[p] = 1
2768+
2769+
i = 0
2770+
while True:
2771+
j = src.find("<%", i)
2772+
if j < 0:
2773+
break
2774+
if j + 2 < n and src[j + 2] == "%": # `<%%` — a literal `<%`
2775+
for p in range(j, min(j + 3, n)):
2776+
keep[p] = 0
2777+
i = j + 3
2778+
continue
2779+
marker = src[j + 2] if j + 2 < n else ""
2780+
close = src.find("%>", j + 2)
2781+
if close < 0:
2782+
break
2783+
# The `<%` … `%>` delimiters are never JS, even inside a <script> body.
2784+
for p in (j, j + 1, close, close + 1):
2785+
if p < n:
2786+
keep[p] = 0
2787+
if marker in ("=", "-"):
2788+
for p in range(j + 2, close):
2789+
if keep[p]:
2790+
neutralize[p] = 1
2791+
elif marker == "#":
2792+
for p in range(j, close + 2):
2793+
keep[p] = 0
2794+
else:
2795+
# Code tag (`<%` or `<%_`): its body is real JS.
2796+
body_start = j + 3 if marker == "_" else j + 2
2797+
if marker == "_":
2798+
keep[j + 2] = 0 # the `<%_` whitespace-slurp modifier
2799+
for p in range(body_start, close):
2800+
keep[p] = 1
2801+
i = close + 2
2802+
2803+
out: list[str] = []
2804+
in_output = False
2805+
for p in range(n):
2806+
c = src[p]
2807+
if c in "\r\n":
2808+
out.append(c)
2809+
in_output = False
2810+
elif not keep[p]:
2811+
out.append(" ")
2812+
in_output = False
2813+
elif neutralize[p]:
2814+
out.append(" " if in_output else "0")
2815+
in_output = True
2816+
else:
2817+
out.append(c)
2818+
in_output = False
2819+
return "".join(out)
2820+
2821+
2822+
def _emit_ejs_include(
2823+
result: dict,
2824+
existing_ids: set,
2825+
file_node_id: str,
2826+
path: Path,
2827+
raw: str,
2828+
line: int,
2829+
) -> None:
2830+
"""Emit the template-composition edge for ``<%- include('partial') %>``.
2831+
2832+
EJS resolves an include relative to the including template, so probe the
2833+
template's own directory through :func:`_resolve_js_import_path` — which,
2834+
now that ``.ejs`` is a JS resolve extension, appends ``.ejs``/``index.ejs``
2835+
the way EJS itself does. A relative hit is stamped with ``target_file`` so
2836+
the #2169 canonicalization pass repoints it at the real template node; a
2837+
bare/views-root include that cannot be resolved keeps a stub node, so the
2838+
edge is never dropped.
2839+
"""
2840+
base = Path(os.path.normpath(path.parent / raw))
2841+
resolved = _resolve_js_import_path(base)
2842+
edge = {
2843+
"source": file_node_id, "relation": "includes", "confidence": "EXTRACTED",
2844+
"source_file": str(path), "source_location": f"L{line}",
2845+
}
2846+
if resolved.is_file():
2847+
edge["target"] = _make_id(str(resolved))
2848+
edge["target_file"] = str(resolved)
2849+
result.setdefault("edges", []).append(edge)
2850+
return
2851+
node_id = _make_id(raw)
2852+
if node_id not in existing_ids:
2853+
existing_ids.add(node_id)
2854+
result.setdefault("nodes", []).append({
2855+
"id": node_id, "label": raw, "file_type": "code",
2856+
"source_file": str(path), "source_location": f"L{line}",
2857+
"confidence": "EXTRACTED",
2858+
})
2859+
edge["target"] = node_id
2860+
result.setdefault("edges", []).append(edge)
2861+
2862+
2863+
def extract_ejs(path: Path) -> dict:
2864+
"""Extract imports, symbols, and `include()` composition from an EJS template.
2865+
2866+
EJS is HTML carrying ``<% %>`` scriptlets and inline ``<script>`` blocks, so
2867+
the whole file is not JS: fed to the JS grammar it becomes a top-level ERROR
2868+
and every symbol inside a scriptlet is lost (``_ejs_mask_non_script`` keeps
2869+
only the JS regions, preserving line numbers). The AST pass then reads the
2870+
template's real JavaScript — ``require``/``import`` edges, functions,
2871+
classes — and two regex passes add what no JS grammar can see: dynamic
2872+
``import('./X')`` calls written in a scriptlet, and the EJS
2873+
``<%- include('partial') %>`` composition edge an Express view graph is
2874+
built on (#3811, #2511).
2875+
"""
2876+
try:
2877+
src = _read_source_text(path)
2878+
except OSError as e:
2879+
return {"nodes": [], "edges": [], "error": str(e)}
2880+
2881+
masked = _ejs_mask_non_script(src).encode("utf-8")
2882+
masked = _normalize_ts_import_types(masked) or masked
2883+
result = _extract_generic(path, _TS_CONFIG, source_override=masked)
2884+
2885+
try:
2886+
existing_ids = {n["id"] for n in result.get("nodes", [])}
2887+
file_node_id = _make_id(str(path))
2888+
aliases = _load_tsconfig_aliases(path.parent)
2889+
base_url = _load_tsconfig_base_url(path.parent)
2890+
for m in re.finditer(r"""import\(\s*['"]([^'"]+)['"]\s*\)""", src):
2891+
if m.group(1):
2892+
_emit_rescued_import(
2893+
result, existing_ids, file_node_id, path, m.group(1),
2894+
"dynamic_import", aliases, base_url,
2895+
)
2896+
for m in _EJS_INCLUDE_RE.finditer(src):
2897+
if m.group(1):
2898+
_emit_ejs_include(
2899+
result, existing_ids, file_node_id, path, m.group(1),
2900+
src.count("\n", 0, m.start()) + 1,
2901+
)
2902+
except Exception:
2903+
pass
2904+
return result
2905+
2906+
27372907
# The open-tag matcher skips over quoted attribute values so a `>` inside one
27382908
# (e.g. Vue 3.3+ generic components: `<script setup lang="ts"
27392909
# generic="T extends Record<string, unknown>">`) doesn't prematurely end the tag.
@@ -3578,7 +3748,7 @@ def _lang_is_case_insensitive(source_file: object) -> bool:
35783748
# JS/TS module graph (SFCs embed JS/TS)
35793749
".js": "jsts", ".jsx": "jsts", ".mjs": "jsts", ".cjs": "jsts",
35803750
".ts": "jsts", ".tsx": "jsts", ".mts": "jsts", ".cts": "jsts",
3581-
".vue": "jsts", ".svelte": "jsts", ".astro": "jsts",
3751+
".vue": "jsts", ".svelte": "jsts", ".astro": "jsts", ".ejs": "jsts",
35823752
# JVM interop
35833753
".java": "jvm", ".kt": "jvm", ".kts": "jvm",
35843754
".scala": "jvm", ".groovy": "jvm", ".gradle": "jvm",
@@ -7811,6 +7981,7 @@ def add_existing_edge(edge: dict) -> None:
78117981
".vue": extract_vue,
78127982
".svelte": extract_svelte,
78137983
".astro": extract_astro,
7984+
".ejs": extract_ejs,
78147985
".dart": extract_dart,
78157986
".ml": extract_ocaml,
78167987
".mli": extract_ocaml,

‎graphify/extractors/models.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
_WORKSPACE_PACKAGE_CACHE: dict[str, dict[str, Path]] = {}
1010

11-
_JS_CACHE_BYPASS_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte"}
11+
_JS_CACHE_BYPASS_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte", ".ejs"}
1212

1313
@dataclass
1414
class LanguageConfig:

‎graphify/extractors/resolution.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@
3333
# mtime component, so extract() clears it per run.
3434
_PACKAGE_IMPORTS_CACHE: "dict[str, tuple[Path, dict] | None]" = {}
3535

36-
_JS_RESOLVE_EXTS = (".ts", ".tsx", ".mts", ".cts", ".svelte", ".js", ".jsx", ".mjs", ".cjs")
36+
_JS_RESOLVE_EXTS = (".ts", ".tsx", ".mts", ".cts", ".svelte", ".ejs", ".js", ".jsx", ".mjs", ".cjs")
3737

38-
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.svelte", "index.js", "index.jsx", "index.mjs")
38+
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.svelte", "index.ejs", "index.js", "index.jsx", "index.mjs")
3939

4040
def _declared_language_suffixes(target_exts: tuple[str, ...]) -> tuple[str, ...]:
4141
"""Return declared literal suffixes for these languages in deterministic order."""

0 commit comments

Comments
 (0)