Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat: TypeScript parser for ingestion pipeline (.ts/.tsx)

riley0227947ce355f855
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
index 7d2b3ea8..13035545 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
@@ -28,6 +28,10 @@ object GraphPatchBuilder {
def edgeIdFor(src: String, dst: String, predicate: String): EdgeId =
EdgeId(UUID.nameUUIDFromBytes(s"$src:$dst:$predicate".getBytes("UTF-8")))
+ val extractor = if (filePath.endsWith(".py")) "tree-sitter-python/1.0"
+ else if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) "typescript-parser/1.0"
+ else "unknown-parser/1.0"
+
val nodeOps = parseResult.entities.map { e =>
PatchOp.UpsertNode(nodeIdFor(e.name), e.kind, e.name, e.attrs)
}
@@ -70,7 +74,7 @@ object GraphPatchBuilder {
patchId = PatchId(UUID.randomUUID()),
actor = "ix/ingestion",
timestamp = Instant.now(),
- source = PatchSource(filePath, sourceHash, "tree-sitter-python/1.0", SourceType.Code),
+ source = PatchSource(filePath, sourceHash, extractor, SourceType.Code),
baseRev = Rev(0L),
ops = allOps,
replaces = Vector.empty,
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala b/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
index d37f2854..366ef8e2 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
@@ -33,7 +33,10 @@ class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi, quer
.mkString
)
// Check for existing patch from same source+extractor
- existing <- queryApi.getPatchesBySource(filePath.toString, "tree-sitter-python/1.0")
+ extractor = if (filePath.toString.endsWith(".py")) "tree-sitter-python/1.0"
+ else if (filePath.toString.endsWith(".ts") || filePath.toString.endsWith(".tsx")) "typescript-parser/1.0"
+ else "unknown-parser/1.0"
+ existing <- queryApi.getPatchesBySource(filePath.toString, extractor)
prevPatch = existing.headOption
prevHash = prevPatch.flatMap(_.hcursor.downField("data").downField("source").get[String]("sourceHash").toOption)
// If hash unchanged, skip (idempotent)
@@ -88,8 +91,9 @@ class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi, quer
import scala.jdk.CollectionConverters._
val extensions = language match {
- case Some("python") => Set(".py")
- case _ => Set(".py") // default: all supported extensions
+ case Some("python") => Set(".py")
+ case Some("typescript") => Set(".ts", ".tsx")
+ case _ => Set(".py", ".ts", ".tsx") // all supported
}
if (Files.isRegularFile(path)) {
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/Parser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/Parser.scala
new file mode 100644
index 00000000..cec94982
--- /dev/null
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/Parser.scala
@@ -0,0 +1,9 @@
+package ix.memory.ingestion
+
+/**
+ * Common trait for language-specific source code parsers.
+ * Both TreeSitterPythonParser and TypeScriptParser implement this.
+ */
+trait Parser {
+ def parse(fileName: String, source: String): ParseResult
+}
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala b/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
index 228f28f4..385b8e10 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
@@ -1,16 +1,18 @@
package ix.memory.ingestion
-import ix.memory.ingestion.parsers.TreeSitterPythonParser
+import ix.memory.ingestion.parsers.{TreeSitterPythonParser, TypeScriptParser}
/**
* Routes file paths to the appropriate language parser.
- * Currently supports Python (.py) files only.
+ * Supports Python (.py), TypeScript (.ts), and TSX (.tsx) files.
*/
class ParserRouter {
private val pythonParser = new TreeSitterPythonParser()
+ private val tsParser = new TypeScriptParser()
- def parserFor(filePath: String): Option[TreeSitterPythonParser] = {
+ def parserFor(filePath: String): Option[Parser] = {
if (filePath.endsWith(".py")) Some(pythonParser)
+ else if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) Some(tsParser)
else None
}
}
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterPythonParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterPythonParser.scala
index bd9b51c7..80e32e39 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterPythonParser.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterPythonParser.scala
@@ -1,6 +1,6 @@
package ix.memory.ingestion.parsers
-import ix.memory.ingestion.{ParseResult, ParsedEntity, ParsedRelationship}
+import ix.memory.ingestion.{Parser, ParseResult, ParsedEntity, ParsedRelationship}
import ix.memory.model.NodeKind
import io.circe.Json
@@ -14,7 +14,7 @@ import scala.util.matching.Regex
* The regex fallback is sufficient for Phase 1 since the goal is the pipeline
* structure, not production-grade parsing.
*/
-class TreeSitterPythonParser {
+class TreeSitterPythonParser extends Parser {
/**
* Parse a Python source file and extract entities and relationships.
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
new file mode 100644
index 00000000..16752be1
--- /dev/null
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
@@ -0,0 +1,322 @@
+package ix.memory.ingestion.parsers
+
+import ix.memory.ingestion.{Parser, ParseResult, ParsedEntity, ParsedRelationship}
+import ix.memory.model.NodeKind
+import io.circe.Json
+
+import scala.util.matching.Regex
+
+/**
+ * TypeScript/TSX source parser that extracts structural entities and relationships.
+ *
+ * Uses regex-based extraction for .ts/.tsx files, following the same pattern as
+ * TreeSitterPythonParser. Uses brace counting for block boundaries instead of
+ * indentation.
+ */
+class TypeScriptParser extends Parser {
+
+ def parse(fileName: String, source: String): ParseResult = {
+ regexParse(fileName, source)
+ }
+
+ // ---------------------------------------------------------------------------
+ // Regex patterns
+ // ---------------------------------------------------------------------------
+
+ private val ClassPattern: Regex = """(?:export\s+)?(?:abstract\s+)?class\s+(\w+)""".r
+ private val FuncPattern: Regex = """(?:export\s+)?(?:async\s+)?function\s+(\w+)""".r
+ private val ArrowFuncPattern: Regex = """(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[a-zA-Z_]\w*)\s*(?::\s*[^=]+)?\s*=>""".r
+ private val ConstFuncPattern: Regex = """(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?function""".r
+ private val InterfacePattern: Regex = """(?:export\s+)?interface\s+(\w+)""".r
+ private val TypeAliasPattern: Regex = """(?:export\s+)?type\s+(\w+)\s*(?:<[^>]+>)?\s*=""".r
+ private val ImportPattern: Regex = """import\s+.*?from\s+['"]([^'"]+)['"]""".r
+ private val SideEffectImportPattern: Regex = """^import\s+['"]([^'"]+)['"]""".r
+ private val MethodPattern: Regex = """^\s+(?:async\s+)?(?:private\s+|public\s+|protected\s+|static\s+|readonly\s+)*(\w+)\s*(?:<[^>]+>)?\s*\(""".r
+ private val CallPattern: Regex = """(?:(?:this|self|await)\.)?\b(\w+)\s*\(""".r
+
+ // ---------------------------------------------------------------------------
+ // Builtins to filter from CALLS
+ // ---------------------------------------------------------------------------
+
+ private val TsBuiltins: Set[String] = Set(
+ "console", "parseInt", "parseFloat", "String", "Number", "Boolean",
+ "Array", "Object", "Promise", "JSON", "Math", "Date", "Error",
+ "RegExp", "Map", "Set", "WeakMap", "WeakSet", "Symbol",
+ "require", "setTimeout", "setInterval", "clearTimeout", "clearInterval",
+ "fetch", "Response", "Request", "URL", "Buffer", "process"
+ )
+
+ // ---------------------------------------------------------------------------
+ // Regex-based parser
+ // ---------------------------------------------------------------------------
+
+ private def regexParse(fileName: String, source: String): ParseResult = {
+ val lines = source.split("\n", -1)
+
+ // -- File entity --
+ val fileEntity = ParsedEntity(
+ name = fileName,
+ kind = NodeKind.File,
+ attrs = Map("language" -> Json.fromString("typescript")),
+ lineStart = 1,
+ lineEnd = lines.length
+ )
+
+ var entities = Vector(fileEntity)
+ var relationships = Vector.empty[ParsedRelationship]
+
+ // Track class ranges for containment checks
+ var classRanges = Vector.empty[(String, Int, Int)]
+
+ for ((line, idx) <- lines.zipWithIndex) {
+ val lineNum = idx + 1
+ val trimmed = line.trim
+
+ // Skip comment lines
+ if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*")) {
+ // no-op
+ } else {
+
+ // Check for class definition
+ ClassPattern.findFirstMatchIn(line).foreach { m =>
+ val className = m.group(1)
+ val classEnd = findBraceBlockEnd(lines, idx)
+ entities = entities :+ ParsedEntity(
+ name = className,
+ kind = NodeKind.Class,
+ attrs = Map("language" -> Json.fromString("typescript")),
+ lineStart = lineNum,
+ lineEnd = classEnd
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, className, "DEFINES")
+ classRanges = classRanges :+ (className, lineNum, classEnd)
+
+ // Extract methods inside this class
+ val methods = extractMethods(lines, idx, classEnd, className)
+ entities = entities ++ methods._1
+ relationships = relationships ++ methods._2
+ }
+
+ // Check for function definition (but not if it's a method inside a class)
+ if (!isInsideClass(lineNum, classRanges)) {
+ FuncPattern.findFirstMatchIn(line).foreach { m =>
+ val funcName = m.group(1)
+ val funcEnd = findBraceBlockEnd(lines, idx)
+ entities = entities :+ ParsedEntity(
+ name = funcName,
+ kind = NodeKind.Function,
+ attrs = Map("language" -> Json.fromString("typescript")),
+ lineStart = lineNum,
+ lineEnd = funcEnd
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, funcName, "DEFINES")
+
+ // Extract calls within this function
+ val callRels = extractCalls(lines, idx, funcEnd, funcName)
+ relationships = relationships ++ callRels
+ }
+
+ // Check for arrow function / const function
+ val arrowMatch = ArrowFuncPattern.findFirstMatchIn(line)
+ val constFuncMatch = ConstFuncPattern.findFirstMatchIn(line)
+ val funcMatch = arrowMatch.orElse(constFuncMatch)
+ funcMatch.foreach { m =>
+ val funcName = m.group(1)
+ // Avoid duplicates if already captured by FuncPattern
+ if (!entities.exists(e => e.name == funcName && e.kind == NodeKind.Function)) {
+ val funcEnd = findBraceBlockEnd(lines, idx)
+ entities = entities :+ ParsedEntity(
+ name = funcName,
+ kind = NodeKind.Function,
+ attrs = Map("language" -> Json.fromString("typescript")),
+ lineStart = lineNum,
+ lineEnd = funcEnd
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, funcName, "DEFINES")
+
+ val callRels = extractCalls(lines, idx, funcEnd, funcName)
+ relationships = relationships ++ callRels
+ }
+ }
+ }
+
+ // Check for interface definition
+ InterfacePattern.findFirstMatchIn(line).foreach { m =>
+ val ifaceName = m.group(1)
+ // Don't match if this is already matched as a class pattern
+ if (!entities.exists(e => e.name == ifaceName && e.kind == NodeKind.Class && !e.attrs.contains("ts_kind"))) {
+ val ifaceEnd = findBraceBlockEnd(lines, idx)
+ entities = entities :+ ParsedEntity(
+ name = ifaceName,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("typescript"),
+ "ts_kind" -> Json.fromString("interface")
+ ),
+ lineStart = lineNum,
+ lineEnd = ifaceEnd
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, ifaceName, "DEFINES")
+ }
+ }
+
+ // Check for type alias
+ TypeAliasPattern.findFirstMatchIn(line).foreach { m =>
+ val typeName = m.group(1)
+ // Avoid matching 'import type' lines
+ if (!trimmed.startsWith("import")) {
+ entities = entities :+ ParsedEntity(
+ name = typeName,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("typescript"),
+ "ts_kind" -> Json.fromString("type_alias")
+ ),
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, typeName, "DEFINES")
+ }
+ }
+
+ // Check for imports
+ ImportPattern.findFirstMatchIn(line).foreach { m =>
+ val moduleName = m.group(1)
+ if (!entities.exists(e => e.name == moduleName && e.kind == NodeKind.Module)) {
+ entities = entities :+ ParsedEntity(
+ name = moduleName,
+ kind = NodeKind.Module,
+ attrs = Map.empty,
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ }
+ relationships = relationships :+ ParsedRelationship(fileName, moduleName, "IMPORTS")
+ }
+
+ SideEffectImportPattern.findFirstMatchIn(line).foreach { m =>
+ val moduleName = m.group(1)
+ // Only add if not already captured by the regular ImportPattern
+ if (!relationships.exists(r => r.dstName == moduleName && r.predicate == "IMPORTS")) {
+ if (!entities.exists(e => e.name == moduleName && e.kind == NodeKind.Module)) {
+ entities = entities :+ ParsedEntity(
+ name = moduleName,
+ kind = NodeKind.Module,
+ attrs = Map.empty,
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ }
+ relationships = relationships :+ ParsedRelationship(fileName, moduleName, "IMPORTS")
+ }
+ }
+
+ } // end else (non-comment line)
+ }
+
+ ParseResult(entities, relationships)
+ }
+
+ // ---------------------------------------------------------------------------
+ // Block boundary detection using brace counting
+ // ---------------------------------------------------------------------------
+
+ private def findBraceBlockEnd(lines: Array[String], startIdx: Int): Int = {
+ var braceCount = 0
+ var foundOpen = false
+ var i = startIdx
+ while (i < lines.length) {
+ for (ch <- lines(i)) {
+ if (ch == '{') { braceCount += 1; foundOpen = true }
+ else if (ch == '}') { braceCount -= 1 }
+ }
+ if (foundOpen && braceCount <= 0) return i + 1
+ i += 1
+ }
+ lines.length
+ }
+
+ // ---------------------------------------------------------------------------
+ // Helper: check if a line is inside a class range
+ // ---------------------------------------------------------------------------
+
+ private def isInsideClass(lineNum: Int, classRanges: Vector[(String, Int, Int)]): Boolean = {
+ classRanges.exists { case (_, start, end) =>
+ lineNum > start && lineNum <= end
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Extract methods inside a class block
+ // ---------------------------------------------------------------------------
+
+ private def extractMethods(
+ lines: Array[String],
+ classStartIdx: Int,
+ classEndLine: Int,
+ className: String
+ ): (Vector[ParsedEntity], Vector[ParsedRelationship]) = {
+ var methodEntities = Vector.empty[ParsedEntity]
+ var methodRels = Vector.empty[ParsedRelationship]
+
+ var i = classStartIdx + 1
+ while (i < lines.length && (i + 1) <= classEndLine) {
+ val line = lines(i)
+ MethodPattern.findFirstMatchIn(line).foreach { m =>
+ val methodName = m.group(1)
+ // Skip constructor and common keywords that look like methods
+ if (methodName != "constructor" && methodName != "if" && methodName != "for" &&
+ methodName != "while" && methodName != "switch" && methodName != "return" &&
+ methodName != "new" && methodName != "throw" && methodName != "catch") {
+ val methodEnd = findBraceBlockEnd(lines, i)
+ methodEntities = methodEntities :+ ParsedEntity(
+ name = methodName,
+ kind = NodeKind.Function,
+ attrs = Map("language" -> Json.fromString("typescript")),
+ lineStart = i + 1,
+ lineEnd = methodEnd
+ )
+ methodRels = methodRels :+ ParsedRelationship(className, methodName, "DEFINES")
+
+ // Extract calls within this method
+ val callRels = extractCalls(lines, i, methodEnd, methodName)
+ methodRels = methodRels ++ callRels
+ }
+ }
+ i += 1
+ }
+
+ (methodEntities, methodRels)
+ }
+
+ // ---------------------------------------------------------------------------
+ // Extract CALLS relationships from a function/method body
+ // ---------------------------------------------------------------------------
+
+ private def extractCalls(
+ lines: Array[String],
+ funcStartIdx: Int,
+ funcEndLine: Int,
+ callerName: String
+ ): Vector[ParsedRelationship] = {
+ var calls = Vector.empty[ParsedRelationship]
+ val seen = scala.collection.mutable.Set.empty[String]
+ var i = funcStartIdx + 1
+
+ while (i < lines.length && (i + 1) <= funcEndLine) {
+ val line = lines(i)
+ CallPattern.findAllMatchIn(line).foreach { m =>
+ val callee = m.group(1)
+ if (callee != callerName && !TsBuiltins.contains(callee) && !seen.contains(callee) &&
+ callee != "if" && callee != "for" && callee != "while" && callee != "switch" &&
+ callee != "return" && callee != "new" && callee != "throw" && callee != "catch" &&
+ callee != "constructor") {
+ seen += callee
+ calls = calls :+ ParsedRelationship(callerName, callee, "CALLS")
+ }
+ }
+ i += 1
+ }
+ calls
+ }
+}
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
new file mode 100644
index 00000000..9065511a
--- /dev/null
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
@@ -0,0 +1,172 @@
+package ix.memory.ingestion.parsers
+
+import org.scalatest.flatspec.AnyFlatSpec
+import org.scalatest.matchers.should.Matchers
+import ix.memory.model.NodeKind
+
+class TypeScriptParserSpec extends AnyFlatSpec with Matchers {
+
+ val parser = new TypeScriptParser()
+
+ // Test 1: Extract file entity
+ "TypeScriptParser" should "create a File entity for the source file" in {
+ val result = parser.parse("app.ts", "const x = 1;")
+ result.entities.exists(e => e.name == "app.ts" && e.kind == NodeKind.File) shouldBe true
+ }
+
+ // Test 2: Extract class
+ it should "extract class definitions" in {
+ val source = """
+ |export class UserService {
+ | private db: Database;
+ |
+ | getUser(id: string): User {
+ | return this.db.find(id);
+ | }
+ |}
+ """.stripMargin
+ val result = parser.parse("service.ts", source)
+ result.entities.exists(e => e.name == "UserService" && e.kind == NodeKind.Class) shouldBe true
+ // File DEFINES UserService
+ result.relationships.exists(r => r.srcName == "service.ts" && r.dstName == "UserService" && r.predicate == "DEFINES") shouldBe true
+ }
+
+ // Test 3: Extract functions
+ it should "extract function definitions" in {
+ val source = """
+ |export function calculateTotal(items: Item[]): number {
+ | return items.reduce((sum, i) => sum + i.price, 0);
+ |}
+ |
+ |async function fetchData(url: string): Promise<Response> {
+ | return fetch(url);
+ |}
+ """.stripMargin
+ val result = parser.parse("utils.ts", source)
+ result.entities.exists(e => e.name == "calculateTotal" && e.kind == NodeKind.Function) shouldBe true
+ result.entities.exists(e => e.name == "fetchData" && e.kind == NodeKind.Function) shouldBe true
+ }
+
+ // Test 4: Extract arrow functions
+ it should "extract arrow function declarations" in {
+ val source = """
+ |export const handler = async (req: Request): Promise<Response> => {
+ | return new Response("ok");
+ |};
+ """.stripMargin
+ val result = parser.parse("handler.ts", source)
+ result.entities.exists(e => e.name == "handler" && e.kind == NodeKind.Function) shouldBe true
+ }
+
+ // Test 5: Extract interfaces
+ it should "extract interface definitions" in {
+ val source = """
+ |export interface UserProps {
+ | name: string;
+ | age: number;
+ |}
+ """.stripMargin
+ val result = parser.parse("types.ts", source)
+ val iface = result.entities.find(e => e.name == "UserProps")
+ iface shouldBe defined
+ iface.get.kind shouldBe NodeKind.Class // using Class for interfaces
+ iface.get.attrs.get("ts_kind").map(_.noSpaces) shouldBe Some("\"interface\"")
+ }
+
+ // Test 6: Extract type aliases
+ it should "extract type alias definitions" in {
+ val source = """
+ |export type UserId = string;
+ |type Config<T> = Partial<T> & Required<BaseConfig>;
+ """.stripMargin
+ val result = parser.parse("types.ts", source)
+ result.entities.exists(e => e.name == "UserId") shouldBe true
+ result.entities.exists(e => e.name == "Config") shouldBe true
+ }
+
+ // Test 7: Extract imports
+ it should "extract import relationships" in {
+ val source = """
+ |import { Router } from 'express';
+ |import * as path from 'node:path';
+ |import './side-effect';
+ """.stripMargin
+ val result = parser.parse("app.ts", source)
+ result.relationships.exists(r => r.dstName == "express" && r.predicate == "IMPORTS") shouldBe true
+ result.relationships.exists(r => r.dstName == "node:path" && r.predicate == "IMPORTS") shouldBe true
+ }
+
+ // Test 8: Extract method-in-class
+ it should "detect methods inside classes" in {
+ val source = """
+ |class Api {
+ | async fetch(url: string) {
+ | return this.http.get(url);
+ | }
+ |
+ | private parse(data: string) {
+ | return data.split(',');
+ | }
+ |}
+ """.stripMargin
+ val result = parser.parse("api.ts", source)
+ // Api DEFINES fetch
+ result.relationships.exists(r => r.srcName == "Api" && r.dstName == "fetch" && r.predicate == "DEFINES") shouldBe true
+ result.relationships.exists(r => r.srcName == "Api" && r.dstName == "parse" && r.predicate == "DEFINES") shouldBe true
+ }
+
+ // Test 9: Extract function calls
+ it should "extract function call relationships" in {
+ val source = """
+ |function main() {
+ | const data = loadConfig();
+ | processData(data);
+ |}
+ """.stripMargin
+ val result = parser.parse("main.ts", source)
+ result.relationships.exists(r => r.srcName == "main" && r.dstName == "loadConfig" && r.predicate == "CALLS") shouldBe true
+ result.relationships.exists(r => r.srcName == "main" && r.dstName == "processData" && r.predicate == "CALLS") shouldBe true
+ }
+
+ // Test 10: Filter builtins from calls
+ it should "filter TypeScript builtins from CALLS" in {
+ val source = """
+ |function test() {
+ | console.log("hi");
+ | const n = parseInt("42");
+ | myFunction();
+ |}
+ """.stripMargin
+ val result = parser.parse("test.ts", source)
+ result.relationships.exists(r => r.predicate == "CALLS" && r.dstName == "console") shouldBe false
+ result.relationships.exists(r => r.predicate == "CALLS" && r.dstName == "parseInt") shouldBe false
+ result.relationships.exists(r => r.predicate == "CALLS" && r.dstName == "myFunction") shouldBe true
+ }
+
+ // Test 11: Handles .tsx files
+ it should "parse .tsx files with JSX" in {
+ val source = """
+ |import React from 'react';
+ |
+ |interface Props {
+ | name: string;
+ |}
+ |
+ |export function Greeting({ name }: Props) {
+ | return <div>Hello {name}</div>;
+ |}
+ """.stripMargin
+ val result = parser.parse("Greeting.tsx", source)
+ result.entities.exists(e => e.name == "Greeting" && e.kind == NodeKind.Function) shouldBe true
+ result.entities.exists(e => e.name == "Props") shouldBe true
+ result.relationships.exists(r => r.dstName == "react" && r.predicate == "IMPORTS") shouldBe true
+ }
+
+ // Test 12: Language attrs set to "typescript"
+ it should "set language attr to typescript" in {
+ val result = parser.parse("app.ts", "const x = 1;")
+ val fileEntity = result.entities.find(_.name == "app.ts")
+ fileEntity shouldBe defined
+ fileEntity.get.attrs.get("language").map(_.noSpaces) shouldBe Some("\"typescript\"")
+ }
+}