frameworks.test.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. import { describe, it, expect } from 'vitest';
  2. import type { FrameworkResolver, UnresolvedRef } from '../src/resolution/types';
  3. import type { Node } from '../src/types';
  4. describe('FrameworkResolver.extract interface', () => {
  5. it('extract() returns { nodes, references }', () => {
  6. const resolver: FrameworkResolver = {
  7. name: 'fake',
  8. detect: () => true,
  9. resolve: () => null,
  10. languages: ['python'],
  11. extract: (_filePath: string, _content: string) => ({
  12. nodes: [] as Node[],
  13. references: [] as UnresolvedRef[],
  14. }),
  15. };
  16. const result = resolver.extract!('foo.py', '');
  17. expect(result).toEqual({ nodes: [], references: [] });
  18. });
  19. });
  20. import { getApplicableFrameworks } from '../src/resolution/frameworks';
  21. import type { FrameworkResolver } from '../src/resolution/types';
  22. describe('getApplicableFrameworks', () => {
  23. const pyFw: FrameworkResolver = { name: 'py', languages: ['python'], detect: () => true, resolve: () => null };
  24. const jsFw: FrameworkResolver = { name: 'js', languages: ['javascript', 'typescript'], detect: () => true, resolve: () => null };
  25. const anyFw: FrameworkResolver = { name: 'any', detect: () => true, resolve: () => null };
  26. it('filters by language', () => {
  27. const result = getApplicableFrameworks([pyFw, jsFw, anyFw], 'python');
  28. expect(result.map(r => r.name)).toEqual(['py', 'any']);
  29. });
  30. it('returns anyFw-only when language has no matches', () => {
  31. const result = getApplicableFrameworks([pyFw, jsFw, anyFw], 'rust');
  32. expect(result.map(r => r.name)).toEqual(['any']);
  33. });
  34. });
  35. import { djangoResolver } from '../src/resolution/frameworks/python';
  36. describe('djangoResolver.extract', () => {
  37. it('extracts route node and reference for path() with CBV.as_view()', () => {
  38. const src = `
  39. from django.urls import path
  40. from users.views import UserListView
  41. urlpatterns = [
  42. path('users/', UserListView.as_view(), name='user-list'),
  43. ]
  44. `;
  45. const { nodes, references } = djangoResolver.extract!('users/urls.py', src);
  46. expect(nodes).toHaveLength(1);
  47. expect(nodes[0].kind).toBe('route');
  48. expect(nodes[0].name).toBe('users/');
  49. expect(references).toHaveLength(1);
  50. expect(references[0].referenceName).toBe('UserListView');
  51. expect(references[0].referenceKind).toBe('references');
  52. expect(references[0].fromNodeId).toBe(nodes[0].id);
  53. });
  54. it('extracts route for path() with dotted module.Class.as_view()', () => {
  55. const src = `from django.urls import path\nfrom api.v1 import views as api_v1_views\nurlpatterns = [path('api/', api_v1_views.UserListView.as_view())]\n`;
  56. const { nodes, references } = djangoResolver.extract!('api/urls.py', src);
  57. expect(nodes).toHaveLength(1);
  58. expect(references[0].referenceName).toBe('UserListView');
  59. });
  60. it('extracts route for path() with bare function view', () => {
  61. const src = `from django.urls import path\nurlpatterns = [path('home/', home_view, name='home')]\n`;
  62. const { nodes, references } = djangoResolver.extract!('home/urls.py', src);
  63. expect(references[0].referenceName).toBe('home_view');
  64. });
  65. it('extracts route for path() with include()', () => {
  66. const src = `from django.urls import path, include\nurlpatterns = [path('api/', include('api.urls'))]\n`;
  67. const { nodes, references } = djangoResolver.extract!('root/urls.py', src);
  68. expect(nodes).toHaveLength(1);
  69. expect(nodes[0].kind).toBe('route');
  70. expect(references[0].referenceName).toBe('api.urls');
  71. expect(references[0].referenceKind).toBe('imports');
  72. });
  73. it('extracts routes for re_path and url', () => {
  74. const src = `from django.urls import re_path, url\nurlpatterns = [re_path(r'^users/$', UserView), url(r'^old/$', OldView)]\n`;
  75. const { nodes } = djangoResolver.extract!('legacy/urls.py', src);
  76. expect(nodes).toHaveLength(2);
  77. expect(nodes.map(n => n.name)).toEqual(['^users/$', '^old/$']);
  78. });
  79. it('returns empty result for a non-urls.py python file', () => {
  80. const src = `def foo(): return 1\n`;
  81. const { nodes, references } = djangoResolver.extract!('views.py', src);
  82. expect(nodes).toEqual([]);
  83. expect(references).toEqual([]);
  84. });
  85. });
  86. import { flaskResolver, fastapiResolver } from '../src/resolution/frameworks/python';
  87. describe('flaskResolver.extract', () => {
  88. it('extracts route and reference from @app.route', () => {
  89. const src = `
  90. @app.route('/users')
  91. def list_users():
  92. return []
  93. `;
  94. const { nodes, references } = flaskResolver.extract!('app.py', src);
  95. expect(nodes).toHaveLength(1);
  96. expect(nodes[0].kind).toBe('route');
  97. expect(nodes[0].name).toBe('GET /users');
  98. expect(references[0].referenceName).toBe('list_users');
  99. });
  100. it('extracts blueprint routes', () => {
  101. const src = `
  102. @users_bp.route('/<id>', methods=['POST'])
  103. def create_user(id):
  104. pass
  105. `;
  106. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  107. expect(nodes[0].name).toBe('POST /<id>');
  108. expect(references[0].referenceName).toBe('create_user');
  109. });
  110. it('resolves the handler across an intervening decorator (@login_required)', () => {
  111. const src = `
  112. @bp.route('/profile')
  113. @login_required
  114. def profile():
  115. return render_template('profile.html')
  116. `;
  117. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  118. expect(nodes[0].name).toBe('GET /profile');
  119. expect(references[0].referenceName).toBe('profile');
  120. });
  121. it('extracts stacked @x.route decorators bound to one view', () => {
  122. const src = `
  123. @bp.route('/', methods=['GET', 'POST'])
  124. @bp.route('/index', methods=['GET', 'POST'])
  125. @login_required
  126. def index():
  127. return render_template('index.html')
  128. `;
  129. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  130. expect(nodes.map((n) => n.name)).toEqual(['GET /', 'GET /index']);
  131. expect(references.map((r) => r.referenceName)).toEqual(['index', 'index']);
  132. });
  133. });
  134. describe('fastapiResolver.extract', () => {
  135. it('extracts route and reference from @app.get', () => {
  136. const src = `
  137. @app.get('/users')
  138. async def list_users():
  139. return []
  140. `;
  141. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  142. expect(nodes[0].name).toBe('GET /users');
  143. expect(references[0].referenceName).toBe('list_users');
  144. });
  145. it('extracts route from router.post', () => {
  146. const src = `
  147. @router.post('/items')
  148. def create_item(item: Item):
  149. pass
  150. `;
  151. const { nodes, references } = fastapiResolver.extract!('items.py', src);
  152. expect(nodes[0].name).toBe('POST /items');
  153. expect(references[0].referenceName).toBe('create_item');
  154. });
  155. it('extracts a route mounted at the router/prefix root (empty path)', () => {
  156. const src = `
  157. @router.get("", response_model=ListOfArticles, name="articles:list")
  158. async def list_articles():
  159. return []
  160. `;
  161. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  162. expect(nodes[0].name).toBe('GET /');
  163. expect(references[0].referenceName).toBe('list_articles');
  164. });
  165. it('extracts a multi-line decorator with an empty path', () => {
  166. const src = `
  167. @router.post(
  168. "",
  169. status_code=201,
  170. response_model=ArticleInResponse,
  171. )
  172. async def create_article():
  173. pass
  174. `;
  175. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  176. expect(nodes[0].name).toBe('POST /');
  177. expect(references[0].referenceName).toBe('create_article');
  178. });
  179. });
  180. import { expressResolver } from '../src/resolution/frameworks/express';
  181. describe('expressResolver.extract', () => {
  182. it('extracts route with inline handler reference', () => {
  183. const src = `app.get('/users', listUsers);\n`;
  184. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  185. expect(nodes).toHaveLength(1);
  186. expect(nodes[0].name).toBe('GET /users');
  187. expect(references[0].referenceName).toBe('listUsers');
  188. });
  189. it('extracts route with router.post and middleware chain', () => {
  190. const src = `router.post('/items', auth, createItem);\n`;
  191. const { nodes, references } = expressResolver.extract!('items.ts', src);
  192. expect(nodes[0].name).toBe('POST /items');
  193. // Multiple handlers: prefer the LAST one (convention: middleware first, handler last)
  194. expect(references[0].referenceName).toBe('createItem');
  195. });
  196. it('extracts route with controller method reference', () => {
  197. const src = `app.get('/x', userController.list);\n`;
  198. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  199. expect(references[0].referenceName).toBe('list');
  200. });
  201. });
  202. import { nestjsResolver } from '../src/resolution/frameworks/nestjs';
  203. describe('nestjsResolver.extract — HTTP', () => {
  204. it('joins @Controller prefix with @Get and links the handler', () => {
  205. const src = `
  206. @Controller('users')
  207. export class UsersController {
  208. @Get()
  209. findAll() { return []; }
  210. }
  211. `;
  212. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  213. expect(nodes).toHaveLength(1);
  214. expect(nodes[0].kind).toBe('route');
  215. expect(nodes[0].name).toBe('GET /users');
  216. expect(references[0].referenceName).toBe('findAll');
  217. expect(references[0].referenceKind).toBe('references');
  218. expect(references[0].fromNodeId).toBe(nodes[0].id);
  219. });
  220. it('joins controller prefix with a method-level path param', () => {
  221. const src = `
  222. @Controller('cats')
  223. export class CatsController {
  224. @Get(':id')
  225. findOne(@Param('id') id: string) { return id; }
  226. }
  227. `;
  228. const { nodes, references } = nestjsResolver.extract!('cats.controller.ts', src);
  229. expect(nodes[0].name).toBe('GET /cats/:id');
  230. expect(references[0].referenceName).toBe('findOne');
  231. });
  232. it('handles an empty @Controller() and empty @Post()', () => {
  233. const src = `
  234. @Controller()
  235. export class AppController {
  236. @Post()
  237. create() {}
  238. }
  239. `;
  240. const { nodes, references } = nestjsResolver.extract!('app.controller.ts', src);
  241. expect(nodes[0].name).toBe('POST /');
  242. expect(references[0].referenceName).toBe('create');
  243. });
  244. it('covers HTTP verbs and skips intervening method decorators', () => {
  245. const src = `
  246. @Controller('todos')
  247. export class TodosController {
  248. @Put(':id')
  249. @UseGuards(AuthGuard)
  250. update(@Param('id') id: string) {}
  251. @Delete(':id')
  252. async remove(@Param('id') id: string) {}
  253. }
  254. `;
  255. const { nodes, references } = nestjsResolver.extract!('todos.controller.ts', src);
  256. expect(nodes.map((n) => n.name)).toEqual(['PUT /todos/:id', 'DELETE /todos/:id']);
  257. expect(references.map((r) => r.referenceName)).toEqual(['update', 'remove']);
  258. });
  259. it('attributes methods to the right controller when a file has two', () => {
  260. const src = `
  261. @Controller('a')
  262. export class AController {
  263. @Get('x')
  264. ax() {}
  265. }
  266. @Controller('b')
  267. export class BController {
  268. @Get('y')
  269. by() {}
  270. }
  271. `;
  272. const { nodes } = nestjsResolver.extract!('multi.controller.ts', src);
  273. expect(nodes.map((n) => n.name)).toEqual(['GET /a/x', 'GET /b/y']);
  274. });
  275. });
  276. describe('nestjsResolver.extract — GraphQL', () => {
  277. it('emits QUERY/MUTATION nodes from a resolver, defaulting to the method name', () => {
  278. const src = `
  279. @Resolver(() => User)
  280. export class UsersResolver {
  281. @Query(() => [User])
  282. users() { return []; }
  283. @Mutation(() => User)
  284. createUser(@Args('input') input: CreateUserInput) {}
  285. }
  286. `;
  287. const { nodes, references } = nestjsResolver.extract!('users.resolver.ts', src);
  288. expect(nodes.map((n) => n.name)).toEqual(['QUERY users', 'MUTATION createUser']);
  289. expect(references.map((r) => r.referenceName)).toEqual(['users', 'createUser']);
  290. });
  291. it('uses an explicit operation name when given', () => {
  292. const src = `
  293. @Resolver()
  294. export class CatsResolver {
  295. @Query(() => Cat, { name: 'cat' })
  296. getCat() {}
  297. }
  298. `;
  299. const { nodes } = nestjsResolver.extract!('cats.resolver.ts', src);
  300. expect(nodes[0].name).toBe('QUERY cat');
  301. });
  302. it('does NOT treat the REST @Query() parameter decorator as a GraphQL op', () => {
  303. const src = `
  304. @Controller('search')
  305. export class SearchController {
  306. @Get()
  307. search(@Query() query: SearchDto) { return query; }
  308. }
  309. `;
  310. const { nodes } = nestjsResolver.extract!('search.controller.ts', src);
  311. // Only the HTTP route — the @Query() param decorator must be ignored.
  312. expect(nodes.map((n) => n.name)).toEqual(['GET /search']);
  313. });
  314. });
  315. describe('nestjsResolver.extract — microservices & websockets', () => {
  316. it('extracts @MessagePattern and @EventPattern handlers', () => {
  317. const src = `
  318. @Controller()
  319. export class MathController {
  320. @MessagePattern({ cmd: 'sum' })
  321. accumulate(data: number[]) {}
  322. @EventPattern('user.created')
  323. handleUserCreated(data: any) {}
  324. }
  325. `;
  326. const { nodes, references } = nestjsResolver.extract!('math.controller.ts', src);
  327. expect(nodes.map((n) => n.name)).toEqual(['MESSAGE sum', 'EVENT user.created']);
  328. expect(references.map((r) => r.referenceName)).toEqual(['accumulate', 'handleUserCreated']);
  329. });
  330. it('extracts @SubscribeMessage handlers with the gateway namespace', () => {
  331. const src = `
  332. @WebSocketGateway({ namespace: 'chat' })
  333. export class ChatGateway {
  334. @SubscribeMessage('message')
  335. handleMessage(@MessageBody() data: string) {}
  336. }
  337. `;
  338. const { nodes, references } = nestjsResolver.extract!('chat.gateway.ts', src);
  339. expect(nodes[0].name).toBe('WS chat:message');
  340. expect(references[0].referenceName).toBe('handleMessage');
  341. });
  342. it('extracts @SubscribeMessage without a namespace', () => {
  343. const src = `
  344. @WebSocketGateway()
  345. export class EventsGateway {
  346. @SubscribeMessage('events')
  347. onEvent() {}
  348. }
  349. `;
  350. const { nodes } = nestjsResolver.extract!('events.gateway.ts', src);
  351. expect(nodes[0].name).toBe('WS events');
  352. });
  353. it('returns empty for a non-JS/TS file', () => {
  354. const { nodes, references } = nestjsResolver.extract!('thing.py', '@Controller("x")');
  355. expect(nodes).toEqual([]);
  356. expect(references).toEqual([]);
  357. });
  358. });
  359. describe('nestjsResolver.detect', () => {
  360. const baseContext = {
  361. getNodesInFile: () => [],
  362. getNodesByName: () => [],
  363. getNodesByQualifiedName: () => [],
  364. getNodesByKind: () => [],
  365. fileExists: () => false,
  366. getProjectRoot: () => '/test',
  367. getAllFiles: () => [],
  368. getNodesByLowerName: () => [],
  369. getImportMappings: () => [],
  370. };
  371. it('detects @nestjs/* in package.json', () => {
  372. const context = {
  373. ...baseContext,
  374. readFile: (p: string) =>
  375. p === 'package.json'
  376. ? JSON.stringify({ dependencies: { '@nestjs/common': '^10.0.0' } })
  377. : null,
  378. };
  379. expect(nestjsResolver.detect(context as any)).toBe(true);
  380. });
  381. it('detects @Controller in a *.controller.ts file when package.json is absent', () => {
  382. const context = {
  383. ...baseContext,
  384. getAllFiles: () => ['src/users.controller.ts'],
  385. readFile: (p: string) =>
  386. p === 'src/users.controller.ts'
  387. ? `@Controller('users')\nexport class UsersController {}`
  388. : null,
  389. };
  390. expect(nestjsResolver.detect(context as any)).toBe(true);
  391. });
  392. it('returns false for a non-Nest project', () => {
  393. const context = {
  394. ...baseContext,
  395. readFile: (p: string) =>
  396. p === 'package.json' ? JSON.stringify({ dependencies: { express: '^4' } }) : null,
  397. };
  398. expect(nestjsResolver.detect(context as any)).toBe(false);
  399. });
  400. });
  401. describe('nestjsResolver.resolve', () => {
  402. const baseContext = {
  403. getNodesInFile: () => [],
  404. getNodesByName: () => [],
  405. getNodesByQualifiedName: () => [],
  406. getNodesByKind: () => [],
  407. fileExists: () => false,
  408. readFile: () => null,
  409. getProjectRoot: () => '/test',
  410. getAllFiles: () => [],
  411. getNodesByLowerName: () => [],
  412. getImportMappings: () => [],
  413. };
  414. it('resolves an injected *Service reference to the class in a *.service.ts file', () => {
  415. const svcNode: Node = {
  416. id: 'class:src/users/users.service.ts:UsersService:3',
  417. kind: 'class',
  418. name: 'UsersService',
  419. qualifiedName: 'src/users/users.service.ts::UsersService',
  420. filePath: 'src/users/users.service.ts',
  421. language: 'typescript',
  422. startLine: 3,
  423. endLine: 3,
  424. startColumn: 0,
  425. endColumn: 0,
  426. updatedAt: Date.now(),
  427. };
  428. const context = {
  429. ...baseContext,
  430. getNodesByName: (n: string) => (n === 'UsersService' ? [svcNode] : []),
  431. };
  432. const ref = {
  433. fromNodeId: 'class:src/users/users.controller.ts:UsersController:5',
  434. referenceName: 'UsersService',
  435. referenceKind: 'references' as const,
  436. line: 6,
  437. column: 4,
  438. filePath: 'src/users/users.controller.ts',
  439. language: 'typescript' as const,
  440. };
  441. const result = nestjsResolver.resolve(ref, context as any);
  442. expect(result?.targetNodeId).toBe(svcNode.id);
  443. expect(result?.resolvedBy).toBe('framework');
  444. expect(result?.confidence).toBeGreaterThanOrEqual(0.85);
  445. });
  446. it('returns null for a name without a provider suffix', () => {
  447. const ref = {
  448. fromNodeId: 'x',
  449. referenceName: 'doThing',
  450. referenceKind: 'references' as const,
  451. line: 1,
  452. column: 1,
  453. filePath: 'a.ts',
  454. language: 'typescript' as const,
  455. };
  456. expect(nestjsResolver.resolve(ref, baseContext as any)).toBeNull();
  457. });
  458. });
  459. import { laravelResolver } from '../src/resolution/frameworks/laravel';
  460. describe('laravelResolver.extract', () => {
  461. it('extracts route with controller tuple syntax', () => {
  462. const src = `Route::get('/users', [UserController::class, 'index']);\n`;
  463. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  464. expect(nodes[0].name).toBe('GET /users');
  465. expect(references[0].referenceName).toBe('UserController@index');
  466. });
  467. it('extracts route with Controller@action syntax', () => {
  468. const src = `Route::post('/users', 'UserController@store');\n`;
  469. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  470. expect(references[0].referenceName).toBe('UserController@store');
  471. });
  472. it('extracts resource route', () => {
  473. const src = `Route::resource('users', UserController::class);\n`;
  474. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  475. expect(nodes[0].kind).toBe('route');
  476. expect(references[0].referenceName).toBe('UserController');
  477. });
  478. });
  479. import { railsResolver } from '../src/resolution/frameworks/ruby';
  480. describe('railsResolver.extract', () => {
  481. it('extracts route with controller#action syntax', () => {
  482. const src = `get '/users', to: 'users#index'\n`;
  483. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  484. expect(nodes[0].name).toBe('GET /users');
  485. expect(references[0].referenceName).toBe('users#index');
  486. });
  487. it('extracts route without to: keyword', () => {
  488. const src = `post '/items' => 'items#create'\n`;
  489. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  490. expect(references[0].referenceName).toBe('items#create');
  491. });
  492. });
  493. import { springResolver } from '../src/resolution/frameworks/java';
  494. describe('springResolver.extract', () => {
  495. it('extracts route with @GetMapping and next method', () => {
  496. const src = `
  497. @GetMapping("/users")
  498. public List<User> listUsers() {
  499. return users;
  500. }
  501. `;
  502. const { nodes, references } = springResolver.extract!('UserController.java', src);
  503. expect(nodes[0].name).toBe('GET /users');
  504. expect(references[0].referenceName).toBe('listUsers');
  505. });
  506. it('extracts a Kotlin @GetMapping with a fun handler', () => {
  507. const src = `
  508. @GetMapping("/vets")
  509. fun showVetList(model: MutableMap<String, Any>): String {
  510. return "vets"
  511. }
  512. `;
  513. const { nodes, references } = springResolver.extract!('VetController.kt', src);
  514. expect(nodes[0].name).toBe('GET /vets');
  515. expect(references[0].referenceName).toBe('showVetList');
  516. expect(nodes[0].language).toBe('kotlin');
  517. });
  518. it('joins a Kotlin class @RequestMapping prefix and skips a stacked annotation', () => {
  519. const src = `
  520. @RestController
  521. @RequestMapping("/owners")
  522. class OwnerController {
  523. @GetMapping("/{ownerId}")
  524. @ResponseBody
  525. fun showOwner(@PathVariable ownerId: Int): String {
  526. return "owner"
  527. }
  528. }
  529. `;
  530. const { nodes, references } = springResolver.extract!('OwnerController.kt', src);
  531. expect(nodes[0].name).toBe('GET /owners/{ownerId}');
  532. expect(references[0].referenceName).toBe('showOwner');
  533. });
  534. });
  535. import { playResolver } from '../src/resolution/frameworks/play';
  536. import { isSourceFile, isPlayRoutesFile } from '../src/extraction/grammars';
  537. describe('playResolver.extract (conf/routes)', () => {
  538. it('extracts METHOD /path Controller.action routes, dropping the package + args', () => {
  539. const src = `# Routes
  540. GET / controllers.Application.index
  541. GET /computers controllers.Application.list(p: Int ?= 0, s: Int ?= 2)
  542. POST /computers controllers.Application.save
  543. -> /v1/posts v1.post.PostRouter
  544. `;
  545. const { nodes, references } = playResolver.extract!('conf/routes', src);
  546. expect(nodes.map((n) => n.name)).toEqual([
  547. 'GET /',
  548. 'GET /computers',
  549. 'POST /computers',
  550. ]); // the `->` include is skipped
  551. expect(references.map((r) => r.referenceName)).toEqual([
  552. 'Application.index',
  553. 'Application.list',
  554. 'Application.save',
  555. ]);
  556. });
  557. it('only runs on Play routes files', () => {
  558. expect(playResolver.extract!('app/Foo.scala', 'GET / controllers.X.y').nodes).toHaveLength(0);
  559. });
  560. });
  561. describe('Play routes file detection', () => {
  562. it('recognizes conf/routes (extensionless) and *.routes as source files', () => {
  563. expect(isPlayRoutesFile('conf/routes')).toBe(true);
  564. expect(isPlayRoutesFile('myapp/conf/routes')).toBe(true);
  565. expect(isPlayRoutesFile('conf/admin.routes')).toBe(true);
  566. expect(isSourceFile('conf/routes')).toBe(true);
  567. expect(isPlayRoutesFile('src/routes.ts')).toBe(false);
  568. });
  569. });
  570. import { goResolver } from '../src/resolution/frameworks/go';
  571. describe('goResolver.extract', () => {
  572. it('extracts route from r.GET', () => {
  573. const src = `r.GET("/users", listUsers)\n`;
  574. const { nodes, references } = goResolver.extract!('main.go', src);
  575. expect(nodes[0].name).toBe('GET /users');
  576. expect(references[0].referenceName).toBe('listUsers');
  577. });
  578. it('extracts route from router.HandleFunc', () => {
  579. const src = `router.HandleFunc("/items", createItem)\n`;
  580. const { nodes, references } = goResolver.extract!('main.go', src);
  581. expect(references[0].referenceName).toBe('createItem');
  582. });
  583. });
  584. import { rustResolver } from '../src/resolution/frameworks/rust';
  585. describe('rustResolver.extract', () => {
  586. it('extracts route from axum .route with get()', () => {
  587. const src = `let app = Router::new().route("/users", get(list_users));\n`;
  588. const { nodes, references } = rustResolver.extract!('main.rs', src);
  589. expect(nodes[0].name).toBe('GET /users');
  590. expect(references[0].referenceName).toBe('list_users');
  591. });
  592. it('extracts every method from a chained axum .route (get().put())', () => {
  593. const src = `let app = Router::new().route("/user", get(get_current_user).put(update_user));\n`;
  594. const { nodes, references } = rustResolver.extract!('main.rs', src);
  595. expect(nodes.map((n) => n.name)).toEqual(['GET /user', 'PUT /user']);
  596. expect(references.map((r) => r.referenceName)).toEqual([
  597. 'get_current_user',
  598. 'update_user',
  599. ]);
  600. });
  601. it('extracts a multi-line axum .route with a namespaced handler', () => {
  602. const src = `
  603. let app = Router::new()
  604. .route(
  605. "/articles/feed",
  606. get(listing::feed_articles),
  607. );
  608. `;
  609. const { nodes, references } = rustResolver.extract!('main.rs', src);
  610. expect(nodes[0].name).toBe('GET /articles/feed');
  611. expect(references[0].referenceName).toBe('feed_articles');
  612. });
  613. it('extracts actix web::resource().route(web::METHOD().to(handler))', () => {
  614. const src = `App::new().service(web::resource("/user/{id}").route(web::get().to(get_user)))\n`;
  615. const { nodes, references } = rustResolver.extract!('main.rs', src);
  616. expect(nodes[0].name).toBe('GET /user/{id}');
  617. expect(references[0].referenceName).toBe('get_user');
  618. });
  619. it('extracts actix web::resource("/").to(handler) (all methods)', () => {
  620. const src = `App::new().service(web::resource("/").to(index))\n`;
  621. const { nodes, references } = rustResolver.extract!('main.rs', src);
  622. expect(nodes[0].name).toBe('ANY /');
  623. expect(references[0].referenceName).toBe('index');
  624. });
  625. it('extracts actix App-level .route("/path", web::METHOD().to(handler))', () => {
  626. const src = `App::new().route("/health", web::get().to(health_check))\n`;
  627. const { nodes, references } = rustResolver.extract!('main.rs', src);
  628. expect(nodes[0].name).toBe('GET /health');
  629. expect(references[0].referenceName).toBe('health_check');
  630. });
  631. });
  632. describe('rustResolver.resolve cargo workspace crates', () => {
  633. it('resolves crate name from workspace member lib.rs', () => {
  634. const workspaceCargo = `
  635. [workspace]
  636. members = ["crates/mytool-core", "crates/mytool-fetcher"]
  637. `;
  638. const coreCargo = `
  639. [package]
  640. name = "mytool-core"
  641. version = "0.1.0"
  642. `;
  643. const libNode: Node = {
  644. id: 'module:crates/mytool-core/src/lib.rs:mytool_core:1',
  645. kind: 'module',
  646. name: 'mytool_core',
  647. qualifiedName: 'crates/mytool-core/src/lib.rs::mytool_core',
  648. filePath: 'crates/mytool-core/src/lib.rs',
  649. language: 'rust',
  650. startLine: 1,
  651. endLine: 1,
  652. startColumn: 0,
  653. endColumn: 0,
  654. updatedAt: Date.now(),
  655. };
  656. const context = {
  657. getNodesInFile: (fp: string) => (fp === 'crates/mytool-core/src/lib.rs' ? [libNode] : []),
  658. getNodesByName: () => [],
  659. getNodesByQualifiedName: () => [],
  660. getNodesByKind: () => [],
  661. fileExists: (p: string) => (
  662. p === 'Cargo.toml' ||
  663. p === 'crates/mytool-core/Cargo.toml' ||
  664. p === 'crates/mytool-core/src/lib.rs'
  665. ),
  666. readFile: (p: string) => {
  667. if (p === 'Cargo.toml') return workspaceCargo;
  668. if (p === 'crates/mytool-core/Cargo.toml') return coreCargo;
  669. return null;
  670. },
  671. getProjectRoot: () => '/test',
  672. getAllFiles: () => [
  673. 'Cargo.toml',
  674. 'crates/mytool-core/Cargo.toml',
  675. 'crates/mytool-core/src/lib.rs',
  676. ],
  677. getNodesByLowerName: () => [],
  678. getImportMappings: () => [],
  679. };
  680. const ref = {
  681. fromNodeId: 'fn:crates/mytool-fetcher/src/main.rs:main:1',
  682. referenceName: 'mytool_core',
  683. referenceKind: 'references' as const,
  684. line: 1,
  685. column: 1,
  686. filePath: 'crates/mytool-fetcher/src/main.rs',
  687. language: 'rust' as const,
  688. };
  689. const result = rustResolver.resolve(ref, context);
  690. expect(result?.targetNodeId).toBe(libNode.id);
  691. expect(result?.resolvedBy).toBe('framework');
  692. // Workspace-manifest hits are unambiguous and must beat name-matcher's
  693. // self-file matches (0.7) so cross-crate `imports` edges materialize.
  694. expect(result?.confidence).toBeGreaterThanOrEqual(0.9);
  695. });
  696. it('resolves crate name from workspace member main.rs when lib.rs is absent', () => {
  697. const workspaceCargo = `
  698. [workspace]
  699. members = [
  700. "crates/mytool-runner",
  701. ]
  702. `;
  703. const runnerCargo = `
  704. [package]
  705. name = "mytool-runner"
  706. version = "0.1.0"
  707. `;
  708. const mainNode: Node = {
  709. id: 'module:crates/mytool-runner/src/main.rs:mytool_runner:1',
  710. kind: 'module',
  711. name: 'mytool_runner',
  712. qualifiedName: 'crates/mytool-runner/src/main.rs::mytool_runner',
  713. filePath: 'crates/mytool-runner/src/main.rs',
  714. language: 'rust',
  715. startLine: 1,
  716. endLine: 1,
  717. startColumn: 0,
  718. endColumn: 0,
  719. updatedAt: Date.now(),
  720. };
  721. const context = {
  722. getNodesInFile: (fp: string) => (fp === 'crates/mytool-runner/src/main.rs' ? [mainNode] : []),
  723. getNodesByName: () => [],
  724. getNodesByQualifiedName: () => [],
  725. getNodesByKind: () => [],
  726. fileExists: (p: string) => (
  727. p === 'Cargo.toml' ||
  728. p === 'crates/mytool-runner/Cargo.toml' ||
  729. p === 'crates/mytool-runner/src/main.rs'
  730. ),
  731. readFile: (p: string) => {
  732. if (p === 'Cargo.toml') return workspaceCargo;
  733. if (p === 'crates/mytool-runner/Cargo.toml') return runnerCargo;
  734. return null;
  735. },
  736. getProjectRoot: () => '/test',
  737. getAllFiles: () => [
  738. 'Cargo.toml',
  739. 'crates/mytool-runner/Cargo.toml',
  740. 'crates/mytool-runner/src/main.rs',
  741. ],
  742. getNodesByLowerName: () => [],
  743. getImportMappings: () => [],
  744. };
  745. const ref = {
  746. fromNodeId: 'fn:crates/mytool-runner/src/main.rs:main:1',
  747. referenceName: 'mytool_runner',
  748. referenceKind: 'references' as const,
  749. line: 1,
  750. column: 1,
  751. filePath: 'crates/mytool-runner/src/main.rs',
  752. language: 'rust' as const,
  753. };
  754. const result = rustResolver.resolve(ref, context);
  755. expect(result?.targetNodeId).toBe(mainNode.id);
  756. expect(result?.resolvedBy).toBe('framework');
  757. });
  758. it('resolves crate name when members uses a glob (crates/*)', () => {
  759. const workspaceCargo = `
  760. [workspace]
  761. members = ["crates/*"]
  762. `;
  763. const fooCargo = `
  764. [package]
  765. name = "mytool-foo"
  766. version = "0.1.0"
  767. `;
  768. const barCargo = `
  769. [package]
  770. name = "mytool-bar"
  771. version = "0.1.0"
  772. `;
  773. const fooLib: Node = {
  774. id: 'module:crates/mytool-foo/src/lib.rs:mytool_foo:1',
  775. kind: 'module',
  776. name: 'mytool_foo',
  777. qualifiedName: 'crates/mytool-foo/src/lib.rs::mytool_foo',
  778. filePath: 'crates/mytool-foo/src/lib.rs',
  779. language: 'rust',
  780. startLine: 1,
  781. endLine: 1,
  782. startColumn: 0,
  783. endColumn: 0,
  784. updatedAt: Date.now(),
  785. };
  786. const barLib: Node = {
  787. id: 'module:crates/mytool-bar/src/lib.rs:mytool_bar:1',
  788. kind: 'module',
  789. name: 'mytool_bar',
  790. qualifiedName: 'crates/mytool-bar/src/lib.rs::mytool_bar',
  791. filePath: 'crates/mytool-bar/src/lib.rs',
  792. language: 'rust',
  793. startLine: 1,
  794. endLine: 1,
  795. startColumn: 0,
  796. endColumn: 0,
  797. updatedAt: Date.now(),
  798. };
  799. const filesByPath: Record<string, string> = {
  800. 'Cargo.toml': workspaceCargo,
  801. 'crates/mytool-foo/Cargo.toml': fooCargo,
  802. 'crates/mytool-bar/Cargo.toml': barCargo,
  803. };
  804. const nodesByFile: Record<string, Node[]> = {
  805. 'crates/mytool-foo/src/lib.rs': [fooLib],
  806. 'crates/mytool-bar/src/lib.rs': [barLib],
  807. };
  808. const dirsByPath: Record<string, string[]> = {
  809. '.': ['crates'],
  810. crates: ['mytool-foo', 'mytool-bar'],
  811. 'crates/mytool-foo': ['src'],
  812. 'crates/mytool-bar': ['src'],
  813. };
  814. const context = {
  815. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  816. getNodesByName: () => [],
  817. getNodesByQualifiedName: () => [],
  818. getNodesByKind: () => [],
  819. fileExists: (p: string) => (
  820. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  821. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  822. ),
  823. readFile: (p: string) => filesByPath[p] ?? null,
  824. getProjectRoot: () => '/test',
  825. getAllFiles: () => [
  826. 'Cargo.toml',
  827. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  828. ...Object.keys(nodesByFile),
  829. ],
  830. getNodesByLowerName: () => [],
  831. getImportMappings: () => [],
  832. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  833. };
  834. const fooRef = {
  835. fromNodeId: 'fn:crates/mytool-bar/src/lib.rs:other:1',
  836. referenceName: 'mytool_foo',
  837. referenceKind: 'references' as const,
  838. line: 1,
  839. column: 1,
  840. filePath: 'crates/mytool-bar/src/lib.rs',
  841. language: 'rust' as const,
  842. };
  843. const barRef = {
  844. fromNodeId: 'fn:crates/mytool-foo/src/lib.rs:other:1',
  845. referenceName: 'mytool_bar',
  846. referenceKind: 'references' as const,
  847. line: 1,
  848. column: 1,
  849. filePath: 'crates/mytool-foo/src/lib.rs',
  850. language: 'rust' as const,
  851. };
  852. expect(rustResolver.resolve(fooRef, context)?.targetNodeId).toBe(fooLib.id);
  853. expect(rustResolver.resolve(barRef, context)?.targetNodeId).toBe(barLib.id);
  854. });
  855. it('resolves crate name when members uses a name glob at root (helix-*)', () => {
  856. const workspaceCargo = `
  857. [workspace]
  858. members = ["helix-*"]
  859. `;
  860. const coreCargo = `
  861. [package]
  862. name = "helix-core"
  863. version = "0.1.0"
  864. `;
  865. const coreLib: Node = {
  866. id: 'module:helix-core/src/lib.rs:helix_core:1',
  867. kind: 'module',
  868. name: 'helix_core',
  869. qualifiedName: 'helix-core/src/lib.rs::helix_core',
  870. filePath: 'helix-core/src/lib.rs',
  871. language: 'rust',
  872. startLine: 1,
  873. endLine: 1,
  874. startColumn: 0,
  875. endColumn: 0,
  876. updatedAt: Date.now(),
  877. };
  878. const filesByPath: Record<string, string> = {
  879. 'Cargo.toml': workspaceCargo,
  880. 'helix-core/Cargo.toml': coreCargo,
  881. };
  882. const nodesByFile: Record<string, Node[]> = {
  883. 'helix-core/src/lib.rs': [coreLib],
  884. };
  885. const dirsByPath: Record<string, string[]> = {
  886. '.': ['helix-core', 'docs', 'target'],
  887. 'helix-core': ['src'],
  888. };
  889. const context = {
  890. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  891. getNodesByName: () => [],
  892. getNodesByQualifiedName: () => [],
  893. getNodesByKind: () => [],
  894. fileExists: (p: string) => (
  895. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  896. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  897. ),
  898. readFile: (p: string) => filesByPath[p] ?? null,
  899. getProjectRoot: () => '/test',
  900. getAllFiles: () => [
  901. 'Cargo.toml',
  902. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  903. ...Object.keys(nodesByFile),
  904. ],
  905. getNodesByLowerName: () => [],
  906. getImportMappings: () => [],
  907. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  908. };
  909. const ref = {
  910. fromNodeId: 'fn:helix-core/src/lib.rs:other:1',
  911. referenceName: 'helix_core',
  912. referenceKind: 'references' as const,
  913. line: 1,
  914. column: 1,
  915. filePath: 'helix-core/src/lib.rs',
  916. language: 'rust' as const,
  917. };
  918. expect(rustResolver.resolve(ref, context)?.targetNodeId).toBe(coreLib.id);
  919. });
  920. });
  921. import { aspnetResolver } from '../src/resolution/frameworks/csharp';
  922. describe('aspnetResolver.extract', () => {
  923. it('extracts route from [HttpGet] attribute', () => {
  924. const src = `
  925. [HttpGet("/users")]
  926. public IActionResult ListUsers()
  927. {
  928. return Ok();
  929. }
  930. `;
  931. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  932. expect(nodes[0].name).toBe('GET /users');
  933. expect(references[0].referenceName).toBe('ListUsers');
  934. });
  935. });
  936. import { vaporResolver } from '../src/resolution/frameworks/swift';
  937. describe('vaporResolver.extract', () => {
  938. it('extracts route from app.get with use:', () => {
  939. const src = `app.get("users", use: listUsers)\n`;
  940. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  941. expect(nodes[0].name).toBe('GET /users');
  942. expect(references[0].referenceName).toBe('listUsers');
  943. });
  944. it('extracts grouped RouteCollection routes with the group prefix and no path arg', () => {
  945. const src = `
  946. func boot(routes: RoutesBuilder) throws {
  947. let todos = routes.grouped("todos")
  948. todos.get(use: index)
  949. todos.post(use: create)
  950. todos.group(":todoID") { todo in
  951. todo.delete(use: delete)
  952. }
  953. }
  954. `;
  955. const { nodes, references } = vaporResolver.extract!('TodoController.swift', src);
  956. expect(nodes.map((n) => n.name).sort()).toEqual([
  957. 'DELETE /todos/:todoID',
  958. 'GET /todos',
  959. 'POST /todos',
  960. ]);
  961. expect(references.map((r) => r.referenceName).sort()).toEqual([
  962. 'create',
  963. 'delete',
  964. 'index',
  965. ]);
  966. });
  967. it('handles use: self.handler and non-string path segments', () => {
  968. const src = `router.get("users", User.parameter, "edit", use: self.editUserHandler)\n`;
  969. const { nodes, references } = vaporResolver.extract!('UserController.swift', src);
  970. expect(nodes[0].name).toBe('GET /users/edit');
  971. expect(references[0].referenceName).toBe('editUserHandler');
  972. });
  973. it('ignores non-route .get calls that lack use: (e.g. Environment.get)', () => {
  974. const src = `let host = Environment.get("DATABASE_HOST") ?? "localhost"\n`;
  975. const { nodes } = vaporResolver.extract!('configure.swift', src);
  976. expect(nodes).toHaveLength(0);
  977. });
  978. });
  979. import { reactResolver } from '../src/resolution/frameworks/react';
  980. import { svelteResolver } from '../src/resolution/frameworks/svelte';
  981. describe('reactResolver.extract — React Router', () => {
  982. it('extracts a v6 <Route path element={<Comp/>}>', () => {
  983. const src = `<Route path="/users" element={<UsersPage/>}/>`;
  984. const { nodes, references } = reactResolver.extract!('App.tsx', src);
  985. const route = nodes.find((n) => n.kind === 'route');
  986. expect(route?.name).toBe('/users');
  987. expect(references[0]?.referenceName).toBe('UsersPage');
  988. });
  989. it('extracts a v5 <Route path component={Comp}> with attributes in any order', () => {
  990. const src = `<Route exact path="/login" component={Login} />`;
  991. const { nodes, references } = reactResolver.extract!('App.jsx', src);
  992. const route = nodes.find((n) => n.kind === 'route');
  993. expect(route?.name).toBe('/login');
  994. expect(references[0]?.referenceName).toBe('Login');
  995. });
  996. it('does not treat the <Routes> container as a route', () => {
  997. const src = `<Routes><Route path="/x" element={<X/>}/></Routes>`;
  998. const routes = reactResolver.extract!('App.tsx', src).nodes.filter((n) => n.kind === 'route');
  999. expect(routes).toHaveLength(1);
  1000. expect(routes[0]?.name).toBe('/x');
  1001. });
  1002. it('extracts createBrowserRouter object routes ({ path, element/Component })', () => {
  1003. const src = `const router = createBrowserRouter([
  1004. { path: "/dashboard", element: <Dashboard /> },
  1005. { path: "/login", Component: Login },
  1006. ]);`;
  1007. const { nodes, references } = reactResolver.extract!('router.tsx', src);
  1008. const routes = nodes.filter((n) => n.kind === 'route');
  1009. expect(routes.map((n) => n.name).sort()).toEqual(['/dashboard', '/login']);
  1010. expect(references.map((r) => r.referenceName).sort()).toEqual(['Dashboard', 'Login']);
  1011. });
  1012. it('does not treat config files or a nextjs-pages dir as Next.js routes', () => {
  1013. const cfg = reactResolver.extract!('apps/nextjs-pages/next.config.mjs', 'export default {}');
  1014. expect(cfg.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1015. const vite = reactResolver.extract!('src/pages/vite.config.ts', 'export default {}');
  1016. expect(vite.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1017. // a real page still works
  1018. const page = reactResolver.extract!('src/pages/about.tsx', 'export default function About(){return null}');
  1019. expect(page.nodes.filter((n) => n.kind === 'route').map((n) => n.name)).toEqual(['/about']);
  1020. });
  1021. });
  1022. describe('svelteResolver.extract (smoke)', () => {
  1023. it('returns { nodes, references } shape', () => {
  1024. const result = svelteResolver.extract!('+page.svelte', '');
  1025. expect(result).toHaveProperty('nodes');
  1026. expect(result).toHaveProperty('references');
  1027. });
  1028. });
  1029. // Regression tests: commented-out and docstring route examples must NOT
  1030. // surface as phantom route nodes. These would have failed before the
  1031. // strip-comments wiring (the regex would happily scan comments/docstrings).
  1032. describe('framework extractors ignore commented-out routes', () => {
  1033. it('django: skips line-comment and docstring routes', () => {
  1034. const src = `
  1035. # urls.py example:
  1036. # path('/admin/', AdminPanel.as_view())
  1037. """
  1038. Other routing example:
  1039. path('/users/', UserListView.as_view())
  1040. """
  1041. urlpatterns = [path('/real/', RealView.as_view())]
  1042. `;
  1043. const result = djangoResolver.extract!('app/urls.py', src);
  1044. const urls = result.nodes.map((n) => n.name);
  1045. expect(urls).toEqual(['/real/']);
  1046. });
  1047. it('flask: skips commented-out @app.route', () => {
  1048. const src = `
  1049. # @app.route('/fake')
  1050. # def fake_view():
  1051. # return ''
  1052. @app.route('/real')
  1053. def real_view():
  1054. return ''
  1055. `;
  1056. const { nodes, references } = flaskResolver.extract!('app.py', src);
  1057. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1058. expect(references.map((r) => r.referenceName)).toEqual(['real_view']);
  1059. });
  1060. it('fastapi: skips docstring example routes', () => {
  1061. const src = `
  1062. """
  1063. Example:
  1064. @app.get('/in-docstring')
  1065. async def doc():
  1066. pass
  1067. """
  1068. @app.get('/real')
  1069. async def real_handler():
  1070. return {}
  1071. `;
  1072. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  1073. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1074. expect(references.map((r) => r.referenceName)).toEqual(['real_handler']);
  1075. });
  1076. it('express: skips // and /* */ commented routes', () => {
  1077. const src = `
  1078. // app.get('/fake', fakeHandler);
  1079. /* router.post('/also-fake', otherHandler); */
  1080. app.get('/real', realHandler);
  1081. `;
  1082. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  1083. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1084. expect(references.map((r) => r.referenceName)).toEqual(['realHandler']);
  1085. });
  1086. it('laravel: skips // # and /* */ commented Route::* calls', () => {
  1087. const src = `<?php
  1088. // Route::get('/fake', [FakeController::class, 'index']);
  1089. # Route::get('/also-fake', 'FakeController@show');
  1090. /* Route::post('/another-fake', [X::class, 'y']); */
  1091. Route::get('/real', [RealController::class, 'index']);
  1092. `;
  1093. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  1094. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1095. expect(references.map((r) => r.referenceName)).toEqual(['RealController@index']);
  1096. });
  1097. it('rails: skips =begin/=end and # commented routes', () => {
  1098. const src = `
  1099. # get '/fake', to: 'fake#index'
  1100. =begin
  1101. get '/also-fake', to: 'fake#show'
  1102. =end
  1103. get '/real', to: 'real#index'
  1104. `;
  1105. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  1106. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1107. expect(references.map((r) => r.referenceName)).toEqual(['real#index']);
  1108. });
  1109. it('spring: skips // and /* */ commented @GetMapping', () => {
  1110. const src = `
  1111. // @GetMapping("/fake")
  1112. // public List<X> fake() { return null; }
  1113. /* @PostMapping("/also-fake")
  1114. public void alsoFake() {} */
  1115. @GetMapping("/real")
  1116. public List<User> listUsers() { return users; }
  1117. `;
  1118. const { nodes, references } = springResolver.extract!('UserController.java', src);
  1119. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1120. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1121. });
  1122. it('go: skips // and /* */ commented router.METHOD calls', () => {
  1123. const src = `
  1124. // r.GET("/fake", fakeHandler)
  1125. /* r.POST("/also-fake", anotherHandler) */
  1126. r.GET("/real", listUsers)
  1127. `;
  1128. const { nodes, references } = goResolver.extract!('main.go', src);
  1129. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1130. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1131. });
  1132. it('rust: skips // and nested /* */ commented .route() calls', () => {
  1133. const src = `
  1134. // .route("/fake", get(fake_handler))
  1135. /* outer /* inner .route("/inner-fake", get(x)) */ still .route("/outer-fake", get(y)) */
  1136. let app = Router::new().route("/real", get(list_users));
  1137. `;
  1138. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1139. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1140. expect(references.map((r) => r.referenceName)).toEqual(['list_users']);
  1141. });
  1142. it('aspnet: skips // and /* */ commented [HttpGet] attributes', () => {
  1143. const src = `
  1144. // [HttpGet("/fake")]
  1145. // public IActionResult Fake() { return Ok(); }
  1146. /* [HttpPost("/also-fake")]
  1147. public IActionResult AlsoFake() { return Ok(); } */
  1148. [HttpGet("/real")]
  1149. public IActionResult ListUsers() { return Ok(); }
  1150. `;
  1151. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  1152. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1153. expect(references.map((r) => r.referenceName)).toEqual(['ListUsers']);
  1154. });
  1155. it('vapor: skips // and /* */ commented app.METHOD calls', () => {
  1156. const src = `
  1157. // app.get("fake", use: fakeHandler)
  1158. /* app.post("also-fake", use: anotherHandler) */
  1159. app.get("real", use: listUsers)
  1160. `;
  1161. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  1162. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1163. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1164. });
  1165. it('nestjs: skips // and /* */ commented decorators', () => {
  1166. const src = `
  1167. @Controller('users')
  1168. export class UsersController {
  1169. // @Get('fake')
  1170. // fake() {}
  1171. /* @Post('also-fake')
  1172. alsoFake() {} */
  1173. @Get('real')
  1174. real() {}
  1175. }
  1176. `;
  1177. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  1178. expect(nodes.map((n) => n.name)).toEqual(['GET /users/real']);
  1179. expect(references.map((r) => r.referenceName)).toEqual(['real']);
  1180. });
  1181. });