extraction.test.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { extractFromSource } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages } from '../src/extraction/grammars';
  13. // Create a temporary directory for each test
  14. function createTempDir(): string {
  15. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  16. }
  17. // Clean up temporary directory
  18. function cleanupTempDir(dir: string): void {
  19. if (fs.existsSync(dir)) {
  20. fs.rmSync(dir, { recursive: true, force: true });
  21. }
  22. }
  23. describe('Language Detection', () => {
  24. it('should detect TypeScript files', () => {
  25. expect(detectLanguage('src/index.ts')).toBe('typescript');
  26. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  27. });
  28. it('should detect JavaScript files', () => {
  29. expect(detectLanguage('index.js')).toBe('javascript');
  30. expect(detectLanguage('App.jsx')).toBe('jsx');
  31. expect(detectLanguage('config.mjs')).toBe('javascript');
  32. });
  33. it('should detect Python files', () => {
  34. expect(detectLanguage('main.py')).toBe('python');
  35. });
  36. it('should detect Go files', () => {
  37. expect(detectLanguage('main.go')).toBe('go');
  38. });
  39. it('should detect Rust files', () => {
  40. expect(detectLanguage('lib.rs')).toBe('rust');
  41. });
  42. it('should detect Java files', () => {
  43. expect(detectLanguage('Main.java')).toBe('java');
  44. });
  45. it('should detect C files', () => {
  46. expect(detectLanguage('main.c')).toBe('c');
  47. expect(detectLanguage('utils.h')).toBe('c');
  48. });
  49. it('should detect C++ files', () => {
  50. expect(detectLanguage('main.cpp')).toBe('cpp');
  51. expect(detectLanguage('class.hpp')).toBe('cpp');
  52. });
  53. it('should detect C# files', () => {
  54. expect(detectLanguage('Program.cs')).toBe('csharp');
  55. });
  56. it('should detect PHP files', () => {
  57. expect(detectLanguage('index.php')).toBe('php');
  58. });
  59. it('should detect Ruby files', () => {
  60. expect(detectLanguage('app.rb')).toBe('ruby');
  61. });
  62. it('should detect Swift files', () => {
  63. expect(detectLanguage('ViewController.swift')).toBe('swift');
  64. });
  65. it('should detect Kotlin files', () => {
  66. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  67. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  68. });
  69. it('should detect Dart files', () => {
  70. expect(detectLanguage('main.dart')).toBe('dart');
  71. });
  72. it('should return unknown for unsupported extensions', () => {
  73. expect(detectLanguage('styles.css')).toBe('unknown');
  74. expect(detectLanguage('data.json')).toBe('unknown');
  75. });
  76. });
  77. describe('Language Support', () => {
  78. it('should report supported languages', () => {
  79. expect(isLanguageSupported('typescript')).toBe(true);
  80. expect(isLanguageSupported('python')).toBe(true);
  81. expect(isLanguageSupported('go')).toBe(true);
  82. expect(isLanguageSupported('unknown')).toBe(false);
  83. });
  84. it('should list all supported languages', () => {
  85. const languages = getSupportedLanguages();
  86. expect(languages).toContain('typescript');
  87. expect(languages).toContain('javascript');
  88. expect(languages).toContain('python');
  89. expect(languages).toContain('go');
  90. expect(languages).toContain('rust');
  91. expect(languages).toContain('java');
  92. expect(languages).toContain('csharp');
  93. expect(languages).toContain('php');
  94. expect(languages).toContain('ruby');
  95. expect(languages).toContain('swift');
  96. expect(languages).toContain('kotlin');
  97. expect(languages).toContain('dart');
  98. });
  99. });
  100. describe('TypeScript Extraction', () => {
  101. it('should extract function declarations', () => {
  102. const code = `
  103. export function processPayment(amount: number): Promise<Receipt> {
  104. return stripe.charge(amount);
  105. }
  106. `;
  107. const result = extractFromSource('payment.ts', code);
  108. expect(result.nodes).toHaveLength(1);
  109. expect(result.nodes[0]).toMatchObject({
  110. kind: 'function',
  111. name: 'processPayment',
  112. language: 'typescript',
  113. isExported: true,
  114. });
  115. expect(result.nodes[0]?.signature).toContain('amount: number');
  116. });
  117. it('should extract class declarations', () => {
  118. const code = `
  119. export class PaymentService {
  120. private stripe: StripeClient;
  121. constructor(apiKey: string) {
  122. this.stripe = new StripeClient(apiKey);
  123. }
  124. async charge(amount: number): Promise<Receipt> {
  125. return this.stripe.charge(amount);
  126. }
  127. }
  128. `;
  129. const result = extractFromSource('service.ts', code);
  130. const classNode = result.nodes.find((n) => n.kind === 'class');
  131. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  132. expect(classNode).toBeDefined();
  133. expect(classNode?.name).toBe('PaymentService');
  134. expect(classNode?.isExported).toBe(true);
  135. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  136. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  137. expect(chargeMethod).toBeDefined();
  138. });
  139. it('should extract interfaces', () => {
  140. const code = `
  141. export interface User {
  142. id: string;
  143. name: string;
  144. email: string;
  145. }
  146. `;
  147. const result = extractFromSource('types.ts', code);
  148. expect(result.nodes).toHaveLength(1);
  149. expect(result.nodes[0]).toMatchObject({
  150. kind: 'interface',
  151. name: 'User',
  152. isExported: true,
  153. });
  154. });
  155. it('should track function calls', () => {
  156. const code = `
  157. function main() {
  158. const result = processData();
  159. console.log(result);
  160. }
  161. `;
  162. const result = extractFromSource('main.ts', code);
  163. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  164. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  165. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  166. });
  167. });
  168. describe('Python Extraction', () => {
  169. it('should extract function definitions', () => {
  170. const code = `
  171. def calculate_total(items: list, tax_rate: float) -> float:
  172. """Calculate total with tax."""
  173. subtotal = sum(item.price for item in items)
  174. return subtotal * (1 + tax_rate)
  175. `;
  176. const result = extractFromSource('calc.py', code);
  177. expect(result.nodes).toHaveLength(1);
  178. expect(result.nodes[0]).toMatchObject({
  179. kind: 'function',
  180. name: 'calculate_total',
  181. language: 'python',
  182. });
  183. });
  184. it('should extract class definitions', () => {
  185. const code = `
  186. class UserService:
  187. """Service for managing users."""
  188. def __init__(self, db):
  189. self.db = db
  190. def get_user(self, user_id: str) -> User:
  191. return self.db.find_user(user_id)
  192. `;
  193. const result = extractFromSource('service.py', code);
  194. const classNode = result.nodes.find((n) => n.kind === 'class');
  195. expect(classNode).toBeDefined();
  196. expect(classNode?.name).toBe('UserService');
  197. });
  198. });
  199. describe('Go Extraction', () => {
  200. it('should extract function declarations', () => {
  201. const code = `
  202. package main
  203. func ProcessOrder(order Order) (Receipt, error) {
  204. // Process the order
  205. return Receipt{}, nil
  206. }
  207. `;
  208. const result = extractFromSource('main.go', code);
  209. const funcNode = result.nodes.find((n) => n.kind === 'function');
  210. expect(funcNode).toBeDefined();
  211. expect(funcNode?.name).toBe('ProcessOrder');
  212. });
  213. it('should extract method declarations', () => {
  214. const code = `
  215. package main
  216. type Service struct {
  217. db *Database
  218. }
  219. func (s *Service) GetUser(id string) (*User, error) {
  220. return s.db.FindUser(id)
  221. }
  222. `;
  223. const result = extractFromSource('service.go', code);
  224. const methodNode = result.nodes.find((n) => n.kind === 'method');
  225. expect(methodNode).toBeDefined();
  226. expect(methodNode?.name).toBe('GetUser');
  227. });
  228. });
  229. describe('Rust Extraction', () => {
  230. it('should extract function declarations', () => {
  231. const code = `
  232. pub fn process_data(input: &str) -> Result<Output, Error> {
  233. // Process data
  234. Ok(Output::new())
  235. }
  236. `;
  237. const result = extractFromSource('lib.rs', code);
  238. const funcNode = result.nodes.find((n) => n.kind === 'function');
  239. expect(funcNode).toBeDefined();
  240. expect(funcNode?.name).toBe('process_data');
  241. expect(funcNode?.visibility).toBe('public');
  242. });
  243. it('should extract struct declarations', () => {
  244. const code = `
  245. pub struct User {
  246. pub id: String,
  247. pub name: String,
  248. email: String,
  249. }
  250. `;
  251. const result = extractFromSource('models.rs', code);
  252. const structNode = result.nodes.find((n) => n.kind === 'struct');
  253. expect(structNode).toBeDefined();
  254. expect(structNode?.name).toBe('User');
  255. });
  256. it('should extract trait declarations', () => {
  257. const code = `
  258. pub trait Repository {
  259. fn find(&self, id: &str) -> Option<Entity>;
  260. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  261. }
  262. `;
  263. const result = extractFromSource('traits.rs', code);
  264. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  265. expect(traitNode).toBeDefined();
  266. expect(traitNode?.name).toBe('Repository');
  267. });
  268. });
  269. describe('Java Extraction', () => {
  270. it('should extract class declarations', () => {
  271. const code = `
  272. public class UserService {
  273. private final UserRepository repository;
  274. public UserService(UserRepository repository) {
  275. this.repository = repository;
  276. }
  277. public User getUser(String id) {
  278. return repository.findById(id);
  279. }
  280. }
  281. `;
  282. const result = extractFromSource('UserService.java', code);
  283. const classNode = result.nodes.find((n) => n.kind === 'class');
  284. expect(classNode).toBeDefined();
  285. expect(classNode?.name).toBe('UserService');
  286. expect(classNode?.visibility).toBe('public');
  287. });
  288. it('should extract method declarations', () => {
  289. const code = `
  290. public class Calculator {
  291. public static int add(int a, int b) {
  292. return a + b;
  293. }
  294. }
  295. `;
  296. const result = extractFromSource('Calculator.java', code);
  297. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  298. expect(methodNode).toBeDefined();
  299. expect(methodNode?.isStatic).toBe(true);
  300. });
  301. });
  302. describe('C# Extraction', () => {
  303. it('should extract class declarations', () => {
  304. const code = `
  305. public class OrderService
  306. {
  307. private readonly IOrderRepository _repository;
  308. public OrderService(IOrderRepository repository)
  309. {
  310. _repository = repository;
  311. }
  312. public async Task<Order> GetOrderAsync(string id)
  313. {
  314. return await _repository.FindByIdAsync(id);
  315. }
  316. }
  317. `;
  318. const result = extractFromSource('OrderService.cs', code);
  319. const classNode = result.nodes.find((n) => n.kind === 'class');
  320. expect(classNode).toBeDefined();
  321. expect(classNode?.name).toBe('OrderService');
  322. expect(classNode?.visibility).toBe('public');
  323. });
  324. });
  325. describe('PHP Extraction', () => {
  326. it('should extract class declarations', () => {
  327. const code = `<?php
  328. class UserController
  329. {
  330. private UserService $userService;
  331. public function __construct(UserService $userService)
  332. {
  333. $this->userService = $userService;
  334. }
  335. public function show(string $id): User
  336. {
  337. return $this->userService->find($id);
  338. }
  339. }
  340. `;
  341. const result = extractFromSource('UserController.php', code);
  342. const classNode = result.nodes.find((n) => n.kind === 'class');
  343. expect(classNode).toBeDefined();
  344. expect(classNode?.name).toBe('UserController');
  345. });
  346. });
  347. describe('Swift Extraction', () => {
  348. it('should extract class declarations', () => {
  349. const code = `
  350. public class NetworkManager {
  351. private let session: URLSession
  352. public init(session: URLSession = .shared) {
  353. self.session = session
  354. }
  355. public func fetchData(from url: URL) async throws -> Data {
  356. let (data, _) = try await session.data(from: url)
  357. return data
  358. }
  359. }
  360. `;
  361. const result = extractFromSource('NetworkManager.swift', code);
  362. const classNode = result.nodes.find((n) => n.kind === 'class');
  363. expect(classNode).toBeDefined();
  364. expect(classNode?.name).toBe('NetworkManager');
  365. });
  366. it('should extract function declarations', () => {
  367. const code = `
  368. func calculateSum(_ numbers: [Int]) -> Int {
  369. return numbers.reduce(0, +)
  370. }
  371. public func formatCurrency(amount: Double) -> String {
  372. return String(format: "$%.2f", amount)
  373. }
  374. `;
  375. const result = extractFromSource('utils.swift', code);
  376. const functions = result.nodes.filter((n) => n.kind === 'function');
  377. expect(functions.length).toBeGreaterThanOrEqual(1);
  378. });
  379. it('should extract struct declarations', () => {
  380. const code = `
  381. public struct User {
  382. let id: UUID
  383. var name: String
  384. var email: String
  385. func displayName() -> String {
  386. return name
  387. }
  388. }
  389. `;
  390. const result = extractFromSource('User.swift', code);
  391. const structNode = result.nodes.find((n) => n.kind === 'struct');
  392. expect(structNode).toBeDefined();
  393. expect(structNode?.name).toBe('User');
  394. });
  395. it('should extract protocol declarations', () => {
  396. const code = `
  397. public protocol Repository {
  398. associatedtype Entity
  399. func find(id: String) async throws -> Entity?
  400. func save(_ entity: Entity) async throws
  401. }
  402. `;
  403. const result = extractFromSource('Repository.swift', code);
  404. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  405. expect(protocolNode).toBeDefined();
  406. expect(protocolNode?.name).toBe('Repository');
  407. });
  408. });
  409. describe('Kotlin Extraction', () => {
  410. it('should extract class declarations', () => {
  411. const code = `
  412. class UserRepository(private val database: Database) {
  413. fun findById(id: String): User? {
  414. return database.query("SELECT * FROM users WHERE id = ?", id)
  415. }
  416. suspend fun save(user: User) {
  417. database.insert(user)
  418. }
  419. }
  420. `;
  421. const result = extractFromSource('UserRepository.kt', code);
  422. const classNode = result.nodes.find((n) => n.kind === 'class');
  423. expect(classNode).toBeDefined();
  424. expect(classNode?.name).toBe('UserRepository');
  425. });
  426. it('should extract function declarations', () => {
  427. const code = `
  428. fun calculateTotal(items: List<Item>): Double {
  429. return items.sumOf { it.price }
  430. }
  431. suspend fun fetchUserData(userId: String): User {
  432. return api.getUser(userId)
  433. }
  434. `;
  435. const result = extractFromSource('utils.kt', code);
  436. const functions = result.nodes.filter((n) => n.kind === 'function');
  437. expect(functions.length).toBeGreaterThanOrEqual(1);
  438. });
  439. it('should detect suspend functions as async', () => {
  440. const code = `
  441. suspend fun loadData(): List<String> {
  442. delay(1000)
  443. return listOf("a", "b", "c")
  444. }
  445. `;
  446. const result = extractFromSource('loader.kt', code);
  447. const funcNode = result.nodes.find((n) => n.kind === 'function');
  448. expect(funcNode).toBeDefined();
  449. expect(funcNode?.isAsync).toBe(true);
  450. });
  451. });
  452. describe('Dart Extraction', () => {
  453. it('should extract class declarations', () => {
  454. const code = `
  455. class UserService {
  456. final Database _db;
  457. Future<User> findById(String id) async {
  458. return await _db.query(id);
  459. }
  460. void _privateMethod() {}
  461. }
  462. `;
  463. const result = extractFromSource('service.dart', code);
  464. const classNode = result.nodes.find((n) => n.kind === 'class');
  465. expect(classNode).toBeDefined();
  466. expect(classNode?.name).toBe('UserService');
  467. expect(classNode?.visibility).toBe('public');
  468. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  469. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  470. const findById = methodNodes.find((m) => m.name === 'findById');
  471. expect(findById).toBeDefined();
  472. expect(findById?.isAsync).toBe(true);
  473. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  474. expect(privateMethod).toBeDefined();
  475. expect(privateMethod?.visibility).toBe('private');
  476. });
  477. it('should extract top-level function declarations', () => {
  478. const code = `
  479. void topLevelFunction(String name) {
  480. print(name);
  481. }
  482. `;
  483. const result = extractFromSource('utils.dart', code);
  484. const funcNode = result.nodes.find((n) => n.kind === 'function');
  485. expect(funcNode).toBeDefined();
  486. expect(funcNode?.name).toBe('topLevelFunction');
  487. expect(funcNode?.language).toBe('dart');
  488. });
  489. it('should extract enum declarations', () => {
  490. const code = `
  491. enum Status { active, inactive, pending }
  492. `;
  493. const result = extractFromSource('models.dart', code);
  494. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  495. expect(enumNode).toBeDefined();
  496. expect(enumNode?.name).toBe('Status');
  497. });
  498. it('should extract mixin declarations', () => {
  499. const code = `
  500. mixin LoggerMixin {
  501. void log(String message) {}
  502. }
  503. `;
  504. const result = extractFromSource('mixins.dart', code);
  505. const classNode = result.nodes.find((n) => n.kind === 'class');
  506. expect(classNode).toBeDefined();
  507. expect(classNode?.name).toBe('LoggerMixin');
  508. const methodNode = result.nodes.find((n) => n.kind === 'method');
  509. expect(methodNode).toBeDefined();
  510. expect(methodNode?.name).toBe('log');
  511. });
  512. it('should extract extension declarations', () => {
  513. const code = `
  514. extension StringExt on String {
  515. bool get isBlank => trim().isEmpty;
  516. }
  517. `;
  518. const result = extractFromSource('extensions.dart', code);
  519. const classNode = result.nodes.find((n) => n.kind === 'class');
  520. expect(classNode).toBeDefined();
  521. expect(classNode?.name).toBe('StringExt');
  522. });
  523. it('should detect static methods', () => {
  524. const code = `
  525. class Utils {
  526. static void doWork() {}
  527. }
  528. `;
  529. const result = extractFromSource('utils.dart', code);
  530. const methodNode = result.nodes.find((n) => n.kind === 'method');
  531. expect(methodNode).toBeDefined();
  532. expect(methodNode?.name).toBe('doWork');
  533. expect(methodNode?.isStatic).toBe(true);
  534. });
  535. it('should detect async functions', () => {
  536. const code = `
  537. Future<String> fetchData() async {
  538. return await http.get('/data');
  539. }
  540. `;
  541. const result = extractFromSource('api.dart', code);
  542. const funcNode = result.nodes.find((n) => n.kind === 'function');
  543. expect(funcNode).toBeDefined();
  544. expect(funcNode?.name).toBe('fetchData');
  545. expect(funcNode?.isAsync).toBe(true);
  546. });
  547. it('should detect private visibility via underscore convention', () => {
  548. const code = `
  549. void _privateHelper() {}
  550. void publicFunction() {}
  551. `;
  552. const result = extractFromSource('helpers.dart', code);
  553. const functions = result.nodes.filter((n) => n.kind === 'function');
  554. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  555. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  556. expect(privateFunc?.visibility).toBe('private');
  557. expect(publicFunc?.visibility).toBe('public');
  558. });
  559. });
  560. describe('Import Extraction', () => {
  561. describe('TypeScript/JavaScript imports', () => {
  562. it('should extract default imports', () => {
  563. const code = `import React from 'react';`;
  564. const result = extractFromSource('app.tsx', code);
  565. const importNode = result.nodes.find((n) => n.kind === 'import');
  566. expect(importNode).toBeDefined();
  567. expect(importNode?.name).toBe('react');
  568. expect(importNode?.signature).toBe("import React from 'react';");
  569. });
  570. it('should extract named imports', () => {
  571. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  572. const result = extractFromSource('icons.tsx', code);
  573. const importNode = result.nodes.find((n) => n.kind === 'import');
  574. expect(importNode).toBeDefined();
  575. expect(importNode?.name).toBe('@phosphor-icons/react');
  576. expect(importNode?.signature).toContain('Bug');
  577. expect(importNode?.signature).toContain('Database');
  578. });
  579. it('should extract namespace imports', () => {
  580. const code = `import * as Icons from '@phosphor-icons/react';`;
  581. const result = extractFromSource('icons.tsx', code);
  582. const importNode = result.nodes.find((n) => n.kind === 'import');
  583. expect(importNode).toBeDefined();
  584. expect(importNode?.name).toBe('@phosphor-icons/react');
  585. expect(importNode?.signature).toContain('* as Icons');
  586. });
  587. it('should extract side-effect imports', () => {
  588. const code = `import './styles.css';`;
  589. const result = extractFromSource('app.tsx', code);
  590. const importNode = result.nodes.find((n) => n.kind === 'import');
  591. expect(importNode).toBeDefined();
  592. expect(importNode?.name).toBe('./styles.css');
  593. });
  594. it('should extract mixed imports (default + named)', () => {
  595. const code = `import React, { useState, useEffect } from 'react';`;
  596. const result = extractFromSource('app.tsx', code);
  597. const importNode = result.nodes.find((n) => n.kind === 'import');
  598. expect(importNode).toBeDefined();
  599. expect(importNode?.name).toBe('react');
  600. expect(importNode?.signature).toContain('React');
  601. expect(importNode?.signature).toContain('useState');
  602. expect(importNode?.signature).toContain('useEffect');
  603. });
  604. it('should extract multiple import statements', () => {
  605. const code = `
  606. import React from 'react';
  607. import { Button } from './components';
  608. import './styles.css';
  609. `;
  610. const result = extractFromSource('app.tsx', code);
  611. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  612. expect(importNodes.length).toBe(3);
  613. const names = importNodes.map((n) => n.name);
  614. expect(names).toContain('react');
  615. expect(names).toContain('./components');
  616. expect(names).toContain('./styles.css');
  617. });
  618. it('should extract type imports', () => {
  619. const code = `import type { FC, ReactNode } from 'react';`;
  620. const result = extractFromSource('types.ts', code);
  621. const importNode = result.nodes.find((n) => n.kind === 'import');
  622. expect(importNode).toBeDefined();
  623. expect(importNode?.name).toBe('react');
  624. expect(importNode?.signature).toContain('type');
  625. expect(importNode?.signature).toContain('FC');
  626. });
  627. it('should extract aliased named imports', () => {
  628. const code = `import { useState as useStateAlias } from 'react';`;
  629. const result = extractFromSource('hooks.ts', code);
  630. const importNode = result.nodes.find((n) => n.kind === 'import');
  631. expect(importNode).toBeDefined();
  632. expect(importNode?.name).toBe('react');
  633. expect(importNode?.signature).toContain('useState');
  634. expect(importNode?.signature).toContain('useStateAlias');
  635. });
  636. it('should extract relative path imports', () => {
  637. const code = `import { helper } from '../utils/helper';`;
  638. const result = extractFromSource('components/Button.tsx', code);
  639. const importNode = result.nodes.find((n) => n.kind === 'import');
  640. expect(importNode).toBeDefined();
  641. expect(importNode?.name).toBe('../utils/helper');
  642. expect(importNode?.signature).toContain('helper');
  643. });
  644. });
  645. describe('Python imports', () => {
  646. it('should extract simple import statement', () => {
  647. const code = `import json`;
  648. const result = extractFromSource('utils.py', code);
  649. const importNode = result.nodes.find((n) => n.kind === 'import');
  650. expect(importNode).toBeDefined();
  651. expect(importNode?.name).toBe('json');
  652. });
  653. it('should extract from import statement', () => {
  654. const code = `from os import path`;
  655. const result = extractFromSource('utils.py', code);
  656. const importNode = result.nodes.find((n) => n.kind === 'import');
  657. expect(importNode).toBeDefined();
  658. expect(importNode?.name).toBe('os');
  659. expect(importNode?.signature).toContain('path');
  660. });
  661. it('should extract multiple imports from same module', () => {
  662. const code = `from typing import List, Dict, Optional`;
  663. const result = extractFromSource('types.py', code);
  664. const importNode = result.nodes.find((n) => n.kind === 'import');
  665. expect(importNode).toBeDefined();
  666. expect(importNode?.name).toBe('typing');
  667. expect(importNode?.signature).toContain('List');
  668. expect(importNode?.signature).toContain('Dict');
  669. });
  670. it('should extract multiple import statements', () => {
  671. const code = `
  672. import os
  673. import sys
  674. `;
  675. const result = extractFromSource('main.py', code);
  676. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  677. expect(importNodes.length).toBe(2);
  678. const names = importNodes.map((n) => n.name);
  679. expect(names).toContain('os');
  680. expect(names).toContain('sys');
  681. });
  682. it('should extract aliased import', () => {
  683. const code = `import numpy as np`;
  684. const result = extractFromSource('data.py', code);
  685. const importNode = result.nodes.find((n) => n.kind === 'import');
  686. expect(importNode).toBeDefined();
  687. expect(importNode?.name).toBe('numpy');
  688. expect(importNode?.signature).toContain('as np');
  689. });
  690. it('should extract relative import', () => {
  691. const code = `from .utils import helper`;
  692. const result = extractFromSource('module.py', code);
  693. const importNode = result.nodes.find((n) => n.kind === 'import');
  694. expect(importNode).toBeDefined();
  695. expect(importNode?.name).toBe('.utils');
  696. expect(importNode?.signature).toContain('helper');
  697. });
  698. it('should extract wildcard import', () => {
  699. const code = `from typing import *`;
  700. const result = extractFromSource('types.py', code);
  701. const importNode = result.nodes.find((n) => n.kind === 'import');
  702. expect(importNode).toBeDefined();
  703. expect(importNode?.name).toBe('typing');
  704. expect(importNode?.signature).toContain('*');
  705. });
  706. });
  707. describe('Rust imports', () => {
  708. it('should extract simple use declaration', () => {
  709. const code = `use std::io;`;
  710. const result = extractFromSource('main.rs', code);
  711. const importNode = result.nodes.find((n) => n.kind === 'import');
  712. expect(importNode).toBeDefined();
  713. expect(importNode?.name).toBe('std');
  714. expect(importNode?.signature).toBe('use std::io;');
  715. });
  716. it('should extract scoped use list', () => {
  717. const code = `use std::{ffi::OsStr, io, path::Path};`;
  718. const result = extractFromSource('main.rs', code);
  719. const importNode = result.nodes.find((n) => n.kind === 'import');
  720. expect(importNode).toBeDefined();
  721. expect(importNode?.name).toBe('std');
  722. expect(importNode?.signature).toContain('ffi::OsStr');
  723. expect(importNode?.signature).toContain('path::Path');
  724. });
  725. it('should extract crate imports', () => {
  726. const code = `use crate::error::Error;`;
  727. const result = extractFromSource('lib.rs', code);
  728. const importNode = result.nodes.find((n) => n.kind === 'import');
  729. expect(importNode).toBeDefined();
  730. expect(importNode?.name).toBe('crate');
  731. });
  732. it('should extract super imports', () => {
  733. const code = `use super::utils;`;
  734. const result = extractFromSource('submod.rs', code);
  735. const importNode = result.nodes.find((n) => n.kind === 'import');
  736. expect(importNode).toBeDefined();
  737. expect(importNode?.name).toBe('super');
  738. });
  739. it('should extract external crate imports', () => {
  740. const code = `use serde::{Serialize, Deserialize};`;
  741. const result = extractFromSource('types.rs', code);
  742. const importNode = result.nodes.find((n) => n.kind === 'import');
  743. expect(importNode).toBeDefined();
  744. expect(importNode?.name).toBe('serde');
  745. expect(importNode?.signature).toContain('Serialize');
  746. expect(importNode?.signature).toContain('Deserialize');
  747. });
  748. });
  749. describe('Go imports', () => {
  750. it('should extract single import', () => {
  751. const code = `
  752. package main
  753. import "fmt"
  754. `;
  755. const result = extractFromSource('main.go', code);
  756. const importNode = result.nodes.find((n) => n.kind === 'import');
  757. expect(importNode).toBeDefined();
  758. expect(importNode?.name).toBe('fmt');
  759. });
  760. it('should extract grouped imports', () => {
  761. const code = `
  762. package main
  763. import (
  764. "fmt"
  765. "os"
  766. "encoding/json"
  767. )
  768. `;
  769. const result = extractFromSource('main.go', code);
  770. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  771. expect(importNodes.length).toBe(3);
  772. const names = importNodes.map((n) => n.name);
  773. expect(names).toContain('fmt');
  774. expect(names).toContain('os');
  775. expect(names).toContain('encoding/json');
  776. });
  777. it('should extract aliased import', () => {
  778. const code = `
  779. package main
  780. import f "fmt"
  781. `;
  782. const result = extractFromSource('main.go', code);
  783. const importNode = result.nodes.find((n) => n.kind === 'import');
  784. expect(importNode).toBeDefined();
  785. expect(importNode?.name).toBe('fmt');
  786. expect(importNode?.signature).toContain('f');
  787. });
  788. it('should extract dot import', () => {
  789. const code = `
  790. package main
  791. import . "math"
  792. `;
  793. const result = extractFromSource('main.go', code);
  794. const importNode = result.nodes.find((n) => n.kind === 'import');
  795. expect(importNode).toBeDefined();
  796. expect(importNode?.name).toBe('math');
  797. expect(importNode?.signature).toContain('.');
  798. });
  799. it('should extract blank import', () => {
  800. const code = `
  801. package main
  802. import _ "github.com/go-sql-driver/mysql"
  803. `;
  804. const result = extractFromSource('main.go', code);
  805. const importNode = result.nodes.find((n) => n.kind === 'import');
  806. expect(importNode).toBeDefined();
  807. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  808. expect(importNode?.signature).toContain('_');
  809. });
  810. });
  811. describe('Swift imports', () => {
  812. it('should extract simple import', () => {
  813. const code = `import Foundation`;
  814. const result = extractFromSource('main.swift', code);
  815. const importNode = result.nodes.find((n) => n.kind === 'import');
  816. expect(importNode).toBeDefined();
  817. expect(importNode?.name).toBe('Foundation');
  818. expect(importNode?.signature).toBe('import Foundation');
  819. });
  820. it('should extract @testable import', () => {
  821. const code = `@testable import Alamofire`;
  822. const result = extractFromSource('Tests.swift', code);
  823. const importNode = result.nodes.find((n) => n.kind === 'import');
  824. expect(importNode).toBeDefined();
  825. expect(importNode?.name).toBe('Alamofire');
  826. expect(importNode?.signature).toContain('@testable');
  827. });
  828. it('should extract @preconcurrency import', () => {
  829. const code = `@preconcurrency import Security`;
  830. const result = extractFromSource('Auth.swift', code);
  831. const importNode = result.nodes.find((n) => n.kind === 'import');
  832. expect(importNode).toBeDefined();
  833. expect(importNode?.name).toBe('Security');
  834. });
  835. it('should extract multiple imports', () => {
  836. const code = `
  837. import Foundation
  838. import UIKit
  839. import Alamofire
  840. `;
  841. const result = extractFromSource('App.swift', code);
  842. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  843. expect(importNodes.length).toBe(3);
  844. const names = importNodes.map((n) => n.name);
  845. expect(names).toContain('Foundation');
  846. expect(names).toContain('UIKit');
  847. expect(names).toContain('Alamofire');
  848. });
  849. });
  850. describe('Kotlin imports', () => {
  851. it('should extract simple import', () => {
  852. const code = `import java.io.IOException`;
  853. const result = extractFromSource('Main.kt', code);
  854. const importNode = result.nodes.find((n) => n.kind === 'import');
  855. expect(importNode).toBeDefined();
  856. expect(importNode?.name).toBe('java.io.IOException');
  857. expect(importNode?.signature).toBe('import java.io.IOException');
  858. });
  859. it('should extract aliased import', () => {
  860. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  861. const result = extractFromSource('Utils.kt', code);
  862. const importNode = result.nodes.find((n) => n.kind === 'import');
  863. expect(importNode).toBeDefined();
  864. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  865. expect(importNode?.signature).toContain('as RequestBuilder');
  866. });
  867. it('should extract wildcard import', () => {
  868. const code = `import java.util.concurrent.TimeUnit.*`;
  869. const result = extractFromSource('Time.kt', code);
  870. const importNode = result.nodes.find((n) => n.kind === 'import');
  871. expect(importNode).toBeDefined();
  872. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  873. expect(importNode?.signature).toContain('.*');
  874. });
  875. it('should extract multiple imports', () => {
  876. const code = `
  877. import java.io.IOException
  878. import kotlin.test.assertFailsWith
  879. import okhttp3.OkHttpClient
  880. `;
  881. const result = extractFromSource('Test.kt', code);
  882. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  883. expect(importNodes.length).toBe(3);
  884. const names = importNodes.map((n) => n.name);
  885. expect(names).toContain('java.io.IOException');
  886. expect(names).toContain('kotlin.test.assertFailsWith');
  887. expect(names).toContain('okhttp3.OkHttpClient');
  888. });
  889. });
  890. describe('Java imports', () => {
  891. it('should extract simple import', () => {
  892. const code = `import java.util.List;`;
  893. const result = extractFromSource('Main.java', code);
  894. const importNode = result.nodes.find((n) => n.kind === 'import');
  895. expect(importNode).toBeDefined();
  896. expect(importNode?.name).toBe('java.util.List');
  897. expect(importNode?.signature).toBe('import java.util.List;');
  898. });
  899. it('should extract static import', () => {
  900. const code = `import static java.util.Collections.emptyList;`;
  901. const result = extractFromSource('Utils.java', code);
  902. const importNode = result.nodes.find((n) => n.kind === 'import');
  903. expect(importNode).toBeDefined();
  904. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  905. expect(importNode?.signature).toContain('static');
  906. });
  907. it('should extract wildcard import', () => {
  908. const code = `import java.util.*;`;
  909. const result = extractFromSource('App.java', code);
  910. const importNode = result.nodes.find((n) => n.kind === 'import');
  911. expect(importNode).toBeDefined();
  912. expect(importNode?.name).toBe('java.util');
  913. expect(importNode?.signature).toContain('.*');
  914. });
  915. it('should extract nested class import', () => {
  916. const code = `import java.util.Map.Entry;`;
  917. const result = extractFromSource('MapUtil.java', code);
  918. const importNode = result.nodes.find((n) => n.kind === 'import');
  919. expect(importNode).toBeDefined();
  920. expect(importNode?.name).toBe('java.util.Map.Entry');
  921. });
  922. it('should extract multiple imports', () => {
  923. const code = `
  924. import java.util.List;
  925. import java.util.Map;
  926. import java.io.IOException;
  927. `;
  928. const result = extractFromSource('Service.java', code);
  929. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  930. expect(importNodes.length).toBe(3);
  931. const names = importNodes.map((n) => n.name);
  932. expect(names).toContain('java.util.List');
  933. expect(names).toContain('java.util.Map');
  934. expect(names).toContain('java.io.IOException');
  935. });
  936. });
  937. describe('C# imports', () => {
  938. it('should extract simple using', () => {
  939. const code = `using System;`;
  940. const result = extractFromSource('Program.cs', code);
  941. const importNode = result.nodes.find((n) => n.kind === 'import');
  942. expect(importNode).toBeDefined();
  943. expect(importNode?.name).toBe('System');
  944. expect(importNode?.signature).toBe('using System;');
  945. });
  946. it('should extract qualified using', () => {
  947. const code = `using System.Collections.Generic;`;
  948. const result = extractFromSource('Utils.cs', code);
  949. const importNode = result.nodes.find((n) => n.kind === 'import');
  950. expect(importNode).toBeDefined();
  951. expect(importNode?.name).toBe('System.Collections.Generic');
  952. });
  953. it('should extract static using', () => {
  954. const code = `using static System.Console;`;
  955. const result = extractFromSource('App.cs', code);
  956. const importNode = result.nodes.find((n) => n.kind === 'import');
  957. expect(importNode).toBeDefined();
  958. expect(importNode?.name).toBe('System.Console');
  959. expect(importNode?.signature).toContain('static');
  960. });
  961. it('should extract alias using', () => {
  962. const code = `using MyList = System.Collections.Generic.List<int>;`;
  963. const result = extractFromSource('Types.cs', code);
  964. const importNode = result.nodes.find((n) => n.kind === 'import');
  965. expect(importNode).toBeDefined();
  966. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  967. expect(importNode?.signature).toContain('MyList =');
  968. });
  969. it('should extract multiple usings', () => {
  970. const code = `
  971. using System;
  972. using System.Threading.Tasks;
  973. using Microsoft.Extensions.DependencyInjection;
  974. `;
  975. const result = extractFromSource('Service.cs', code);
  976. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  977. expect(importNodes.length).toBe(3);
  978. const names = importNodes.map((n) => n.name);
  979. expect(names).toContain('System');
  980. expect(names).toContain('System.Threading.Tasks');
  981. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  982. });
  983. });
  984. describe('PHP imports', () => {
  985. it('should extract simple use', () => {
  986. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  987. const result = extractFromSource('Test.php', code);
  988. const importNode = result.nodes.find((n) => n.kind === 'import');
  989. expect(importNode).toBeDefined();
  990. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  991. });
  992. it('should extract aliased use', () => {
  993. const code = `<?php use Mockery as m;`;
  994. const result = extractFromSource('Test.php', code);
  995. const importNode = result.nodes.find((n) => n.kind === 'import');
  996. expect(importNode).toBeDefined();
  997. expect(importNode?.name).toBe('Mockery');
  998. expect(importNode?.signature).toContain('as m');
  999. });
  1000. it('should extract function use', () => {
  1001. const code = `<?php use function Illuminate\\Support\\env;`;
  1002. const result = extractFromSource('helpers.php', code);
  1003. const importNode = result.nodes.find((n) => n.kind === 'import');
  1004. expect(importNode).toBeDefined();
  1005. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1006. expect(importNode?.signature).toContain('function');
  1007. });
  1008. it('should extract grouped use', () => {
  1009. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1010. const result = extractFromSource('Models.php', code);
  1011. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1012. expect(importNodes.length).toBe(2);
  1013. const names = importNodes.map((n) => n.name);
  1014. expect(names).toContain('Illuminate\\Database\\Model');
  1015. expect(names).toContain('Illuminate\\Database\\Builder');
  1016. });
  1017. it('should extract multiple uses', () => {
  1018. const code = `<?php
  1019. use Illuminate\\Support\\Collection;
  1020. use Illuminate\\Support\\Str;
  1021. use Closure;
  1022. `;
  1023. const result = extractFromSource('Service.php', code);
  1024. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1025. expect(importNodes.length).toBe(3);
  1026. const names = importNodes.map((n) => n.name);
  1027. expect(names).toContain('Illuminate\\Support\\Collection');
  1028. expect(names).toContain('Illuminate\\Support\\Str');
  1029. expect(names).toContain('Closure');
  1030. });
  1031. });
  1032. describe('Ruby imports', () => {
  1033. it('should extract require', () => {
  1034. const code = `require 'json'`;
  1035. const result = extractFromSource('app.rb', code);
  1036. const importNode = result.nodes.find((n) => n.kind === 'import');
  1037. expect(importNode).toBeDefined();
  1038. expect(importNode?.name).toBe('json');
  1039. expect(importNode?.signature).toBe("require 'json'");
  1040. });
  1041. it('should extract require with path', () => {
  1042. const code = `require 'active_support/core_ext/string'`;
  1043. const result = extractFromSource('config.rb', code);
  1044. const importNode = result.nodes.find((n) => n.kind === 'import');
  1045. expect(importNode).toBeDefined();
  1046. expect(importNode?.name).toBe('active_support/core_ext/string');
  1047. });
  1048. it('should extract require_relative', () => {
  1049. const code = `require_relative '../test_helper'`;
  1050. const result = extractFromSource('test/my_test.rb', code);
  1051. const importNode = result.nodes.find((n) => n.kind === 'import');
  1052. expect(importNode).toBeDefined();
  1053. expect(importNode?.name).toBe('../test_helper');
  1054. expect(importNode?.signature).toContain('require_relative');
  1055. });
  1056. it('should not extract non-require calls', () => {
  1057. const code = `puts 'hello'`;
  1058. const result = extractFromSource('app.rb', code);
  1059. const importNode = result.nodes.find((n) => n.kind === 'import');
  1060. expect(importNode).toBeUndefined();
  1061. });
  1062. it('should extract multiple requires', () => {
  1063. const code = `
  1064. require 'json'
  1065. require 'yaml'
  1066. require_relative 'helper'
  1067. `;
  1068. const result = extractFromSource('lib.rb', code);
  1069. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1070. expect(importNodes.length).toBe(3);
  1071. const names = importNodes.map((n) => n.name);
  1072. expect(names).toContain('json');
  1073. expect(names).toContain('yaml');
  1074. expect(names).toContain('helper');
  1075. });
  1076. });
  1077. describe('C/C++ imports', () => {
  1078. it('should extract system include', () => {
  1079. const code = `#include <iostream>`;
  1080. const result = extractFromSource('main.cpp', code);
  1081. const importNode = result.nodes.find((n) => n.kind === 'import');
  1082. expect(importNode).toBeDefined();
  1083. expect(importNode?.name).toBe('iostream');
  1084. expect(importNode?.signature).toBe('#include <iostream>');
  1085. });
  1086. it('should extract system include with path', () => {
  1087. const code = `#include <nlohmann/json.hpp>`;
  1088. const result = extractFromSource('app.cpp', code);
  1089. const importNode = result.nodes.find((n) => n.kind === 'import');
  1090. expect(importNode).toBeDefined();
  1091. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1092. });
  1093. it('should extract local include', () => {
  1094. const code = `#include "myheader.h"`;
  1095. const result = extractFromSource('main.cpp', code);
  1096. const importNode = result.nodes.find((n) => n.kind === 'import');
  1097. expect(importNode).toBeDefined();
  1098. expect(importNode?.name).toBe('myheader.h');
  1099. });
  1100. it('should extract C header', () => {
  1101. const code = `#include <stdio.h>`;
  1102. const result = extractFromSource('main.c', code);
  1103. const importNode = result.nodes.find((n) => n.kind === 'import');
  1104. expect(importNode).toBeDefined();
  1105. expect(importNode?.name).toBe('stdio.h');
  1106. });
  1107. it('should extract multiple includes', () => {
  1108. const code = `
  1109. #include <iostream>
  1110. #include <vector>
  1111. #include "config.h"
  1112. `;
  1113. const result = extractFromSource('app.cpp', code);
  1114. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1115. expect(importNodes.length).toBe(3);
  1116. const names = importNodes.map((n) => n.name);
  1117. expect(names).toContain('iostream');
  1118. expect(names).toContain('vector');
  1119. expect(names).toContain('config.h');
  1120. });
  1121. });
  1122. describe('Dart imports', () => {
  1123. it('should extract dart: import', () => {
  1124. const code = `import 'dart:async';`;
  1125. const result = extractFromSource('main.dart', code);
  1126. const importNode = result.nodes.find((n) => n.kind === 'import');
  1127. expect(importNode).toBeDefined();
  1128. expect(importNode?.name).toBe('dart:async');
  1129. expect(importNode?.signature).toBe("import 'dart:async';");
  1130. });
  1131. it('should extract package import', () => {
  1132. const code = `import 'package:flutter/material.dart';`;
  1133. const result = extractFromSource('app.dart', code);
  1134. const importNode = result.nodes.find((n) => n.kind === 'import');
  1135. expect(importNode).toBeDefined();
  1136. expect(importNode?.name).toBe('package:flutter/material.dart');
  1137. });
  1138. it('should extract aliased import', () => {
  1139. const code = `import 'package:http/http.dart' as http;`;
  1140. const result = extractFromSource('api.dart', code);
  1141. const importNode = result.nodes.find((n) => n.kind === 'import');
  1142. expect(importNode).toBeDefined();
  1143. expect(importNode?.name).toBe('package:http/http.dart');
  1144. expect(importNode?.signature).toContain('as http');
  1145. });
  1146. it('should extract multiple imports', () => {
  1147. const code = `
  1148. import 'dart:async';
  1149. import 'dart:convert';
  1150. import 'package:flutter/material.dart';
  1151. `;
  1152. const result = extractFromSource('main.dart', code);
  1153. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1154. expect(importNodes.length).toBe(3);
  1155. const names = importNodes.map((n) => n.name);
  1156. expect(names).toContain('dart:async');
  1157. expect(names).toContain('dart:convert');
  1158. expect(names).toContain('package:flutter/material.dart');
  1159. });
  1160. it('should extract relative import', () => {
  1161. const code = `import '../utils/helpers.dart';`;
  1162. const result = extractFromSource('lib/main.dart', code);
  1163. const importNode = result.nodes.find((n) => n.kind === 'import');
  1164. expect(importNode).toBeDefined();
  1165. expect(importNode?.name).toBe('../utils/helpers.dart');
  1166. });
  1167. });
  1168. describe('Liquid imports', () => {
  1169. it('should extract render tag', () => {
  1170. const code = `{% render 'loading-spinner' %}`;
  1171. const result = extractFromSource('template.liquid', code);
  1172. const importNode = result.nodes.find((n) => n.kind === 'import');
  1173. expect(importNode).toBeDefined();
  1174. expect(importNode?.name).toBe('loading-spinner');
  1175. expect(importNode?.signature).toContain('render');
  1176. });
  1177. it('should extract section tag', () => {
  1178. const code = `{% section 'header' %}`;
  1179. const result = extractFromSource('layout/theme.liquid', code);
  1180. const importNode = result.nodes.find((n) => n.kind === 'import');
  1181. expect(importNode).toBeDefined();
  1182. expect(importNode?.name).toBe('header');
  1183. expect(importNode?.signature).toContain('section');
  1184. });
  1185. it('should extract include tag', () => {
  1186. const code = `{% include 'icon-cart' %}`;
  1187. const result = extractFromSource('snippets/header.liquid', code);
  1188. const importNode = result.nodes.find((n) => n.kind === 'import');
  1189. expect(importNode).toBeDefined();
  1190. expect(importNode?.name).toBe('icon-cart');
  1191. expect(importNode?.signature).toContain('include');
  1192. });
  1193. it('should extract render with whitespace control', () => {
  1194. const code = `{%- render 'price' -%}`;
  1195. const result = extractFromSource('snippets/product.liquid', code);
  1196. const importNode = result.nodes.find((n) => n.kind === 'import');
  1197. expect(importNode).toBeDefined();
  1198. expect(importNode?.name).toBe('price');
  1199. });
  1200. it('should extract multiple imports', () => {
  1201. const code = `
  1202. {% section 'header' %}
  1203. {% render 'loading-spinner' %}
  1204. {% render 'cart-drawer' %}
  1205. `;
  1206. const result = extractFromSource('layout/theme.liquid', code);
  1207. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1208. expect(importNodes.length).toBe(3);
  1209. const names = importNodes.map((n) => n.name);
  1210. expect(names).toContain('header');
  1211. expect(names).toContain('loading-spinner');
  1212. expect(names).toContain('cart-drawer');
  1213. });
  1214. });
  1215. });
  1216. describe('Full Indexing', () => {
  1217. let tempDir: string;
  1218. beforeEach(() => {
  1219. tempDir = createTempDir();
  1220. });
  1221. afterEach(() => {
  1222. cleanupTempDir(tempDir);
  1223. });
  1224. it('should index a TypeScript file', async () => {
  1225. // Create test file
  1226. const srcDir = path.join(tempDir, 'src');
  1227. fs.mkdirSync(srcDir);
  1228. fs.writeFileSync(
  1229. path.join(srcDir, 'utils.ts'),
  1230. `
  1231. export function add(a: number, b: number): number {
  1232. return a + b;
  1233. }
  1234. export function multiply(a: number, b: number): number {
  1235. return a * b;
  1236. }
  1237. `
  1238. );
  1239. // Initialize and index
  1240. const cg = CodeGraph.initSync(tempDir);
  1241. const result = await cg.indexAll();
  1242. expect(result.success).toBe(true);
  1243. expect(result.filesIndexed).toBe(1);
  1244. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  1245. // Check nodes were stored
  1246. const nodes = cg.getNodesInFile('src/utils.ts');
  1247. expect(nodes.length).toBeGreaterThanOrEqual(2);
  1248. const addFunc = nodes.find((n) => n.name === 'add');
  1249. expect(addFunc).toBeDefined();
  1250. expect(addFunc?.kind).toBe('function');
  1251. cg.close();
  1252. });
  1253. it('should index multiple files', async () => {
  1254. // Create test files
  1255. const srcDir = path.join(tempDir, 'src');
  1256. fs.mkdirSync(srcDir);
  1257. fs.writeFileSync(
  1258. path.join(srcDir, 'math.ts'),
  1259. `export function add(a: number, b: number) { return a + b; }`
  1260. );
  1261. fs.writeFileSync(
  1262. path.join(srcDir, 'string.ts'),
  1263. `export function capitalize(s: string) { return s.toUpperCase(); }`
  1264. );
  1265. // Initialize and index
  1266. const cg = CodeGraph.initSync(tempDir);
  1267. const result = await cg.indexAll();
  1268. expect(result.success).toBe(true);
  1269. expect(result.filesIndexed).toBe(2);
  1270. const files = cg.getFiles();
  1271. expect(files.length).toBe(2);
  1272. cg.close();
  1273. });
  1274. it('should track file hashes for incremental updates', async () => {
  1275. // Create initial file
  1276. const srcDir = path.join(tempDir, 'src');
  1277. fs.mkdirSync(srcDir);
  1278. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  1279. // Initialize and index
  1280. const cg = CodeGraph.initSync(tempDir);
  1281. await cg.indexAll();
  1282. // Check file is tracked
  1283. const file = cg.getFile('src/main.ts');
  1284. expect(file).toBeDefined();
  1285. expect(file?.contentHash).toBeDefined();
  1286. // Modify file
  1287. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  1288. // Check for changes
  1289. const changes = cg.getChangedFiles();
  1290. expect(changes.modified).toContain('src/main.ts');
  1291. cg.close();
  1292. });
  1293. it('should sync and detect changes', async () => {
  1294. // Create initial file
  1295. const srcDir = path.join(tempDir, 'src');
  1296. fs.mkdirSync(srcDir);
  1297. fs.writeFileSync(
  1298. path.join(srcDir, 'main.ts'),
  1299. `export function original() { return 1; }`
  1300. );
  1301. // Initialize and index
  1302. const cg = CodeGraph.initSync(tempDir);
  1303. await cg.indexAll();
  1304. const initialNodes = cg.getNodesInFile('src/main.ts');
  1305. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  1306. // Modify file
  1307. fs.writeFileSync(
  1308. path.join(srcDir, 'main.ts'),
  1309. `export function updated() { return 2; }`
  1310. );
  1311. // Sync
  1312. const syncResult = await cg.sync();
  1313. expect(syncResult.filesModified).toBe(1);
  1314. // Check nodes were updated
  1315. const updatedNodes = cg.getNodesInFile('src/main.ts');
  1316. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  1317. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  1318. cg.close();
  1319. });
  1320. });