Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: TS import normalization, file-level CALLS fix, Scala nested CONTAINS and REFERENCES

Tanner Kocherbe99e1111a7e
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 885f40cc..ea66a6bb 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
@@ -59,6 +59,8 @@ class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi, quer
commit <- writeApi.commitPatch(patch)
// Resolve cross-file import edges after main patch is committed
_ <- resolveImportEdges(filePath, result, hash).attempt.void
+ // Resolve named import symbols to their actual source entities
+ _ <- resolveNamedImports(filePath, result, hash).attempt.void
} yield commit
}
@@ -144,16 +146,82 @@ class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi, quer
}
}
+ private def resolveNamedImports(
+ filePath: Path,
+ parseResult: ParseResult,
+ sourceHash: Option[String]
+ ): IO[Unit] = {
+ val namedImports = parseResult.relationships.filter { rel =>
+ rel.predicate == "IMPORTS" && !rel.dstName.contains("/") && !rel.dstName.contains(".")
+ }
+ namedImports.traverse_ { rel =>
+ queryApi.searchNodes(rel.dstName, limit = 5, nameOnly = true).flatMap { nodes =>
+ val external = nodes.filter { n =>
+ n.name == rel.dstName &&
+ n.provenance.sourceUri != filePath.toString
+ }
+ external.headOption match {
+ case Some(target) =>
+ val srcId = NodeId(UUID.nameUUIDFromBytes(
+ s"${filePath}:${filePath.getFileName}".getBytes("UTF-8")))
+ val edgeId = EdgeId(UUID.nameUUIDFromBytes(
+ s"${srcId.value}:${target.id.value}:IMPORTS".getBytes("UTF-8")))
+ val patch = GraphPatch(
+ patchId = PatchId(UUID.randomUUID()),
+ actor = "ix/cross-file",
+ timestamp = Instant.now(),
+ source = PatchSource(filePath.toString, sourceHash,
+ "cross-file-resolver/1.0", SourceType.Code),
+ baseRev = Rev(0L),
+ ops = Vector(PatchOp.UpsertEdge(
+ edgeId, srcId, target.id, EdgePredicate("IMPORTS"), Map.empty)),
+ replaces = Vector.empty,
+ intent = Some(s"Named import: ${filePath.getFileName} -> ${rel.dstName}")
+ )
+ writeApi.commitPatch(patch).void
+ case None => IO.unit
+ }
+ }
+ }
+ }
+
private def resolveRelativePath(from: Path, importTarget: String): Option[Path] = {
if (importTarget.startsWith("./") || importTarget.startsWith("../")) {
val base = from.getParent
if (base == null) return None
- val extensions = List("", ".ts", ".tsx", ".scala", ".py", ".js")
- extensions.collectFirst {
+
+ // 1. Try the import target as-is and with source extensions appended
+ val directExtensions = List("", ".ts", ".tsx", ".scala", ".py", ".js")
+ val directMatch = directExtensions.collectFirst {
case ext =>
val candidate = base.resolve(importTarget + ext).normalize()
if (Files.exists(candidate)) candidate else null
}.flatMap(Option(_))
+ if (directMatch.isDefined) return directMatch
+
+ // 2. Strip compiled extensions (.js/.mjs/.cjs) and try source extensions
+ val strippable = List(".js", ".mjs", ".cjs")
+ val stripped = strippable.collectFirst {
+ case ext if importTarget.endsWith(ext) =>
+ importTarget.stripSuffix(ext)
+ }
+ val strippedMatch = stripped.flatMap { baseName =>
+ val sourceExtensions = List(".ts", ".tsx")
+ sourceExtensions.collectFirst {
+ case ext =>
+ val candidate = base.resolve(baseName + ext).normalize()
+ if (Files.exists(candidate)) candidate else null
+ }.flatMap(Option(_))
+ }
+ if (strippedMatch.isDefined) return strippedMatch
+
+ // 3. Try directory index files (e.g., ./utils -> ./utils/index.ts)
+ val indexExtensions = List("index.ts", "index.tsx", "index.js")
+ indexExtensions.collectFirst {
+ case idx =>
+ val candidate = base.resolve(importTarget).resolve(idx).normalize()
+ if (Files.exists(candidate)) candidate else null
+ }.flatMap(Option(_))
} else None
}
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala
index e5ec8221..deac202c 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala
@@ -22,6 +22,15 @@ class ScalaParser extends Parser {
private val DefPattern: Regex = """^\s*(?:override\s+)?(?:private(?:\[\w+\])?\s+|protected(?:\[\w+\])?\s+)?(?:final\s+)?def\s+(\w+)""".r
private val ImportPattern: Regex = """^\s*import\s+(.+)$""".r
private val CallPattern: Regex = """(?:(?:this|super)\.)?\b(\w+)\s*(?:\[.*?\])?\s*\(""".r
+ private val ExtendsPattern: Regex = """extends\s+(\w+)""".r
+ private val TypeRefPattern: Regex = """\b([A-Z]\w+)""".r
+ private val QualifiedRefPattern: Regex = """\b([A-Z]\w+)\.(\w+)""".r
+
+ private val ScalaBuiltinTypes: Set[String] = Set(
+ "String", "Int", "Long", "Double", "Float", "Boolean", "Unit", "Any", "AnyRef", "AnyVal",
+ "Nothing", "Null", "Option", "List", "Map", "Set", "Vector", "Seq", "Array", "Future",
+ "IO", "Either", "Try", "Some", "None", "Right", "Left", "Success", "Failure"
+ )
private val ScalaBuiltins: Set[String] = Set(
"println", "print", "require", "assert", "assume",
@@ -82,8 +91,13 @@ class ScalaParser extends Parser {
lineEnd = endLine,
contentFingerprint = Some(fp)
)
- relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ val enclosingType = typeRanges.find { case (_, start, end) => lineNum > start && lineNum <= end }
+ val containsSrc = enclosingType.map(_._1).getOrElse(fileName)
+ relationships = relationships :+ ParsedRelationship(containsSrc, name, "CONTAINS")
typeRanges = typeRanges :+ (name, lineNum, endLine)
+ ExtendsPattern.findFirstMatchIn(line).foreach { em =>
+ relationships = relationships :+ ParsedRelationship(name, em.group(1), "EXTENDS")
+ }
true
case None =>
@@ -103,8 +117,13 @@ class ScalaParser extends Parser {
lineEnd = endLine,
contentFingerprint = Some(fp)
)
- relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ val enclosingType = typeRanges.find { case (_, start, end) => lineNum > start && lineNum <= end }
+ val containsSrc = enclosingType.map(_._1).getOrElse(fileName)
+ relationships = relationships :+ ParsedRelationship(containsSrc, name, "CONTAINS")
typeRanges = typeRanges :+ (name, lineNum, endLine)
+ ExtendsPattern.findFirstMatchIn(line).foreach { em =>
+ relationships = relationships :+ ParsedRelationship(name, em.group(1), "EXTENDS")
+ }
true
case None =>
@@ -124,8 +143,13 @@ class ScalaParser extends Parser {
lineEnd = endLine,
contentFingerprint = Some(fp)
)
- relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ val enclosingType = typeRanges.find { case (_, start, end) => lineNum > start && lineNum <= end }
+ val containsSrc = enclosingType.map(_._1).getOrElse(fileName)
+ relationships = relationships :+ ParsedRelationship(containsSrc, name, "CONTAINS")
typeRanges = typeRanges :+ (name, lineNum, endLine)
+ ExtendsPattern.findFirstMatchIn(line).foreach { em =>
+ relationships = relationships :+ ParsedRelationship(name, em.group(1), "EXTENDS")
+ }
true
case None =>
@@ -145,8 +169,13 @@ class ScalaParser extends Parser {
lineEnd = endLine,
contentFingerprint = Some(fp)
)
- relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ val enclosingType = typeRanges.find { case (_, start, end) => lineNum > start && lineNum <= end }
+ val containsSrc = enclosingType.map(_._1).getOrElse(fileName)
+ relationships = relationships :+ ParsedRelationship(containsSrc, name, "CONTAINS")
typeRanges = typeRanges :+ (name, lineNum, endLine)
+ ExtendsPattern.findFirstMatchIn(line).foreach { em =>
+ relationships = relationships :+ ParsedRelationship(name, em.group(1), "EXTENDS")
+ }
true
case None => false
}
@@ -192,9 +221,18 @@ class ScalaParser extends Parser {
relationships = relationships :+ ParsedRelationship(edgeSrc, funcName, edgePredicate)
- // Extract CALLS from method/function body
+ // Extract CALLS and REFERENCES from method/function body
val callsInFunc = extractCalls(lines, idx, endLine, funcName)
relationships = relationships ++ callsInFunc
+
+ // Extract REFERENCES from method signature type annotations
+ val enclosingTypeName = enclosing.map(_._1).getOrElse("")
+ val sigRefs = TypeRefPattern.findAllMatchIn(signature).map(_.group(1)).toSet
+ for (ref <- sigRefs) {
+ if (!ScalaBuiltinTypes.contains(ref) && ref != funcName && ref != enclosingTypeName && ref != fileName) {
+ relationships = relationships :+ ParsedRelationship(funcName, ref, "REFERENCES")
+ }
+ }
}
}
@@ -262,10 +300,11 @@ class ScalaParser extends Parser {
if (foundOpen) Some(lines.length) else None
}
- /** Extract CALLS relationships from a method/function body. */
+ /** Extract CALLS and qualified REFERENCES relationships from a method/function body. */
private def extractCalls(lines: Array[String], startIdx: Int, endIdx: Int, callerName: String): Vector[ParsedRelationship] = {
var calls = Vector.empty[ParsedRelationship]
val seen = scala.collection.mutable.Set.empty[String]
+ val refSeen = scala.collection.mutable.Set.empty[String]
for (i <- (startIdx + 1) until endIdx.min(lines.length)) {
val line = lines(i).trim
if (!line.startsWith("//") && !line.startsWith("*")) {
@@ -277,6 +316,15 @@ class ScalaParser extends Parser {
calls = calls :+ ParsedRelationship(callerName, callee, "CALLS")
}
}
+ // Extract qualified REFERENCES (e.g., NodeKind.File, SourceType.Code)
+ QualifiedRefPattern.findAllMatchIn(line).foreach { m =>
+ val qualifier = m.group(1)
+ if (!ScalaBuiltinTypes.contains(qualifier) && !ScalaBuiltins.contains(qualifier) &&
+ !refSeen.contains(qualifier) && qualifier != callerName) {
+ refSeen += qualifier
+ calls = calls :+ ParsedRelationship(callerName, qualifier, "REFERENCES")
+ }
+ }
}
}
calls
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
index 9535a061..fc2670a2 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
@@ -52,10 +52,11 @@ class TypeScriptParser extends Parser {
val classEnd = findBraceBlockEnd(lines, idx)
val bodyText = lines.slice(idx, classEnd).mkString("\n")
val fp = Fingerprint.compute(trimmed.replaceAll("""\s*\{\s*$""", "").take(120), bodyText)
+ val exported = trimmed.startsWith("export ") || trimmed.startsWith("export{")
entities = entities :+ ParsedEntity(
name = className,
kind = NodeKind.Class,
- attrs = Map("language" -> Json.fromString("typescript")),
+ attrs = Map("language" -> Json.fromString("typescript"), "exported" -> Json.fromBoolean(exported)),
lineStart = lineNum,
lineEnd = classEnd,
contentFingerprint = Some(fp)
@@ -77,6 +78,7 @@ class TypeScriptParser extends Parser {
val summary = line.trim.take(120)
val bodyText = lines.slice(idx, funcEnd).mkString("\n")
val fp = Fingerprint.compute(summary, bodyText)
+ val exported = trimmed.startsWith("export ") || trimmed.startsWith("export{")
entities = entities :+ ParsedEntity(
name = funcName,
kind = NodeKind.Function,
@@ -84,7 +86,8 @@ class TypeScriptParser extends Parser {
"language" -> Json.fromString("typescript"),
"summary" -> Json.fromString(summary),
"signature" -> Json.fromString(summary),
- "visibility" -> Json.fromString("public")
+ "visibility" -> Json.fromString("public"),
+ "exported" -> Json.fromBoolean(exported)
),
lineStart = lineNum,
lineEnd = funcEnd,
@@ -109,6 +112,7 @@ class TypeScriptParser extends Parser {
val summary = line.trim.take(120)
val bodyText = lines.slice(idx, funcEnd).mkString("\n")
val fp = Fingerprint.compute(summary, bodyText)
+ val exported = trimmed.startsWith("export ") || trimmed.startsWith("export{")
entities = entities :+ ParsedEntity(
name = funcName,
kind = NodeKind.Function,
@@ -116,7 +120,8 @@ class TypeScriptParser extends Parser {
"language" -> Json.fromString("typescript"),
"summary" -> Json.fromString(summary),
"signature" -> Json.fromString(summary),
- "visibility" -> Json.fromString("public")
+ "visibility" -> Json.fromString("public"),
+ "exported" -> Json.fromBoolean(exported)
),
lineStart = lineNum,
lineEnd = funcEnd,
@@ -145,6 +150,17 @@ class TypeScriptParser extends Parser {
relationships = relationships :+ ParsedRelationship(fileName, moduleName, "IMPORTS")
}
+ // Extract named import bindings: import { foo, bar } from "mod"
+ NamedImportPattern.findFirstMatchIn(line).foreach { m =>
+ val names = m.group(1).split(",").map(_.trim).filter(_.nonEmpty)
+ for (rawName <- names) {
+ val symbolName = if (rawName.contains(" as ")) rawName.split("\\s+as\\s+").last.trim else rawName
+ if (symbolName.nonEmpty && !relationships.exists(r => r.srcName == fileName && r.dstName == symbolName && r.predicate == "IMPORTS")) {
+ relationships = relationships :+ ParsedRelationship(fileName, symbolName, "IMPORTS")
+ }
+ }
+ }
+
SideEffectImportPattern.findFirstMatchIn(line).foreach { m =>
val moduleName = m.group(1)
if (!relationships.exists(r => r.dstName == moduleName && r.predicate == "IMPORTS")) {
@@ -168,12 +184,14 @@ class TypeScriptParser extends Parser {
val ifaceEnd = findBraceBlockEnd(lines, idx)
val bodyText = lines.slice(idx, ifaceEnd).mkString("\n")
val fp = Fingerprint.compute(trimmed.replaceAll("""\s*\{\s*$""", "").take(120), bodyText)
+ val exported = trimmed.startsWith("export ") || trimmed.startsWith("export{")
entities = entities :+ ParsedEntity(
name = ifaceName,
kind = NodeKind.Interface,
attrs = Map(
"language" -> Json.fromString("typescript"),
- "ts_kind" -> Json.fromString("interface")
+ "ts_kind" -> Json.fromString("interface"),
+ "exported" -> Json.fromBoolean(exported)
),
lineStart = lineNum,
lineEnd = ifaceEnd,
@@ -187,13 +205,15 @@ class TypeScriptParser extends Parser {
TypeAliasPattern.findFirstMatchIn(line).foreach { m =>
val typeName = m.group(1)
if (!trimmed.startsWith("import")) {
+ val exported = trimmed.startsWith("export ") || trimmed.startsWith("export{")
val fp = Fingerprint.compute(trimmed.take(120), trimmed)
entities = entities :+ ParsedEntity(
name = typeName,
kind = NodeKind.Class,
attrs = Map(
"language" -> Json.fromString("typescript"),
- "ts_kind" -> Json.fromString("type_alias")
+ "ts_kind" -> Json.fromString("type_alias"),
+ "exported" -> Json.fromBoolean(exported)
),
lineStart = lineNum,
lineEnd = lineNum,
@@ -206,6 +226,27 @@ class TypeScriptParser extends Parser {
} // end else (non-comment)
}
+ // Extract file-level calls from code outside named functions/methods/classes
+ val coveredRanges: Vector[(Int, Int)] = entities
+ .filter(e => e.kind == NodeKind.Function || e.kind == NodeKind.Method || e.kind == NodeKind.Class)
+ .map(e => (e.lineStart, e.lineEnd))
+
+ val fileCallsSeen = scala.collection.mutable.Set.empty[String]
+ for ((line, idx) <- lines.zipWithIndex) {
+ val lineNum = idx + 1
+ val inNamedBody = coveredRanges.exists { case (s, e) => lineNum >= s && lineNum <= e }
+ if (!inNamedBody && !line.trim.startsWith("//") && !line.trim.startsWith("*")) {
+ CallPattern.findAllMatchIn(line).foreach { m =>
+ val callee = m.group(1)
+ if (!TypeScriptBuiltins.contains(callee) && !TypeScriptKeywords.contains(callee)
+ && !fileCallsSeen.contains(callee) && callee != fileName) {
+ fileCallsSeen += callee
+ relationships = relationships :+ ParsedRelationship(fileName, callee, "CALLS")
+ }
+ }
+ }
+ }
+
ParseResult(entities, relationships)
}
@@ -219,6 +260,7 @@ class TypeScriptParser extends Parser {
private val ConstFuncPattern: Regex = """(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?function""".r
private val MethodPattern: Regex = """^\s+(?:async\s+)?(?:private\s+|public\s+|protected\s+|static\s+|readonly\s+)*(\w+)\s*(?:<[^>]+>)?\s*\(""".r
private val ImportPattern: Regex = """import\s+.*?from\s+['"]([^'"]+)['"]""".r
+ private val NamedImportPattern: Regex = """import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]""".r
private val SideEffectImportPattern: Regex = """^import\s+['"]([^'"]+)['"]""".r
private val InterfacePattern: Regex = """(?:export\s+)?interface\s+(\w+)""".r
private val TypeAliasPattern: Regex = """(?:export\s+)?type\s+(\w+)\s*(?:<[^>]+>)?\s*=""".r
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
index 3e41edc0..8b1c0cfa 100644
--- a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
@@ -2,6 +2,7 @@ package ix.memory.ingestion.parsers
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
+import ix.memory.ingestion.ParsedRelationship
import ix.memory.model.NodeKind
import io.circe.Json
@@ -187,6 +188,102 @@ class ScalaParserSpec extends AnyFlatSpec with Matchers {
obj.lineEnd should be > obj.lineStart
}
+ // --- EXTENDS edge tests ---
+
+ it should "extract EXTENDS from class declaration" in {
+ val source = """class MyService extends BaseService {
+ | def run(): Unit = {}
+ |}""".stripMargin
+ val result = parser.parse("Service.scala", source)
+ val extends_ = result.relationships.filter(_.predicate == "EXTENDS")
+ extends_ should have length 1
+ extends_.head.srcName shouldBe "MyService"
+ extends_.head.dstName shouldBe "BaseService"
+ }
+
+ it should "extract EXTENDS from case class" in {
+ val source = """sealed trait Event
+ |case class Created(id: String) extends Event""".stripMargin
+ val result = parser.parse("Event.scala", source)
+ val extends_ = result.relationships.filter(_.predicate == "EXTENDS")
+ extends_.map(_.srcName) should contain ("Created")
+ extends_.filter(_.srcName == "Created").head.dstName shouldBe "Event"
+ }
+
+ it should "extract EXTENDS from case object" in {
+ val source = """sealed trait Color
+ |case object Red extends Color
+ |case object Blue extends Color""".stripMargin
+ val result = parser.parse("Color.scala", source)
+ val extends_ = result.relationships.filter(_.predicate == "EXTENDS")
+ extends_ should have length 2
+ extends_.map(_.srcName) should contain allOf ("Red", "Blue")
+ extends_.foreach(_.dstName shouldBe "Color")
+ }
+
+ it should "extract EXTENDS from object" in {
+ val source = """object Routes extends BaseRoutes {
+ | def apply() = {}
+ |}""".stripMargin
+ val result = parser.parse("Routes.scala", source)
+ val extends_ = result.relationships.filter(_.predicate == "EXTENDS")
+ extends_.head.srcName shouldBe "Routes"
+ extends_.head.dstName shouldBe "BaseRoutes"
+ }
+
+ // --- Nested CONTAINS tests ---
+
+ it should "create CONTAINS from enclosing object to nested case objects" in {
+ val source = """sealed trait NodeKind
+ |object NodeKind {
+ | case object Module extends NodeKind
+ | case object File extends NodeKind
+ |}""".stripMargin
+ val result = parser.parse("Node.scala", source)
+ val contains = result.relationships.filter(_.predicate == "CONTAINS")
+ contains should contain (ParsedRelationship("NodeKind", "Module", "CONTAINS"))
+ contains should contain (ParsedRelationship("NodeKind", "File", "CONTAINS"))
+ contains should not contain (ParsedRelationship("Node.scala", "Module", "CONTAINS"))
+ }
+
+ it should "create CONTAINS from enclosing object for nested case classes" in {
+ val source = """sealed trait Event
+ |object Event {
+ | case class Created(id: String) extends Event
+ | case class Deleted(id: String) extends Event
+ |}""".stripMargin
+ val result = parser.parse("Event.scala", source)
+ val contains = result.relationships.filter(_.predicate == "CONTAINS")
+ contains should contain (ParsedRelationship("Event", "Created", "CONTAINS"))
+ contains should contain (ParsedRelationship("Event", "Deleted", "CONTAINS"))
+ }
+
+ // --- REFERENCES tests ---
+
+ it should "extract REFERENCES from method signatures" in {
+ val source = """class Service {
+ | def process(kind: NodeKind, node: GraphNode): Unit = {
+ | println(kind)
+ | }
+ |}""".stripMargin
+ val result = parser.parse("Service.scala", source)
+ val refs = result.relationships.filter(_.predicate == "REFERENCES")
+ refs.map(_.dstName) should contain allOf ("NodeKind", "GraphNode")
+ refs.map(_.dstName) should not contain ("Unit")
+ }
+
+ it should "extract REFERENCES for qualified value access" in {
+ val source = """class Handler {
+ | def handle(n: Any): Unit = {
+ | val kind = NodeKind.File
+ | val src = SourceType.Code
+ | }
+ |}""".stripMargin
+ val result = parser.parse("Handler.scala", source)
+ val refs = result.relationships.filter(_.predicate == "REFERENCES")
+ refs.map(_.dstName) should contain allOf ("NodeKind", "SourceType")
+ }
+
it should "compute method spans with valid ranges" in {
val result = parser.parse("ConfidenceScorer.scala", sampleCode)
val methods = result.entities.filter(_.kind == NodeKind.Method)
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
index 37fbdf4d..2037315c 100644
--- a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
@@ -4,6 +4,7 @@ import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import ix.memory.model.NodeKind
+import io.circe.Json
class TypeScriptParserSpec extends AnyFlatSpec with Matchers {
val parser = new TypeScriptParser()
@@ -483,6 +484,85 @@ class TypeScriptParserSpec extends AnyFlatSpec with Matchers {
calls.map(_.dstName) should not contain "join"
}
+ // --- File-level CALLS tests ---
+
+ it should "extract calls from anonymous callback bodies" in {
+ val source = """
+ |import { Command } from "commander";
+ |program.command("test").action(async (opts) => {
+ | const result = await resolveEntity(client, name);
+ | printResolved(result);
+ |});
+ """.stripMargin
+ val result = parser.parse("test.ts", source)
+ val calls = result.relationships.filter(r => r.predicate == "CALLS" && r.srcName == "test.ts")
+ calls.map(_.dstName) should contain allOf ("resolveEntity", "printResolved")
+ }
+
+ // --- Named import bindings tests ---
+
+ it should "extract named import bindings" in {
+ val source = """import { pickBest, resolveEntity } from "./resolve.js";"""
+ val result = parser.parse("api.ts", source)
+ val imports = result.relationships.filter(_.predicate == "IMPORTS")
+ imports.map(_.dstName) should contain allOf ("pickBest", "resolveEntity", "./resolve.js")
+ }
+
+ it should "handle import aliases" in {
+ val source = """import { Foo as Bar } from "./mod.js";"""
+ val result = parser.parse("test.ts", source)
+ val imports = result.relationships.filter(_.predicate == "IMPORTS")
+ imports.map(_.dstName) should contain ("Bar")
+ imports.map(_.dstName) should not contain ("Foo")
+ }
+
+ // --- Export tracking tests ---
+
+ it should "track exported entities" in {
+ val source = """export function verify() { return true; }"""
+ val result = parser.parse("auth.ts", source)
+ val func = result.entities.find(_.name == "verify").get
+ func.attrs("exported") shouldBe Json.fromBoolean(true)
+ }
+
+ it should "mark non-exported entities" in {
+ val source = """function helper() { return 1; }"""
+ val result = parser.parse("util.ts", source)
+ val func = result.entities.find(_.name == "helper").get
+ func.attrs("exported") shouldBe Json.fromBoolean(false)
+ }
+
+ it should "not emit file-level CALLS for locally defined functions" in {
+ val source = """
+ |export function registerCommand(program: any): void {
+ | program.action(async () => {
+ | const result = await doWork();
+ | });
+ |}
+ """.stripMargin
+ val result = parser.parse("cmd.ts", source)
+ val fileCalls = result.relationships.filter(r =>
+ r.predicate == "CALLS" && r.srcName == "cmd.ts")
+ fileCalls.map(_.dstName) should not contain ("registerCommand")
+ }
+
+ it should "not emit file-level CALLS for code inside class bodies" in {
+ val source = """
+ |class Service {
+ | async handle() {
+ | return processData();
+ | }
+ |}
+ |initApp();
+ """.stripMargin
+ val result = parser.parse("app.ts", source)
+ val fileCalls = result.relationships.filter(r =>
+ r.predicate == "CALLS" && r.srcName == "app.ts")
+ fileCalls.map(_.dstName) should contain ("initApp")
+ fileCalls.map(_.dstName) should not contain ("processData")
+ fileCalls.map(_.dstName) should not contain ("handle")
+ }
+
it should "compute method spans bounded within their class" in {
val source = """export class Api {
| fetch(url: string) {