featuregraph-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- featuregraph/__init__.py +6 -0
- featuregraph/cli.py +758 -0
- featuregraph/core/annotator.py +491 -0
- featuregraph/core/dependency_resolver.py +480 -0
- featuregraph/core/graph.py +123 -0
- featuregraph/core/lexmask.py +264 -0
- featuregraph/core/parser_generic.py +233 -0
- featuregraph/core/parser_protocol.py +18 -0
- featuregraph/core/parser_py.py +243 -0
- featuregraph/core/parser_ts.py +350 -0
- featuregraph/core/scanner.py +429 -0
- featuregraph/core/tags.py +51 -0
- featuregraph/formatters/json_formatter.py +164 -0
- featuregraph/formatters/markdown_formatter.py +110 -0
- featuregraph/hooks/git_hook.py +82 -0
- featuregraph/skills/__init__.py +3 -0
- featuregraph/skills/featuregraph/SKILL.md +211 -0
- featuregraph/skills/skill_manager.py +51 -0
- featuregraph_cli-0.1.0.dist-info/METADATA +338 -0
- featuregraph_cli-0.1.0.dist-info/RECORD +23 -0
- featuregraph_cli-0.1.0.dist-info/WHEEL +4 -0
- featuregraph_cli-0.1.0.dist-info/entry_points.txt +2 -0
- featuregraph_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import re
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from . import lexmask
|
|
7
|
+
from .tags import (
|
|
8
|
+
DEPENDS_TAG_REGEX,
|
|
9
|
+
FEATURE_TAG_REGEX,
|
|
10
|
+
extract_contract_tags,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
# Django model bases. Used only for untagged files: a class outside models.py
|
|
14
|
+
# still becomes a MODEL feature when its base names a Django model/mixin.
|
|
15
|
+
MODEL_BASE_REGEX = re.compile(
|
|
16
|
+
r"\b(?:models\.)?(?:Model|AbstractUser|AbstractBaseUser|TenantMixin|DomainMixin|PermissionsMixin)\b"
|
|
17
|
+
)
|
|
18
|
+
SETTING_NAME_REGEX = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
|
19
|
+
SENSITIVE_SETTING_REGEX = re.compile(
|
|
20
|
+
r"(SECRET|PASSWORD|TOKEN|API_KEY|PRIVATE_KEY|DATABASE_URL|CREDENTIAL)"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# Route decorator detection: only framework receivers, never generic calls like @cache.get().
|
|
24
|
+
_ROUTE_RECEIVERS = {"app", "router", "bp", "blueprint", "api", "routes"}
|
|
25
|
+
_ROUTE_METHODS = {
|
|
26
|
+
"get", "post", "put", "delete", "patch", "head", "options",
|
|
27
|
+
"route", "api_route", "websocket",
|
|
28
|
+
}
|
|
29
|
+
_ROUTE_BARE_NAMES = {"route", "api_route"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_route_decorator(dec: ast.expr) -> bool:
|
|
33
|
+
"""True only for framework route decorators (app/router/bp/api), never generic calls."""
|
|
34
|
+
if not isinstance(dec, ast.Call):
|
|
35
|
+
return False
|
|
36
|
+
func = dec.func
|
|
37
|
+
if isinstance(func, ast.Name):
|
|
38
|
+
return func.id.lower() in _ROUTE_BARE_NAMES
|
|
39
|
+
if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name):
|
|
40
|
+
receiver = func.value.id.lower()
|
|
41
|
+
if receiver in _ROUTE_RECEIVERS or receiver.endswith(("_router", "_app", "_bp")):
|
|
42
|
+
return func.attr.lower() in _ROUTE_METHODS
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _model_bases(node: ast.ClassDef) -> str:
|
|
47
|
+
try:
|
|
48
|
+
return " ".join(ast.unparse(base) for base in node.bases)
|
|
49
|
+
except Exception:
|
|
50
|
+
return ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _auto_model_items(file_path: Path, tree: ast.Module) -> list[dict[str, Any]]:
|
|
54
|
+
"""Top-level model classes in an untagged models module (or with a Django base)."""
|
|
55
|
+
items: list[dict[str, Any]] = []
|
|
56
|
+
models_module = file_path.name == "models.py" or "models" in file_path.parts[:-1]
|
|
57
|
+
for node in tree.body:
|
|
58
|
+
if not isinstance(node, ast.ClassDef):
|
|
59
|
+
continue
|
|
60
|
+
if not models_module and not MODEL_BASE_REGEX.search(_model_bases(node)):
|
|
61
|
+
continue
|
|
62
|
+
docstring = ast.get_docstring(node) or ""
|
|
63
|
+
items.append({
|
|
64
|
+
"feature_id": "",
|
|
65
|
+
"name": docstring.split("\n")[0] if docstring else f"{node.name} model",
|
|
66
|
+
"symbol": node.name,
|
|
67
|
+
"qualname": node.name,
|
|
68
|
+
"type": "model",
|
|
69
|
+
"start_line": node.lineno,
|
|
70
|
+
"end_line": node.end_lineno,
|
|
71
|
+
"depends_on": [],
|
|
72
|
+
"file": str(file_path),
|
|
73
|
+
"auto": True,
|
|
74
|
+
})
|
|
75
|
+
return items
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _auto_config_items(file_path: Path, tree: ast.Module) -> list[dict[str, Any]]:
|
|
79
|
+
"""Top-level UPPER_CASE assignments in an untagged Django settings module."""
|
|
80
|
+
items: list[dict[str, Any]] = []
|
|
81
|
+
for node in tree.body:
|
|
82
|
+
if isinstance(node, ast.Assign):
|
|
83
|
+
targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
|
|
84
|
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
|
85
|
+
targets = [node.target.id]
|
|
86
|
+
else:
|
|
87
|
+
continue
|
|
88
|
+
for name in targets:
|
|
89
|
+
if not SETTING_NAME_REGEX.match(name):
|
|
90
|
+
continue
|
|
91
|
+
item = {
|
|
92
|
+
"feature_id": "",
|
|
93
|
+
"name": f"Setting {name}",
|
|
94
|
+
"symbol": name,
|
|
95
|
+
"qualname": name,
|
|
96
|
+
"type": "config",
|
|
97
|
+
"start_line": node.lineno,
|
|
98
|
+
"end_line": node.end_lineno,
|
|
99
|
+
"depends_on": [],
|
|
100
|
+
"file": str(file_path),
|
|
101
|
+
"auto": True,
|
|
102
|
+
}
|
|
103
|
+
if SENSITIVE_SETTING_REGEX.search(name):
|
|
104
|
+
# Keep the key as the symbol (needed for a stable ID) but never emit values.
|
|
105
|
+
item["sensitive"] = True
|
|
106
|
+
item["name"] = "Setting (redacted)"
|
|
107
|
+
item["category"] = "sensitive"
|
|
108
|
+
items.append(item)
|
|
109
|
+
return items
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _auto_python_items(file_path: Path, tree: ast.Module) -> list[dict[str, Any]]:
|
|
113
|
+
if file_path.name == "models.py" or "models" in file_path.parts[:-1]:
|
|
114
|
+
return _auto_model_items(file_path, tree)
|
|
115
|
+
if file_path.name == "settings.py":
|
|
116
|
+
return _auto_config_items(file_path, tree)
|
|
117
|
+
return _auto_model_items(file_path, tree)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# @feature [PARSER_PY-01] Python feature parser
|
|
121
|
+
class PythonFeatureParser:
|
|
122
|
+
"""Parses Python source code with AST to extract feature tags, routes, classes, and exact line spans."""
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
# @feature [PARSER_PY-02] Parse file
|
|
126
|
+
def parse_file(file_path: Path) -> list[dict[str, Any]]:
|
|
127
|
+
if not file_path.exists() or not file_path.is_file():
|
|
128
|
+
return []
|
|
129
|
+
|
|
130
|
+
results = []
|
|
131
|
+
try:
|
|
132
|
+
source = file_path.read_text(encoding="utf-8")
|
|
133
|
+
tree = ast.parse(source, filename=str(file_path))
|
|
134
|
+
lines = source.splitlines()
|
|
135
|
+
comment_lines = lexmask.comment_only(source, "python").splitlines()
|
|
136
|
+
|
|
137
|
+
# Map method nodes to their enclosing class path (for qualified symbol resolution)
|
|
138
|
+
parent_class: dict[int, str] = {}
|
|
139
|
+
|
|
140
|
+
def visit(node, prefix: str):
|
|
141
|
+
for child in ast.iter_child_nodes(node):
|
|
142
|
+
if isinstance(child, ast.ClassDef):
|
|
143
|
+
visit(child, f"{prefix}{child.name}.")
|
|
144
|
+
elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
145
|
+
if prefix:
|
|
146
|
+
parent_class[id(child)] = prefix.rstrip(".")
|
|
147
|
+
visit(child, "") # nested defs inside methods are not methods
|
|
148
|
+
else:
|
|
149
|
+
visit(child, prefix)
|
|
150
|
+
|
|
151
|
+
visit(tree, "")
|
|
152
|
+
|
|
153
|
+
# 1. AST Node Traversal
|
|
154
|
+
for node in ast.walk(tree):
|
|
155
|
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
docstring = ast.get_docstring(node) or ""
|
|
159
|
+
|
|
160
|
+
# Check for explicit feature comments above node
|
|
161
|
+
start_line = node.lineno
|
|
162
|
+
end_line = node.end_lineno
|
|
163
|
+
|
|
164
|
+
# Look upwards in preceding lines for comment tags (closest first)
|
|
165
|
+
feat_match = None
|
|
166
|
+
dep_match = None
|
|
167
|
+
comment_window: list[str] = []
|
|
168
|
+
|
|
169
|
+
for i in range(start_line - 2, max(-1, start_line - 8), -1):
|
|
170
|
+
if i < len(lines):
|
|
171
|
+
line_str = lines[i].strip()
|
|
172
|
+
comment_line = comment_lines[i].strip()
|
|
173
|
+
# Only real comment lines count — string literals must not create features
|
|
174
|
+
if comment_line.startswith("#") and line_str.startswith("#"):
|
|
175
|
+
comment_window.append(comment_line)
|
|
176
|
+
if not feat_match:
|
|
177
|
+
feat_match = FEATURE_TAG_REGEX.search(comment_line)
|
|
178
|
+
if not dep_match:
|
|
179
|
+
dep_match = DEPENDS_TAG_REGEX.search(comment_line)
|
|
180
|
+
if line_str and not line_str.startswith("#") and not line_str.startswith("@"):
|
|
181
|
+
break
|
|
182
|
+
|
|
183
|
+
node_name = getattr(node, "name", "")
|
|
184
|
+
node_qual = f"{parent_class[id(node)]}.{node_name}" if id(node) in parent_class else node_name
|
|
185
|
+
deps = []
|
|
186
|
+
if dep_match:
|
|
187
|
+
raw_deps = dep_match.group(1).split(",")
|
|
188
|
+
deps = [d.strip().strip("[]") for d in raw_deps if d.strip()]
|
|
189
|
+
contract = extract_contract_tags("\n".join(reversed(comment_window)))
|
|
190
|
+
|
|
191
|
+
# If tagged explicitly
|
|
192
|
+
if feat_match:
|
|
193
|
+
feat_id = feat_match.group(1).upper()
|
|
194
|
+
desc = feat_match.group(2) or (docstring.split("\n")[0] if docstring else node_name)
|
|
195
|
+
is_endpoint = any(
|
|
196
|
+
_is_route_decorator(d)
|
|
197
|
+
for d in getattr(node, "decorator_list", ())
|
|
198
|
+
)
|
|
199
|
+
if isinstance(node, ast.ClassDef):
|
|
200
|
+
node_type = "class"
|
|
201
|
+
elif is_endpoint:
|
|
202
|
+
node_type = "endpoint"
|
|
203
|
+
else:
|
|
204
|
+
node_type = "function"
|
|
205
|
+
results.append({
|
|
206
|
+
"feature_id": feat_id,
|
|
207
|
+
"name": desc,
|
|
208
|
+
"symbol": node_name,
|
|
209
|
+
"qualname": node_qual,
|
|
210
|
+
"type": node_type,
|
|
211
|
+
"start_line": start_line,
|
|
212
|
+
"end_line": end_line,
|
|
213
|
+
"depends_on": deps,
|
|
214
|
+
"file": str(file_path),
|
|
215
|
+
**contract,
|
|
216
|
+
})
|
|
217
|
+
# Also discover FastAPI / Flask route handlers automatically
|
|
218
|
+
elif getattr(node, "decorator_list", None):
|
|
219
|
+
for dec in node.decorator_list:
|
|
220
|
+
if not _is_route_decorator(dec):
|
|
221
|
+
continue
|
|
222
|
+
dec_src = ast.unparse(dec)
|
|
223
|
+
results.append({
|
|
224
|
+
"feature_id": f"ROUTE-{node_name.upper()}",
|
|
225
|
+
"name": f"API Endpoint `{node_name}` ({dec_src})",
|
|
226
|
+
"symbol": node_name,
|
|
227
|
+
"qualname": node_qual,
|
|
228
|
+
"type": "endpoint",
|
|
229
|
+
"start_line": start_line,
|
|
230
|
+
"end_line": end_line,
|
|
231
|
+
"depends_on": [],
|
|
232
|
+
"file": str(file_path),
|
|
233
|
+
**contract,
|
|
234
|
+
})
|
|
235
|
+
break
|
|
236
|
+
|
|
237
|
+
if not results:
|
|
238
|
+
results.extend(_auto_python_items(file_path, tree))
|
|
239
|
+
|
|
240
|
+
except (SyntaxError, UnicodeDecodeError, ValueError, OSError):
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
return results
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from . import lexmask
|
|
6
|
+
from .tags import (
|
|
7
|
+
DEPENDS_TAG_REGEX,
|
|
8
|
+
FEATURE_TAG_REGEX,
|
|
9
|
+
extract_contract_tags,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
# Tags are only honoured on comment lines; the comment mask rejects string/template text
|
|
13
|
+
COMMENT_LINE_REGEX = re.compile(r"^[ \t]*(?://|/\*|\*|#)")
|
|
14
|
+
COMPONENT_EXPORT_REGEX = re.compile(
|
|
15
|
+
r"export\s+(?:default\s+)?(?:async\s+function|function|const|let|var|class|type|interface|enum)"
|
|
16
|
+
r"\s+([A-Za-z0-9_$]+)",
|
|
17
|
+
re.MULTILINE,
|
|
18
|
+
)
|
|
19
|
+
# End estimate: when the symbol's opening brace closes its (masked) line, brace depth runs
|
|
20
|
+
# to the real close — strings, comments and template literals cannot close the block early.
|
|
21
|
+
# JSX-paren arrows (`const X = () => (`) track balanced parentheses the same way.
|
|
22
|
+
# Everything else (single-line bodies) keeps the fixed lookahead window.
|
|
23
|
+
# ponytail: exact JSX ranges need tree-sitter; the window is the honest ceiling until then.
|
|
24
|
+
TS_END_LINE_LOOKAHEAD = 35 # fallback max-lines window when no block brace is found
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ts_symbol_end(
|
|
28
|
+
code_lines: list[str], start_idx: int, fallback_end: int, header_limit: int = 4
|
|
29
|
+
) -> int:
|
|
30
|
+
"""1-based inclusive end of the block opening in the symbol's header lines.
|
|
31
|
+
|
|
32
|
+
The opener must end its masked line; depth then runs to the matching close.
|
|
33
|
+
Returns fallback_end when no opener is found or the block never closes.
|
|
34
|
+
"""
|
|
35
|
+
limit = min(start_idx + max(1, header_limit), len(code_lines))
|
|
36
|
+
# Whole block on one line: `export class Store {}`
|
|
37
|
+
first = code_lines[start_idx].rstrip() if code_lines else ""
|
|
38
|
+
if first.endswith("}") and first.count("{") == first.count("}"):
|
|
39
|
+
return start_idx + 1
|
|
40
|
+
opener = None
|
|
41
|
+
for i in range(start_idx, limit):
|
|
42
|
+
if code_lines[i].rstrip().endswith("{"):
|
|
43
|
+
opener = i
|
|
44
|
+
break
|
|
45
|
+
if opener is not None:
|
|
46
|
+
depth = 0
|
|
47
|
+
for i in range(opener, len(code_lines)):
|
|
48
|
+
depth += code_lines[i].count("{") - code_lines[i].count("}")
|
|
49
|
+
if depth <= 0:
|
|
50
|
+
return i + 1
|
|
51
|
+
return fallback_end
|
|
52
|
+
|
|
53
|
+
# Arrow with a parenthesized JSX return: `export const Card = () => (` ... `);`
|
|
54
|
+
for i in range(start_idx, limit):
|
|
55
|
+
arrow = code_lines[i].find("=>")
|
|
56
|
+
if arrow == -1:
|
|
57
|
+
continue
|
|
58
|
+
rest = code_lines[i][arrow + 2:]
|
|
59
|
+
if "(" not in rest:
|
|
60
|
+
break
|
|
61
|
+
depth = rest.count("(") - rest.count(")")
|
|
62
|
+
if depth <= 0:
|
|
63
|
+
return i + 1
|
|
64
|
+
for j in range(i + 1, len(code_lines)):
|
|
65
|
+
depth += code_lines[j].count("(") - code_lines[j].count(")")
|
|
66
|
+
if depth <= 0:
|
|
67
|
+
return j + 1
|
|
68
|
+
return fallback_end
|
|
69
|
+
|
|
70
|
+
# Concise single-line body: `export const x = 1;`
|
|
71
|
+
for i in range(start_idx, limit):
|
|
72
|
+
if code_lines[i].rstrip().endswith(";"):
|
|
73
|
+
return i + 1
|
|
74
|
+
return fallback_end
|
|
75
|
+
|
|
76
|
+
# Untagged TS/TSX/JSX coverage: exported declarations and arrow components.
|
|
77
|
+
TS_EXPORT_DECL_REGEX = re.compile(
|
|
78
|
+
r"(?m)^[ \t]*export\s+(?:default\s+)?(?:async\s+)?"
|
|
79
|
+
r"(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)"
|
|
80
|
+
)
|
|
81
|
+
# CommonJS extractor. Untagged .js files get synthetic feature IDs for their
|
|
82
|
+
# declarations/exports; explicit @feature tags keep the existing tag-only path above.
|
|
83
|
+
CJS_CLASS_REGEX = re.compile(r"(?m)^[ \t]*(?:module\.exports\s*=\s*)?class\s+([A-Za-z_$][\w$]*)")
|
|
84
|
+
CJS_FUNCTION_REGEX = re.compile(r"(?m)^[ \t]*(?:module\.exports\s*=\s*)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)")
|
|
85
|
+
CJS_ARROW_REGEX = re.compile(
|
|
86
|
+
r"(?m)^[ \t]*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
|
|
87
|
+
r"(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)"
|
|
88
|
+
)
|
|
89
|
+
CJS_PROTOTYPE_REGEX = re.compile(
|
|
90
|
+
r"(?m)^[ \t]*([A-Za-z_$][\w$]*)\.prototype\.([A-Za-z_$][\w$]*)\s*="
|
|
91
|
+
)
|
|
92
|
+
CJS_EXPORT_MEMBER_REGEX = re.compile(
|
|
93
|
+
r"(?m)^[ \t]*(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*="
|
|
94
|
+
)
|
|
95
|
+
CJS_EXPORT_OBJECT_REGEX = re.compile(r"module\.exports\s*=\s*\{")
|
|
96
|
+
CJS_CLASS_MEMBER_REGEX = re.compile(
|
|
97
|
+
r"^[ \t]*(?:static\s+)?(?:async\s+)?(?:get\s+|set\s+)?"
|
|
98
|
+
r"([A-Za-z_$][\w$]*)\s*\("
|
|
99
|
+
)
|
|
100
|
+
CJS_CLASS_FIELD_REGEX = re.compile(
|
|
101
|
+
r"^[ \t]*(?:static\s+)?([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
|
|
102
|
+
r"(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"
|
|
103
|
+
)
|
|
104
|
+
CJS_OBJECT_PROPERTY_REGEX = re.compile(
|
|
105
|
+
r"^[ \t]*(?:async\s+)?(?:get\s+|set\s+)?([A-Za-z_$][\w$]*)\s*(?:\(|:|,|$)"
|
|
106
|
+
)
|
|
107
|
+
CJS_SKIP_MEMBER_NAMES = {
|
|
108
|
+
"if", "for", "while", "switch", "catch", "function", "return", "new",
|
|
109
|
+
"constructor", "do", "else", "try", "with",
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _cjs_brace_end(code_lines: list[str], start_idx: int) -> int:
|
|
114
|
+
"""Line after the block that opens at/after start_idx (0-indexed)."""
|
|
115
|
+
depth = 0
|
|
116
|
+
opened = False
|
|
117
|
+
for i in range(start_idx, len(code_lines)):
|
|
118
|
+
line = code_lines[i]
|
|
119
|
+
opens = line.count("{")
|
|
120
|
+
closes = line.count("}")
|
|
121
|
+
if opens:
|
|
122
|
+
opened = True
|
|
123
|
+
depth += opens - closes
|
|
124
|
+
if opened and depth <= 0:
|
|
125
|
+
return i + 1
|
|
126
|
+
return min(start_idx + 40, len(code_lines))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _cjs_value_end(code_lines: list[str], start_idx: int) -> int:
|
|
130
|
+
"""End line for an assignment whose value may be a block or concise expression."""
|
|
131
|
+
line = code_lines[start_idx]
|
|
132
|
+
if "{" in line or re.search(r"\b(?:function|class)\b", line):
|
|
133
|
+
return _cjs_brace_end(code_lines, start_idx)
|
|
134
|
+
if "=>" in line:
|
|
135
|
+
for i in range(start_idx, min(start_idx + 10, len(code_lines))):
|
|
136
|
+
if ";" in code_lines[i] or code_lines[i].rstrip().endswith(","):
|
|
137
|
+
return i + 1
|
|
138
|
+
return start_idx + 1
|
|
139
|
+
return start_idx + 1
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _cjs_human(name: str) -> str:
|
|
143
|
+
name = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name).replace("_", " ")
|
|
144
|
+
return name[:1].upper() + name[1:]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _cjs_auto_symbols(file_path: Path, code: str) -> list[dict[str, Any]]:
|
|
148
|
+
"""Extract classes/functions/methods/export names from masked CommonJS code."""
|
|
149
|
+
lines = code.splitlines()
|
|
150
|
+
found: list[dict[str, Any]] = []
|
|
151
|
+
|
|
152
|
+
def add(name: str, kind: str, start: int, end: int, qualname: str = ""):
|
|
153
|
+
found.append({
|
|
154
|
+
"feature_id": "",
|
|
155
|
+
"name": _cjs_human(name),
|
|
156
|
+
"symbol": name,
|
|
157
|
+
"qualname": qualname or name,
|
|
158
|
+
"type": kind,
|
|
159
|
+
"start_line": start,
|
|
160
|
+
"end_line": end,
|
|
161
|
+
"depends_on": [],
|
|
162
|
+
"auto": True,
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
class_ranges = []
|
|
166
|
+
for match in CJS_CLASS_REGEX.finditer(code):
|
|
167
|
+
start = code[: match.start()].count("\n")
|
|
168
|
+
end = _cjs_brace_end(lines, start)
|
|
169
|
+
class_ranges.append((match.group(1), start, end))
|
|
170
|
+
add(match.group(1), "class", start + 1, end, match.group(1))
|
|
171
|
+
|
|
172
|
+
for class_name, start, end in class_ranges:
|
|
173
|
+
depth = 0
|
|
174
|
+
opened = False
|
|
175
|
+
for i in range(start, end):
|
|
176
|
+
line = lines[i]
|
|
177
|
+
if not opened:
|
|
178
|
+
depth += line.count("{") - line.count("}")
|
|
179
|
+
opened = "{" in line
|
|
180
|
+
continue
|
|
181
|
+
if depth == 1:
|
|
182
|
+
match = CJS_CLASS_MEMBER_REGEX.match(line)
|
|
183
|
+
if not match:
|
|
184
|
+
match = CJS_CLASS_FIELD_REGEX.match(line)
|
|
185
|
+
if match:
|
|
186
|
+
name = match.group(1)
|
|
187
|
+
if name not in CJS_SKIP_MEMBER_NAMES:
|
|
188
|
+
add(name, "method", i + 1, _cjs_value_end(lines, i), f"{class_name}.{name}")
|
|
189
|
+
depth += line.count("{") - line.count("}")
|
|
190
|
+
|
|
191
|
+
for match in CJS_FUNCTION_REGEX.finditer(code):
|
|
192
|
+
start = code[: match.start()].count("\n")
|
|
193
|
+
add(match.group(1), "function", start + 1, _cjs_value_end(lines, start), match.group(1))
|
|
194
|
+
|
|
195
|
+
for match in CJS_ARROW_REGEX.finditer(code):
|
|
196
|
+
start = code[: match.start()].count("\n")
|
|
197
|
+
add(match.group(1), "function", start + 1, _cjs_value_end(lines, start), match.group(1))
|
|
198
|
+
|
|
199
|
+
for match in CJS_PROTOTYPE_REGEX.finditer(code):
|
|
200
|
+
start = code[: match.start()].count("\n")
|
|
201
|
+
add(match.group(2), "method", start + 1, _cjs_value_end(lines, start), f"{match.group(1)}.{match.group(2)}")
|
|
202
|
+
|
|
203
|
+
for match in CJS_EXPORT_MEMBER_REGEX.finditer(code):
|
|
204
|
+
start = code[: match.start()].count("\n")
|
|
205
|
+
add(match.group(1), "export", start + 1, _cjs_value_end(lines, start), match.group(1))
|
|
206
|
+
|
|
207
|
+
for match in CJS_EXPORT_OBJECT_REGEX.finditer(code):
|
|
208
|
+
start = code[: match.start()].count("\n")
|
|
209
|
+
end = _cjs_brace_end(lines, start)
|
|
210
|
+
depth = 0
|
|
211
|
+
for i in range(start, end):
|
|
212
|
+
line = lines[i]
|
|
213
|
+
if i != start and depth == 1:
|
|
214
|
+
prop = CJS_OBJECT_PROPERTY_REGEX.match(line)
|
|
215
|
+
if prop and prop.group(1) not in CJS_SKIP_MEMBER_NAMES:
|
|
216
|
+
end_line = _cjs_value_end(lines, i)
|
|
217
|
+
add(prop.group(1), "export", i + 1, end_line, prop.group(1))
|
|
218
|
+
depth += line.count("{") - line.count("}")
|
|
219
|
+
|
|
220
|
+
# Export aliases point at an already-extracted function/class; keep one feature per symbol.
|
|
221
|
+
seen = {item["symbol"] for item in found if item["type"] != "export"}
|
|
222
|
+
unique = []
|
|
223
|
+
seen_locations = set()
|
|
224
|
+
for item in found:
|
|
225
|
+
if item["type"] == "export" and item["symbol"] in seen:
|
|
226
|
+
continue
|
|
227
|
+
key = (item["symbol"], item["start_line"], item["qualname"])
|
|
228
|
+
if key not in seen_locations:
|
|
229
|
+
seen_locations.add(key)
|
|
230
|
+
unique.append(item)
|
|
231
|
+
|
|
232
|
+
for item in unique:
|
|
233
|
+
item["file"] = str(file_path)
|
|
234
|
+
return unique
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _ts_auto_symbols(file_path: Path, code: str) -> list[dict[str, Any]]:
|
|
238
|
+
"""Untagged .ts/.tsx/.jsx exports become TS-* coverage entries."""
|
|
239
|
+
lines = code.splitlines()
|
|
240
|
+
matches = list(TS_EXPORT_DECL_REGEX.finditer(code))
|
|
241
|
+
starts = [code[: match.start()].count("\n") for match in matches]
|
|
242
|
+
found: list[dict[str, Any]] = []
|
|
243
|
+
seen: set[str] = set()
|
|
244
|
+
for pos, match in enumerate(matches):
|
|
245
|
+
name = match.group(1)
|
|
246
|
+
if name in seen:
|
|
247
|
+
continue
|
|
248
|
+
seen.add(name)
|
|
249
|
+
start = starts[pos]
|
|
250
|
+
# A declaration's header stops before the next export on a following line.
|
|
251
|
+
next_start = next(
|
|
252
|
+
(s for s in starts[pos + 1:] if s > start), start + 4
|
|
253
|
+
)
|
|
254
|
+
end = _ts_symbol_end(
|
|
255
|
+
lines, start, min(start + 1 + TS_END_LINE_LOOKAHEAD, len(lines)),
|
|
256
|
+
header_limit=min(4, next_start - start),
|
|
257
|
+
)
|
|
258
|
+
found.append({
|
|
259
|
+
"feature_id": "",
|
|
260
|
+
"name": _cjs_human(name),
|
|
261
|
+
"symbol": name,
|
|
262
|
+
"qualname": name,
|
|
263
|
+
"type": "class" if re.search(r"\bclass\b", lines[start]) else "function",
|
|
264
|
+
"start_line": start + 1,
|
|
265
|
+
"end_line": end,
|
|
266
|
+
"depends_on": [],
|
|
267
|
+
"auto": True,
|
|
268
|
+
"prefix": "TS",
|
|
269
|
+
"file": str(file_path),
|
|
270
|
+
})
|
|
271
|
+
return found
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# @feature [PARSER_TS-01] Type script feature parser
|
|
275
|
+
class TypeScriptFeatureParser:
|
|
276
|
+
"""Parses TypeScript/React files to extract UI components, features, and line positions."""
|
|
277
|
+
|
|
278
|
+
@staticmethod
|
|
279
|
+
# @feature [PARSER_TS-02] Parse file
|
|
280
|
+
def parse_file(file_path: Path) -> list[dict[str, Any]]:
|
|
281
|
+
if not file_path.exists() or not file_path.is_file():
|
|
282
|
+
return []
|
|
283
|
+
|
|
284
|
+
results = []
|
|
285
|
+
try:
|
|
286
|
+
content = file_path.read_text(encoding="utf-8")
|
|
287
|
+
lines = content.splitlines()
|
|
288
|
+
code_lines = lexmask.code_only(content, "js").splitlines()
|
|
289
|
+
comment_lines = lexmask.comment_only(content, "js").splitlines()
|
|
290
|
+
|
|
291
|
+
# Find feature tags (comment lines only; template/string text is masked)
|
|
292
|
+
for idx in range(1, len(lines) + 1):
|
|
293
|
+
if not COMMENT_LINE_REGEX.match(lines[idx - 1]):
|
|
294
|
+
continue
|
|
295
|
+
match = FEATURE_TAG_REGEX.search(comment_lines[idx - 1])
|
|
296
|
+
if match:
|
|
297
|
+
feat_id = match.group(1).upper()
|
|
298
|
+
desc = match.group(2) or "UI Feature Component"
|
|
299
|
+
|
|
300
|
+
# Look ahead for component export
|
|
301
|
+
symbol_name = file_path.stem
|
|
302
|
+
sym_idx = idx - 1
|
|
303
|
+
|
|
304
|
+
# Check next 6 lines for export statement
|
|
305
|
+
for sub_idx in range(idx, min(idx + 6, len(lines))):
|
|
306
|
+
exp_match = COMPONENT_EXPORT_REGEX.search(code_lines[sub_idx])
|
|
307
|
+
if exp_match:
|
|
308
|
+
symbol_name = exp_match.group(1)
|
|
309
|
+
sym_idx = sub_idx
|
|
310
|
+
break
|
|
311
|
+
end_line = _ts_symbol_end(
|
|
312
|
+
code_lines, sym_idx, min(idx + TS_END_LINE_LOOKAHEAD, len(lines))
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
context = "\n".join(comment_lines[max(0, idx - 2):min(len(lines), idx + 3)])
|
|
316
|
+
dep_match = DEPENDS_TAG_REGEX.search(context)
|
|
317
|
+
deps = []
|
|
318
|
+
if dep_match:
|
|
319
|
+
deps = [d.strip().strip("[]") for d in dep_match.group(1).split(",") if d.strip()]
|
|
320
|
+
contract = extract_contract_tags(context)
|
|
321
|
+
|
|
322
|
+
results.append({
|
|
323
|
+
"feature_id": feat_id,
|
|
324
|
+
"name": desc.strip(),
|
|
325
|
+
"symbol": symbol_name,
|
|
326
|
+
"type": "component",
|
|
327
|
+
"start_line": idx,
|
|
328
|
+
"end_line": end_line,
|
|
329
|
+
"depends_on": deps,
|
|
330
|
+
"file": str(file_path),
|
|
331
|
+
**contract,
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
except (UnicodeDecodeError, OSError):
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
if not results and file_path.suffix.lower() in (".js", ".ts", ".tsx", ".jsx"):
|
|
338
|
+
try:
|
|
339
|
+
content = file_path.read_text(encoding="utf-8")
|
|
340
|
+
except (UnicodeDecodeError, OSError):
|
|
341
|
+
return []
|
|
342
|
+
masked = lexmask.code_only(content, "js")
|
|
343
|
+
# ponytail: brace-balance gate — syntactically broken JS must not mint features;
|
|
344
|
+
# real syntax validation needs node/tree-sitter.
|
|
345
|
+
if masked.count("{") != masked.count("}"):
|
|
346
|
+
return []
|
|
347
|
+
if file_path.suffix.lower() == ".js":
|
|
348
|
+
return _cjs_auto_symbols(file_path, masked)
|
|
349
|
+
return _ts_auto_symbols(file_path, masked)
|
|
350
|
+
return results
|