frameworks-integration.test.ts 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as os from 'os';
  5. import { CodeGraph } from '../src';
  6. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  7. beforeAll(async () => {
  8. await initGrammars();
  9. await loadAllGrammars();
  10. });
  11. describe('Django end-to-end framework extraction', () => {
  12. let tmpDir: string | undefined;
  13. afterEach(() => {
  14. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  15. tmpDir = undefined;
  16. });
  17. it('creates a route->view edge from urls.py to view class', async () => {
  18. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-django-'));
  19. fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# marker\n');
  20. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n');
  21. fs.mkdirSync(path.join(tmpDir, 'users'));
  22. fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), '');
  23. fs.writeFileSync(
  24. path.join(tmpDir, 'users/views.py'),
  25. 'class UserListView:\n def get(self, request): pass\n'
  26. );
  27. fs.writeFileSync(
  28. path.join(tmpDir, 'users/urls.py'),
  29. 'from django.urls import path\n' +
  30. 'from users.views import UserListView\n' +
  31. 'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n'
  32. );
  33. const cg = CodeGraph.initSync(tmpDir);
  34. await cg.indexAll();
  35. // Route node exists
  36. const routes = cg.getNodesByKind('route');
  37. expect(routes.length).toBeGreaterThan(0);
  38. const route = routes.find((n) => n.name === 'users/');
  39. expect(route).toBeDefined();
  40. // View class exists
  41. const classNodes = cg.getNodesByKind('class');
  42. const view = classNodes.find((n) => n.name === 'UserListView');
  43. expect(view).toBeDefined();
  44. // Edge route -> view exists
  45. const edges = cg.getOutgoingEdges(route!.id);
  46. const toView = edges.find((e) => e.target === view!.id);
  47. expect(toView).toBeDefined();
  48. expect(toView!.kind).toBe('references');
  49. cg.close();
  50. });
  51. });
  52. describe('Flask end-to-end framework extraction', () => {
  53. let tmpDir: string | undefined;
  54. afterEach(() => {
  55. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  56. tmpDir = undefined;
  57. });
  58. it('resolves stacked routes across @login_required to a view named after a builtin (index)', async () => {
  59. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flask-'));
  60. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'flask==3.0\n');
  61. fs.writeFileSync(
  62. path.join(tmpDir, 'app.py'),
  63. 'from flask import Blueprint, render_template\n' +
  64. 'from flask_login import login_required\n' +
  65. 'bp = Blueprint("main", __name__)\n' +
  66. '\n' +
  67. '@bp.route("/", methods=["GET", "POST"])\n' +
  68. '@bp.route("/index", methods=["GET", "POST"])\n' +
  69. '@login_required\n' +
  70. 'def index():\n' +
  71. ' return render_template("index.html")\n'
  72. );
  73. const cg = CodeGraph.initSync(tmpDir);
  74. await cg.indexAll();
  75. // Both stacked @bp.route decorators are extracted (the second was previously
  76. // dropped because @login_required broke the "def must follow" assumption).
  77. const routes = cg.getNodesByKind('route');
  78. expect(routes.map((r) => r.name).sort()).toEqual(['GET /', 'GET /index']);
  79. // The view function exists even though its name is a Python builtin method.
  80. const fn = cg.getNodesByKind('function').find((n) => n.name === 'index');
  81. expect(fn).toBeDefined();
  82. // Both routes resolve to it — exercises the bare-name builtin guard, which
  83. // previously filtered the `index` reference as a builtin method.
  84. for (const route of routes) {
  85. const edges = cg.getOutgoingEdges(route.id);
  86. const toView = edges.find((e) => e.target === fn!.id && e.kind === 'references');
  87. expect(toView, `route ${route.name} should resolve to index()`).toBeDefined();
  88. }
  89. cg.close();
  90. });
  91. });
  92. describe('Flutter end-to-end — setState→build synthesis', () => {
  93. let tmpDir: string | undefined;
  94. afterEach(() => {
  95. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  96. tmpDir = undefined;
  97. });
  98. it('synthesizes a handler→build edge when a State method calls setState', async () => {
  99. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flutter-'));
  100. fs.writeFileSync(
  101. path.join(tmpDir, 'main.dart'),
  102. 'import "package:flutter/material.dart";\n' +
  103. 'class CounterPage extends StatefulWidget {\n' +
  104. ' @override\n' +
  105. ' State<CounterPage> createState() => _CounterPageState();\n' +
  106. '}\n' +
  107. 'class _CounterPageState extends State<CounterPage> {\n' +
  108. ' int _count = 0;\n' +
  109. ' void _increment() {\n' +
  110. ' setState(() {\n' +
  111. ' _count++;\n' +
  112. ' });\n' +
  113. ' }\n' +
  114. ' @override\n' +
  115. ' Widget build(BuildContext context) {\n' +
  116. ' return Text("$_count");\n' +
  117. ' }\n' +
  118. '}\n'
  119. );
  120. const cg = CodeGraph.initSync(tmpDir);
  121. await cg.indexAll();
  122. const methods = cg.getNodesByKind('method');
  123. const increment = methods.find((n) => n.name === '_increment');
  124. const build = methods.find((n) => n.name === 'build');
  125. expect(increment).toBeDefined();
  126. expect(build).toBeDefined();
  127. // setState re-runs build (Flutter-internal, no static edge). The synthesizer
  128. // bridges the handler → build so the "tap → setState → rebuilt UI" flow connects.
  129. const edges = cg.getOutgoingEdges(increment!.id);
  130. const toBuild = edges.find((e) => e.target === build!.id && e.kind === 'calls');
  131. expect(toBuild, '_increment should reach build via setState synthesis').toBeDefined();
  132. cg.close();
  133. });
  134. });
  135. describe('C++ end-to-end — virtual override synthesis', () => {
  136. let tmpDir: string | undefined;
  137. afterEach(() => {
  138. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  139. tmpDir = undefined;
  140. });
  141. it('resolves callers through typed object pointers', async () => {
  142. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  143. let cg: CodeGraph | undefined;
  144. try {
  145. fs.writeFileSync(
  146. path.join(tmpDir, 'detect.hpp'),
  147. 'class CDetect {\n' +
  148. ' public:\n' +
  149. ' int Processing();\n' +
  150. '};\n' +
  151. 'class CDetector {\n' +
  152. ' private:\n' +
  153. ' CDetect* m_cpAlg = nullptr;\n' +
  154. ' public:\n' +
  155. ' int Run();\n' +
  156. ' int Flush();\n' +
  157. '};\n'
  158. );
  159. fs.writeFileSync(
  160. path.join(tmpDir, 'detect.cpp'),
  161. '#include "detect.hpp"\n' +
  162. 'int CDetector::Run() { return m_cpAlg->Processing(); }\n' +
  163. 'int CDetector::Flush() { return m_cpAlg->Processing(); }\n' +
  164. 'int CDetect::Processing() { return 0; }\n'
  165. );
  166. cg = CodeGraph.initSync(tmpDir);
  167. await cg.indexAll();
  168. const processing = cg
  169. .getNodesByKind('method')
  170. .find((n) => n.qualifiedName.endsWith('CDetect::Processing'));
  171. expect(processing).toBeDefined();
  172. const callers = cg.getCallers(processing!.id).map((c) => c.node.qualifiedName);
  173. expect(callers).toContain('CDetector::Run');
  174. expect(callers).toContain('CDetector::Flush');
  175. const runMethod = cg
  176. .getNodesByKind('method')
  177. .find((n) => n.qualifiedName.endsWith('CDetector::Run'));
  178. expect(runMethod).toBeDefined();
  179. const callees = cg.getCallees(runMethod!.id).map((c) => c.node.qualifiedName);
  180. expect(callees).toContain('CDetect::Processing');
  181. } finally {
  182. cg?.close();
  183. }
  184. });
  185. it('resolves typed pointer callers when the method name is ambiguous and the call sits inside a return/declaration', async () => {
  186. // Regression: an earlier version of the C++ receiver-type inference matched
  187. // the call line itself (`return m_cpAlg->Processing()`) and treated `return`
  188. // as the type, OR grabbed `int r =` as a type from the prefix. With Strategy
  189. // 3's "unique method name" fallback, the original issue example resolved
  190. // anyway — but as soon as two classes share a method name (very common in
  191. // real C++), both calls go unresolved.
  192. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  193. let cg: CodeGraph | undefined;
  194. try {
  195. fs.writeFileSync(
  196. path.join(tmpDir, 'detect.hpp'),
  197. 'class CDetect { public: int Processing(); };\n' +
  198. 'class CWidget { public: int Processing(); };\n' +
  199. 'class CDetector {\n' +
  200. ' private:\n' +
  201. ' CDetect* m_cpAlg = nullptr;\n' +
  202. ' public:\n' +
  203. ' int RunReturn();\n' +
  204. ' int RunAssign();\n' +
  205. '};\n'
  206. );
  207. fs.writeFileSync(
  208. path.join(tmpDir, 'detect.cpp'),
  209. '#include "detect.hpp"\n' +
  210. 'int CDetector::RunReturn() { return m_cpAlg->Processing(); }\n' +
  211. 'int CDetector::RunAssign() { int r = m_cpAlg->Processing(); return r; }\n' +
  212. 'int CDetect::Processing() { return 0; }\n' +
  213. 'int CWidget::Processing() { return 0; }\n'
  214. );
  215. cg = CodeGraph.initSync(tmpDir);
  216. await cg.indexAll();
  217. const detectProc = cg
  218. .getNodesByKind('method')
  219. .find((n) => n.qualifiedName === 'CDetect::Processing');
  220. const widgetProc = cg
  221. .getNodesByKind('method')
  222. .find((n) => n.qualifiedName === 'CWidget::Processing');
  223. expect(detectProc).toBeDefined();
  224. expect(widgetProc).toBeDefined();
  225. const detectCallers = cg.getCallers(detectProc!.id).map((c) => c.node.qualifiedName);
  226. expect(detectCallers).toContain('CDetector::RunReturn');
  227. expect(detectCallers).toContain('CDetector::RunAssign');
  228. // CWidget::Processing is never called — calls must NOT misroute here.
  229. const widgetCallers = cg.getCallers(widgetProc!.id).map((c) => c.node.qualifiedName);
  230. expect(widgetCallers).not.toContain('CDetector::RunReturn');
  231. expect(widgetCallers).not.toContain('CDetector::RunAssign');
  232. } finally {
  233. cg?.close();
  234. }
  235. });
  236. it('bridges a base virtual method to the subclass override', async () => {
  237. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  238. fs.writeFileSync(
  239. path.join(tmpDir, 'iter.cpp'),
  240. 'class Iterator {\n' +
  241. ' public:\n' +
  242. ' virtual void Next() { }\n' +
  243. '};\n' +
  244. 'class DBIter : public Iterator {\n' +
  245. ' public:\n' +
  246. ' void Next() override { advance(); }\n' +
  247. ' void advance() { }\n' +
  248. '};\n'
  249. );
  250. const cg = CodeGraph.initSync(tmpDir);
  251. await cg.indexAll();
  252. // Two methods named Next: the base virtual (lower line) and the override.
  253. const nexts = cg
  254. .getNodesByKind('method')
  255. .filter((n) => n.name === 'Next')
  256. .sort((a, b) => a.startLine - b.startLine);
  257. expect(nexts.length).toBe(2);
  258. const [baseNext, overrideNext] = nexts;
  259. // A vtable call to Iterator::Next dispatches to DBIter::Next — bridge it so
  260. // trace/callees from the interface method reaches the implementation.
  261. const edge = cg
  262. .getOutgoingEdges(baseNext!.id)
  263. .find((e) => e.target === overrideNext!.id && e.kind === 'calls');
  264. expect(edge, 'Iterator::Next should reach DBIter::Next via override synthesis').toBeDefined();
  265. cg.close();
  266. });
  267. });
  268. describe('Java end-to-end — field-injected bean trace (issue #389)', () => {
  269. let tmpDir: string | undefined;
  270. afterEach(() => {
  271. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  272. tmpDir = undefined;
  273. });
  274. // Mirrors the issue's Spring MVC pattern:
  275. // UserAction(@Resource UserBO userbo).toLogin2() -> this.userbo.toLogin2()
  276. // -> UserBO.toLogin2() -> userService.toLogin() -> UserService.toLogin (iface)
  277. // -> UserServiceImpl.toLogin() via interface→impl synthesis.
  278. // Without the extractor `this.` strip + field-typed receiver lookup, the very
  279. // first hop (controller -> bean) was missing entirely, breaking trace.
  280. it('connects controller -> @Resource bean -> interface -> impl end-to-end', async () => {
  281. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-bean-'));
  282. const javaDir = path.join(tmpDir, 'src/main/java/com/example/user');
  283. fs.mkdirSync(path.join(javaDir, 'action'), { recursive: true });
  284. fs.mkdirSync(path.join(javaDir, 'bo'), { recursive: true });
  285. fs.mkdirSync(path.join(javaDir, 'service'), { recursive: true });
  286. fs.mkdirSync(path.join(javaDir, 'service/impl'), { recursive: true });
  287. fs.writeFileSync(
  288. path.join(tmpDir, 'pom.xml'),
  289. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>\n'
  290. );
  291. fs.writeFileSync(
  292. path.join(javaDir, 'action/UserAction.java'),
  293. 'package com.example.user.action;\n' +
  294. 'import com.example.user.bo.UserBO;\n' +
  295. 'import javax.annotation.Resource;\n' +
  296. '@org.springframework.stereotype.Controller\n' +
  297. 'public class UserAction {\n' +
  298. ' @Resource(name = "userBO") private UserBO userbo;\n' +
  299. ' public void toLogin2() { this.userbo.toLogin2(); }\n' +
  300. '}\n'
  301. );
  302. fs.writeFileSync(
  303. path.join(javaDir, 'bo/UserBO.java'),
  304. 'package com.example.user.bo;\n' +
  305. 'import com.example.user.service.UserService;\n' +
  306. 'import javax.annotation.Resource;\n' +
  307. '@org.springframework.stereotype.Component("userBO")\n' +
  308. 'public class UserBO {\n' +
  309. ' @Resource private UserService userService;\n' +
  310. ' public void toLogin2() { userService.toLogin(); }\n' +
  311. '}\n'
  312. );
  313. fs.writeFileSync(
  314. path.join(javaDir, 'service/UserService.java'),
  315. 'package com.example.user.service;\n' +
  316. 'public interface UserService { void toLogin(); }\n'
  317. );
  318. fs.writeFileSync(
  319. path.join(javaDir, 'service/impl/UserServiceImpl.java'),
  320. 'package com.example.user.service.impl;\n' +
  321. 'import com.example.user.service.UserService;\n' +
  322. '@org.springframework.stereotype.Service("userService")\n' +
  323. 'public class UserServiceImpl implements UserService {\n' +
  324. ' public void toLogin() { }\n' +
  325. '}\n'
  326. );
  327. const cg = CodeGraph.initSync(tmpDir);
  328. await cg.indexAll();
  329. const methods = cg.getNodesByKind('method');
  330. const find = (cls: string, name: string) =>
  331. methods.find((m) => m.name === name && m.filePath.endsWith(`${cls}.java`));
  332. const action = find('UserAction', 'toLogin2');
  333. const bo = find('UserBO', 'toLogin2');
  334. const svc = find('UserService', 'toLogin');
  335. const impl = find('UserServiceImpl', 'toLogin');
  336. expect(action).toBeDefined();
  337. expect(bo).toBeDefined();
  338. expect(svc).toBeDefined();
  339. expect(impl).toBeDefined();
  340. // UserAction.toLogin2 -> UserBO.toLogin2 (the regressed hop — `this.userbo`
  341. // receiver was emitted verbatim and the field-type lookup didn't exist).
  342. const actionToBo = cg.getOutgoingEdges(action!.id).find((e) => e.target === bo!.id);
  343. expect(actionToBo, 'controller `this.userbo.toLogin2()` should reach UserBO.toLogin2').toBeDefined();
  344. expect(actionToBo!.kind).toBe('calls');
  345. // UserBO.toLogin2 -> UserService.toLogin (plain identifier receiver, works pre-fix).
  346. const boToSvc = cg.getOutgoingEdges(bo!.id).find((e) => e.target === svc!.id);
  347. expect(boToSvc).toBeDefined();
  348. // UserService.toLogin -> UserServiceImpl.toLogin (interface->impl synth).
  349. const svcToImpl = cg.getOutgoingEdges(svc!.id).find((e) => e.target === impl!.id);
  350. expect(svcToImpl).toBeDefined();
  351. cg.close();
  352. });
  353. it('bridges a Java mapper interface method to its MyBatis XML statement (incl. SQL fragments)', async () => {
  354. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-mybatis-'));
  355. const javaDir = path.join(tmpDir, 'src/main/java/com/example/dao');
  356. const xmlDir = path.join(tmpDir, 'src/main/resources/mappers');
  357. fs.mkdirSync(javaDir, { recursive: true });
  358. fs.mkdirSync(xmlDir, { recursive: true });
  359. fs.writeFileSync(
  360. path.join(tmpDir, 'pom.xml'),
  361. '<project><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency></dependencies></project>\n'
  362. );
  363. fs.writeFileSync(
  364. path.join(javaDir, 'UserDAOMapper.java'),
  365. 'package com.example.dao;\n' +
  366. 'public interface UserDAOMapper {\n' +
  367. ' Object getById(int id);\n' +
  368. ' int updateUser(Object u);\n' +
  369. '}\n'
  370. );
  371. fs.writeFileSync(
  372. path.join(xmlDir, 'UserDAOMapper.xml'),
  373. '<?xml version="1.0" encoding="UTF-8"?>\n' +
  374. '<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">\n' +
  375. '<mapper namespace="com.example.dao.UserDAOMapper">\n' +
  376. ' <sql id="userCols">id, name, email</sql>\n' +
  377. ' <select id="getById" parameterType="int" resultType="User">\n' +
  378. ' SELECT <include refid="userCols"/> FROM users WHERE id = #{id}\n' +
  379. ' </select>\n' +
  380. ' <update id="updateUser" parameterType="User">\n' +
  381. ' UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}\n' +
  382. ' </update>\n' +
  383. '</mapper>\n'
  384. );
  385. const cg = CodeGraph.initSync(tmpDir);
  386. await cg.indexAll();
  387. const methods = cg.getNodesByKind('method');
  388. const getByIdJava = methods.find((m) => m.name === 'getById' && m.language === 'java');
  389. const getByIdXml = methods.find((m) => m.name === 'getById' && m.language === 'xml');
  390. const updateJava = methods.find((m) => m.name === 'updateUser' && m.language === 'java');
  391. const updateXml = methods.find((m) => m.name === 'updateUser' && m.language === 'xml');
  392. const sqlFrag = methods.find((m) => m.name === 'userCols' && m.language === 'xml');
  393. expect(getByIdJava).toBeDefined();
  394. expect(getByIdXml).toBeDefined();
  395. expect(updateJava).toBeDefined();
  396. expect(updateXml).toBeDefined();
  397. expect(sqlFrag).toBeDefined();
  398. // XML statement qualified name must be `<namespace>::<id>` so the
  399. // synthesizer can match against the Java method's `<Class>::<method>`
  400. // suffix — this is the load-bearing contract between extractor + synthesis.
  401. expect(getByIdXml!.qualifiedName).toBe('com.example.dao.UserDAOMapper::getById');
  402. // Bridge: Java mapper method -> XML statement, kind 'calls'.
  403. const j2xGet = cg.getOutgoingEdges(getByIdJava!.id).find((e) => e.target === getByIdXml!.id);
  404. expect(j2xGet, 'Java getById should reach the XML <select id="getById">').toBeDefined();
  405. expect(j2xGet!.kind).toBe('calls');
  406. const j2xUpd = cg.getOutgoingEdges(updateJava!.id).find((e) => e.target === updateXml!.id);
  407. expect(j2xUpd, 'Java updateUser should reach the XML <update id="updateUser">').toBeDefined();
  408. // <include refid="userCols"/> inside <select> -> <sql id="userCols"> in same mapper.
  409. const incEdge = cg.getOutgoingEdges(getByIdXml!.id).find((e) => e.target === sqlFrag!.id);
  410. expect(incEdge, '<include refid="userCols"/> should reach the <sql> fragment').toBeDefined();
  411. cg.close();
  412. });
  413. it('binds @Value / @ConfigurationProperties to YAML + .properties keys (incl. relaxed binding)', async () => {
  414. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-config-'));
  415. const javaDir = path.join(tmpDir, 'src/main/java/com/example');
  416. const resDir = path.join(tmpDir, 'src/main/resources');
  417. fs.mkdirSync(javaDir, { recursive: true });
  418. fs.mkdirSync(resDir, { recursive: true });
  419. fs.writeFileSync(
  420. path.join(tmpDir, 'pom.xml'),
  421. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>\n'
  422. );
  423. fs.writeFileSync(
  424. path.join(resDir, 'application.yml'),
  425. 'app:\n' +
  426. ' cache:\n' +
  427. ' name:\n' +
  428. ' user-token: "example-service:auth:token"\n' +
  429. ' enabled: true\n' +
  430. 'db:\n' +
  431. ' url: "jdbc:mysql://localhost/x"\n'
  432. );
  433. fs.writeFileSync(
  434. path.join(resDir, 'application.properties'),
  435. 'app.retry-count=3\n'
  436. );
  437. fs.writeFileSync(
  438. path.join(javaDir, 'CacheConfig.java'),
  439. 'package com.example;\n' +
  440. 'import org.springframework.beans.factory.annotation.Value;\n' +
  441. 'public class CacheConfig {\n' +
  442. ' @Value("${app.cache.name.user-token}") private String tokenCacheName;\n' +
  443. ' @Value("${app.cache.enabled:true}") private boolean enabled;\n' +
  444. ' // relaxed binding: java camelCase, properties kebab-case\n' +
  445. ' @Value("${app.retryCount}") private int retry;\n' +
  446. '}\n'
  447. );
  448. fs.writeFileSync(
  449. path.join(javaDir, 'CacheProperties.java'),
  450. 'package com.example;\n' +
  451. 'import org.springframework.boot.context.properties.ConfigurationProperties;\n' +
  452. '@ConfigurationProperties(prefix = "app.cache")\n' +
  453. 'public class CacheProperties { private boolean enabled; }\n'
  454. );
  455. const cg = CodeGraph.initSync(tmpDir);
  456. await cg.indexAll();
  457. // YAML/properties leaf keys: one constant node per dotted path.
  458. const cfgKeys = cg
  459. .getNodesByKind('constant')
  460. .filter((n) => n.language === 'yaml' || n.language === 'properties');
  461. const cfgByQn = (qn: string) => cfgKeys.find((n) => n.qualifiedName === qn);
  462. expect(cfgByQn('app.cache.name.user-token')).toBeDefined();
  463. expect(cfgByQn('app.cache.enabled')).toBeDefined();
  464. expect(cfgByQn('db.url')).toBeDefined();
  465. expect(cfgByQn('app.retry-count')).toBeDefined();
  466. // @Value("${app.cache.name.user-token}") -> the YAML leaf key.
  467. const valueBindings = cg
  468. .getNodesByKind('constant')
  469. .filter((n) => n.id.startsWith('spring-value:'));
  470. const userToken = valueBindings.find((n) => n.name === 'app.cache.name.user-token');
  471. expect(userToken).toBeDefined();
  472. const userTokenEdges = cg.getOutgoingEdges(userToken!.id);
  473. const userTokenTarget = userTokenEdges.find((e) =>
  474. cfgKeys.some((c) => c.id === e.target && c.qualifiedName === 'app.cache.name.user-token'),
  475. );
  476. expect(userTokenTarget, '@Value should reference the YAML leaf key').toBeDefined();
  477. // Default-value form `${k:default}` — strip the `:default` and bind the key.
  478. const enabledBind = valueBindings.find((n) => n.name === 'app.cache.enabled');
  479. expect(enabledBind).toBeDefined();
  480. expect(cg.getOutgoingEdges(enabledBind!.id).some((e) => {
  481. const t = cfgByQn('app.cache.enabled');
  482. return t && e.target === t.id;
  483. })).toBe(true);
  484. // Relaxed binding: `app.retryCount` (camel) -> `app.retry-count` (kebab).
  485. const retryBind = valueBindings.find((n) => n.name === 'app.retryCount');
  486. expect(retryBind).toBeDefined();
  487. expect(cg.getOutgoingEdges(retryBind!.id).some((e) => {
  488. const t = cfgByQn('app.retry-count');
  489. return t && e.target === t.id;
  490. })).toBe(true);
  491. // @ConfigurationProperties(prefix="app.cache") -> a key under that prefix.
  492. const cpBindings = cg
  493. .getNodesByKind('constant')
  494. .filter((n) => n.id.startsWith('spring-cp:'));
  495. const cpAppCache = cpBindings.find((n) => n.name === 'app.cache');
  496. expect(cpAppCache).toBeDefined();
  497. const cpEdges = cg.getOutgoingEdges(cpAppCache!.id);
  498. expect(cpEdges.length).toBeGreaterThan(0);
  499. cg.close();
  500. });
  501. it('emits only a file node for non-MyBatis XML (pom.xml, beans.xml, log4j.xml)', async () => {
  502. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-xml-non-mybatis-'));
  503. fs.writeFileSync(
  504. path.join(tmpDir, 'pom.xml'),
  505. '<project><groupId>x</groupId><artifactId>y</artifactId></project>\n'
  506. );
  507. fs.writeFileSync(
  508. path.join(tmpDir, 'log4j.xml'),
  509. '<?xml version="1.0"?><Configuration><Loggers><Root level="info"/></Loggers></Configuration>\n'
  510. );
  511. const cg = CodeGraph.initSync(tmpDir);
  512. await cg.indexAll();
  513. // No method nodes — non-mapper XML produces no symbols (just file rows).
  514. expect(cg.getNodesByKind('method').filter((n) => n.language === 'xml').length).toBe(0);
  515. cg.close();
  516. });
  517. it('resolves a `this.field.method()` call to a unique implementation class', async () => {
  518. // Standalone test of the extractor `this.` strip: even without Spring annotations,
  519. // `this.svc.run()` where `svc` is typed as a concrete class should route to that
  520. // class's method. This is the general Java fix, Spring is only one consumer.
  521. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-java-this-field-'));
  522. fs.writeFileSync(
  523. path.join(tmpDir, 'App.java'),
  524. 'class Svc { public void run() { } }\n' +
  525. 'class App {\n' +
  526. ' private Svc svc;\n' +
  527. ' public void go() { this.svc.run(); }\n' +
  528. '}\n'
  529. );
  530. const cg = CodeGraph.initSync(tmpDir);
  531. await cg.indexAll();
  532. const methods = cg.getNodesByKind('method');
  533. const go = methods.find((m) => m.name === 'go');
  534. const run = methods.find((m) => m.name === 'run');
  535. expect(go && run).toBeTruthy();
  536. const edge = cg.getOutgoingEdges(go!.id).find((e) => e.target === run!.id);
  537. expect(edge, '`this.svc.run()` should resolve to Svc.run').toBeDefined();
  538. cg.close();
  539. });
  540. });
  541. describe('JVM FQN imports — end-to-end', () => {
  542. let tmpDir: string | undefined;
  543. afterEach(() => {
  544. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  545. tmpDir = undefined;
  546. });
  547. it('resolves a Kotlin import when the file name differs from the class name', async () => {
  548. // Bar lives in Models.kt — the filesystem-based Java-style path lookup
  549. // (com/example/Bar.kt) misses this; only FQN-via-qualifiedName finds it.
  550. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  551. fs.writeFileSync(
  552. path.join(tmpDir, 'Models.kt'),
  553. 'package com.example\n\nclass Bar {\n fun greet(): String = "hi"\n}\n'
  554. );
  555. fs.writeFileSync(
  556. path.join(tmpDir, 'Caller.kt'),
  557. 'package com.example.app\n\nimport com.example.Bar\n\nclass App {\n fun run() { Bar().greet() }\n}\n'
  558. );
  559. const cg = CodeGraph.initSync(tmpDir);
  560. await cg.indexAll();
  561. const bar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::Bar');
  562. expect(bar, 'Bar should be extracted with package-qualified name').toBeDefined();
  563. const importNode = cg.getNodesByKind('import').find((n) => n.name === 'com.example.Bar');
  564. expect(importNode, 'import statement node should exist').toBeDefined();
  565. // The imports edge may originate from the import node OR from a parent
  566. // scope (file / namespace) — accept either, but require that an
  567. // imports-kind edge to Bar exists.
  568. const reachesBar = cg
  569. .getIncomingEdges(bar!.id)
  570. .find((e) => e.kind === 'imports');
  571. expect(reachesBar, 'an imports edge should resolve to Bar via FQN').toBeDefined();
  572. cg.close();
  573. });
  574. it('resolves a Kotlin top-level function import', async () => {
  575. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  576. fs.writeFileSync(
  577. path.join(tmpDir, 'Utils.kt'),
  578. 'package com.example\n\nfun util(): Int = 42\n'
  579. );
  580. fs.writeFileSync(
  581. path.join(tmpDir, 'Caller.kt'),
  582. 'package com.example.app\n\nimport com.example.util\n\nfun main() { util() }\n'
  583. );
  584. const cg = CodeGraph.initSync(tmpDir);
  585. await cg.indexAll();
  586. const util = cg.getNodesByKind('function').find((n) => n.qualifiedName === 'com.example::util');
  587. expect(util, 'top-level util() should be extracted under com.example').toBeDefined();
  588. const edge = cg.getIncomingEdges(util!.id).find((e) => e.kind === 'imports');
  589. expect(edge, 'imports edge should reach the top-level function by FQN').toBeDefined();
  590. });
  591. it('resolves cross-language: Kotlin importing a Java class', async () => {
  592. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  593. fs.writeFileSync(
  594. path.join(tmpDir, 'JavaBar.java'),
  595. 'package com.example;\n\npublic class JavaBar {\n public String greet() { return "hi"; }\n}\n'
  596. );
  597. fs.writeFileSync(
  598. path.join(tmpDir, 'Caller.kt'),
  599. 'package com.example.app\n\nimport com.example.JavaBar\n\nfun main() { JavaBar().greet() }\n'
  600. );
  601. const cg = CodeGraph.initSync(tmpDir);
  602. await cg.indexAll();
  603. const javaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::JavaBar');
  604. expect(javaBar, 'JavaBar should be extracted under com.example regardless of language').toBeDefined();
  605. const edge = cg.getIncomingEdges(javaBar!.id).find((e) => e.kind === 'imports');
  606. expect(edge, 'Kotlin caller should resolve its import to the Java class').toBeDefined();
  607. });
  608. it('disambiguates a class-name collision across packages', async () => {
  609. // Two `Bar` classes in different packages — each importer should reach
  610. // ITS Bar, not the other one. This is the central failure mode that
  611. // name-matcher alone cannot disambiguate.
  612. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  613. fs.writeFileSync(
  614. path.join(tmpDir, 'AlphaBar.kt'),
  615. 'package com.example.alpha\n\nclass Bar { fun who() = "alpha" }\n'
  616. );
  617. fs.writeFileSync(
  618. path.join(tmpDir, 'BetaBar.kt'),
  619. 'package com.example.beta\n\nclass Bar { fun who() = "beta" }\n'
  620. );
  621. fs.writeFileSync(
  622. path.join(tmpDir, 'CallerA.kt'),
  623. 'package app\n\nimport com.example.alpha.Bar\n\nfun a() { Bar().who() }\n'
  624. );
  625. fs.writeFileSync(
  626. path.join(tmpDir, 'CallerB.kt'),
  627. 'package app\n\nimport com.example.beta.Bar\n\nfun b() { Bar().who() }\n'
  628. );
  629. const cg = CodeGraph.initSync(tmpDir);
  630. await cg.indexAll();
  631. const alphaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.alpha::Bar');
  632. const betaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.beta::Bar');
  633. expect(alphaBar).toBeDefined();
  634. expect(betaBar).toBeDefined();
  635. expect(alphaBar!.id).not.toBe(betaBar!.id);
  636. // Each Bar receives exactly one imports edge — from its own caller.
  637. const alphaIncoming = cg.getIncomingEdges(alphaBar!.id).filter((e) => e.kind === 'imports');
  638. const betaIncoming = cg.getIncomingEdges(betaBar!.id).filter((e) => e.kind === 'imports');
  639. expect(alphaIncoming.length).toBeGreaterThan(0);
  640. expect(betaIncoming.length).toBeGreaterThan(0);
  641. // Sanity: the edges don't cross — alpha's incoming sources don't include
  642. // beta's filePath and vice versa.
  643. const sourceFiles = (edges: typeof alphaIncoming) =>
  644. edges.map((e) => cg.getNode(e.source)?.filePath).filter(Boolean);
  645. expect(sourceFiles(alphaIncoming).some((p) => p?.includes('CallerA.kt'))).toBe(true);
  646. expect(sourceFiles(betaIncoming).some((p) => p?.includes('CallerB.kt'))).toBe(true);
  647. });
  648. });
  649. describe('Java anonymous-class override synthesis — end-to-end', () => {
  650. let tmpDir: string | undefined;
  651. afterEach(() => {
  652. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  653. tmpDir = undefined;
  654. });
  655. it('bridges an abstract base method to overrides inside `new Base() { ... }`', async () => {
  656. // Mirrors guava Splitter: a factory returns `new BaseIter() {
  657. // @Override int separatorStart(...) { ... } }`. Without anon-class
  658. // extraction the override is invisible — Phase 5.5 interface-impl
  659. // has no class to bridge — and an agent investigating `BaseIter.separatorStart`
  660. // can't see its real implementation without reading the file.
  661. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-anon-java-'));
  662. fs.writeFileSync(
  663. path.join(tmpDir, 'Splitter.java'),
  664. 'package com.example;\n' +
  665. '\n' +
  666. 'abstract class BaseIter {\n' +
  667. ' abstract int separatorStart(int start);\n' +
  668. '}\n' +
  669. '\n' +
  670. 'public class Splitter {\n' +
  671. ' public BaseIter make() {\n' +
  672. ' return new BaseIter() {\n' +
  673. ' @Override\n' +
  674. ' int separatorStart(int start) { return start + 1; }\n' +
  675. ' };\n' +
  676. ' }\n' +
  677. '}\n'
  678. );
  679. const cg = CodeGraph.initSync(tmpDir);
  680. await cg.indexAll();
  681. // The anon class is extracted and contains the override.
  682. const anonClass = cg
  683. .getNodesByKind('class')
  684. .find((n) => /BaseIter\$anon@/.test(n.name));
  685. expect(anonClass, 'anonymous BaseIter subclass should be a class node').toBeDefined();
  686. const baseAbstract = cg
  687. .getNodesByKind('method')
  688. .find((n) => n.qualifiedName === 'com.example::BaseIter::separatorStart');
  689. const anonOverride = cg
  690. .getNodesByKind('method')
  691. .find(
  692. (n) =>
  693. n.name === 'separatorStart' &&
  694. n.qualifiedName.includes('$anon@') &&
  695. n.qualifiedName.startsWith('com.example::Splitter::make::')
  696. );
  697. expect(baseAbstract, 'base abstract method should be in the graph').toBeDefined();
  698. expect(anonOverride, 'anon-class override should be in the graph').toBeDefined();
  699. // Phase 5.5 interface-impl: the abstract method has a synthesized
  700. // `calls` edge to the anon override. Without this hop the agent
  701. // would have to Read the file to discover the implementation.
  702. const synthEdge = cg
  703. .getOutgoingEdges(baseAbstract!.id)
  704. .find((e) => e.target === anonOverride!.id && e.kind === 'calls');
  705. expect(synthEdge, 'BaseIter.separatorStart should bridge to anon.separatorStart').toBeDefined();
  706. expect(synthEdge!.provenance).toBe('heuristic');
  707. expect((synthEdge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  708. 'interface-impl'
  709. );
  710. cg.close();
  711. });
  712. });
  713. describe('Go gRPC stub→impl synthesis', () => {
  714. let tmpDir: string | undefined;
  715. afterEach(() => {
  716. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  717. tmpDir = undefined;
  718. });
  719. it('bridges UnimplementedMsgServer methods to the hand-written keeper impl', async () => {
  720. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-'));
  721. // Mimic protoc-gen-go-grpc output: `*_grpc.pb.go` carrying the
  722. // UnimplementedMsgServer stub.
  723. fs.writeFileSync(
  724. path.join(tmpDir, 'tx_grpc.pb.go'),
  725. 'package banktypes\n\n' +
  726. 'type UnimplementedMsgServer struct{}\n\n' +
  727. 'func (UnimplementedMsgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) { return nil, nil }\n' +
  728. 'func (UnimplementedMsgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) { return nil, nil }\n' +
  729. 'func (UnimplementedMsgServer) mustEmbedUnimplementedMsgServer() {}\n' +
  730. 'func (UnimplementedMsgServer) testEmbeddedByValue() {}\n'
  731. );
  732. // Hand-written impl in a non-generated file — what an agent actually
  733. // wants the trace to land on.
  734. fs.writeFileSync(
  735. path.join(tmpDir, 'msg_server.go'),
  736. 'package keeper\n\n' +
  737. 'type msgServer struct{ k Keeper }\n\n' +
  738. 'func (m msgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) {\n' +
  739. ' return m.k.SendCoins(ctx, req.From, req.To, req.Amount)\n' +
  740. '}\n' +
  741. 'func (m msgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) {\n' +
  742. ' return nil, nil\n' +
  743. '}\n'
  744. );
  745. let cg: CodeGraph | undefined;
  746. try {
  747. cg = CodeGraph.initSync(tmpDir);
  748. await cg.indexAll();
  749. const stubSend = cg
  750. .getNodesByKind('method')
  751. .find((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'));
  752. const implSend = cg
  753. .getNodesByKind('method')
  754. .find((n) => n.qualifiedName.endsWith('msgServer::Send'));
  755. expect(stubSend, 'UnimplementedMsgServer.Send should be indexed').toBeDefined();
  756. expect(implSend, 'msgServer.Send should be indexed').toBeDefined();
  757. const bridge = cg
  758. .getOutgoingEdges(stubSend!.id)
  759. .find((e) => e.target === implSend!.id && e.kind === 'calls');
  760. expect(bridge, 'stub Send should bridge to impl Send').toBeDefined();
  761. expect(bridge!.provenance).toBe('heuristic');
  762. expect((bridge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  763. 'go-grpc-stub-impl'
  764. );
  765. } finally {
  766. cg?.close();
  767. }
  768. });
  769. it('does not bridge to candidates living in another generated file', async () => {
  770. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-sib-'));
  771. // `*_grpc.pb.go` also contains a sibling `msgClient` struct that
  772. // happens to satisfy the same method set. We must NOT bridge to it —
  773. // it's not the hand-written impl, just the gRPC client wrapper.
  774. fs.writeFileSync(
  775. path.join(tmpDir, 'tx_grpc.pb.go'),
  776. 'package banktypes\n\n' +
  777. 'type UnimplementedMsgServer struct{}\n' +
  778. 'func (UnimplementedMsgServer) Send() {}\n' +
  779. 'func (UnimplementedMsgServer) MultiSend() {}\n\n' +
  780. 'type msgClient struct{}\n' +
  781. 'func (m msgClient) Send() {}\n' +
  782. 'func (m msgClient) MultiSend() {}\n'
  783. );
  784. let cg: CodeGraph | undefined;
  785. try {
  786. cg = CodeGraph.initSync(tmpDir);
  787. await cg.indexAll();
  788. const stub = cg
  789. .getNodesByKind('struct')
  790. .find((n) => n.name === 'UnimplementedMsgServer');
  791. expect(stub).toBeDefined();
  792. const bridges = cg
  793. .getNodesByKind('method')
  794. .filter((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'))
  795. .flatMap((stubSend) => cg!.getOutgoingEdges(stubSend.id))
  796. .filter(
  797. (e) =>
  798. e.kind === 'calls' &&
  799. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  800. 'go-grpc-stub-impl',
  801. );
  802. expect(bridges, 'no bridge to msgClient (also generated)').toHaveLength(0);
  803. } finally {
  804. cg?.close();
  805. }
  806. });
  807. });
  808. describe('React Router end-to-end route extraction (.tsx/.jsx)', () => {
  809. let tmpDir: string | undefined;
  810. afterEach(() => {
  811. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  812. tmpDir = undefined;
  813. });
  814. // Regression for the resolver language-gate bug: the `react` resolver's
  815. // `extract()` was filtered out of the .tsx/.jsx grammars, so `<Route>` routes
  816. // — which only live in JSX files — were never indexed through the real
  817. // indexing path (the unit tests call extract() directly and so missed this).
  818. it('indexes <Route element={<X/>}> routes from a .tsx file and links them to the component', async () => {
  819. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-rr-'));
  820. fs.writeFileSync(
  821. path.join(tmpDir, 'package.json'),
  822. '{"dependencies":{"react":"^18.0.0","react-router-dom":"^6.0.0"}}'
  823. );
  824. fs.writeFileSync(
  825. path.join(tmpDir, 'Home.tsx'),
  826. 'export function Home() { return null; }\n'
  827. );
  828. fs.writeFileSync(
  829. path.join(tmpDir, 'routes.tsx'),
  830. `import { Routes, Route } from 'react-router-dom';
  831. import { Home } from './Home';
  832. export function AppRoutes() {
  833. return (
  834. <Routes>
  835. <Route path="/home" element={<Home/>} />
  836. </Routes>
  837. );
  838. }
  839. `
  840. );
  841. const cg = CodeGraph.initSync(tmpDir);
  842. await cg.indexAll();
  843. try {
  844. // The route node from the .tsx file exists (the bug: it didn't).
  845. const route = cg.getNodesByKind('route').find((n) => n.name === '/home');
  846. expect(route, '/home route from .tsx should be indexed').toBeDefined();
  847. // ...and it links to the Home component.
  848. const home = cg.getNodesByName('Home').find((n) => n.kind === 'function');
  849. expect(home).toBeDefined();
  850. const toHome = cg.getOutgoingEdges(route!.id).find((e) => e.target === home!.id);
  851. expect(toHome, 'route → Home component edge').toBeDefined();
  852. } finally {
  853. cg.close();
  854. }
  855. });
  856. });
  857. describe('Terraform end-to-end module-boundary resolution', () => {
  858. let tmpDir: string | undefined;
  859. afterEach(() => {
  860. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  861. tmpDir = undefined;
  862. });
  863. function writeMultiModuleRepo(root: string) {
  864. fs.mkdirSync(path.join(root, 'modules/vpc'), { recursive: true });
  865. fs.mkdirSync(path.join(root, 'modules/other'), { recursive: true });
  866. fs.mkdirSync(path.join(root, 'envs'), { recursive: true });
  867. fs.writeFileSync(
  868. path.join(root, 'main.tf'),
  869. 'variable "vpc_cidr" {\n type = string\n}\n\n' +
  870. 'module "vpc" {\n source = "./modules/vpc"\n cidr = var.vpc_cidr\n}\n\n' +
  871. 'module "registry_thing" {\n source = "terraform-aws-modules/s3-bucket/aws"\n bucket = "x"\n}\n\n' +
  872. 'output "vpc_id" {\n value = module.vpc.vpc_id\n}\n'
  873. );
  874. fs.writeFileSync(
  875. path.join(root, 'modules/vpc/variables.tf'),
  876. 'variable "cidr" {\n type = string\n}\n'
  877. );
  878. fs.writeFileSync(
  879. path.join(root, 'modules/vpc/main.tf'),
  880. 'resource "aws_vpc" "this" {\n cidr_block = var.cidr\n}\n'
  881. );
  882. fs.writeFileSync(
  883. path.join(root, 'modules/vpc/outputs.tf'),
  884. 'output "vpc_id" {\n value = aws_vpc.this.id\n}\n'
  885. );
  886. // Same-named variable in an UNRELATED module — must never receive edges
  887. // from outside its own directory.
  888. fs.writeFileSync(
  889. path.join(root, 'modules/other/variables.tf'),
  890. 'variable "cidr" {\n type = string\n}\nvariable "orphan_ref_target" {}\n'
  891. );
  892. // References a variable that has no same-dir declaration: must stay unlinked.
  893. fs.writeFileSync(
  894. path.join(root, 'modules/other/main.tf'),
  895. 'resource "aws_eip" "e" {\n tags = { Name = var.undeclared_here_elsewhere_yes }\n}\n'
  896. );
  897. fs.writeFileSync(path.join(root, 'envs/prod.tfvars'), 'vpc_cidr = "10.0.0.0/16"\n');
  898. }
  899. it('bridges module inputs/outputs/source and enforces directory scoping', async () => {
  900. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-'));
  901. writeMultiModuleRepo(tmpDir);
  902. const cg = CodeGraph.initSync(tmpDir);
  903. await cg.indexAll();
  904. try {
  905. const byQname = (q: string, file?: string) =>
  906. cg
  907. .getNodesByName(q.split('.').pop()!)
  908. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  909. const moduleDecl = byQname('module.vpc')[0];
  910. expect(moduleDecl, 'module.vpc declaration node').toBeDefined();
  911. const childCidr = byQname('var.cidr', 'modules/vpc/variables.tf')[0];
  912. expect(childCidr, "child module's var.cidr").toBeDefined();
  913. const childOutput = byQname('output.vpc_id', 'modules/vpc/outputs.tf')[0];
  914. expect(childOutput, "child module's output.vpc_id").toBeDefined();
  915. const rootOutput = byQname('output.vpc_id', 'main.tf')[0];
  916. expect(rootOutput, 'root output.vpc_id').toBeDefined();
  917. const declEdges = cg.getOutgoingEdges(moduleDecl!.id);
  918. // Input wiring: module block → child variable (cross-directory).
  919. expect(
  920. declEdges.find((e) => e.target === childCidr!.id),
  921. 'module.vpc → child var.cidr input edge'
  922. ).toBeDefined();
  923. // Source wiring: module block → child entry file.
  924. const fileNode = cg
  925. .getNodesInFile('modules/vpc/main.tf')
  926. .find((n) => n.kind === 'file');
  927. expect(fileNode).toBeDefined();
  928. const importEdge = declEdges.find((e) => e.target === fileNode!.id);
  929. expect(importEdge, 'module.vpc → modules/vpc/main.tf imports edge').toBeDefined();
  930. expect(importEdge!.kind).toBe('imports');
  931. // Output bridge: root output → child output (not just the declaration).
  932. const rootOutEdges = cg.getOutgoingEdges(rootOutput!.id);
  933. expect(
  934. rootOutEdges.find((e) => e.target === childOutput!.id),
  935. 'root output.vpc_id → child output.vpc_id'
  936. ).toBeDefined();
  937. expect(
  938. rootOutEdges.find((e) => e.target === moduleDecl!.id),
  939. 'root output.vpc_id → module.vpc declaration'
  940. ).toBeDefined();
  941. // tfvars assignment walks up to the ROOT variable.
  942. const rootVar = byQname('var.vpc_cidr', 'main.tf')[0];
  943. expect(rootVar).toBeDefined();
  944. const tfvarsFile = cg.getNodesInFile('envs/prod.tfvars').find((n) => n.kind === 'file');
  945. expect(tfvarsFile).toBeDefined();
  946. expect(
  947. cg.getOutgoingEdges(tfvarsFile!.id).find((e) => e.target === rootVar!.id),
  948. 'envs/prod.tfvars → var.vpc_cidr'
  949. ).toBeDefined();
  950. // Directory scoping: the unrelated module's same-named var.cidr gets
  951. // NO incoming edges from outside its own directory…
  952. const otherCidr = byQname('var.cidr', 'modules/other/variables.tf')[0];
  953. expect(otherCidr).toBeDefined();
  954. const incomingOther = cg.getIncomingEdges(otherCidr!.id).filter((e) => e.kind !== 'contains');
  955. expect(incomingOther, 'unrelated module var.cidr must stay isolated').toHaveLength(0);
  956. // …and a reference with no same-dir declaration stays unlinked rather
  957. // than borrowing another module's declaration.
  958. const orphanEdges = cg
  959. .getNodesInFile('modules/other/main.tf')
  960. .filter((n) => n.qualifiedName === 'aws_eip.e')
  961. .flatMap((n) => cg.getOutgoingEdges(n.id))
  962. .filter((e) => e.kind === 'references');
  963. const orphanTargets = orphanEdges.map((e) => cg.getNode(e.target)?.qualifiedName);
  964. expect(orphanTargets).not.toContain('var.undeclared_here_elsewhere_yes');
  965. // Registry-sourced module: inputs stay unresolved (no guessed edges).
  966. const registryDecl = byQname('module.registry_thing')[0];
  967. expect(registryDecl).toBeDefined();
  968. const registryEdges = cg
  969. .getOutgoingEdges(registryDecl!.id)
  970. .filter((e) => e.kind !== 'contains');
  971. expect(registryEdges, 'registry module must not link anywhere').toHaveLength(0);
  972. } finally {
  973. cg.close();
  974. }
  975. });
  976. });
  977. describe('Terraform follow-ups: remote-state bridge, provider alias, moved blocks', () => {
  978. let tmpDir: string | undefined;
  979. afterEach(() => {
  980. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  981. tmpDir = undefined;
  982. });
  983. it('bridges atmos remote-state to the target component, resolves provider aliases up the tree, links moved blocks', async () => {
  984. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-fu-'));
  985. // Component producing state.
  986. fs.mkdirSync(path.join(tmpDir, 'components/terraform/vpc'), { recursive: true });
  987. fs.writeFileSync(
  988. path.join(tmpDir, 'components/terraform/vpc/outputs.tf'),
  989. 'output "vpc_id" {\n value = "vpc-123"\n}\n'
  990. );
  991. // Component consuming it via the cloudposse remote-state module.
  992. fs.mkdirSync(path.join(tmpDir, 'components/terraform/eks/cluster'), { recursive: true });
  993. fs.writeFileSync(
  994. path.join(tmpDir, 'components/terraform/eks/cluster/remote-state.tf'),
  995. 'module "vpc" {\n' +
  996. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  997. ' component = var.vpc_component_name\n' +
  998. '}\n' +
  999. 'variable "vpc_component_name" {\n' +
  1000. ' type = string\n' +
  1001. ' default = "vpc"\n' +
  1002. '}\n'
  1003. );
  1004. fs.writeFileSync(
  1005. path.join(tmpDir, 'components/terraform/eks/cluster/main.tf'),
  1006. 'resource "aws_eks_cluster" "this" {\n vpc_id = module.vpc.outputs.vpc_id\n}\n'
  1007. );
  1008. // Ambiguous component name — two directories called "dns" with the same
  1009. // output; the bridge must refuse to pick one.
  1010. fs.mkdirSync(path.join(tmpDir, 'components/terraform/dns'), { recursive: true });
  1011. fs.mkdirSync(path.join(tmpDir, 'legacy/dns'), { recursive: true });
  1012. fs.writeFileSync(path.join(tmpDir, 'components/terraform/dns/outputs.tf'), 'output "zone_id" {\n value = "z1"\n}\n');
  1013. fs.writeFileSync(path.join(tmpDir, 'legacy/dns/outputs.tf'), 'output "zone_id" {\n value = "z2"\n}\n');
  1014. fs.writeFileSync(
  1015. path.join(tmpDir, 'components/terraform/eks/cluster/dns.tf'),
  1016. 'module "dns" {\n' +
  1017. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  1018. ' component = "dns"\n' +
  1019. '}\n' +
  1020. 'output "zone" {\n value = module.dns.outputs.zone_id\n}\n'
  1021. );
  1022. // Provider alias declared at the root, selected inside a module dir.
  1023. fs.writeFileSync(
  1024. path.join(tmpDir, 'providers.tf'),
  1025. 'provider "aws" {\n region = "us-east-1"\n}\n' +
  1026. 'provider "aws" {\n alias = "east"\n region = "us-east-2"\n}\n'
  1027. );
  1028. fs.mkdirSync(path.join(tmpDir, 'modules/app'), { recursive: true });
  1029. fs.writeFileSync(
  1030. path.join(tmpDir, 'modules/app/main.tf'),
  1031. 'resource "aws_s3_bucket" "b" {\n provider = aws.east\n bucket = "x"\n}\n'
  1032. );
  1033. // Moved block referencing a live resource.
  1034. fs.writeFileSync(
  1035. path.join(tmpDir, 'main.tf'),
  1036. 'resource "aws_instance" "renamed" {}\n' +
  1037. 'moved {\n from = aws_instance.old\n to = aws_instance.renamed\n}\n'
  1038. );
  1039. const cg = CodeGraph.initSync(tmpDir);
  1040. await cg.indexAll();
  1041. try {
  1042. const byQname = (q: string, file?: string) =>
  1043. cg
  1044. .getNodesByName(q.split('.').pop()!)
  1045. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  1046. // 1. remote-state bridge: consumer resource → producer component's output.
  1047. const consumer = byQname('aws_eks_cluster.this')[0] ??
  1048. cg.getNodesInFile('components/terraform/eks/cluster/main.tf').find((n) => n.qualifiedName === 'aws_eks_cluster.this');
  1049. expect(consumer, 'consumer resource').toBeDefined();
  1050. const producerOut = byQname('output.vpc_id', 'components/terraform/vpc/outputs.tf')[0];
  1051. expect(producerOut, "producer component's output").toBeDefined();
  1052. expect(
  1053. cg.getOutgoingEdges(consumer!.id).find((e) => e.target === producerOut!.id),
  1054. 'remote-state bridge edge eks/cluster → vpc output'
  1055. ).toBeDefined();
  1056. // 2. Ambiguous component name → no bridge edge to either candidate.
  1057. const zoneOut = byQname('output.zone', 'components/terraform/eks/cluster/dns.tf')[0];
  1058. expect(zoneOut).toBeDefined();
  1059. const zoneTargets = cg
  1060. .getOutgoingEdges(zoneOut!.id)
  1061. .map((e) => cg.getNode(e.target))
  1062. .filter((n) => n?.qualifiedName === 'output.zone_id');
  1063. expect(zoneTargets, 'ambiguous component must not be guessed').toHaveLength(0);
  1064. // 3. Provider alias: nodes are distinct, and the selection inside the
  1065. // module resolves up the tree to the aliased configuration.
  1066. const provNodes = cg.getNodesInFile('providers.tf');
  1067. const aliased = provNodes.find((n) => n.qualifiedName === 'provider.aws.east');
  1068. const defaultProv = provNodes.find((n) => n.qualifiedName === 'provider.aws');
  1069. expect(aliased, 'aliased provider node').toBeDefined();
  1070. expect(defaultProv, 'default provider node').toBeDefined();
  1071. const bucket = cg.getNodesInFile('modules/app/main.tf').find((n) => n.qualifiedName === 'aws_s3_bucket.b');
  1072. expect(bucket).toBeDefined();
  1073. const bucketEdges = cg.getOutgoingEdges(bucket!.id);
  1074. expect(
  1075. bucketEdges.find((e) => e.target === aliased!.id),
  1076. 'provider = aws.east → aliased provider (ancestor walk)'
  1077. ).toBeDefined();
  1078. expect(bucketEdges.find((e) => e.target === defaultProv!.id), 'must not link the default provider').toBeUndefined();
  1079. // 4. moved block: the file references the live resource.
  1080. const renamed = cg.getNodesInFile('main.tf').find((n) => n.qualifiedName === 'aws_instance.renamed');
  1081. expect(renamed).toBeDefined();
  1082. const rootFile = cg.getNodesInFile('main.tf').find((n) => n.kind === 'file');
  1083. expect(
  1084. cg.getOutgoingEdges(rootFile!.id).find((e) => e.target === renamed!.id),
  1085. 'moved block → live resource edge'
  1086. ).toBeDefined();
  1087. } finally {
  1088. cg.close();
  1089. }
  1090. });
  1091. });