lattice-graph 0.1.0

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.
@@ -0,0 +1,142 @@
1
+ import type { TreeSitterNode, TreeSitterTree } from "../parser.ts";
2
+
3
+ /** A detected framework pattern on a function. */
4
+ type FrameworkDetection = {
5
+ readonly functionName: string;
6
+ readonly route: string | undefined;
7
+ readonly isEntryPoint: boolean;
8
+ readonly line: number;
9
+ };
10
+
11
+ /** HTTP methods recognized in route decorators. */
12
+ const HTTP_METHODS = new Set(["get", "post", "put", "delete", "patch", "head", "options"]);
13
+
14
+ /**
15
+ * Detects framework patterns (FastAPI, Flask, Celery) on decorated functions.
16
+ * Used by the linter to flag untagged entry points and by populate to suggest tags.
17
+ *
18
+ * @param tree - Parsed tree-sitter tree
19
+ * @param _filePath - Relative file path (unused, kept for interface consistency)
20
+ * @returns Detected framework patterns with route info and entry point flags
21
+ */
22
+ function detectPythonFrameworks(
23
+ tree: TreeSitterTree,
24
+ _filePath: string,
25
+ ): readonly FrameworkDetection[] {
26
+ const results: FrameworkDetection[] = [];
27
+
28
+ for (const child of tree.rootNode.children) {
29
+ if (child.type === "decorated_definition") {
30
+ processDecoratedDefinition(child, results);
31
+ }
32
+ }
33
+
34
+ return results;
35
+ }
36
+
37
+ /** Processes a decorated_definition node to check for framework patterns. */
38
+ function processDecoratedDefinition(node: TreeSitterNode, results: FrameworkDetection[]): void {
39
+ const funcDef = node.children.find((c) => c.type === "function_definition");
40
+ if (!funcDef) return;
41
+
42
+ const funcName = funcDef.childForFieldName("name")?.text;
43
+ if (!funcName) return;
44
+
45
+ const decorators = node.children.filter((c) => c.type === "decorator");
46
+
47
+ for (const decorator of decorators) {
48
+ const detection = analyzeDecorator(decorator, funcName, node.startPosition.row + 1);
49
+ if (detection) {
50
+ results.push(detection);
51
+ }
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Analyzes a single decorator to determine if it matches a framework pattern.
57
+ * Recognizes: @app.get("/path"), @router.post("/path"), @app.route("/path"),
58
+ * @bp.route("/path"), @app.task, @shared_task
59
+ */
60
+ function analyzeDecorator(
61
+ decorator: TreeSitterNode,
62
+ funcName: string,
63
+ line: number,
64
+ ): FrameworkDetection | undefined {
65
+ // The decorator's child after '@' is either a call or an attribute/identifier
66
+ const content = decorator.children.find(
67
+ (c) => c.type === "call" || c.type === "attribute" || c.type === "identifier",
68
+ );
69
+ if (!content) return undefined;
70
+
71
+ // Case 1: @shared_task (bare identifier)
72
+ if (content.type === "identifier" && content.text === "shared_task") {
73
+ return { functionName: funcName, route: undefined, isEntryPoint: true, line };
74
+ }
75
+
76
+ // Case 2: @app.task (bare attribute, no call)
77
+ if (content.type === "attribute") {
78
+ const attrName = content.children.at(-1)?.text;
79
+ if (attrName === "task") {
80
+ return { functionName: funcName, route: undefined, isEntryPoint: true, line };
81
+ }
82
+ }
83
+
84
+ // Case 3: @app.get("/path") or @router.post("/path") or @app.route("/path") — a call
85
+ if (content.type === "call") {
86
+ return analyzeDecoratorCall(content, funcName, line);
87
+ }
88
+
89
+ return undefined;
90
+ }
91
+
92
+ /** Analyzes a decorator that is a function call, e.g., @app.post("/api/checkout"). */
93
+ function analyzeDecoratorCall(
94
+ callNode: TreeSitterNode,
95
+ funcName: string,
96
+ line: number,
97
+ ): FrameworkDetection | undefined {
98
+ const callee = callNode.children[0];
99
+ if (!callee || callee.type !== "attribute") return undefined;
100
+
101
+ const methodName = callee.children.at(-1)?.text;
102
+ if (!methodName) return undefined;
103
+
104
+ const args = callNode.children.find((c) => c.type === "argument_list");
105
+ const firstArg = args?.children.find((c) => c.type === "string");
106
+ const routePath = firstArg ? extractStringContent(firstArg) : undefined;
107
+
108
+ // @app.get("/path"), @router.post("/path"), etc.
109
+ if (HTTP_METHODS.has(methodName) && routePath) {
110
+ return {
111
+ functionName: funcName,
112
+ route: `${methodName.toUpperCase()} ${routePath}`,
113
+ isEntryPoint: true,
114
+ line,
115
+ };
116
+ }
117
+
118
+ // @app.route("/path") or @bp.route("/path")
119
+ if (methodName === "route" && routePath) {
120
+ return {
121
+ functionName: funcName,
122
+ route: routePath,
123
+ isEntryPoint: true,
124
+ line,
125
+ };
126
+ }
127
+
128
+ // @app.task() with parentheses
129
+ if (methodName === "task") {
130
+ return { functionName: funcName, route: undefined, isEntryPoint: true, line };
131
+ }
132
+
133
+ return undefined;
134
+ }
135
+
136
+ /** Extracts the string content from a tree-sitter string node, stripping quotes. */
137
+ function extractStringContent(stringNode: TreeSitterNode): string | undefined {
138
+ const contentNode = stringNode.children.find((c) => c.type === "string_content");
139
+ return contentNode?.text;
140
+ }
141
+
142
+ export { detectPythonFrameworks, type FrameworkDetection };
@@ -0,0 +1,115 @@
1
+ import type { TreeSitterNode, TreeSitterTree } from "../parser.ts";
2
+
3
+ /** A parsed import statement from Python source. */
4
+ type PythonImport = {
5
+ readonly module: string;
6
+ readonly names: readonly string[];
7
+ readonly isRelative: boolean;
8
+ readonly aliases: Map<string, string> | undefined;
9
+ readonly line: number;
10
+ };
11
+
12
+ /**
13
+ * Extracts import statements from a Python AST.
14
+ *
15
+ * @param tree - Parsed tree-sitter tree
16
+ * @param _filePath - Relative file path (unused, kept for interface consistency)
17
+ * @returns Parsed imports with module paths, imported names, and alias mappings
18
+ */
19
+ function extractPythonImports(tree: TreeSitterTree, _filePath: string): readonly PythonImport[] {
20
+ const imports: PythonImport[] = [];
21
+
22
+ for (const child of tree.rootNode.children) {
23
+ if (child.type === "import_statement") {
24
+ parseImportStatement(child, imports);
25
+ } else if (child.type === "import_from_statement") {
26
+ parseImportFromStatement(child, imports);
27
+ }
28
+ }
29
+
30
+ return imports;
31
+ }
32
+
33
+ /** Parses `import x` or `import x as y` statements. */
34
+ function parseImportStatement(node: TreeSitterNode, results: PythonImport[]): void {
35
+ for (const child of node.children) {
36
+ if (child.type === "dotted_name") {
37
+ results.push({
38
+ module: child.text,
39
+ names: [],
40
+ isRelative: false,
41
+ aliases: undefined,
42
+ line: node.startPosition.row + 1,
43
+ });
44
+ } else if (child.type === "aliased_import") {
45
+ const moduleName = extractDottedName(child);
46
+ const alias = extractAlias(child);
47
+ const aliases = alias ? new Map([[moduleName, alias]]) : undefined;
48
+ results.push({
49
+ module: moduleName,
50
+ names: [],
51
+ isRelative: false,
52
+ aliases,
53
+ line: node.startPosition.row + 1,
54
+ });
55
+ }
56
+ }
57
+ }
58
+
59
+ /** Parses `from x import y` or `from .x import y as z` statements. */
60
+ function parseImportFromStatement(node: TreeSitterNode, results: PythonImport[]): void {
61
+ let module = "";
62
+ let isRelative = false;
63
+ const names: string[] = [];
64
+ const aliases = new Map<string, string>();
65
+
66
+ for (const child of node.children) {
67
+ if (child.type === "dotted_name" && !module) {
68
+ module = child.text;
69
+ } else if (child.type === "relative_import") {
70
+ isRelative = true;
71
+ const prefix = child.children.find((c) => c.type === "import_prefix");
72
+ const dottedName = child.children.find((c) => c.type === "dotted_name");
73
+ const dots = prefix?.text ?? ".";
74
+ module = dottedName ? `${dots}${dottedName.text}` : dots;
75
+ } else if (child.type === "dotted_name" && module) {
76
+ names.push(child.text);
77
+ } else if (child.type === "aliased_import") {
78
+ const name = extractDottedName(child);
79
+ names.push(name);
80
+ const alias = extractAlias(child);
81
+ if (alias) {
82
+ aliases.set(name, alias);
83
+ }
84
+ }
85
+ }
86
+
87
+ results.push({
88
+ module,
89
+ names,
90
+ isRelative,
91
+ aliases: aliases.size > 0 ? aliases : undefined,
92
+ line: node.startPosition.row + 1,
93
+ });
94
+ }
95
+
96
+ /** Extracts the dotted name from an aliased_import node. */
97
+ function extractDottedName(aliasedNode: TreeSitterNode): string {
98
+ const dottedName = aliasedNode.children.find((c) => c.type === "dotted_name");
99
+ return dottedName?.text ?? "";
100
+ }
101
+
102
+ /** Extracts the alias identifier from an aliased_import node. */
103
+ function extractAlias(aliasedNode: TreeSitterNode): string | undefined {
104
+ const children = aliasedNode.children;
105
+ const asIdx = children.findIndex((c) => c.type === "as");
106
+ if (asIdx >= 0) {
107
+ const aliasNode = children[asIdx + 1];
108
+ if (aliasNode?.type === "identifier") {
109
+ return aliasNode.text;
110
+ }
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ export { extractPythonImports, type PythonImport };
@@ -0,0 +1,121 @@
1
+ import type { Node, NodeKind } from "../../types/graph.ts";
2
+ import type { TreeSitterNode, TreeSitterTree } from "../parser.ts";
3
+
4
+ /** Scope entry tracking the name and whether it's a class scope. */
5
+ type ScopeEntry = { readonly name: string; readonly isClass: boolean };
6
+
7
+ /**
8
+ * Extracts symbols (functions, classes, methods) from a Python AST.
9
+ *
10
+ * @param tree - Parsed tree-sitter tree
11
+ * @param filePath - Relative file path for node ID construction
12
+ * @param _source - Original source text (unused but kept for interface consistency)
13
+ * @returns Extracted nodes with deterministic IDs
14
+ */
15
+ function extractPythonSymbols(
16
+ tree: TreeSitterTree,
17
+ filePath: string,
18
+ _source: string,
19
+ ): readonly Node[] {
20
+ const nodes: Node[] = [];
21
+ visitNode(tree.rootNode, filePath, [], nodes);
22
+ return nodes;
23
+ }
24
+
25
+ /**
26
+ * Recursively visits AST nodes to extract symbols.
27
+ * Tracks parent scope for generating nested IDs (e.g., Class.method, outer.inner).
28
+ */
29
+ function visitNode(
30
+ node: TreeSitterNode,
31
+ filePath: string,
32
+ scopeStack: readonly ScopeEntry[],
33
+ results: Node[],
34
+ ): void {
35
+ if (node.type === "decorated_definition") {
36
+ // Decorated definitions wrap a function/class. Find the inner definition
37
+ // and use the decorated_definition's line range (includes decorators).
38
+ const inner = node.children.find(
39
+ (c) => c.type === "function_definition" || c.type === "class_definition",
40
+ );
41
+ if (inner) {
42
+ extractDefinition(inner, filePath, scopeStack, results, node);
43
+ }
44
+ } else if (node.type === "function_definition" || node.type === "class_definition") {
45
+ extractDefinition(node, filePath, scopeStack, results, undefined);
46
+ } else {
47
+ for (const child of node.children) {
48
+ visitNode(child, filePath, scopeStack, results);
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Extracts a function or class definition into a Node and recurses into its body.
55
+ * If a decorated parent is provided, uses its line range to include decorator lines.
56
+ */
57
+ function extractDefinition(
58
+ node: TreeSitterNode,
59
+ filePath: string,
60
+ scopeStack: readonly ScopeEntry[],
61
+ results: Node[],
62
+ decoratedParent: TreeSitterNode | undefined,
63
+ ): void {
64
+ const nameNode = node.childForFieldName("name");
65
+ if (!nameNode) return;
66
+
67
+ const name = nameNode.text;
68
+ const isClass = node.type === "class_definition";
69
+ const kind = resolveKind(isClass, scopeStack);
70
+ const qualifiedName = [...scopeStack.map((s) => s.name), name].join(".");
71
+ const id = `${filePath}::${qualifiedName}`;
72
+
73
+ const signature = kind !== "class" ? buildSignature(node, name) : undefined;
74
+
75
+ // Use the decorated parent's line range if it exists (includes decorator lines)
76
+ const rangeNode = decoratedParent ?? node;
77
+
78
+ results.push({
79
+ id,
80
+ kind,
81
+ name,
82
+ file: filePath,
83
+ lineStart: rangeNode.startPosition.row + 1,
84
+ lineEnd: rangeNode.endPosition.row + 1,
85
+ language: "python",
86
+ signature,
87
+ isTest: false,
88
+ metadata: undefined,
89
+ });
90
+
91
+ // Recurse into children with updated scope
92
+ const newScope: readonly ScopeEntry[] = [...scopeStack, { name, isClass }];
93
+ for (const child of node.children) {
94
+ visitNode(child, filePath, newScope, results);
95
+ }
96
+ }
97
+
98
+ /** Determines the node kind based on whether this is a class or function, and the parent scope. */
99
+ function resolveKind(isClass: boolean, scopeStack: readonly ScopeEntry[]): NodeKind {
100
+ if (isClass) return "class";
101
+ // A function directly inside a class is a method
102
+ const parentScope = scopeStack.at(-1);
103
+ if (parentScope?.isClass) return "method";
104
+ return "function";
105
+ }
106
+
107
+ /**
108
+ * Builds a human-readable signature from a function definition node.
109
+ * Includes parameter names with type annotations and return type.
110
+ */
111
+ function buildSignature(node: TreeSitterNode, name: string): string {
112
+ const paramsNode = node.childForFieldName("parameters");
113
+ const returnTypeNode = node.childForFieldName("return_type");
114
+
115
+ const params = paramsNode ? paramsNode.text : "()";
116
+ const returnType = returnTypeNode ? ` -> ${returnTypeNode.text}` : "";
117
+
118
+ return `${name}${params}${returnType}`;
119
+ }
120
+
121
+ export { extractPythonSymbols };
@@ -0,0 +1,77 @@
1
+ import type { TagKind } from "../types/graph.ts";
2
+ import { err, ok, type Result } from "../types/result.ts";
3
+
4
+ /** A parsed tag before it's associated with a specific node ID. */
5
+ type ParsedTag = {
6
+ readonly kind: TagKind;
7
+ readonly value: string;
8
+ };
9
+
10
+ const VALID_TAG_KINDS = new Set<string>(["flow", "boundary", "emits", "handles"]);
11
+
12
+ /** Matches @lattice:<kind> <value> at the START of a stripped comment line. */
13
+ const TAG_PATTERN = /^@lattice:(\w+)\s+(.+)/;
14
+
15
+ /** Valid tag name: lowercase letters, numbers, hyphens, dots. Must start with a letter or number. */
16
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9\-.]*$/;
17
+
18
+ /** Strips common comment prefixes from a line. */
19
+ function stripCommentPrefix(line: string): string {
20
+ const trimmed = line.trim();
21
+ // Try each prefix in order
22
+ if (trimmed.startsWith("//")) return trimmed.slice(2).trim();
23
+ if (trimmed.startsWith("#")) return trimmed.slice(1).trim();
24
+ if (trimmed.startsWith("--")) return trimmed.slice(2).trim();
25
+ if (trimmed.startsWith("/*"))
26
+ return trimmed
27
+ .slice(2)
28
+ .replace(/\*\/\s*$/, "")
29
+ .trim();
30
+ return trimmed;
31
+ }
32
+
33
+ /**
34
+ * Parses lattice tags from a comment block.
35
+ * Recognizes any comment style: #, //, /∗ ∗/, --.
36
+ * Returns parsed tags or an error for invalid tag name syntax.
37
+ *
38
+ * @param commentBlock - Raw comment text, possibly multiline
39
+ * @returns Parsed tags or an error message
40
+ */
41
+ function parseTags(commentBlock: string): Result<readonly ParsedTag[], string> {
42
+ if (!commentBlock.trim()) return ok([]);
43
+
44
+ const tags: ParsedTag[] = [];
45
+ const lines = commentBlock.split("\n");
46
+
47
+ for (const line of lines) {
48
+ const stripped = stripCommentPrefix(line);
49
+ const match = TAG_PATTERN.exec(stripped);
50
+ if (!match) continue;
51
+
52
+ const kindStr = match[1];
53
+ const valuesStr = match[2];
54
+ if (!kindStr || !valuesStr) continue;
55
+
56
+ if (!VALID_TAG_KINDS.has(kindStr)) continue;
57
+
58
+ const kind = kindStr as TagKind;
59
+ const rawValues = valuesStr.split(",").map((v) => v.trim());
60
+
61
+ for (const value of rawValues) {
62
+ if (!value) continue;
63
+
64
+ if (!NAME_PATTERN.test(value)) {
65
+ return err(
66
+ `Invalid tag name "${value}": must be kebab-case (lowercase letters, numbers, hyphens, dots)`,
67
+ );
68
+ }
69
+
70
+ tags.push({ kind, value });
71
+ }
72
+ }
73
+
74
+ return ok(tags);
75
+ }
76
+
77
+ export { type ParsedTag, parseTags };
@@ -0,0 +1,110 @@
1
+ import type { TreeSitterNode, TreeSitterTree } from "../parser.ts";
2
+
3
+ /** A raw call detected in the TypeScript AST. */
4
+ type RawCall = {
5
+ readonly sourceId: string;
6
+ readonly callee: string;
7
+ readonly line: number;
8
+ };
9
+
10
+ /**
11
+ * Extracts function calls from a TypeScript AST.
12
+ * Each call is scoped to its enclosing function, method, or arrow function.
13
+ *
14
+ * @param tree - Parsed tree-sitter tree
15
+ * @param filePath - Relative file path for source ID construction
16
+ * @returns Raw calls with caller ID and callee expression
17
+ */
18
+ function extractTypeScriptCalls(tree: TreeSitterTree, filePath: string): readonly RawCall[] {
19
+ const calls: RawCall[] = [];
20
+ visitForCalls(tree.rootNode, filePath, [], calls);
21
+ return calls;
22
+ }
23
+
24
+ type ScopeEntry = { readonly name: string };
25
+
26
+ /** Recursively walks the AST finding call_expression nodes inside functions. */
27
+ function visitForCalls(
28
+ node: TreeSitterNode,
29
+ filePath: string,
30
+ scopeStack: readonly ScopeEntry[],
31
+ results: RawCall[],
32
+ ): void {
33
+ // Enter new scope for function/method/class declarations
34
+ if (
35
+ node.type === "function_declaration" ||
36
+ node.type === "method_definition" ||
37
+ node.type === "class_declaration"
38
+ ) {
39
+ const nameNode = node.childForFieldName("name");
40
+ if (nameNode) {
41
+ const newScope = [...scopeStack, { name: nameNode.text }];
42
+ for (const child of node.children) {
43
+ visitForCalls(child, filePath, newScope, results);
44
+ }
45
+ return;
46
+ }
47
+ }
48
+
49
+ // Arrow function assigned to const
50
+ if (node.type === "variable_declarator") {
51
+ const nameNode = node.childForFieldName("name");
52
+ const valueNode = node.childForFieldName("value");
53
+ if (nameNode && valueNode?.type === "arrow_function") {
54
+ const newScope = [...scopeStack, { name: nameNode.text }];
55
+ for (const child of valueNode.children) {
56
+ visitForCalls(child, filePath, newScope, results);
57
+ }
58
+ return;
59
+ }
60
+ }
61
+
62
+ // Export statement — unwrap
63
+ if (node.type === "export_statement") {
64
+ for (const child of node.children) {
65
+ visitForCalls(child, filePath, scopeStack, results);
66
+ }
67
+ return;
68
+ }
69
+
70
+ // Detect call expressions inside a function scope
71
+ if (node.type === "call_expression" && scopeStack.length > 0) {
72
+ const callee = extractCalleeName(node);
73
+ if (callee) {
74
+ const sourceId = `${filePath}::${scopeStack.map((s) => s.name).join(".")}`;
75
+ results.push({ sourceId, callee, line: node.startPosition.row + 1 });
76
+ }
77
+ }
78
+
79
+ for (const child of node.children) {
80
+ visitForCalls(child, filePath, scopeStack, results);
81
+ }
82
+ }
83
+
84
+ /** Extracts the callee name from a call_expression node. */
85
+ function extractCalleeName(callNode: TreeSitterNode): string | undefined {
86
+ const funcNode = callNode.children[0];
87
+ if (!funcNode) return undefined;
88
+ if (funcNode.type === "identifier") return funcNode.text;
89
+ if (funcNode.type === "member_expression") return flattenMemberExpression(funcNode);
90
+ return undefined;
91
+ }
92
+
93
+ /** Flattens a.b.c member expression into "a.b.c". */
94
+ function flattenMemberExpression(node: TreeSitterNode): string {
95
+ const parts: string[] = [];
96
+ let current: TreeSitterNode | null = node;
97
+
98
+ while (current?.type === "member_expression") {
99
+ const prop = current.children.find((c) => c.type === "property_identifier");
100
+ if (prop) parts.unshift(prop.text);
101
+ current = current.children[0] ?? null;
102
+ }
103
+
104
+ if (current?.type === "identifier") parts.unshift(current.text);
105
+ if (current?.type === "this") parts.unshift("this");
106
+
107
+ return parts.join(".");
108
+ }
109
+
110
+ export { extractTypeScriptCalls, type RawCall };
@@ -0,0 +1,130 @@
1
+ import type { Edge, ExtractionResult, Tag } from "../../types/graph.ts";
2
+ import { isOk, unwrap } from "../../types/result.ts";
3
+ import type { Extractor } from "../extractor.ts";
4
+ import { createParser, type TreeSitterParser } from "../parser.ts";
5
+ import { parseTags } from "../tags.ts";
6
+ import { extractTypeScriptCalls } from "./calls.ts";
7
+ import { extractTypeScriptSymbols } from "./symbols.ts";
8
+
9
+ /**
10
+ * Creates a TypeScript extractor with an initialized tree-sitter parser.
11
+ * Must be called after initTreeSitter().
12
+ *
13
+ * @returns An Extractor configured for TypeScript source files
14
+ */
15
+ async function createTypeScriptExtractor(): Promise<Extractor> {
16
+ const parser = await createParser("typescript");
17
+
18
+ return {
19
+ language: "typescript",
20
+ fileExtensions: [".ts", ".tsx"],
21
+ extract: (filePath: string, source: string): Promise<ExtractionResult> =>
22
+ extractTypeScript(parser, filePath, source),
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Extracts symbols, calls, and tags from a TypeScript file.
28
+ *
29
+ * @param parser - Initialized tree-sitter parser for TypeScript
30
+ * @param filePath - Relative file path
31
+ * @param source - Raw source code
32
+ * @returns Complete extraction result
33
+ */
34
+ async function extractTypeScript(
35
+ parser: TreeSitterParser,
36
+ filePath: string,
37
+ source: string,
38
+ ): Promise<ExtractionResult> {
39
+ if (!source.trim()) {
40
+ return { nodes: [], edges: [], tags: [], unresolved: [] };
41
+ }
42
+
43
+ const tree = parser.parse(source);
44
+
45
+ // 1. Extract symbols
46
+ const nodes = [...extractTypeScriptSymbols(tree, filePath, source)];
47
+
48
+ // 2. Extract calls and convert to edges
49
+ const rawCalls = extractTypeScriptCalls(tree, filePath);
50
+ const edges: Edge[] = [];
51
+ const nodeIds = new Set(nodes.map((n) => n.id));
52
+
53
+ for (const call of rawCalls) {
54
+ const targetId = resolveCalleeInFile(call.callee, filePath, nodeIds);
55
+ if (targetId) {
56
+ edges.push({ sourceId: call.sourceId, targetId, kind: "calls", certainty: "certain" });
57
+ } else {
58
+ edges.push({
59
+ sourceId: call.sourceId,
60
+ targetId: call.callee,
61
+ kind: "calls",
62
+ certainty: "uncertain",
63
+ });
64
+ }
65
+ }
66
+
67
+ // 3. Parse lattice tags from comments above functions
68
+ const tags = extractTagsFromSource(source, nodes);
69
+
70
+ return { nodes, edges, tags, unresolved: [] };
71
+ }
72
+
73
+ /** Resolves a callee name to a node ID within the same file. */
74
+ function resolveCalleeInFile(
75
+ callee: string,
76
+ filePath: string,
77
+ nodeIds: Set<string>,
78
+ ): string | undefined {
79
+ const directId = `${filePath}::${callee}`;
80
+ if (nodeIds.has(directId)) return directId;
81
+
82
+ // this.method → try ClassName.method
83
+ if (callee.startsWith("this.")) {
84
+ const methodName = callee.slice(5);
85
+ for (const id of nodeIds) {
86
+ if (id.endsWith(`.${methodName}`) && id.startsWith(`${filePath}::`)) return id;
87
+ }
88
+ }
89
+
90
+ return undefined;
91
+ }
92
+
93
+ /** Extracts lattice tags from comment blocks above functions. */
94
+ function extractTagsFromSource(
95
+ source: string,
96
+ nodes: readonly { readonly id: string; readonly lineStart: number }[],
97
+ ): readonly Tag[] {
98
+ const lines = source.split("\n");
99
+ const tags: Tag[] = [];
100
+
101
+ for (const node of nodes) {
102
+ const commentLines: string[] = [];
103
+ let lineIdx = node.lineStart - 2; // 1-based to 0-based
104
+ while (lineIdx >= 0) {
105
+ const line = lines[lineIdx]?.trim();
106
+ if (!line) break;
107
+ if (line.startsWith("//") || line.startsWith("/*") || line.startsWith("*")) {
108
+ commentLines.unshift(line);
109
+ lineIdx--;
110
+ } else if (line.startsWith("@")) {
111
+ lineIdx--;
112
+ } else {
113
+ break;
114
+ }
115
+ }
116
+
117
+ if (commentLines.length === 0) continue;
118
+
119
+ const parseResult = parseTags(commentLines.join("\n"));
120
+ if (isOk(parseResult)) {
121
+ for (const parsed of unwrap(parseResult)) {
122
+ tags.push({ nodeId: node.id, kind: parsed.kind, value: parsed.value });
123
+ }
124
+ }
125
+ }
126
+
127
+ return tags;
128
+ }
129
+
130
+ export { createTypeScriptExtractor };