extraction.test.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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, scanDirectory, shouldIncludeFile } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. import { DEFAULT_CONFIG } from '../src/types';
  15. // Create a temporary directory for each test
  16. function createTempDir(): string {
  17. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  18. }
  19. // Clean up temporary directory
  20. function cleanupTempDir(dir: string): void {
  21. if (fs.existsSync(dir)) {
  22. fs.rmSync(dir, { recursive: true, force: true });
  23. }
  24. }
  25. describe('Language Detection', () => {
  26. it('should detect TypeScript files', () => {
  27. expect(detectLanguage('src/index.ts')).toBe('typescript');
  28. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  29. });
  30. it('should detect JavaScript files', () => {
  31. expect(detectLanguage('index.js')).toBe('javascript');
  32. expect(detectLanguage('App.jsx')).toBe('jsx');
  33. expect(detectLanguage('config.mjs')).toBe('javascript');
  34. });
  35. it('should detect Python files', () => {
  36. expect(detectLanguage('main.py')).toBe('python');
  37. });
  38. it('should detect Go files', () => {
  39. expect(detectLanguage('main.go')).toBe('go');
  40. });
  41. it('should detect Rust files', () => {
  42. expect(detectLanguage('lib.rs')).toBe('rust');
  43. });
  44. it('should detect Java files', () => {
  45. expect(detectLanguage('Main.java')).toBe('java');
  46. });
  47. it('should detect C files', () => {
  48. expect(detectLanguage('main.c')).toBe('c');
  49. expect(detectLanguage('utils.h')).toBe('c');
  50. });
  51. it('should detect C++ files', () => {
  52. expect(detectLanguage('main.cpp')).toBe('cpp');
  53. expect(detectLanguage('class.hpp')).toBe('cpp');
  54. });
  55. it('should detect C# files', () => {
  56. expect(detectLanguage('Program.cs')).toBe('csharp');
  57. });
  58. it('should detect PHP files', () => {
  59. expect(detectLanguage('index.php')).toBe('php');
  60. });
  61. it('should detect Ruby files', () => {
  62. expect(detectLanguage('app.rb')).toBe('ruby');
  63. });
  64. it('should detect Swift files', () => {
  65. expect(detectLanguage('ViewController.swift')).toBe('swift');
  66. });
  67. it('should detect Kotlin files', () => {
  68. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  69. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  70. });
  71. it('should detect Dart files', () => {
  72. expect(detectLanguage('main.dart')).toBe('dart');
  73. });
  74. it('should return unknown for unsupported extensions', () => {
  75. expect(detectLanguage('styles.css')).toBe('unknown');
  76. expect(detectLanguage('data.json')).toBe('unknown');
  77. });
  78. });
  79. describe('Language Support', () => {
  80. it('should report supported languages', () => {
  81. expect(isLanguageSupported('typescript')).toBe(true);
  82. expect(isLanguageSupported('python')).toBe(true);
  83. expect(isLanguageSupported('go')).toBe(true);
  84. expect(isLanguageSupported('unknown')).toBe(false);
  85. });
  86. it('should list all supported languages', () => {
  87. const languages = getSupportedLanguages();
  88. expect(languages).toContain('typescript');
  89. expect(languages).toContain('javascript');
  90. expect(languages).toContain('python');
  91. expect(languages).toContain('go');
  92. expect(languages).toContain('rust');
  93. expect(languages).toContain('java');
  94. expect(languages).toContain('csharp');
  95. expect(languages).toContain('php');
  96. expect(languages).toContain('ruby');
  97. expect(languages).toContain('swift');
  98. expect(languages).toContain('kotlin');
  99. expect(languages).toContain('dart');
  100. });
  101. });
  102. describe('TypeScript Extraction', () => {
  103. it('should extract function declarations', () => {
  104. const code = `
  105. export function processPayment(amount: number): Promise<Receipt> {
  106. return stripe.charge(amount);
  107. }
  108. `;
  109. const result = extractFromSource('payment.ts', code);
  110. // File node + function node
  111. const fileNode = result.nodes.find((n) => n.kind === 'file');
  112. expect(fileNode).toBeDefined();
  113. expect(fileNode?.name).toBe('payment.ts');
  114. const funcNode = result.nodes.find((n) => n.kind === 'function');
  115. expect(funcNode).toMatchObject({
  116. kind: 'function',
  117. name: 'processPayment',
  118. language: 'typescript',
  119. isExported: true,
  120. });
  121. expect(funcNode?.signature).toContain('amount: number');
  122. });
  123. it('should extract class declarations', () => {
  124. const code = `
  125. export class PaymentService {
  126. private stripe: StripeClient;
  127. constructor(apiKey: string) {
  128. this.stripe = new StripeClient(apiKey);
  129. }
  130. async charge(amount: number): Promise<Receipt> {
  131. return this.stripe.charge(amount);
  132. }
  133. }
  134. `;
  135. const result = extractFromSource('service.ts', code);
  136. const classNode = result.nodes.find((n) => n.kind === 'class');
  137. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  138. expect(classNode).toBeDefined();
  139. expect(classNode?.name).toBe('PaymentService');
  140. expect(classNode?.isExported).toBe(true);
  141. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  142. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  143. expect(chargeMethod).toBeDefined();
  144. });
  145. it('should extract interfaces', () => {
  146. const code = `
  147. export interface User {
  148. id: string;
  149. name: string;
  150. email: string;
  151. }
  152. `;
  153. const result = extractFromSource('types.ts', code);
  154. const fileNode = result.nodes.find((n) => n.kind === 'file');
  155. expect(fileNode).toBeDefined();
  156. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  157. expect(ifaceNode).toMatchObject({
  158. kind: 'interface',
  159. name: 'User',
  160. isExported: true,
  161. });
  162. });
  163. it('should track function calls', () => {
  164. const code = `
  165. function main() {
  166. const result = processData();
  167. console.log(result);
  168. }
  169. `;
  170. const result = extractFromSource('main.ts', code);
  171. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  172. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  173. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  174. });
  175. });
  176. describe('Arrow Function Export Extraction', () => {
  177. it('should extract exported arrow functions assigned to const', () => {
  178. const code = `
  179. export const useAuth = (): AuthContextValue => {
  180. return useContext(AuthContext);
  181. };
  182. `;
  183. const result = extractFromSource('hooks.ts', code);
  184. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  185. expect(funcNode).toBeDefined();
  186. expect(funcNode).toMatchObject({
  187. kind: 'function',
  188. name: 'useAuth',
  189. isExported: true,
  190. });
  191. });
  192. it('should extract exported function expressions assigned to const', () => {
  193. const code = `
  194. export const processData = function(input: string): string {
  195. return input.trim();
  196. };
  197. `;
  198. const result = extractFromSource('utils.ts', code);
  199. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  200. expect(funcNode).toBeDefined();
  201. expect(funcNode).toMatchObject({
  202. kind: 'function',
  203. name: 'processData',
  204. isExported: true,
  205. });
  206. });
  207. it('should not extract non-exported arrow functions as exported', () => {
  208. const code = `
  209. const internalHelper = () => {
  210. return 42;
  211. };
  212. `;
  213. const result = extractFromSource('internal.ts', code);
  214. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  215. expect(helperNode).toBeDefined();
  216. expect(helperNode?.isExported).toBeFalsy();
  217. });
  218. it('should still skip truly anonymous arrow functions', () => {
  219. const code = `
  220. const items = [1, 2, 3].map((x) => x * 2);
  221. `;
  222. const result = extractFromSource('anon.ts', code);
  223. // The inline arrow function passed to .map() has no variable_declarator parent
  224. // and should remain anonymous (skipped)
  225. const anonFunctions = result.nodes.filter(
  226. (n) => n.kind === 'function' && n.name === '<anonymous>'
  227. );
  228. expect(anonFunctions).toHaveLength(0);
  229. });
  230. it('should extract multiple exported arrow functions from the same file', () => {
  231. const code = `
  232. export const add = (a: number, b: number): number => a + b;
  233. export const subtract = (a: number, b: number): number => a - b;
  234. const internal = () => 'not exported';
  235. `;
  236. const result = extractFromSource('math.ts', code);
  237. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  238. expect(exported).toHaveLength(2);
  239. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  240. const internalNode = result.nodes.find((n) => n.name === 'internal');
  241. expect(internalNode).toBeDefined();
  242. expect(internalNode?.isExported).toBeFalsy();
  243. });
  244. it('should extract arrow functions in JavaScript files', () => {
  245. const code = `
  246. export const fetchData = async () => {
  247. const response = await fetch('/api/data');
  248. return response.json();
  249. };
  250. `;
  251. const result = extractFromSource('api.js', code);
  252. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  253. expect(funcNode).toBeDefined();
  254. expect(funcNode).toMatchObject({
  255. kind: 'function',
  256. name: 'fetchData',
  257. isExported: true,
  258. });
  259. });
  260. });
  261. describe('Type Alias Extraction', () => {
  262. it('should extract exported type aliases in TypeScript', () => {
  263. const code = `
  264. export type AuthContextValue = {
  265. user: User | null;
  266. login: () => void;
  267. logout: () => void;
  268. };
  269. `;
  270. const result = extractFromSource('types.ts', code);
  271. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  272. expect(typeNode).toMatchObject({
  273. kind: 'type_alias',
  274. name: 'AuthContextValue',
  275. isExported: true,
  276. });
  277. });
  278. it('should extract non-exported type aliases', () => {
  279. const code = `
  280. type InternalState = {
  281. loading: boolean;
  282. error: string | null;
  283. };
  284. `;
  285. const result = extractFromSource('internal.ts', code);
  286. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  287. expect(typeNode).toMatchObject({
  288. kind: 'type_alias',
  289. name: 'InternalState',
  290. isExported: false,
  291. });
  292. });
  293. it('should extract multiple type aliases from the same file', () => {
  294. const code = `
  295. export type UnitSystem = 'metric' | 'imperial';
  296. export type DateFormat = 'ISO' | 'US' | 'EU';
  297. type Internal = string;
  298. `;
  299. const result = extractFromSource('config.ts', code);
  300. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  301. expect(typeAliases).toHaveLength(3);
  302. const exported = typeAliases.filter((n) => n.isExported);
  303. expect(exported).toHaveLength(2);
  304. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  305. });
  306. });
  307. describe('Exported Variable Extraction', () => {
  308. it('should extract exported const with call expression (Zustand store)', () => {
  309. const code = `
  310. export const useUIStore = create<UIState>((set) => ({
  311. isOpen: false,
  312. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  313. }));
  314. `;
  315. const result = extractFromSource('store.ts', code);
  316. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'useUIStore');
  317. expect(varNode).toBeDefined();
  318. expect(varNode?.isExported).toBe(true);
  319. });
  320. it('should extract exported const with object literal', () => {
  321. const code = `
  322. export const config = {
  323. apiUrl: 'https://api.example.com',
  324. timeout: 5000,
  325. };
  326. `;
  327. const result = extractFromSource('config.ts', code);
  328. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'config');
  329. expect(varNode).toBeDefined();
  330. expect(varNode?.isExported).toBe(true);
  331. });
  332. it('should extract exported const with array literal', () => {
  333. const code = `
  334. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  335. `;
  336. const result = extractFromSource('constants.ts', code);
  337. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'SCREEN_NAMES');
  338. expect(varNode).toBeDefined();
  339. expect(varNode?.isExported).toBe(true);
  340. });
  341. it('should extract exported const with primitive value', () => {
  342. const code = `
  343. export const MAX_RETRIES = 3;
  344. export const API_VERSION = "v2";
  345. `;
  346. const result = extractFromSource('constants.ts', code);
  347. const variables = result.nodes.filter((n) => n.kind === 'variable');
  348. expect(variables).toHaveLength(2);
  349. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  350. });
  351. it('should NOT duplicate arrow functions as both function and variable', () => {
  352. const code = `
  353. export const useAuth = () => {
  354. return useContext(AuthContext);
  355. };
  356. `;
  357. const result = extractFromSource('hooks.ts', code);
  358. // Should be extracted as function (from arrow function handler), NOT as variable
  359. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  360. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  361. expect(funcNodes).toHaveLength(1);
  362. expect(varNodes).toHaveLength(0);
  363. });
  364. it('should extract non-exported const as non-exported variable', () => {
  365. const code = `
  366. const internalConfig = {
  367. debug: true,
  368. };
  369. `;
  370. const result = extractFromSource('internal.ts', code);
  371. // Non-exported const at file level should be extracted as a constant (not exported)
  372. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  373. expect(varNodes).toHaveLength(1);
  374. expect(varNodes[0]?.isExported).toBeFalsy();
  375. });
  376. it('should extract Zod schema exports', () => {
  377. const code = `
  378. export const userSchema = z.object({
  379. id: z.string(),
  380. name: z.string(),
  381. email: z.string().email(),
  382. });
  383. `;
  384. const result = extractFromSource('schemas.ts', code);
  385. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'userSchema');
  386. expect(varNode).toBeDefined();
  387. expect(varNode?.isExported).toBe(true);
  388. });
  389. it('should extract XState machine exports', () => {
  390. const code = `
  391. export const authMachine = createMachine({
  392. id: "auth",
  393. initial: "idle",
  394. states: {
  395. idle: {},
  396. authenticated: {},
  397. },
  398. });
  399. `;
  400. const result = extractFromSource('machine.ts', code);
  401. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'authMachine');
  402. expect(varNode).toBeDefined();
  403. expect(varNode?.isExported).toBe(true);
  404. });
  405. });
  406. describe('File Node Extraction', () => {
  407. it('should create a file-kind node for each parsed file', () => {
  408. const code = `
  409. export function greet(name: string): string {
  410. return "Hello " + name;
  411. }
  412. `;
  413. const result = extractFromSource('greeter.ts', code);
  414. const fileNode = result.nodes.find((n) => n.kind === 'file');
  415. expect(fileNode).toBeDefined();
  416. expect(fileNode?.name).toBe('greeter.ts');
  417. expect(fileNode?.filePath).toBe('greeter.ts');
  418. expect(fileNode?.language).toBe('typescript');
  419. expect(fileNode?.startLine).toBe(1);
  420. });
  421. it('should create file nodes for Python files', () => {
  422. const code = `
  423. def main():
  424. pass
  425. `;
  426. const result = extractFromSource('main.py', code);
  427. const fileNode = result.nodes.find((n) => n.kind === 'file');
  428. expect(fileNode).toBeDefined();
  429. expect(fileNode?.name).toBe('main.py');
  430. expect(fileNode?.language).toBe('python');
  431. });
  432. it('should create containment edges from file node to top-level declarations', () => {
  433. const code = `
  434. export function foo() {}
  435. export function bar() {}
  436. `;
  437. const result = extractFromSource('fns.ts', code);
  438. const fileNode = result.nodes.find((n) => n.kind === 'file');
  439. expect(fileNode).toBeDefined();
  440. // There should be contains edges from the file node to each function
  441. const containsEdges = result.edges.filter(
  442. (e) => e.source === fileNode?.id && e.kind === 'contains'
  443. );
  444. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  445. });
  446. });
  447. describe('Arrow Function Variable Extraction', () => {
  448. it('should extract const arrow functions as function nodes', () => {
  449. const code = `
  450. const handleClick = () => {
  451. console.log('clicked');
  452. };
  453. `;
  454. const result = extractFromSource('handler.ts', code);
  455. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  456. expect(funcNode).toBeDefined();
  457. expect(funcNode?.kind).toBe('function');
  458. });
  459. it('should detect async arrow functions', () => {
  460. const code = `
  461. export const fetchUser = async (id: string) => {
  462. return await db.find(id);
  463. };
  464. `;
  465. const result = extractFromSource('api.ts', code);
  466. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchUser');
  467. expect(funcNode).toBeDefined();
  468. expect(funcNode?.isExported).toBe(true);
  469. });
  470. it('should not create duplicate nodes for arrow functions in export statements', () => {
  471. const code = `
  472. export const compute = (x: number) => x * 2;
  473. `;
  474. const result = extractFromSource('math.ts', code);
  475. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'compute');
  476. // Should appear only once, not duplicated between extractFunctionVariable and extractFunction
  477. expect(funcNodes).toHaveLength(1);
  478. });
  479. });
  480. describe('Python Extraction', () => {
  481. it('should extract function definitions', () => {
  482. const code = `
  483. def calculate_total(items: list, tax_rate: float) -> float:
  484. """Calculate total with tax."""
  485. subtotal = sum(item.price for item in items)
  486. return subtotal * (1 + tax_rate)
  487. `;
  488. const result = extractFromSource('calc.py', code);
  489. const fileNode = result.nodes.find((n) => n.kind === 'file');
  490. expect(fileNode).toBeDefined();
  491. const funcNode = result.nodes.find((n) => n.kind === 'function');
  492. expect(funcNode).toMatchObject({
  493. kind: 'function',
  494. name: 'calculate_total',
  495. language: 'python',
  496. });
  497. });
  498. it('should extract class definitions', () => {
  499. const code = `
  500. class UserService:
  501. """Service for managing users."""
  502. def __init__(self, db):
  503. self.db = db
  504. def get_user(self, user_id: str) -> User:
  505. return self.db.find_user(user_id)
  506. `;
  507. const result = extractFromSource('service.py', code);
  508. const classNode = result.nodes.find((n) => n.kind === 'class');
  509. expect(classNode).toBeDefined();
  510. expect(classNode?.name).toBe('UserService');
  511. });
  512. });
  513. describe('Go Extraction', () => {
  514. it('should extract function declarations', () => {
  515. const code = `
  516. package main
  517. func ProcessOrder(order Order) (Receipt, error) {
  518. // Process the order
  519. return Receipt{}, nil
  520. }
  521. `;
  522. const result = extractFromSource('main.go', code);
  523. const funcNode = result.nodes.find((n) => n.kind === 'function');
  524. expect(funcNode).toBeDefined();
  525. expect(funcNode?.name).toBe('ProcessOrder');
  526. });
  527. it('should extract method declarations', () => {
  528. const code = `
  529. package main
  530. type Service struct {
  531. db *Database
  532. }
  533. func (s *Service) GetUser(id string) (*User, error) {
  534. return s.db.FindUser(id)
  535. }
  536. `;
  537. const result = extractFromSource('service.go', code);
  538. const methodNode = result.nodes.find((n) => n.kind === 'method');
  539. expect(methodNode).toBeDefined();
  540. expect(methodNode?.name).toBe('GetUser');
  541. });
  542. });
  543. describe('Rust Extraction', () => {
  544. it('should extract function declarations', () => {
  545. const code = `
  546. pub fn process_data(input: &str) -> Result<Output, Error> {
  547. // Process data
  548. Ok(Output::new())
  549. }
  550. `;
  551. const result = extractFromSource('lib.rs', code);
  552. const funcNode = result.nodes.find((n) => n.kind === 'function');
  553. expect(funcNode).toBeDefined();
  554. expect(funcNode?.name).toBe('process_data');
  555. expect(funcNode?.visibility).toBe('public');
  556. });
  557. it('should extract struct declarations', () => {
  558. const code = `
  559. pub struct User {
  560. pub id: String,
  561. pub name: String,
  562. email: String,
  563. }
  564. `;
  565. const result = extractFromSource('models.rs', code);
  566. const structNode = result.nodes.find((n) => n.kind === 'struct');
  567. expect(structNode).toBeDefined();
  568. expect(structNode?.name).toBe('User');
  569. });
  570. it('should extract trait declarations', () => {
  571. const code = `
  572. pub trait Repository {
  573. fn find(&self, id: &str) -> Option<Entity>;
  574. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  575. }
  576. `;
  577. const result = extractFromSource('traits.rs', code);
  578. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  579. expect(traitNode).toBeDefined();
  580. expect(traitNode?.name).toBe('Repository');
  581. });
  582. });
  583. describe('Java Extraction', () => {
  584. it('should extract class declarations', () => {
  585. const code = `
  586. public class UserService {
  587. private final UserRepository repository;
  588. public UserService(UserRepository repository) {
  589. this.repository = repository;
  590. }
  591. public User getUser(String id) {
  592. return repository.findById(id);
  593. }
  594. }
  595. `;
  596. const result = extractFromSource('UserService.java', code);
  597. const classNode = result.nodes.find((n) => n.kind === 'class');
  598. expect(classNode).toBeDefined();
  599. expect(classNode?.name).toBe('UserService');
  600. expect(classNode?.visibility).toBe('public');
  601. });
  602. it('should extract method declarations', () => {
  603. const code = `
  604. public class Calculator {
  605. public static int add(int a, int b) {
  606. return a + b;
  607. }
  608. }
  609. `;
  610. const result = extractFromSource('Calculator.java', code);
  611. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  612. expect(methodNode).toBeDefined();
  613. expect(methodNode?.isStatic).toBe(true);
  614. });
  615. });
  616. describe('C# Extraction', () => {
  617. it('should extract class declarations', () => {
  618. const code = `
  619. public class OrderService
  620. {
  621. private readonly IOrderRepository _repository;
  622. public OrderService(IOrderRepository repository)
  623. {
  624. _repository = repository;
  625. }
  626. public async Task<Order> GetOrderAsync(string id)
  627. {
  628. return await _repository.FindByIdAsync(id);
  629. }
  630. }
  631. `;
  632. const result = extractFromSource('OrderService.cs', code);
  633. const classNode = result.nodes.find((n) => n.kind === 'class');
  634. expect(classNode).toBeDefined();
  635. expect(classNode?.name).toBe('OrderService');
  636. expect(classNode?.visibility).toBe('public');
  637. });
  638. });
  639. describe('PHP Extraction', () => {
  640. it('should extract class declarations', () => {
  641. const code = `<?php
  642. class UserController
  643. {
  644. private UserService $userService;
  645. public function __construct(UserService $userService)
  646. {
  647. $this->userService = $userService;
  648. }
  649. public function show(string $id): User
  650. {
  651. return $this->userService->find($id);
  652. }
  653. }
  654. `;
  655. const result = extractFromSource('UserController.php', code);
  656. const classNode = result.nodes.find((n) => n.kind === 'class');
  657. expect(classNode).toBeDefined();
  658. expect(classNode?.name).toBe('UserController');
  659. });
  660. });
  661. describe('Swift Extraction', () => {
  662. it('should extract class declarations', () => {
  663. const code = `
  664. public class NetworkManager {
  665. private let session: URLSession
  666. public init(session: URLSession = .shared) {
  667. self.session = session
  668. }
  669. public func fetchData(from url: URL) async throws -> Data {
  670. let (data, _) = try await session.data(from: url)
  671. return data
  672. }
  673. }
  674. `;
  675. const result = extractFromSource('NetworkManager.swift', code);
  676. const classNode = result.nodes.find((n) => n.kind === 'class');
  677. expect(classNode).toBeDefined();
  678. expect(classNode?.name).toBe('NetworkManager');
  679. });
  680. it('should extract function declarations', () => {
  681. const code = `
  682. func calculateSum(_ numbers: [Int]) -> Int {
  683. return numbers.reduce(0, +)
  684. }
  685. public func formatCurrency(amount: Double) -> String {
  686. return String(format: "$%.2f", amount)
  687. }
  688. `;
  689. const result = extractFromSource('utils.swift', code);
  690. const functions = result.nodes.filter((n) => n.kind === 'function');
  691. expect(functions.length).toBeGreaterThanOrEqual(1);
  692. });
  693. it('should extract struct declarations', () => {
  694. const code = `
  695. public struct User {
  696. let id: UUID
  697. var name: String
  698. var email: String
  699. func displayName() -> String {
  700. return name
  701. }
  702. }
  703. `;
  704. const result = extractFromSource('User.swift', code);
  705. const structNode = result.nodes.find((n) => n.kind === 'struct');
  706. expect(structNode).toBeDefined();
  707. expect(structNode?.name).toBe('User');
  708. });
  709. it('should extract protocol declarations', () => {
  710. const code = `
  711. public protocol Repository {
  712. associatedtype Entity
  713. func find(id: String) async throws -> Entity?
  714. func save(_ entity: Entity) async throws
  715. }
  716. `;
  717. const result = extractFromSource('Repository.swift', code);
  718. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  719. expect(protocolNode).toBeDefined();
  720. expect(protocolNode?.name).toBe('Repository');
  721. });
  722. });
  723. describe('Kotlin Extraction', () => {
  724. it('should extract class declarations', () => {
  725. const code = `
  726. class UserRepository(private val database: Database) {
  727. fun findById(id: String): User? {
  728. return database.query("SELECT * FROM users WHERE id = ?", id)
  729. }
  730. suspend fun save(user: User) {
  731. database.insert(user)
  732. }
  733. }
  734. `;
  735. const result = extractFromSource('UserRepository.kt', code);
  736. const classNode = result.nodes.find((n) => n.kind === 'class');
  737. expect(classNode).toBeDefined();
  738. expect(classNode?.name).toBe('UserRepository');
  739. });
  740. it('should extract function declarations', () => {
  741. const code = `
  742. fun calculateTotal(items: List<Item>): Double {
  743. return items.sumOf { it.price }
  744. }
  745. suspend fun fetchUserData(userId: String): User {
  746. return api.getUser(userId)
  747. }
  748. `;
  749. const result = extractFromSource('utils.kt', code);
  750. const functions = result.nodes.filter((n) => n.kind === 'function');
  751. expect(functions.length).toBeGreaterThanOrEqual(1);
  752. });
  753. it('should detect suspend functions as async', () => {
  754. const code = `
  755. suspend fun loadData(): List<String> {
  756. delay(1000)
  757. return listOf("a", "b", "c")
  758. }
  759. `;
  760. const result = extractFromSource('loader.kt', code);
  761. const funcNode = result.nodes.find((n) => n.kind === 'function');
  762. expect(funcNode).toBeDefined();
  763. expect(funcNode?.isAsync).toBe(true);
  764. });
  765. });
  766. describe('Dart Extraction', () => {
  767. it('should extract class declarations', () => {
  768. const code = `
  769. class UserService {
  770. final Database _db;
  771. Future<User> findById(String id) async {
  772. return await _db.query(id);
  773. }
  774. void _privateMethod() {}
  775. }
  776. `;
  777. const result = extractFromSource('service.dart', code);
  778. const classNode = result.nodes.find((n) => n.kind === 'class');
  779. expect(classNode).toBeDefined();
  780. expect(classNode?.name).toBe('UserService');
  781. expect(classNode?.visibility).toBe('public');
  782. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  783. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  784. const findById = methodNodes.find((m) => m.name === 'findById');
  785. expect(findById).toBeDefined();
  786. expect(findById?.isAsync).toBe(true);
  787. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  788. expect(privateMethod).toBeDefined();
  789. expect(privateMethod?.visibility).toBe('private');
  790. });
  791. it('should extract top-level function declarations', () => {
  792. const code = `
  793. void topLevelFunction(String name) {
  794. print(name);
  795. }
  796. `;
  797. const result = extractFromSource('utils.dart', code);
  798. const funcNode = result.nodes.find((n) => n.kind === 'function');
  799. expect(funcNode).toBeDefined();
  800. expect(funcNode?.name).toBe('topLevelFunction');
  801. expect(funcNode?.language).toBe('dart');
  802. });
  803. it('should extract enum declarations', () => {
  804. const code = `
  805. enum Status { active, inactive, pending }
  806. `;
  807. const result = extractFromSource('models.dart', code);
  808. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  809. expect(enumNode).toBeDefined();
  810. expect(enumNode?.name).toBe('Status');
  811. });
  812. it('should extract mixin declarations', () => {
  813. const code = `
  814. mixin LoggerMixin {
  815. void log(String message) {}
  816. }
  817. `;
  818. const result = extractFromSource('mixins.dart', code);
  819. const classNode = result.nodes.find((n) => n.kind === 'class');
  820. expect(classNode).toBeDefined();
  821. expect(classNode?.name).toBe('LoggerMixin');
  822. const methodNode = result.nodes.find((n) => n.kind === 'method');
  823. expect(methodNode).toBeDefined();
  824. expect(methodNode?.name).toBe('log');
  825. });
  826. it('should extract extension declarations', () => {
  827. const code = `
  828. extension StringExt on String {
  829. bool get isBlank => trim().isEmpty;
  830. }
  831. `;
  832. const result = extractFromSource('extensions.dart', code);
  833. const classNode = result.nodes.find((n) => n.kind === 'class');
  834. expect(classNode).toBeDefined();
  835. expect(classNode?.name).toBe('StringExt');
  836. });
  837. it('should detect static methods', () => {
  838. const code = `
  839. class Utils {
  840. static void doWork() {}
  841. }
  842. `;
  843. const result = extractFromSource('utils.dart', code);
  844. const methodNode = result.nodes.find((n) => n.kind === 'method');
  845. expect(methodNode).toBeDefined();
  846. expect(methodNode?.name).toBe('doWork');
  847. expect(methodNode?.isStatic).toBe(true);
  848. });
  849. it('should detect async functions', () => {
  850. const code = `
  851. Future<String> fetchData() async {
  852. return await http.get('/data');
  853. }
  854. `;
  855. const result = extractFromSource('api.dart', code);
  856. const funcNode = result.nodes.find((n) => n.kind === 'function');
  857. expect(funcNode).toBeDefined();
  858. expect(funcNode?.name).toBe('fetchData');
  859. expect(funcNode?.isAsync).toBe(true);
  860. });
  861. it('should detect private visibility via underscore convention', () => {
  862. const code = `
  863. void _privateHelper() {}
  864. void publicFunction() {}
  865. `;
  866. const result = extractFromSource('helpers.dart', code);
  867. const functions = result.nodes.filter((n) => n.kind === 'function');
  868. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  869. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  870. expect(privateFunc?.visibility).toBe('private');
  871. expect(publicFunc?.visibility).toBe('public');
  872. });
  873. });
  874. describe('Import Extraction', () => {
  875. describe('TypeScript/JavaScript imports', () => {
  876. it('should extract default imports', () => {
  877. const code = `import React from 'react';`;
  878. const result = extractFromSource('app.tsx', code);
  879. const importNode = result.nodes.find((n) => n.kind === 'import');
  880. expect(importNode).toBeDefined();
  881. expect(importNode?.name).toBe('react');
  882. expect(importNode?.signature).toBe("import React from 'react';");
  883. });
  884. it('should extract named imports', () => {
  885. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  886. const result = extractFromSource('icons.tsx', code);
  887. const importNode = result.nodes.find((n) => n.kind === 'import');
  888. expect(importNode).toBeDefined();
  889. expect(importNode?.name).toBe('@phosphor-icons/react');
  890. expect(importNode?.signature).toContain('Bug');
  891. expect(importNode?.signature).toContain('Database');
  892. });
  893. it('should extract namespace imports', () => {
  894. const code = `import * as Icons from '@phosphor-icons/react';`;
  895. const result = extractFromSource('icons.tsx', code);
  896. const importNode = result.nodes.find((n) => n.kind === 'import');
  897. expect(importNode).toBeDefined();
  898. expect(importNode?.name).toBe('@phosphor-icons/react');
  899. expect(importNode?.signature).toContain('* as Icons');
  900. });
  901. it('should extract side-effect imports', () => {
  902. const code = `import './styles.css';`;
  903. const result = extractFromSource('app.tsx', code);
  904. const importNode = result.nodes.find((n) => n.kind === 'import');
  905. expect(importNode).toBeDefined();
  906. expect(importNode?.name).toBe('./styles.css');
  907. });
  908. it('should extract mixed imports (default + named)', () => {
  909. const code = `import React, { useState, useEffect } from 'react';`;
  910. const result = extractFromSource('app.tsx', code);
  911. const importNode = result.nodes.find((n) => n.kind === 'import');
  912. expect(importNode).toBeDefined();
  913. expect(importNode?.name).toBe('react');
  914. expect(importNode?.signature).toContain('React');
  915. expect(importNode?.signature).toContain('useState');
  916. expect(importNode?.signature).toContain('useEffect');
  917. });
  918. it('should extract multiple import statements', () => {
  919. const code = `
  920. import React from 'react';
  921. import { Button } from './components';
  922. import './styles.css';
  923. `;
  924. const result = extractFromSource('app.tsx', code);
  925. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  926. expect(importNodes.length).toBe(3);
  927. const names = importNodes.map((n) => n.name);
  928. expect(names).toContain('react');
  929. expect(names).toContain('./components');
  930. expect(names).toContain('./styles.css');
  931. });
  932. it('should extract type imports', () => {
  933. const code = `import type { FC, ReactNode } from 'react';`;
  934. const result = extractFromSource('types.ts', code);
  935. const importNode = result.nodes.find((n) => n.kind === 'import');
  936. expect(importNode).toBeDefined();
  937. expect(importNode?.name).toBe('react');
  938. expect(importNode?.signature).toContain('type');
  939. expect(importNode?.signature).toContain('FC');
  940. });
  941. it('should extract aliased named imports', () => {
  942. const code = `import { useState as useStateAlias } from 'react';`;
  943. const result = extractFromSource('hooks.ts', code);
  944. const importNode = result.nodes.find((n) => n.kind === 'import');
  945. expect(importNode).toBeDefined();
  946. expect(importNode?.name).toBe('react');
  947. expect(importNode?.signature).toContain('useState');
  948. expect(importNode?.signature).toContain('useStateAlias');
  949. });
  950. it('should extract relative path imports', () => {
  951. const code = `import { helper } from '../utils/helper';`;
  952. const result = extractFromSource('components/Button.tsx', code);
  953. const importNode = result.nodes.find((n) => n.kind === 'import');
  954. expect(importNode).toBeDefined();
  955. expect(importNode?.name).toBe('../utils/helper');
  956. expect(importNode?.signature).toContain('helper');
  957. });
  958. });
  959. describe('Python imports', () => {
  960. it('should extract simple import statement', () => {
  961. const code = `import json`;
  962. const result = extractFromSource('utils.py', code);
  963. const importNode = result.nodes.find((n) => n.kind === 'import');
  964. expect(importNode).toBeDefined();
  965. expect(importNode?.name).toBe('json');
  966. });
  967. it('should extract from import statement', () => {
  968. const code = `from os import path`;
  969. const result = extractFromSource('utils.py', code);
  970. const importNode = result.nodes.find((n) => n.kind === 'import');
  971. expect(importNode).toBeDefined();
  972. expect(importNode?.name).toBe('os');
  973. expect(importNode?.signature).toContain('path');
  974. });
  975. it('should extract multiple imports from same module', () => {
  976. const code = `from typing import List, Dict, Optional`;
  977. const result = extractFromSource('types.py', code);
  978. const importNode = result.nodes.find((n) => n.kind === 'import');
  979. expect(importNode).toBeDefined();
  980. expect(importNode?.name).toBe('typing');
  981. expect(importNode?.signature).toContain('List');
  982. expect(importNode?.signature).toContain('Dict');
  983. });
  984. it('should extract multiple import statements', () => {
  985. const code = `
  986. import os
  987. import sys
  988. `;
  989. const result = extractFromSource('main.py', code);
  990. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  991. expect(importNodes.length).toBe(2);
  992. const names = importNodes.map((n) => n.name);
  993. expect(names).toContain('os');
  994. expect(names).toContain('sys');
  995. });
  996. it('should extract aliased import', () => {
  997. const code = `import numpy as np`;
  998. const result = extractFromSource('data.py', code);
  999. const importNode = result.nodes.find((n) => n.kind === 'import');
  1000. expect(importNode).toBeDefined();
  1001. expect(importNode?.name).toBe('numpy');
  1002. expect(importNode?.signature).toContain('as np');
  1003. });
  1004. it('should extract relative import', () => {
  1005. const code = `from .utils import helper`;
  1006. const result = extractFromSource('module.py', code);
  1007. const importNode = result.nodes.find((n) => n.kind === 'import');
  1008. expect(importNode).toBeDefined();
  1009. expect(importNode?.name).toBe('.utils');
  1010. expect(importNode?.signature).toContain('helper');
  1011. });
  1012. it('should extract wildcard import', () => {
  1013. const code = `from typing import *`;
  1014. const result = extractFromSource('types.py', code);
  1015. const importNode = result.nodes.find((n) => n.kind === 'import');
  1016. expect(importNode).toBeDefined();
  1017. expect(importNode?.name).toBe('typing');
  1018. expect(importNode?.signature).toContain('*');
  1019. });
  1020. });
  1021. describe('Rust imports', () => {
  1022. it('should extract simple use declaration', () => {
  1023. const code = `use std::io;`;
  1024. const result = extractFromSource('main.rs', code);
  1025. const importNode = result.nodes.find((n) => n.kind === 'import');
  1026. expect(importNode).toBeDefined();
  1027. expect(importNode?.name).toBe('std');
  1028. expect(importNode?.signature).toBe('use std::io;');
  1029. });
  1030. it('should extract scoped use list', () => {
  1031. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1032. const result = extractFromSource('main.rs', code);
  1033. const importNode = result.nodes.find((n) => n.kind === 'import');
  1034. expect(importNode).toBeDefined();
  1035. expect(importNode?.name).toBe('std');
  1036. expect(importNode?.signature).toContain('ffi::OsStr');
  1037. expect(importNode?.signature).toContain('path::Path');
  1038. });
  1039. it('should extract crate imports', () => {
  1040. const code = `use crate::error::Error;`;
  1041. const result = extractFromSource('lib.rs', code);
  1042. const importNode = result.nodes.find((n) => n.kind === 'import');
  1043. expect(importNode).toBeDefined();
  1044. expect(importNode?.name).toBe('crate');
  1045. });
  1046. it('should extract super imports', () => {
  1047. const code = `use super::utils;`;
  1048. const result = extractFromSource('submod.rs', code);
  1049. const importNode = result.nodes.find((n) => n.kind === 'import');
  1050. expect(importNode).toBeDefined();
  1051. expect(importNode?.name).toBe('super');
  1052. });
  1053. it('should extract external crate imports', () => {
  1054. const code = `use serde::{Serialize, Deserialize};`;
  1055. const result = extractFromSource('types.rs', code);
  1056. const importNode = result.nodes.find((n) => n.kind === 'import');
  1057. expect(importNode).toBeDefined();
  1058. expect(importNode?.name).toBe('serde');
  1059. expect(importNode?.signature).toContain('Serialize');
  1060. expect(importNode?.signature).toContain('Deserialize');
  1061. });
  1062. });
  1063. describe('Go imports', () => {
  1064. it('should extract single import', () => {
  1065. const code = `
  1066. package main
  1067. import "fmt"
  1068. `;
  1069. const result = extractFromSource('main.go', code);
  1070. const importNode = result.nodes.find((n) => n.kind === 'import');
  1071. expect(importNode).toBeDefined();
  1072. expect(importNode?.name).toBe('fmt');
  1073. });
  1074. it('should extract grouped imports', () => {
  1075. const code = `
  1076. package main
  1077. import (
  1078. "fmt"
  1079. "os"
  1080. "encoding/json"
  1081. )
  1082. `;
  1083. const result = extractFromSource('main.go', code);
  1084. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1085. expect(importNodes.length).toBe(3);
  1086. const names = importNodes.map((n) => n.name);
  1087. expect(names).toContain('fmt');
  1088. expect(names).toContain('os');
  1089. expect(names).toContain('encoding/json');
  1090. });
  1091. it('should extract aliased import', () => {
  1092. const code = `
  1093. package main
  1094. import f "fmt"
  1095. `;
  1096. const result = extractFromSource('main.go', code);
  1097. const importNode = result.nodes.find((n) => n.kind === 'import');
  1098. expect(importNode).toBeDefined();
  1099. expect(importNode?.name).toBe('fmt');
  1100. expect(importNode?.signature).toContain('f');
  1101. });
  1102. it('should extract dot import', () => {
  1103. const code = `
  1104. package main
  1105. import . "math"
  1106. `;
  1107. const result = extractFromSource('main.go', code);
  1108. const importNode = result.nodes.find((n) => n.kind === 'import');
  1109. expect(importNode).toBeDefined();
  1110. expect(importNode?.name).toBe('math');
  1111. expect(importNode?.signature).toContain('.');
  1112. });
  1113. it('should extract blank import', () => {
  1114. const code = `
  1115. package main
  1116. import _ "github.com/go-sql-driver/mysql"
  1117. `;
  1118. const result = extractFromSource('main.go', code);
  1119. const importNode = result.nodes.find((n) => n.kind === 'import');
  1120. expect(importNode).toBeDefined();
  1121. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1122. expect(importNode?.signature).toContain('_');
  1123. });
  1124. });
  1125. describe('Swift imports', () => {
  1126. it('should extract simple import', () => {
  1127. const code = `import Foundation`;
  1128. const result = extractFromSource('main.swift', code);
  1129. const importNode = result.nodes.find((n) => n.kind === 'import');
  1130. expect(importNode).toBeDefined();
  1131. expect(importNode?.name).toBe('Foundation');
  1132. expect(importNode?.signature).toBe('import Foundation');
  1133. });
  1134. it('should extract @testable import', () => {
  1135. const code = `@testable import Alamofire`;
  1136. const result = extractFromSource('Tests.swift', code);
  1137. const importNode = result.nodes.find((n) => n.kind === 'import');
  1138. expect(importNode).toBeDefined();
  1139. expect(importNode?.name).toBe('Alamofire');
  1140. expect(importNode?.signature).toContain('@testable');
  1141. });
  1142. it('should extract @preconcurrency import', () => {
  1143. const code = `@preconcurrency import Security`;
  1144. const result = extractFromSource('Auth.swift', code);
  1145. const importNode = result.nodes.find((n) => n.kind === 'import');
  1146. expect(importNode).toBeDefined();
  1147. expect(importNode?.name).toBe('Security');
  1148. });
  1149. it('should extract multiple imports', () => {
  1150. const code = `
  1151. import Foundation
  1152. import UIKit
  1153. import Alamofire
  1154. `;
  1155. const result = extractFromSource('App.swift', code);
  1156. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1157. expect(importNodes.length).toBe(3);
  1158. const names = importNodes.map((n) => n.name);
  1159. expect(names).toContain('Foundation');
  1160. expect(names).toContain('UIKit');
  1161. expect(names).toContain('Alamofire');
  1162. });
  1163. });
  1164. describe('Kotlin imports', () => {
  1165. it('should extract simple import', () => {
  1166. const code = `import java.io.IOException`;
  1167. const result = extractFromSource('Main.kt', code);
  1168. const importNode = result.nodes.find((n) => n.kind === 'import');
  1169. expect(importNode).toBeDefined();
  1170. expect(importNode?.name).toBe('java.io.IOException');
  1171. expect(importNode?.signature).toBe('import java.io.IOException');
  1172. });
  1173. it('should extract aliased import', () => {
  1174. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1175. const result = extractFromSource('Utils.kt', code);
  1176. const importNode = result.nodes.find((n) => n.kind === 'import');
  1177. expect(importNode).toBeDefined();
  1178. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1179. expect(importNode?.signature).toContain('as RequestBuilder');
  1180. });
  1181. it('should extract wildcard import', () => {
  1182. const code = `import java.util.concurrent.TimeUnit.*`;
  1183. const result = extractFromSource('Time.kt', code);
  1184. const importNode = result.nodes.find((n) => n.kind === 'import');
  1185. expect(importNode).toBeDefined();
  1186. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1187. expect(importNode?.signature).toContain('.*');
  1188. });
  1189. it('should extract multiple imports', () => {
  1190. const code = `
  1191. import java.io.IOException
  1192. import kotlin.test.assertFailsWith
  1193. import okhttp3.OkHttpClient
  1194. `;
  1195. const result = extractFromSource('Test.kt', code);
  1196. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1197. expect(importNodes.length).toBe(3);
  1198. const names = importNodes.map((n) => n.name);
  1199. expect(names).toContain('java.io.IOException');
  1200. expect(names).toContain('kotlin.test.assertFailsWith');
  1201. expect(names).toContain('okhttp3.OkHttpClient');
  1202. });
  1203. });
  1204. describe('Java imports', () => {
  1205. it('should extract simple import', () => {
  1206. const code = `import java.util.List;`;
  1207. const result = extractFromSource('Main.java', code);
  1208. const importNode = result.nodes.find((n) => n.kind === 'import');
  1209. expect(importNode).toBeDefined();
  1210. expect(importNode?.name).toBe('java.util.List');
  1211. expect(importNode?.signature).toBe('import java.util.List;');
  1212. });
  1213. it('should extract static import', () => {
  1214. const code = `import static java.util.Collections.emptyList;`;
  1215. const result = extractFromSource('Utils.java', code);
  1216. const importNode = result.nodes.find((n) => n.kind === 'import');
  1217. expect(importNode).toBeDefined();
  1218. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1219. expect(importNode?.signature).toContain('static');
  1220. });
  1221. it('should extract wildcard import', () => {
  1222. const code = `import java.util.*;`;
  1223. const result = extractFromSource('App.java', code);
  1224. const importNode = result.nodes.find((n) => n.kind === 'import');
  1225. expect(importNode).toBeDefined();
  1226. expect(importNode?.name).toBe('java.util');
  1227. expect(importNode?.signature).toContain('.*');
  1228. });
  1229. it('should extract nested class import', () => {
  1230. const code = `import java.util.Map.Entry;`;
  1231. const result = extractFromSource('MapUtil.java', code);
  1232. const importNode = result.nodes.find((n) => n.kind === 'import');
  1233. expect(importNode).toBeDefined();
  1234. expect(importNode?.name).toBe('java.util.Map.Entry');
  1235. });
  1236. it('should extract multiple imports', () => {
  1237. const code = `
  1238. import java.util.List;
  1239. import java.util.Map;
  1240. import java.io.IOException;
  1241. `;
  1242. const result = extractFromSource('Service.java', code);
  1243. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1244. expect(importNodes.length).toBe(3);
  1245. const names = importNodes.map((n) => n.name);
  1246. expect(names).toContain('java.util.List');
  1247. expect(names).toContain('java.util.Map');
  1248. expect(names).toContain('java.io.IOException');
  1249. });
  1250. });
  1251. describe('C# imports', () => {
  1252. it('should extract simple using', () => {
  1253. const code = `using System;`;
  1254. const result = extractFromSource('Program.cs', code);
  1255. const importNode = result.nodes.find((n) => n.kind === 'import');
  1256. expect(importNode).toBeDefined();
  1257. expect(importNode?.name).toBe('System');
  1258. expect(importNode?.signature).toBe('using System;');
  1259. });
  1260. it('should extract qualified using', () => {
  1261. const code = `using System.Collections.Generic;`;
  1262. const result = extractFromSource('Utils.cs', code);
  1263. const importNode = result.nodes.find((n) => n.kind === 'import');
  1264. expect(importNode).toBeDefined();
  1265. expect(importNode?.name).toBe('System.Collections.Generic');
  1266. });
  1267. it('should extract static using', () => {
  1268. const code = `using static System.Console;`;
  1269. const result = extractFromSource('App.cs', code);
  1270. const importNode = result.nodes.find((n) => n.kind === 'import');
  1271. expect(importNode).toBeDefined();
  1272. expect(importNode?.name).toBe('System.Console');
  1273. expect(importNode?.signature).toContain('static');
  1274. });
  1275. it('should extract alias using', () => {
  1276. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1277. const result = extractFromSource('Types.cs', code);
  1278. const importNode = result.nodes.find((n) => n.kind === 'import');
  1279. expect(importNode).toBeDefined();
  1280. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1281. expect(importNode?.signature).toContain('MyList =');
  1282. });
  1283. it('should extract multiple usings', () => {
  1284. const code = `
  1285. using System;
  1286. using System.Threading.Tasks;
  1287. using Microsoft.Extensions.DependencyInjection;
  1288. `;
  1289. const result = extractFromSource('Service.cs', code);
  1290. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1291. expect(importNodes.length).toBe(3);
  1292. const names = importNodes.map((n) => n.name);
  1293. expect(names).toContain('System');
  1294. expect(names).toContain('System.Threading.Tasks');
  1295. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1296. });
  1297. });
  1298. describe('PHP imports', () => {
  1299. it('should extract simple use', () => {
  1300. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1301. const result = extractFromSource('Test.php', code);
  1302. const importNode = result.nodes.find((n) => n.kind === 'import');
  1303. expect(importNode).toBeDefined();
  1304. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1305. });
  1306. it('should extract aliased use', () => {
  1307. const code = `<?php use Mockery as m;`;
  1308. const result = extractFromSource('Test.php', code);
  1309. const importNode = result.nodes.find((n) => n.kind === 'import');
  1310. expect(importNode).toBeDefined();
  1311. expect(importNode?.name).toBe('Mockery');
  1312. expect(importNode?.signature).toContain('as m');
  1313. });
  1314. it('should extract function use', () => {
  1315. const code = `<?php use function Illuminate\\Support\\env;`;
  1316. const result = extractFromSource('helpers.php', code);
  1317. const importNode = result.nodes.find((n) => n.kind === 'import');
  1318. expect(importNode).toBeDefined();
  1319. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1320. expect(importNode?.signature).toContain('function');
  1321. });
  1322. it('should extract grouped use', () => {
  1323. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1324. const result = extractFromSource('Models.php', code);
  1325. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1326. expect(importNodes.length).toBe(2);
  1327. const names = importNodes.map((n) => n.name);
  1328. expect(names).toContain('Illuminate\\Database\\Model');
  1329. expect(names).toContain('Illuminate\\Database\\Builder');
  1330. });
  1331. it('should extract multiple uses', () => {
  1332. const code = `<?php
  1333. use Illuminate\\Support\\Collection;
  1334. use Illuminate\\Support\\Str;
  1335. use Closure;
  1336. `;
  1337. const result = extractFromSource('Service.php', code);
  1338. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1339. expect(importNodes.length).toBe(3);
  1340. const names = importNodes.map((n) => n.name);
  1341. expect(names).toContain('Illuminate\\Support\\Collection');
  1342. expect(names).toContain('Illuminate\\Support\\Str');
  1343. expect(names).toContain('Closure');
  1344. });
  1345. });
  1346. describe('Ruby imports', () => {
  1347. it('should extract require', () => {
  1348. const code = `require 'json'`;
  1349. const result = extractFromSource('app.rb', code);
  1350. const importNode = result.nodes.find((n) => n.kind === 'import');
  1351. expect(importNode).toBeDefined();
  1352. expect(importNode?.name).toBe('json');
  1353. expect(importNode?.signature).toBe("require 'json'");
  1354. });
  1355. it('should extract require with path', () => {
  1356. const code = `require 'active_support/core_ext/string'`;
  1357. const result = extractFromSource('config.rb', code);
  1358. const importNode = result.nodes.find((n) => n.kind === 'import');
  1359. expect(importNode).toBeDefined();
  1360. expect(importNode?.name).toBe('active_support/core_ext/string');
  1361. });
  1362. it('should extract require_relative', () => {
  1363. const code = `require_relative '../test_helper'`;
  1364. const result = extractFromSource('test/my_test.rb', code);
  1365. const importNode = result.nodes.find((n) => n.kind === 'import');
  1366. expect(importNode).toBeDefined();
  1367. expect(importNode?.name).toBe('../test_helper');
  1368. expect(importNode?.signature).toContain('require_relative');
  1369. });
  1370. it('should not extract non-require calls', () => {
  1371. const code = `puts 'hello'`;
  1372. const result = extractFromSource('app.rb', code);
  1373. const importNode = result.nodes.find((n) => n.kind === 'import');
  1374. expect(importNode).toBeUndefined();
  1375. });
  1376. it('should extract multiple requires', () => {
  1377. const code = `
  1378. require 'json'
  1379. require 'yaml'
  1380. require_relative 'helper'
  1381. `;
  1382. const result = extractFromSource('lib.rb', code);
  1383. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1384. expect(importNodes.length).toBe(3);
  1385. const names = importNodes.map((n) => n.name);
  1386. expect(names).toContain('json');
  1387. expect(names).toContain('yaml');
  1388. expect(names).toContain('helper');
  1389. });
  1390. });
  1391. describe('C/C++ imports', () => {
  1392. it('should extract system include', () => {
  1393. const code = `#include <iostream>`;
  1394. const result = extractFromSource('main.cpp', code);
  1395. const importNode = result.nodes.find((n) => n.kind === 'import');
  1396. expect(importNode).toBeDefined();
  1397. expect(importNode?.name).toBe('iostream');
  1398. expect(importNode?.signature).toBe('#include <iostream>');
  1399. });
  1400. it('should extract system include with path', () => {
  1401. const code = `#include <nlohmann/json.hpp>`;
  1402. const result = extractFromSource('app.cpp', code);
  1403. const importNode = result.nodes.find((n) => n.kind === 'import');
  1404. expect(importNode).toBeDefined();
  1405. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1406. });
  1407. it('should extract local include', () => {
  1408. const code = `#include "myheader.h"`;
  1409. const result = extractFromSource('main.cpp', code);
  1410. const importNode = result.nodes.find((n) => n.kind === 'import');
  1411. expect(importNode).toBeDefined();
  1412. expect(importNode?.name).toBe('myheader.h');
  1413. });
  1414. it('should extract C header', () => {
  1415. const code = `#include <stdio.h>`;
  1416. const result = extractFromSource('main.c', code);
  1417. const importNode = result.nodes.find((n) => n.kind === 'import');
  1418. expect(importNode).toBeDefined();
  1419. expect(importNode?.name).toBe('stdio.h');
  1420. });
  1421. it('should extract multiple includes', () => {
  1422. const code = `
  1423. #include <iostream>
  1424. #include <vector>
  1425. #include "config.h"
  1426. `;
  1427. const result = extractFromSource('app.cpp', code);
  1428. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1429. expect(importNodes.length).toBe(3);
  1430. const names = importNodes.map((n) => n.name);
  1431. expect(names).toContain('iostream');
  1432. expect(names).toContain('vector');
  1433. expect(names).toContain('config.h');
  1434. });
  1435. });
  1436. describe('Dart imports', () => {
  1437. it('should extract dart: import', () => {
  1438. const code = `import 'dart:async';`;
  1439. const result = extractFromSource('main.dart', code);
  1440. const importNode = result.nodes.find((n) => n.kind === 'import');
  1441. expect(importNode).toBeDefined();
  1442. expect(importNode?.name).toBe('dart:async');
  1443. expect(importNode?.signature).toBe("import 'dart:async';");
  1444. });
  1445. it('should extract package import', () => {
  1446. const code = `import 'package:flutter/material.dart';`;
  1447. const result = extractFromSource('app.dart', code);
  1448. const importNode = result.nodes.find((n) => n.kind === 'import');
  1449. expect(importNode).toBeDefined();
  1450. expect(importNode?.name).toBe('package:flutter/material.dart');
  1451. });
  1452. it('should extract aliased import', () => {
  1453. const code = `import 'package:http/http.dart' as http;`;
  1454. const result = extractFromSource('api.dart', code);
  1455. const importNode = result.nodes.find((n) => n.kind === 'import');
  1456. expect(importNode).toBeDefined();
  1457. expect(importNode?.name).toBe('package:http/http.dart');
  1458. expect(importNode?.signature).toContain('as http');
  1459. });
  1460. it('should extract multiple imports', () => {
  1461. const code = `
  1462. import 'dart:async';
  1463. import 'dart:convert';
  1464. import 'package:flutter/material.dart';
  1465. `;
  1466. const result = extractFromSource('main.dart', code);
  1467. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1468. expect(importNodes.length).toBe(3);
  1469. const names = importNodes.map((n) => n.name);
  1470. expect(names).toContain('dart:async');
  1471. expect(names).toContain('dart:convert');
  1472. expect(names).toContain('package:flutter/material.dart');
  1473. });
  1474. it('should extract relative import', () => {
  1475. const code = `import '../utils/helpers.dart';`;
  1476. const result = extractFromSource('lib/main.dart', code);
  1477. const importNode = result.nodes.find((n) => n.kind === 'import');
  1478. expect(importNode).toBeDefined();
  1479. expect(importNode?.name).toBe('../utils/helpers.dart');
  1480. });
  1481. });
  1482. describe('Liquid imports', () => {
  1483. it('should extract render tag', () => {
  1484. const code = `{% render 'loading-spinner' %}`;
  1485. const result = extractFromSource('template.liquid', code);
  1486. const importNode = result.nodes.find((n) => n.kind === 'import');
  1487. expect(importNode).toBeDefined();
  1488. expect(importNode?.name).toBe('loading-spinner');
  1489. expect(importNode?.signature).toContain('render');
  1490. });
  1491. it('should extract section tag', () => {
  1492. const code = `{% section 'header' %}`;
  1493. const result = extractFromSource('layout/theme.liquid', code);
  1494. const importNode = result.nodes.find((n) => n.kind === 'import');
  1495. expect(importNode).toBeDefined();
  1496. expect(importNode?.name).toBe('header');
  1497. expect(importNode?.signature).toContain('section');
  1498. });
  1499. it('should extract include tag', () => {
  1500. const code = `{% include 'icon-cart' %}`;
  1501. const result = extractFromSource('snippets/header.liquid', code);
  1502. const importNode = result.nodes.find((n) => n.kind === 'import');
  1503. expect(importNode).toBeDefined();
  1504. expect(importNode?.name).toBe('icon-cart');
  1505. expect(importNode?.signature).toContain('include');
  1506. });
  1507. it('should extract render with whitespace control', () => {
  1508. const code = `{%- render 'price' -%}`;
  1509. const result = extractFromSource('snippets/product.liquid', code);
  1510. const importNode = result.nodes.find((n) => n.kind === 'import');
  1511. expect(importNode).toBeDefined();
  1512. expect(importNode?.name).toBe('price');
  1513. });
  1514. it('should extract multiple imports', () => {
  1515. const code = `
  1516. {% section 'header' %}
  1517. {% render 'loading-spinner' %}
  1518. {% render 'cart-drawer' %}
  1519. `;
  1520. const result = extractFromSource('layout/theme.liquid', code);
  1521. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1522. expect(importNodes.length).toBe(3);
  1523. const names = importNodes.map((n) => n.name);
  1524. expect(names).toContain('header');
  1525. expect(names).toContain('loading-spinner');
  1526. expect(names).toContain('cart-drawer');
  1527. });
  1528. });
  1529. });
  1530. describe('Full Indexing', () => {
  1531. let tempDir: string;
  1532. beforeEach(() => {
  1533. tempDir = createTempDir();
  1534. });
  1535. afterEach(() => {
  1536. cleanupTempDir(tempDir);
  1537. });
  1538. it('should index a TypeScript file', async () => {
  1539. // Create test file
  1540. const srcDir = path.join(tempDir, 'src');
  1541. fs.mkdirSync(srcDir);
  1542. fs.writeFileSync(
  1543. path.join(srcDir, 'utils.ts'),
  1544. `
  1545. export function add(a: number, b: number): number {
  1546. return a + b;
  1547. }
  1548. export function multiply(a: number, b: number): number {
  1549. return a * b;
  1550. }
  1551. `
  1552. );
  1553. // Initialize and index
  1554. const cg = CodeGraph.initSync(tempDir);
  1555. const result = await cg.indexAll();
  1556. expect(result.success).toBe(true);
  1557. expect(result.filesIndexed).toBe(1);
  1558. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  1559. // Check nodes were stored
  1560. const nodes = cg.getNodesInFile('src/utils.ts');
  1561. expect(nodes.length).toBeGreaterThanOrEqual(2);
  1562. const addFunc = nodes.find((n) => n.name === 'add');
  1563. expect(addFunc).toBeDefined();
  1564. expect(addFunc?.kind).toBe('function');
  1565. cg.close();
  1566. });
  1567. it('should index multiple files', async () => {
  1568. // Create test files
  1569. const srcDir = path.join(tempDir, 'src');
  1570. fs.mkdirSync(srcDir);
  1571. fs.writeFileSync(
  1572. path.join(srcDir, 'math.ts'),
  1573. `export function add(a: number, b: number) { return a + b; }`
  1574. );
  1575. fs.writeFileSync(
  1576. path.join(srcDir, 'string.ts'),
  1577. `export function capitalize(s: string) { return s.toUpperCase(); }`
  1578. );
  1579. // Initialize and index
  1580. const cg = CodeGraph.initSync(tempDir);
  1581. const result = await cg.indexAll();
  1582. expect(result.success).toBe(true);
  1583. expect(result.filesIndexed).toBe(2);
  1584. const files = cg.getFiles();
  1585. expect(files.length).toBe(2);
  1586. cg.close();
  1587. });
  1588. it('should track file hashes for incremental updates', async () => {
  1589. // Create initial file
  1590. const srcDir = path.join(tempDir, 'src');
  1591. fs.mkdirSync(srcDir);
  1592. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  1593. // Initialize and index
  1594. const cg = CodeGraph.initSync(tempDir);
  1595. await cg.indexAll();
  1596. // Check file is tracked
  1597. const file = cg.getFile('src/main.ts');
  1598. expect(file).toBeDefined();
  1599. expect(file?.contentHash).toBeDefined();
  1600. // Modify file
  1601. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  1602. // Check for changes
  1603. const changes = cg.getChangedFiles();
  1604. expect(changes.modified).toContain('src/main.ts');
  1605. cg.close();
  1606. });
  1607. it('should sync and detect changes', async () => {
  1608. // Create initial file
  1609. const srcDir = path.join(tempDir, 'src');
  1610. fs.mkdirSync(srcDir);
  1611. fs.writeFileSync(
  1612. path.join(srcDir, 'main.ts'),
  1613. `export function original() { return 1; }`
  1614. );
  1615. // Initialize and index
  1616. const cg = CodeGraph.initSync(tempDir);
  1617. await cg.indexAll();
  1618. const initialNodes = cg.getNodesInFile('src/main.ts');
  1619. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  1620. // Modify file
  1621. fs.writeFileSync(
  1622. path.join(srcDir, 'main.ts'),
  1623. `export function updated() { return 2; }`
  1624. );
  1625. // Sync
  1626. const syncResult = await cg.sync();
  1627. expect(syncResult.filesModified).toBe(1);
  1628. // Check nodes were updated
  1629. const updatedNodes = cg.getNodesInFile('src/main.ts');
  1630. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  1631. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  1632. cg.close();
  1633. });
  1634. });
  1635. describe('Path Normalization', () => {
  1636. it('should convert backslashes to forward slashes', () => {
  1637. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  1638. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  1639. });
  1640. it('should leave forward-slash paths unchanged', () => {
  1641. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  1642. });
  1643. it('should handle empty string', () => {
  1644. expect(normalizePath('')).toBe('');
  1645. });
  1646. });
  1647. describe('Directory Exclusion', () => {
  1648. let tempDir: string;
  1649. beforeEach(() => {
  1650. tempDir = createTempDir();
  1651. });
  1652. afterEach(() => {
  1653. cleanupTempDir(tempDir);
  1654. });
  1655. it('should exclude node_modules directories', () => {
  1656. // Create structure: src/index.ts + node_modules/pkg/index.js
  1657. const srcDir = path.join(tempDir, 'src');
  1658. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  1659. fs.mkdirSync(srcDir, { recursive: true });
  1660. fs.mkdirSync(nmDir, { recursive: true });
  1661. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1662. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  1663. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1664. const files = scanDirectory(tempDir, config);
  1665. expect(files).toContain('src/index.ts');
  1666. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  1667. });
  1668. it('should exclude nested node_modules directories', () => {
  1669. // Create structure: packages/app/node_modules/pkg/index.js
  1670. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  1671. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  1672. fs.mkdirSync(srcDir, { recursive: true });
  1673. fs.mkdirSync(nmDir, { recursive: true });
  1674. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1675. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  1676. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1677. const files = scanDirectory(tempDir, config);
  1678. expect(files).toContain('packages/app/src/index.ts');
  1679. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  1680. });
  1681. it('should exclude .git directories', () => {
  1682. const srcDir = path.join(tempDir, 'src');
  1683. const gitDir = path.join(tempDir, '.git', 'objects');
  1684. fs.mkdirSync(srcDir, { recursive: true });
  1685. fs.mkdirSync(gitDir, { recursive: true });
  1686. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1687. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  1688. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1689. const files = scanDirectory(tempDir, config);
  1690. expect(files).toContain('src/index.ts');
  1691. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  1692. });
  1693. it('should return forward-slash paths on all platforms', () => {
  1694. const srcDir = path.join(tempDir, 'src', 'components');
  1695. fs.mkdirSync(srcDir, { recursive: true });
  1696. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  1697. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1698. const files = scanDirectory(tempDir, config);
  1699. expect(files.length).toBe(1);
  1700. expect(files[0]).toBe('src/components/Button.tsx');
  1701. expect(files[0]).not.toContain('\\');
  1702. });
  1703. it('should respect .codegraphignore marker', () => {
  1704. const srcDir = path.join(tempDir, 'src');
  1705. const vendorDir = path.join(tempDir, 'vendor');
  1706. fs.mkdirSync(srcDir, { recursive: true });
  1707. fs.mkdirSync(vendorDir, { recursive: true });
  1708. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1709. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  1710. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  1711. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1712. const files = scanDirectory(tempDir, config);
  1713. expect(files).toContain('src/index.ts');
  1714. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  1715. });
  1716. });