frameworks.test.ts 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  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. it('extracts the method from a tuple methods=(...) (not just a list)', () => {
  134. const src = `
  135. @blueprint.route('/api/articles', methods=('POST',))
  136. def make_article():
  137. pass
  138. `;
  139. const { nodes, references } = flaskResolver.extract!('views.py', src);
  140. expect(nodes[0].name).toBe('POST /api/articles');
  141. expect(references[0].referenceName).toBe('make_article');
  142. });
  143. it('extracts Flask-RESTful api.add_resource(Resource, paths) → the Resource class', () => {
  144. const src = `
  145. api.add_resource(TodoResource, '/todos/<id>')
  146. api.add_org_resource(AlertResource, '/api/alerts/<id>', endpoint='alert')
  147. `;
  148. const { nodes, references } = flaskResolver.extract!('api.py', src);
  149. expect(nodes.map((n) => n.name)).toEqual(['ANY /todos/<id>', 'ANY /api/alerts/<id>']);
  150. expect(references.map((r) => r.referenceName)).toEqual(['TodoResource', 'AlertResource']);
  151. });
  152. });
  153. describe('fastapiResolver.extract', () => {
  154. it('extracts route and reference from @app.get', () => {
  155. const src = `
  156. @app.get('/users')
  157. async def list_users():
  158. return []
  159. `;
  160. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  161. expect(nodes[0].name).toBe('GET /users');
  162. expect(references[0].referenceName).toBe('list_users');
  163. });
  164. it('extracts route from router.post', () => {
  165. const src = `
  166. @router.post('/items')
  167. def create_item(item: Item):
  168. pass
  169. `;
  170. const { nodes, references } = fastapiResolver.extract!('items.py', src);
  171. expect(nodes[0].name).toBe('POST /items');
  172. expect(references[0].referenceName).toBe('create_item');
  173. });
  174. it('extracts a route mounted at the router/prefix root (empty path)', () => {
  175. const src = `
  176. @router.get("", response_model=ListOfArticles, name="articles:list")
  177. async def list_articles():
  178. return []
  179. `;
  180. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  181. expect(nodes[0].name).toBe('GET /');
  182. expect(references[0].referenceName).toBe('list_articles');
  183. });
  184. it('extracts a multi-line decorator with an empty path', () => {
  185. const src = `
  186. @router.post(
  187. "",
  188. status_code=201,
  189. response_model=ArticleInResponse,
  190. )
  191. async def create_article():
  192. pass
  193. `;
  194. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  195. expect(nodes[0].name).toBe('POST /');
  196. expect(references[0].referenceName).toBe('create_article');
  197. });
  198. });
  199. import { expressResolver } from '../src/resolution/frameworks/express';
  200. describe('expressResolver.extract', () => {
  201. it('extracts route with inline handler reference', () => {
  202. const src = `app.get('/users', listUsers);\n`;
  203. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  204. expect(nodes).toHaveLength(1);
  205. expect(nodes[0].name).toBe('GET /users');
  206. expect(references[0].referenceName).toBe('listUsers');
  207. });
  208. it('extracts route with router.post and middleware chain', () => {
  209. const src = `router.post('/items', auth, createItem);\n`;
  210. const { nodes, references } = expressResolver.extract!('items.ts', src);
  211. expect(nodes[0].name).toBe('POST /items');
  212. // Multiple handlers: prefer the LAST one (convention: middleware first, handler last)
  213. expect(references[0].referenceName).toBe('createItem');
  214. });
  215. it('extracts route with controller method reference', () => {
  216. const src = `app.get('/x', userController.list);\n`;
  217. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  218. expect(references[0].referenceName).toBe('list');
  219. });
  220. });
  221. import { nestjsResolver } from '../src/resolution/frameworks/nestjs';
  222. describe('nestjsResolver.extract — HTTP', () => {
  223. it('joins @Controller prefix with @Get and links the handler', () => {
  224. const src = `
  225. @Controller('users')
  226. export class UsersController {
  227. @Get()
  228. findAll() { return []; }
  229. }
  230. `;
  231. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  232. expect(nodes).toHaveLength(1);
  233. expect(nodes[0].kind).toBe('route');
  234. expect(nodes[0].name).toBe('GET /users');
  235. expect(references[0].referenceName).toBe('findAll');
  236. expect(references[0].referenceKind).toBe('references');
  237. expect(references[0].fromNodeId).toBe(nodes[0].id);
  238. });
  239. it('joins controller prefix with a method-level path param', () => {
  240. const src = `
  241. @Controller('cats')
  242. export class CatsController {
  243. @Get(':id')
  244. findOne(@Param('id') id: string) { return id; }
  245. }
  246. `;
  247. const { nodes, references } = nestjsResolver.extract!('cats.controller.ts', src);
  248. expect(nodes[0].name).toBe('GET /cats/:id');
  249. expect(references[0].referenceName).toBe('findOne');
  250. });
  251. it('handles an empty @Controller() and empty @Post()', () => {
  252. const src = `
  253. @Controller()
  254. export class AppController {
  255. @Post()
  256. create() {}
  257. }
  258. `;
  259. const { nodes, references } = nestjsResolver.extract!('app.controller.ts', src);
  260. expect(nodes[0].name).toBe('POST /');
  261. expect(references[0].referenceName).toBe('create');
  262. });
  263. it('covers HTTP verbs and skips intervening method decorators', () => {
  264. const src = `
  265. @Controller('todos')
  266. export class TodosController {
  267. @Put(':id')
  268. @UseGuards(AuthGuard)
  269. update(@Param('id') id: string) {}
  270. @Delete(':id')
  271. async remove(@Param('id') id: string) {}
  272. }
  273. `;
  274. const { nodes, references } = nestjsResolver.extract!('todos.controller.ts', src);
  275. expect(nodes.map((n) => n.name)).toEqual(['PUT /todos/:id', 'DELETE /todos/:id']);
  276. expect(references.map((r) => r.referenceName)).toEqual(['update', 'remove']);
  277. });
  278. it('attributes methods to the right controller when a file has two', () => {
  279. const src = `
  280. @Controller('a')
  281. export class AController {
  282. @Get('x')
  283. ax() {}
  284. }
  285. @Controller('b')
  286. export class BController {
  287. @Get('y')
  288. by() {}
  289. }
  290. `;
  291. const { nodes } = nestjsResolver.extract!('multi.controller.ts', src);
  292. expect(nodes.map((n) => n.name)).toEqual(['GET /a/x', 'GET /b/y']);
  293. });
  294. });
  295. describe('nestjsResolver.extract — GraphQL', () => {
  296. it('emits QUERY/MUTATION nodes from a resolver, defaulting to the method name', () => {
  297. const src = `
  298. @Resolver(() => User)
  299. export class UsersResolver {
  300. @Query(() => [User])
  301. users() { return []; }
  302. @Mutation(() => User)
  303. createUser(@Args('input') input: CreateUserInput) {}
  304. }
  305. `;
  306. const { nodes, references } = nestjsResolver.extract!('users.resolver.ts', src);
  307. expect(nodes.map((n) => n.name)).toEqual(['QUERY users', 'MUTATION createUser']);
  308. expect(references.map((r) => r.referenceName)).toEqual(['users', 'createUser']);
  309. });
  310. it('uses an explicit operation name when given', () => {
  311. const src = `
  312. @Resolver()
  313. export class CatsResolver {
  314. @Query(() => Cat, { name: 'cat' })
  315. getCat() {}
  316. }
  317. `;
  318. const { nodes } = nestjsResolver.extract!('cats.resolver.ts', src);
  319. expect(nodes[0].name).toBe('QUERY cat');
  320. });
  321. it('does NOT treat the REST @Query() parameter decorator as a GraphQL op', () => {
  322. const src = `
  323. @Controller('search')
  324. export class SearchController {
  325. @Get()
  326. search(@Query() query: SearchDto) { return query; }
  327. }
  328. `;
  329. const { nodes } = nestjsResolver.extract!('search.controller.ts', src);
  330. // Only the HTTP route — the @Query() param decorator must be ignored.
  331. expect(nodes.map((n) => n.name)).toEqual(['GET /search']);
  332. });
  333. });
  334. describe('nestjsResolver.extract — microservices & websockets', () => {
  335. it('extracts @MessagePattern and @EventPattern handlers', () => {
  336. const src = `
  337. @Controller()
  338. export class MathController {
  339. @MessagePattern({ cmd: 'sum' })
  340. accumulate(data: number[]) {}
  341. @EventPattern('user.created')
  342. handleUserCreated(data: any) {}
  343. }
  344. `;
  345. const { nodes, references } = nestjsResolver.extract!('math.controller.ts', src);
  346. expect(nodes.map((n) => n.name)).toEqual(['MESSAGE sum', 'EVENT user.created']);
  347. expect(references.map((r) => r.referenceName)).toEqual(['accumulate', 'handleUserCreated']);
  348. });
  349. it('extracts @SubscribeMessage handlers with the gateway namespace', () => {
  350. const src = `
  351. @WebSocketGateway({ namespace: 'chat' })
  352. export class ChatGateway {
  353. @SubscribeMessage('message')
  354. handleMessage(@MessageBody() data: string) {}
  355. }
  356. `;
  357. const { nodes, references } = nestjsResolver.extract!('chat.gateway.ts', src);
  358. expect(nodes[0].name).toBe('WS chat:message');
  359. expect(references[0].referenceName).toBe('handleMessage');
  360. });
  361. it('extracts @SubscribeMessage without a namespace', () => {
  362. const src = `
  363. @WebSocketGateway()
  364. export class EventsGateway {
  365. @SubscribeMessage('events')
  366. onEvent() {}
  367. }
  368. `;
  369. const { nodes } = nestjsResolver.extract!('events.gateway.ts', src);
  370. expect(nodes[0].name).toBe('WS events');
  371. });
  372. it('returns empty for a non-JS/TS file', () => {
  373. const { nodes, references } = nestjsResolver.extract!('thing.py', '@Controller("x")');
  374. expect(nodes).toEqual([]);
  375. expect(references).toEqual([]);
  376. });
  377. });
  378. describe('nestjsResolver.detect', () => {
  379. const baseContext = {
  380. getNodesInFile: () => [],
  381. getNodesByName: () => [],
  382. getNodesByQualifiedName: () => [],
  383. getNodesByKind: () => [],
  384. fileExists: () => false,
  385. getProjectRoot: () => '/test',
  386. getAllFiles: () => [],
  387. getNodesByLowerName: () => [],
  388. getImportMappings: () => [],
  389. };
  390. it('detects @nestjs/* in package.json', () => {
  391. const context = {
  392. ...baseContext,
  393. readFile: (p: string) =>
  394. p === 'package.json'
  395. ? JSON.stringify({ dependencies: { '@nestjs/common': '^10.0.0' } })
  396. : null,
  397. };
  398. expect(nestjsResolver.detect(context as any)).toBe(true);
  399. });
  400. it('detects @Controller in a *.controller.ts file when package.json is absent', () => {
  401. const context = {
  402. ...baseContext,
  403. getAllFiles: () => ['src/users.controller.ts'],
  404. readFile: (p: string) =>
  405. p === 'src/users.controller.ts'
  406. ? `@Controller('users')\nexport class UsersController {}`
  407. : null,
  408. };
  409. expect(nestjsResolver.detect(context as any)).toBe(true);
  410. });
  411. it('returns false for a non-Nest project', () => {
  412. const context = {
  413. ...baseContext,
  414. readFile: (p: string) =>
  415. p === 'package.json' ? JSON.stringify({ dependencies: { express: '^4' } }) : null,
  416. };
  417. expect(nestjsResolver.detect(context as any)).toBe(false);
  418. });
  419. });
  420. describe('nestjsResolver.resolve', () => {
  421. const baseContext = {
  422. getNodesInFile: () => [],
  423. getNodesByName: () => [],
  424. getNodesByQualifiedName: () => [],
  425. getNodesByKind: () => [],
  426. fileExists: () => false,
  427. readFile: () => null,
  428. getProjectRoot: () => '/test',
  429. getAllFiles: () => [],
  430. getNodesByLowerName: () => [],
  431. getImportMappings: () => [],
  432. };
  433. it('resolves an injected *Service reference to the class in a *.service.ts file', () => {
  434. const svcNode: Node = {
  435. id: 'class:src/users/users.service.ts:UsersService:3',
  436. kind: 'class',
  437. name: 'UsersService',
  438. qualifiedName: 'src/users/users.service.ts::UsersService',
  439. filePath: 'src/users/users.service.ts',
  440. language: 'typescript',
  441. startLine: 3,
  442. endLine: 3,
  443. startColumn: 0,
  444. endColumn: 0,
  445. updatedAt: Date.now(),
  446. };
  447. const context = {
  448. ...baseContext,
  449. getNodesByName: (n: string) => (n === 'UsersService' ? [svcNode] : []),
  450. };
  451. const ref = {
  452. fromNodeId: 'class:src/users/users.controller.ts:UsersController:5',
  453. referenceName: 'UsersService',
  454. referenceKind: 'references' as const,
  455. line: 6,
  456. column: 4,
  457. filePath: 'src/users/users.controller.ts',
  458. language: 'typescript' as const,
  459. };
  460. const result = nestjsResolver.resolve(ref, context as any);
  461. expect(result?.targetNodeId).toBe(svcNode.id);
  462. expect(result?.resolvedBy).toBe('framework');
  463. expect(result?.confidence).toBeGreaterThanOrEqual(0.85);
  464. });
  465. it('returns null for a name without a provider suffix', () => {
  466. const ref = {
  467. fromNodeId: 'x',
  468. referenceName: 'doThing',
  469. referenceKind: 'references' as const,
  470. line: 1,
  471. column: 1,
  472. filePath: 'a.ts',
  473. language: 'typescript' as const,
  474. };
  475. expect(nestjsResolver.resolve(ref, baseContext as any)).toBeNull();
  476. });
  477. });
  478. describe('nestjsResolver.postExtract — RouterModule', () => {
  479. function mkClass(name: string, filePath: string, startLine: number, endLine: number): Node {
  480. return {
  481. id: `class:${filePath}:${startLine}:${name}`,
  482. kind: 'class',
  483. name,
  484. qualifiedName: `${filePath}::${name}`,
  485. filePath,
  486. language: 'typescript',
  487. startLine,
  488. endLine,
  489. startColumn: 0,
  490. endColumn: 0,
  491. updatedAt: 0,
  492. };
  493. }
  494. function mkRoute(
  495. filePath: string,
  496. line: number,
  497. method: string,
  498. path: string,
  499. nameOverride?: string
  500. ): Node {
  501. return {
  502. id: `route:${filePath}:${line}:${method}:${path}`,
  503. kind: 'route',
  504. name: nameOverride ?? `${method} ${path}`,
  505. qualifiedName: `${filePath}::${method}:${path}`,
  506. filePath,
  507. language: 'typescript',
  508. startLine: line,
  509. endLine: line,
  510. startColumn: 0,
  511. endColumn: 0,
  512. updatedAt: 0,
  513. };
  514. }
  515. function makeContext(opts: {
  516. files?: Record<string, string>;
  517. nodes?: Node[];
  518. }) {
  519. const files = opts.files ?? {};
  520. const all = opts.nodes ?? [];
  521. return {
  522. getNodesInFile: (fp: string) => all.filter((n) => n.filePath === fp),
  523. getNodesByName: (name: string) => all.filter((n) => n.name === name),
  524. getNodesByQualifiedName: () => [],
  525. getNodesByKind: (kind: Node['kind']) => all.filter((n) => n.kind === kind),
  526. fileExists: (fp: string) => files[fp] !== undefined,
  527. readFile: (fp: string) => files[fp] ?? null,
  528. getProjectRoot: () => '/test',
  529. getAllFiles: () => Object.keys(files),
  530. getNodesByLowerName: () => [],
  531. getImportMappings: () => [],
  532. } as any;
  533. }
  534. it('prepends RouterModule prefix to a controller route (top-level register)', () => {
  535. const ctx = makeContext({
  536. files: {
  537. 'src/app.module.ts': `
  538. @Module({
  539. imports: [
  540. RouterModule.register([
  541. { path: 'admin', module: AdminModule },
  542. ]),
  543. ],
  544. })
  545. export class AppModule {}
  546. @Module({ controllers: [AdminController] })
  547. export class AdminModule {}
  548. `,
  549. },
  550. nodes: [
  551. mkClass('AdminController', 'src/admin/admin.controller.ts', 1, 10),
  552. mkRoute('src/admin/admin.controller.ts', 3, 'GET', '/'),
  553. ],
  554. });
  555. const updates = nestjsResolver.postExtract!(ctx);
  556. expect(updates).toHaveLength(1);
  557. expect(updates[0]!.name).toBe('GET /admin');
  558. // id and qualifiedName must be preserved so existing route→handler edges
  559. // stay intact and the pass remains idempotent on a second run.
  560. expect(updates[0]!.id).toBe('route:src/admin/admin.controller.ts:3:GET:/');
  561. expect(updates[0]!.qualifiedName).toBe('src/admin/admin.controller.ts::GET:/');
  562. });
  563. it('resolves nested children — the issue #459 example', () => {
  564. const ctx = makeContext({
  565. files: {
  566. 'src/app.module.ts': `
  567. @Module({
  568. imports: [
  569. AdminModule,
  570. UsersModule,
  571. RouterModule.register([
  572. {
  573. path: 'admin',
  574. module: AdminModule,
  575. children: [
  576. { path: 'users', module: UsersModule },
  577. ],
  578. },
  579. ]),
  580. ],
  581. })
  582. export class AppModule {}
  583. `,
  584. 'src/users/users.module.ts': `
  585. @Module({ controllers: [UsersController] })
  586. export class UsersModule {}
  587. `,
  588. },
  589. nodes: [
  590. mkClass('UsersController', 'src/users/users.controller.ts', 1, 10),
  591. mkRoute('src/users/users.controller.ts', 3, 'GET', '/'),
  592. ],
  593. });
  594. const updates = nestjsResolver.postExtract!(ctx);
  595. expect(updates).toHaveLength(1);
  596. expect(updates[0]!.name).toBe('GET /admin/users');
  597. });
  598. it('joins module prefix with a non-empty @Controller path and method params', () => {
  599. const ctx = makeContext({
  600. files: {
  601. 'src/app.module.ts': `
  602. RouterModule.register([{ path: 'admin', module: UsersModule }])
  603. @Module({ controllers: [UsersController] })
  604. export class UsersModule {}
  605. `,
  606. },
  607. nodes: [
  608. mkClass('UsersController', 'src/users.controller.ts', 1, 10),
  609. // Existing extract emitted GET /users/:id from @Controller('users') + @Get(':id')
  610. mkRoute('src/users.controller.ts', 3, 'GET', '/users/:id'),
  611. ],
  612. });
  613. const updates = nestjsResolver.postExtract!(ctx);
  614. expect(updates).toHaveLength(1);
  615. expect(updates[0]!.name).toBe('GET /admin/users/:id');
  616. });
  617. it('is idempotent — a second run returns no updates', () => {
  618. // Simulate the state after one round of postExtract: name is already
  619. // 'GET /admin', but qualifiedName still encodes the original 'GET:/'.
  620. const ctx = makeContext({
  621. files: {
  622. 'src/app.module.ts': `
  623. RouterModule.register([{ path: 'admin', module: UsersModule }])
  624. @Module({ controllers: [UsersController] })
  625. export class UsersModule {}
  626. `,
  627. },
  628. nodes: [
  629. mkClass('UsersController', 'src/users.controller.ts', 1, 10),
  630. mkRoute('src/users.controller.ts', 3, 'GET', '/', 'GET /admin'),
  631. ],
  632. });
  633. const updates = nestjsResolver.postExtract!(ctx);
  634. expect(updates).toHaveLength(0);
  635. });
  636. it('is a no-op when the project does not use RouterModule', () => {
  637. const ctx = makeContext({
  638. files: {
  639. 'src/app.module.ts': `
  640. @Module({ controllers: [UsersController] })
  641. export class AppModule {}
  642. `,
  643. },
  644. nodes: [
  645. mkClass('UsersController', 'src/users.controller.ts', 1, 10),
  646. mkRoute('src/users.controller.ts', 3, 'GET', '/'),
  647. ],
  648. });
  649. const updates = nestjsResolver.postExtract!(ctx);
  650. expect(updates).toHaveLength(0);
  651. });
  652. it('attributes routes to the right controller when one file has two', () => {
  653. // Two controllers in one file, declared in two different modules with
  654. // two different module prefixes. The route's startLine has to match the
  655. // class scope, not just the file path.
  656. const ctx = makeContext({
  657. files: {
  658. 'src/app.module.ts': `
  659. RouterModule.register([
  660. { path: 'p1', module: AModule },
  661. { path: 'p2', module: BModule },
  662. ])
  663. @Module({ controllers: [AController] }) export class AModule {}
  664. @Module({ controllers: [BController] }) export class BModule {}
  665. `,
  666. },
  667. nodes: [
  668. mkClass('AController', 'src/multi.controller.ts', 1, 5),
  669. mkClass('BController', 'src/multi.controller.ts', 7, 12),
  670. mkRoute('src/multi.controller.ts', 3, 'GET', '/a/x'),
  671. mkRoute('src/multi.controller.ts', 9, 'GET', '/b/y'),
  672. ],
  673. });
  674. const updates = nestjsResolver.postExtract!(ctx);
  675. expect(updates).toHaveLength(2);
  676. const byId = new Map(updates.map((u) => [u.id, u.name]));
  677. expect(byId.get('route:src/multi.controller.ts:3:GET:/a/x')).toBe('GET /p1/a/x');
  678. expect(byId.get('route:src/multi.controller.ts:9:GET:/b/y')).toBe('GET /p2/b/y');
  679. });
  680. it('merges RouterModule registrations spread across multiple module files', () => {
  681. const ctx = makeContext({
  682. files: {
  683. 'src/app.module.ts': `
  684. RouterModule.register([{ path: 'a', module: AModule }])
  685. @Module({ controllers: [AController] }) export class AModule {}
  686. `,
  687. 'src/feature.module.ts': `
  688. RouterModule.forChild([{ path: 'b', module: BModule }])
  689. @Module({ controllers: [BController] }) export class BModule {}
  690. `,
  691. },
  692. nodes: [
  693. mkClass('AController', 'src/a.controller.ts', 1, 5),
  694. mkClass('BController', 'src/b.controller.ts', 1, 5),
  695. mkRoute('src/a.controller.ts', 3, 'GET', '/'),
  696. mkRoute('src/b.controller.ts', 3, 'GET', '/'),
  697. ],
  698. });
  699. const updates = nestjsResolver.postExtract!(ctx);
  700. expect(updates).toHaveLength(2);
  701. const byId = new Map(updates.map((u) => [u.id, u.name]));
  702. expect(byId.get('route:src/a.controller.ts:3:GET:/')).toBe('GET /a');
  703. expect(byId.get('route:src/b.controller.ts:3:GET:/')).toBe('GET /b');
  704. });
  705. it('silently skips controllers whose class node is not in the graph', () => {
  706. // RouterModule declares a prefix for a module, but the @Module that
  707. // would link it to a controller is missing — common during partial
  708. // re-extraction. Must not throw.
  709. const ctx = makeContext({
  710. files: {
  711. 'src/app.module.ts': `
  712. RouterModule.register([{ path: 'orphans', module: GhostModule }])
  713. @Module({ controllers: [GhostController] }) export class GhostModule {}
  714. `,
  715. },
  716. nodes: [], // no class or route nodes
  717. });
  718. const updates = nestjsResolver.postExtract!(ctx);
  719. expect(updates).toHaveLength(0);
  720. });
  721. });
  722. import { laravelResolver } from '../src/resolution/frameworks/laravel';
  723. describe('laravelResolver.extract', () => {
  724. it('extracts route with controller tuple syntax', () => {
  725. const src = `Route::get('/users', [UserController::class, 'index']);\n`;
  726. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  727. expect(nodes[0].name).toBe('GET /users');
  728. expect(references[0].referenceName).toBe('UserController@index');
  729. });
  730. it('extracts route with Controller@action syntax', () => {
  731. const src = `Route::post('/users', 'UserController@store');\n`;
  732. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  733. expect(references[0].referenceName).toBe('UserController@store');
  734. });
  735. it('extracts resource route', () => {
  736. const src = `Route::resource('users', UserController::class);\n`;
  737. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  738. expect(nodes[0].kind).toBe('route');
  739. expect(references[0].referenceName).toBe('UserController');
  740. });
  741. });
  742. import { railsResolver } from '../src/resolution/frameworks/ruby';
  743. describe('railsResolver.extract', () => {
  744. it('extracts route with controller#action syntax', () => {
  745. const src = `get '/users', to: 'users#index'\n`;
  746. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  747. expect(nodes[0].name).toBe('GET /users');
  748. expect(references[0].referenceName).toBe('users#index');
  749. });
  750. it('extracts route without to: keyword', () => {
  751. const src = `post '/items' => 'items#create'\n`;
  752. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  753. expect(references[0].referenceName).toBe('items#create');
  754. });
  755. });
  756. import { springResolver } from '../src/resolution/frameworks/java';
  757. describe('springResolver.extract', () => {
  758. it.each([
  759. ['UserController.java', '{"/a", "/b"}', '@GetMapping({"/x", "/y"})', 'public String handle() { return "ok"; }'],
  760. ['UserController.java', 'path = {"/a", "/b"}', '@RequestMapping(value = {"/x", "/y"}, method = RequestMethod.GET)', 'public String handle() { return "ok"; }'],
  761. ['UserController.kt', 'value = ["/a", "/b"]', '@GetMapping(path = ["/x", "/y"])', 'fun handle(): String = "ok"'],
  762. ])('indexes every class/method path pair in %s with %s and %s (#1461)', (filePath, base, mapping, handler) => {
  763. const src = `@RestController
  764. @RequestMapping(${base})
  765. public class UserController {
  766. ${mapping}
  767. ${handler}
  768. }`;
  769. const { nodes, references } = springResolver.extract!(filePath, src);
  770. expect(nodes.map(n => n.name)).toEqual(['GET /a/x', 'GET /a/y', 'GET /b/x', 'GET /b/y']);
  771. expect(new Set(nodes.map(n => n.id)).size).toBe(4);
  772. expect(references.map(r => [r.fromNodeId, r.referenceName])).toEqual(nodes.map(n => [n.id, 'handle']));
  773. });
  774. it.each(['ErrorHandler.PATH', 'PATH', 'value = ErrorHandler.PATH', 'path = PATH'])(
  775. 'resolves a same-file constant prefix in @RequestMapping(%s) (#1461)', (args) => {
  776. const src = `@Controller
  777. @RequestMapping(${args})
  778. public class ErrorHandler {
  779. public static final String PATH = "/error";
  780. @RequestMapping(method = {RequestMethod.GET})
  781. public String handle() { return "err"; }
  782. }`;
  783. const { nodes, references } = springResolver.extract!('ErrorHandler.java', src);
  784. expect(nodes.map(n => n.name)).toEqual(['GET /error']);
  785. expect(references.map(r => [r.fromNodeId, r.referenceName])).toEqual([[nodes[0].id, 'handle']]);
  786. },
  787. );
  788. it('keeps literals and resolved constants in path arrays, including URI variables (#1461)', () => {
  789. const src = `@RequestMapping({"/api", "/{tenant}/api"})
  790. public class ItemController {
  791. public static final String ITEMS = "/items";
  792. @GetMapping(path = {ITEMS, "/items/{id}", External.MISSING}, produces = "application/json")
  793. public String get() { return "ok"; }
  794. }`;
  795. const { nodes, references } = springResolver.extract!('ItemController.java', src);
  796. expect(nodes.map(n => n.name)).toEqual([
  797. 'GET /api/items', 'GET /api/items/{id}', 'GET /{tenant}/api/items', 'GET /{tenant}/api/items/{id}',
  798. ]);
  799. expect(references.map(r => r.referenceName)).toEqual(['get', 'get', 'get', 'get']);
  800. });
  801. it.each([
  802. ['value = "/ok", produces = "application/json"', '/base/ok'],
  803. ['consumes = {"application/json", "text/plain"}, path = "/ok", produces = "application/json"', '/base/ok'],
  804. ['produces = "application/json", consumes = "text/plain"', '/base'],
  805. ])('only treats path arguments as paths: %s (#1461)', (args, expected) => {
  806. const src = `@RequestMapping("/base")
  807. public class UserController {
  808. @GetMapping(${args})
  809. public String handle() { return "ok"; }
  810. }`;
  811. const { nodes } = springResolver.extract!('UserController.java', src);
  812. expect(nodes.map(n => n.name)).toEqual([`GET ${expected}`]);
  813. });
  814. it.each([
  815. ['External.MISSING', '@GetMapping'],
  816. ['value = MISSING, produces = "application/json"', '@GetMapping("/ok")'],
  817. ['"/base"', '@GetMapping(External.MISSING)'],
  818. ['"/base"', '@GetMapping(path = MISSING, produces = "application/json")'],
  819. ['"/base"', '@RequestMapping(value = MISSING, method = RequestMethod.GET)'],
  820. ])('omits unresolved paths: class %s, method %s (#1461)', (base, mapping) => {
  821. const src = `@RequestMapping(${base})
  822. public class UserController {
  823. // public static final String MISSING = "/comment";
  824. ${mapping}
  825. public String handle() { return "ok"; }
  826. }`;
  827. expect(springResolver.extract!('UserController.java', src)).toEqual({ nodes: [], references: [] });
  828. });
  829. it.each([
  830. ['@GetMapping', 'GET'],
  831. ['@GetMapping()', 'GET'],
  832. ['@RequestMapping(method = RequestMethod.GET)', 'GET'],
  833. ['@RequestMapping(method = {RequestMethod.GET})', 'GET'],
  834. ['@RequestMapping', 'ANY'],
  835. ])('inherits the class prefix for %s without emitting a class route (#1461)', (mapping, verb) => {
  836. const src = `@RequestMapping("/base")
  837. public class UserController {
  838. ${mapping}
  839. public String handle() { return "ok"; }
  840. }`;
  841. const { nodes, references } = springResolver.extract!('UserController.java', src);
  842. expect(nodes.map(n => n.name)).toEqual([`${verb} /base`]);
  843. expect(references.map(r => r.referenceName)).toEqual(['handle']);
  844. });
  845. it('preserves annotation and reference line numbers after multiline Javadocs (#1461)', () => {
  846. const src = `/**
  847. * Controller documentation.
  848. */
  849. @RequestMapping("/base")
  850. public class UserController {
  851. /**
  852. * Handler documentation with @GetMapping("/fake").
  853. */
  854. @GetMapping({"/x", "/y"})
  855. public String handle() { return "ok"; }
  856. }`;
  857. const { nodes, references } = springResolver.extract!('UserController.java', src);
  858. expect(nodes.map(n => [n.name, n.startLine, n.endLine])).toEqual([
  859. ['GET /base/x', 9, 9], ['GET /base/y', 9, 9],
  860. ]);
  861. expect(references.map(r => [r.referenceName, r.line])).toEqual([['handle', 9], ['handle', 9]]);
  862. });
  863. it('extracts route with @GetMapping and next method', () => {
  864. const src = `
  865. @GetMapping("/users")
  866. public List<User> listUsers() {
  867. return users;
  868. }
  869. `;
  870. const { nodes, references } = springResolver.extract!('UserController.java', src);
  871. expect(nodes[0].name).toBe('GET /users');
  872. expect(references[0].referenceName).toBe('listUsers');
  873. });
  874. it('extracts a Kotlin @GetMapping with a fun handler', () => {
  875. const src = `
  876. @GetMapping("/vets")
  877. fun showVetList(model: MutableMap<String, Any>): String {
  878. return "vets"
  879. }
  880. `;
  881. const { nodes, references } = springResolver.extract!('VetController.kt', src);
  882. expect(nodes[0].name).toBe('GET /vets');
  883. expect(references[0].referenceName).toBe('showVetList');
  884. expect(nodes[0].language).toBe('kotlin');
  885. });
  886. it('joins a Kotlin class @RequestMapping prefix and skips a stacked annotation', () => {
  887. const src = `
  888. @RestController
  889. @RequestMapping("/owners")
  890. class OwnerController {
  891. @GetMapping("/{ownerId}")
  892. @ResponseBody
  893. fun showOwner(@PathVariable ownerId: Int): String {
  894. return "owner"
  895. }
  896. }
  897. `;
  898. const { nodes, references } = springResolver.extract!('OwnerController.kt', src);
  899. expect(nodes[0].name).toBe('GET /owners/{ownerId}');
  900. expect(references[0].referenceName).toBe('showOwner');
  901. });
  902. });
  903. import { playResolver } from '../src/resolution/frameworks/play';
  904. import { isSourceFile, isPlayRoutesFile } from '../src/extraction/grammars';
  905. describe('playResolver.extract (conf/routes)', () => {
  906. it('extracts METHOD /path Controller.action routes, dropping the package + args', () => {
  907. const src = `# Routes
  908. GET / controllers.Application.index
  909. GET /computers controllers.Application.list(p: Int ?= 0, s: Int ?= 2)
  910. POST /computers controllers.Application.save
  911. -> /v1/posts v1.post.PostRouter
  912. `;
  913. const { nodes, references } = playResolver.extract!('conf/routes', src);
  914. expect(nodes.map((n) => n.name)).toEqual([
  915. 'GET /',
  916. 'GET /computers',
  917. 'POST /computers',
  918. ]); // the `->` include is skipped
  919. expect(references.map((r) => r.referenceName)).toEqual([
  920. 'Application.index',
  921. 'Application.list',
  922. 'Application.save',
  923. ]);
  924. });
  925. it('only runs on Play routes files', () => {
  926. expect(playResolver.extract!('app/Foo.scala', 'GET / controllers.X.y').nodes).toHaveLength(0);
  927. });
  928. });
  929. describe('Play routes file detection', () => {
  930. it('recognizes conf/routes (extensionless) and *.routes as source files', () => {
  931. expect(isPlayRoutesFile('conf/routes')).toBe(true);
  932. expect(isPlayRoutesFile('myapp/conf/routes')).toBe(true);
  933. expect(isPlayRoutesFile('conf/admin.routes')).toBe(true);
  934. expect(isSourceFile('conf/routes')).toBe(true);
  935. expect(isPlayRoutesFile('src/routes.ts')).toBe(false);
  936. });
  937. });
  938. import { goResolver } from '../src/resolution/frameworks/go';
  939. describe('goResolver.extract', () => {
  940. it('extracts route from r.GET', () => {
  941. const src = `r.GET("/users", listUsers)\n`;
  942. const { nodes, references } = goResolver.extract!('main.go', src);
  943. expect(nodes[0].name).toBe('GET /users');
  944. expect(references[0].referenceName).toBe('listUsers');
  945. });
  946. it('extracts route from router.HandleFunc', () => {
  947. const src = `router.HandleFunc("/items", createItem)\n`;
  948. const { nodes, references } = goResolver.extract!('main.go', src);
  949. expect(references[0].referenceName).toBe('createItem');
  950. });
  951. it('extracts gorilla/mux HandleFunc on a subrouter var, ignoring chained .Methods()', () => {
  952. // `s` is a PathPrefix().Subrouter() var — any receiver is matched; the
  953. // trailing .Methods("GET") doesn't break the handler capture.
  954. const src = `s.HandleFunc("/users/{id}", listUsers).Methods("GET")\n`;
  955. const { references } = goResolver.extract!('routes.go', src);
  956. expect(references[0].referenceName).toBe('listUsers');
  957. });
  958. it('does NOT treat verb-named method calls with non-path args as routes (#1259)', () => {
  959. // The issue's repro: a generic cache type whose Put/Get share router verb
  960. // names. First args are keys, not URL paths — no route nodes.
  961. const src = [
  962. `c.Put("a", 1)`,
  963. `c.Put("user:123", value)`,
  964. `store.Get("config", out)`,
  965. `bus.Handle("user.created", onUserCreated)`,
  966. `m.HandleFunc("shutdown", hook)`,
  967. ].join('\n');
  968. const { nodes } = goResolver.extract!('cache.go', src);
  969. expect(nodes).toHaveLength(0);
  970. });
  971. it('keeps real registrations whose paths start with "/" for every router style', () => {
  972. const src = [
  973. `r.Put("/users/{id}", updateUser)`, // chi
  974. `v1.GET("/ping", ping)`, // gin group
  975. `mux.HandleFunc("/healthz", health)`, // net/http
  976. ].join('\n');
  977. const { nodes } = goResolver.extract!('routes.go', src);
  978. expect(nodes.map((n) => n.name)).toEqual(['PUT /users/{id}', 'GET /ping', 'ANY /healthz']);
  979. });
  980. it('recognizes Go 1.22 "METHOD /path" patterns on HandleFunc and extracts the method', () => {
  981. const src = `mux.HandleFunc("GET /api/users/{id}", getUser)\n`;
  982. const { nodes, references } = goResolver.extract!('main.go', src);
  983. expect(nodes[0].name).toBe('GET /api/users/{id}');
  984. expect(references[0].referenceName).toBe('getUser');
  985. });
  986. });
  987. import { goframeResolver } from '../src/resolution/frameworks/goframe';
  988. describe('goframeResolver', () => {
  989. it('detects GoFrame from a gogf/gf dependency in go.mod', () => {
  990. const ctx: any = {
  991. readFile: (f: string) =>
  992. f === 'go.mod' ? 'module example.com/app\nrequire github.com/gogf/gf/v2 v2.7.0\n' : null,
  993. };
  994. expect(goframeResolver.detect(ctx)).toBe(true);
  995. const noGf: any = { readFile: (f: string) => (f === 'go.mod' ? 'module example.com/app\n' : null) };
  996. expect(goframeResolver.detect(noGf)).toBe(false);
  997. });
  998. it('extracts a route node from a g.Meta request struct (method upper-cased)', () => {
  999. const src = `package v1
  1000. import "github.com/gogf/gf/v2/frame/g"
  1001. type SignInReq struct {
  1002. g.Meta \`path:"/user/sign-in" method:"post" tags:"User" summary:"Sign in"\`
  1003. Passport string
  1004. }
  1005. type SignInRes struct{}
  1006. `;
  1007. const { nodes } = goframeResolver.extract!('api/user/v1/user_sign_in.go', src);
  1008. expect(nodes).toHaveLength(1);
  1009. expect(nodes[0].kind).toBe('route');
  1010. expect(nodes[0].name).toBe('POST /user/sign-in');
  1011. // The package-qualified request type is encoded for the synthesizer join.
  1012. expect(nodes[0].qualifiedName).toContain('::goframe-route:v1.SignInReq');
  1013. });
  1014. it('is independent of g.Meta tag attribute order', () => {
  1015. const src = `type DeptSearchReq struct {
  1016. g.Meta \`path:"/dept/list" tags:"Dept" method:"get" summary:"列表"\`
  1017. }`;
  1018. const { nodes } = goframeResolver.extract!('api/system/dept.go', src);
  1019. expect(nodes[0].name).toBe('GET /dept/list');
  1020. expect(nodes[0].qualifiedName).toContain('::goframe-route:DeptSearchReq');
  1021. });
  1022. it('skips a response g.Meta that has no path (mime-only) and other non-route metadata', () => {
  1023. const src = `type ListRes struct {
  1024. g.Meta \`mime:"application/json"\`
  1025. Items []string
  1026. }`;
  1027. const { nodes } = goframeResolver.extract!('api/x.go', src);
  1028. expect(nodes).toHaveLength(0);
  1029. });
  1030. it('defaults method to ANY when method: is omitted', () => {
  1031. const src = `type PingReq struct {
  1032. g.Meta \`path:"/ping"\`
  1033. }`;
  1034. const { nodes } = goframeResolver.extract!('api/ping.go', src);
  1035. expect(nodes[0].name).toBe('ANY /ping');
  1036. });
  1037. it('extracts every request struct in a multi-route api file', () => {
  1038. const src = `type DeptListReq struct { g.Meta \`path:"/dept/list" method:"get"\` }
  1039. type DeptListRes struct { g.Meta \`mime:"application/json"\` }
  1040. type DeptAddReq struct { g.Meta \`path:"/dept/add" method:"post"\` }
  1041. type DeptAddRes struct {}
  1042. `;
  1043. const { nodes } = goframeResolver.extract!('api/dept.go', src);
  1044. expect(nodes.map((n) => n.name).sort()).toEqual(['GET /dept/list', 'POST /dept/add']);
  1045. });
  1046. it('returns nothing for a non-go file or a file without g.Meta', () => {
  1047. expect(goframeResolver.extract!('main.ts', 'const x = 1').nodes).toHaveLength(0);
  1048. expect(goframeResolver.extract!('main.go', 'package main\nfunc main() {}\n').nodes).toHaveLength(0);
  1049. });
  1050. });
  1051. import { rustResolver } from '../src/resolution/frameworks/rust';
  1052. describe('rustResolver.extract', () => {
  1053. it('extracts route from axum .route with get()', () => {
  1054. const src = `let app = Router::new().route("/users", get(list_users));\n`;
  1055. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1056. expect(nodes[0].name).toBe('GET /users');
  1057. expect(references[0].referenceName).toBe('list_users');
  1058. });
  1059. it('extracts every method from a chained axum .route (get().put())', () => {
  1060. const src = `let app = Router::new().route("/user", get(get_current_user).put(update_user));\n`;
  1061. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1062. expect(nodes.map((n) => n.name)).toEqual(['GET /user', 'PUT /user']);
  1063. expect(references.map((r) => r.referenceName)).toEqual([
  1064. 'get_current_user',
  1065. 'update_user',
  1066. ]);
  1067. });
  1068. it('extracts a multi-line axum .route with a namespaced handler', () => {
  1069. const src = `
  1070. let app = Router::new()
  1071. .route(
  1072. "/articles/feed",
  1073. get(listing::feed_articles),
  1074. );
  1075. `;
  1076. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1077. expect(nodes[0].name).toBe('GET /articles/feed');
  1078. expect(references[0].referenceName).toBe('feed_articles');
  1079. });
  1080. it('extracts actix web::resource().route(web::METHOD().to(handler))', () => {
  1081. const src = `App::new().service(web::resource("/user/{id}").route(web::get().to(get_user)))\n`;
  1082. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1083. expect(nodes[0].name).toBe('GET /user/{id}');
  1084. expect(references[0].referenceName).toBe('get_user');
  1085. });
  1086. it('extracts actix web::resource("/").to(handler) (all methods)', () => {
  1087. const src = `App::new().service(web::resource("/").to(index))\n`;
  1088. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1089. expect(nodes[0].name).toBe('ANY /');
  1090. expect(references[0].referenceName).toBe('index');
  1091. });
  1092. it('extracts actix App-level .route("/path", web::METHOD().to(handler))', () => {
  1093. const src = `App::new().route("/health", web::get().to(health_check))\n`;
  1094. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1095. expect(nodes[0].name).toBe('GET /health');
  1096. expect(references[0].referenceName).toBe('health_check');
  1097. });
  1098. });
  1099. describe('rustResolver.resolve cargo workspace crates', () => {
  1100. it('resolves crate name from workspace member lib.rs', () => {
  1101. const workspaceCargo = `
  1102. [workspace]
  1103. members = ["crates/mytool-core", "crates/mytool-fetcher"]
  1104. `;
  1105. const coreCargo = `
  1106. [package]
  1107. name = "mytool-core"
  1108. version = "0.1.0"
  1109. `;
  1110. const libNode: Node = {
  1111. id: 'module:crates/mytool-core/src/lib.rs:mytool_core:1',
  1112. kind: 'module',
  1113. name: 'mytool_core',
  1114. qualifiedName: 'crates/mytool-core/src/lib.rs::mytool_core',
  1115. filePath: 'crates/mytool-core/src/lib.rs',
  1116. language: 'rust',
  1117. startLine: 1,
  1118. endLine: 1,
  1119. startColumn: 0,
  1120. endColumn: 0,
  1121. updatedAt: Date.now(),
  1122. };
  1123. const context = {
  1124. getNodesInFile: (fp: string) => (fp === 'crates/mytool-core/src/lib.rs' ? [libNode] : []),
  1125. getNodesByName: () => [],
  1126. getNodesByQualifiedName: () => [],
  1127. getNodesByKind: () => [],
  1128. fileExists: (p: string) => (
  1129. p === 'Cargo.toml' ||
  1130. p === 'crates/mytool-core/Cargo.toml' ||
  1131. p === 'crates/mytool-core/src/lib.rs'
  1132. ),
  1133. readFile: (p: string) => {
  1134. if (p === 'Cargo.toml') return workspaceCargo;
  1135. if (p === 'crates/mytool-core/Cargo.toml') return coreCargo;
  1136. return null;
  1137. },
  1138. getProjectRoot: () => '/test',
  1139. getAllFiles: () => [
  1140. 'Cargo.toml',
  1141. 'crates/mytool-core/Cargo.toml',
  1142. 'crates/mytool-core/src/lib.rs',
  1143. ],
  1144. getNodesByLowerName: () => [],
  1145. getImportMappings: () => [],
  1146. };
  1147. const ref = {
  1148. fromNodeId: 'fn:crates/mytool-fetcher/src/main.rs:main:1',
  1149. referenceName: 'mytool_core',
  1150. referenceKind: 'references' as const,
  1151. line: 1,
  1152. column: 1,
  1153. filePath: 'crates/mytool-fetcher/src/main.rs',
  1154. language: 'rust' as const,
  1155. };
  1156. const result = rustResolver.resolve(ref, context);
  1157. expect(result?.targetNodeId).toBe(libNode.id);
  1158. expect(result?.resolvedBy).toBe('framework');
  1159. // Workspace-manifest hits are unambiguous and must beat name-matcher's
  1160. // self-file matches (0.7) so cross-crate `imports` edges materialize.
  1161. expect(result?.confidence).toBeGreaterThanOrEqual(0.9);
  1162. });
  1163. it('resolves crate name from workspace member main.rs when lib.rs is absent', () => {
  1164. const workspaceCargo = `
  1165. [workspace]
  1166. members = [
  1167. "crates/mytool-runner",
  1168. ]
  1169. `;
  1170. const runnerCargo = `
  1171. [package]
  1172. name = "mytool-runner"
  1173. version = "0.1.0"
  1174. `;
  1175. const mainNode: Node = {
  1176. id: 'module:crates/mytool-runner/src/main.rs:mytool_runner:1',
  1177. kind: 'module',
  1178. name: 'mytool_runner',
  1179. qualifiedName: 'crates/mytool-runner/src/main.rs::mytool_runner',
  1180. filePath: 'crates/mytool-runner/src/main.rs',
  1181. language: 'rust',
  1182. startLine: 1,
  1183. endLine: 1,
  1184. startColumn: 0,
  1185. endColumn: 0,
  1186. updatedAt: Date.now(),
  1187. };
  1188. const context = {
  1189. getNodesInFile: (fp: string) => (fp === 'crates/mytool-runner/src/main.rs' ? [mainNode] : []),
  1190. getNodesByName: () => [],
  1191. getNodesByQualifiedName: () => [],
  1192. getNodesByKind: () => [],
  1193. fileExists: (p: string) => (
  1194. p === 'Cargo.toml' ||
  1195. p === 'crates/mytool-runner/Cargo.toml' ||
  1196. p === 'crates/mytool-runner/src/main.rs'
  1197. ),
  1198. readFile: (p: string) => {
  1199. if (p === 'Cargo.toml') return workspaceCargo;
  1200. if (p === 'crates/mytool-runner/Cargo.toml') return runnerCargo;
  1201. return null;
  1202. },
  1203. getProjectRoot: () => '/test',
  1204. getAllFiles: () => [
  1205. 'Cargo.toml',
  1206. 'crates/mytool-runner/Cargo.toml',
  1207. 'crates/mytool-runner/src/main.rs',
  1208. ],
  1209. getNodesByLowerName: () => [],
  1210. getImportMappings: () => [],
  1211. };
  1212. const ref = {
  1213. fromNodeId: 'fn:crates/mytool-runner/src/main.rs:main:1',
  1214. referenceName: 'mytool_runner',
  1215. referenceKind: 'references' as const,
  1216. line: 1,
  1217. column: 1,
  1218. filePath: 'crates/mytool-runner/src/main.rs',
  1219. language: 'rust' as const,
  1220. };
  1221. const result = rustResolver.resolve(ref, context);
  1222. expect(result?.targetNodeId).toBe(mainNode.id);
  1223. expect(result?.resolvedBy).toBe('framework');
  1224. });
  1225. it('resolves crate name when members uses a glob (crates/*)', () => {
  1226. const workspaceCargo = `
  1227. [workspace]
  1228. members = ["crates/*"]
  1229. `;
  1230. const fooCargo = `
  1231. [package]
  1232. name = "mytool-foo"
  1233. version = "0.1.0"
  1234. `;
  1235. const barCargo = `
  1236. [package]
  1237. name = "mytool-bar"
  1238. version = "0.1.0"
  1239. `;
  1240. const fooLib: Node = {
  1241. id: 'module:crates/mytool-foo/src/lib.rs:mytool_foo:1',
  1242. kind: 'module',
  1243. name: 'mytool_foo',
  1244. qualifiedName: 'crates/mytool-foo/src/lib.rs::mytool_foo',
  1245. filePath: 'crates/mytool-foo/src/lib.rs',
  1246. language: 'rust',
  1247. startLine: 1,
  1248. endLine: 1,
  1249. startColumn: 0,
  1250. endColumn: 0,
  1251. updatedAt: Date.now(),
  1252. };
  1253. const barLib: Node = {
  1254. id: 'module:crates/mytool-bar/src/lib.rs:mytool_bar:1',
  1255. kind: 'module',
  1256. name: 'mytool_bar',
  1257. qualifiedName: 'crates/mytool-bar/src/lib.rs::mytool_bar',
  1258. filePath: 'crates/mytool-bar/src/lib.rs',
  1259. language: 'rust',
  1260. startLine: 1,
  1261. endLine: 1,
  1262. startColumn: 0,
  1263. endColumn: 0,
  1264. updatedAt: Date.now(),
  1265. };
  1266. const filesByPath: Record<string, string> = {
  1267. 'Cargo.toml': workspaceCargo,
  1268. 'crates/mytool-foo/Cargo.toml': fooCargo,
  1269. 'crates/mytool-bar/Cargo.toml': barCargo,
  1270. };
  1271. const nodesByFile: Record<string, Node[]> = {
  1272. 'crates/mytool-foo/src/lib.rs': [fooLib],
  1273. 'crates/mytool-bar/src/lib.rs': [barLib],
  1274. };
  1275. const dirsByPath: Record<string, string[]> = {
  1276. '.': ['crates'],
  1277. crates: ['mytool-foo', 'mytool-bar'],
  1278. 'crates/mytool-foo': ['src'],
  1279. 'crates/mytool-bar': ['src'],
  1280. };
  1281. const context = {
  1282. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  1283. getNodesByName: () => [],
  1284. getNodesByQualifiedName: () => [],
  1285. getNodesByKind: () => [],
  1286. fileExists: (p: string) => (
  1287. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  1288. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  1289. ),
  1290. readFile: (p: string) => filesByPath[p] ?? null,
  1291. getProjectRoot: () => '/test',
  1292. getAllFiles: () => [
  1293. 'Cargo.toml',
  1294. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  1295. ...Object.keys(nodesByFile),
  1296. ],
  1297. getNodesByLowerName: () => [],
  1298. getImportMappings: () => [],
  1299. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  1300. };
  1301. const fooRef = {
  1302. fromNodeId: 'fn:crates/mytool-bar/src/lib.rs:other:1',
  1303. referenceName: 'mytool_foo',
  1304. referenceKind: 'references' as const,
  1305. line: 1,
  1306. column: 1,
  1307. filePath: 'crates/mytool-bar/src/lib.rs',
  1308. language: 'rust' as const,
  1309. };
  1310. const barRef = {
  1311. fromNodeId: 'fn:crates/mytool-foo/src/lib.rs:other:1',
  1312. referenceName: 'mytool_bar',
  1313. referenceKind: 'references' as const,
  1314. line: 1,
  1315. column: 1,
  1316. filePath: 'crates/mytool-foo/src/lib.rs',
  1317. language: 'rust' as const,
  1318. };
  1319. expect(rustResolver.resolve(fooRef, context)?.targetNodeId).toBe(fooLib.id);
  1320. expect(rustResolver.resolve(barRef, context)?.targetNodeId).toBe(barLib.id);
  1321. });
  1322. it('resolves crate name when members uses a name glob at root (helix-*)', () => {
  1323. const workspaceCargo = `
  1324. [workspace]
  1325. members = ["helix-*"]
  1326. `;
  1327. const coreCargo = `
  1328. [package]
  1329. name = "helix-core"
  1330. version = "0.1.0"
  1331. `;
  1332. const coreLib: Node = {
  1333. id: 'module:helix-core/src/lib.rs:helix_core:1',
  1334. kind: 'module',
  1335. name: 'helix_core',
  1336. qualifiedName: 'helix-core/src/lib.rs::helix_core',
  1337. filePath: 'helix-core/src/lib.rs',
  1338. language: 'rust',
  1339. startLine: 1,
  1340. endLine: 1,
  1341. startColumn: 0,
  1342. endColumn: 0,
  1343. updatedAt: Date.now(),
  1344. };
  1345. const filesByPath: Record<string, string> = {
  1346. 'Cargo.toml': workspaceCargo,
  1347. 'helix-core/Cargo.toml': coreCargo,
  1348. };
  1349. const nodesByFile: Record<string, Node[]> = {
  1350. 'helix-core/src/lib.rs': [coreLib],
  1351. };
  1352. const dirsByPath: Record<string, string[]> = {
  1353. '.': ['helix-core', 'docs', 'target'],
  1354. 'helix-core': ['src'],
  1355. };
  1356. const context = {
  1357. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  1358. getNodesByName: () => [],
  1359. getNodesByQualifiedName: () => [],
  1360. getNodesByKind: () => [],
  1361. fileExists: (p: string) => (
  1362. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  1363. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  1364. ),
  1365. readFile: (p: string) => filesByPath[p] ?? null,
  1366. getProjectRoot: () => '/test',
  1367. getAllFiles: () => [
  1368. 'Cargo.toml',
  1369. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  1370. ...Object.keys(nodesByFile),
  1371. ],
  1372. getNodesByLowerName: () => [],
  1373. getImportMappings: () => [],
  1374. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  1375. };
  1376. const ref = {
  1377. fromNodeId: 'fn:helix-core/src/lib.rs:other:1',
  1378. referenceName: 'helix_core',
  1379. referenceKind: 'references' as const,
  1380. line: 1,
  1381. column: 1,
  1382. filePath: 'helix-core/src/lib.rs',
  1383. language: 'rust' as const,
  1384. };
  1385. expect(rustResolver.resolve(ref, context)?.targetNodeId).toBe(coreLib.id);
  1386. });
  1387. });
  1388. import { aspnetResolver } from '../src/resolution/frameworks/csharp';
  1389. describe('aspnetResolver.extract', () => {
  1390. it('extracts route from [HttpGet] attribute', () => {
  1391. const src = `
  1392. [HttpGet("/users")]
  1393. public IActionResult ListUsers()
  1394. {
  1395. return Ok();
  1396. }
  1397. `;
  1398. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  1399. expect(nodes[0].name).toBe('GET /users');
  1400. expect(references[0].referenceName).toBe('ListUsers');
  1401. });
  1402. it('extracts the handler-first endpoint-group form under the class, with the optional path', () => {
  1403. const src = `
  1404. public class TodoItems : IEndpointGroup
  1405. {
  1406. public static void Map(RouteGroupBuilder groupBuilder)
  1407. {
  1408. groupBuilder.RequireAuthorization();
  1409. groupBuilder.MapPost(CreateTodoItem);
  1410. groupBuilder.MapPut(UpdateTodoItem, "{id}");
  1411. groupBuilder.MapDelete(DeleteTodoItem, "{id}");
  1412. }
  1413. public static async Task<Created<int>> CreateTodoItem(ISender sender, CreateTodoItemCommand command) { }
  1414. }
  1415. `;
  1416. const { nodes, references } = aspnetResolver.extract!('Web/Endpoints/TodoItems.cs', src);
  1417. expect(nodes.map((n) => n.name)).toEqual(['POST /TodoItems', 'PUT /TodoItems/{id}', 'DELETE /TodoItems/{id}']);
  1418. expect(nodes.map((n) => n.startLine)).toEqual([7, 8, 9]);
  1419. expect(references.map((r) => r.referenceName)).toEqual(['CreateTodoItem', 'UpdateTodoItem', 'DeleteTodoItem']);
  1420. expect(nodes[0]!.qualifiedName).toBe('Web/Endpoints/TodoItems.cs::group:TodoItems:POST:');
  1421. });
  1422. it('a class with its own RoutePrefix literal names its routes under it', () => {
  1423. const src = `
  1424. public class TodoLists : IEndpointGroup
  1425. {
  1426. public static string RoutePrefix => "/api/todo-lists";
  1427. public static void Map(RouteGroupBuilder group)
  1428. {
  1429. group.MapGet(GetTodoLists);
  1430. }
  1431. }
  1432. `;
  1433. const { nodes } = aspnetResolver.extract!('TodoLists.cs', src);
  1434. expect(nodes.map((n) => n.name)).toEqual(['GET /api/todo-lists']);
  1435. });
  1436. });
  1437. import { vaporResolver } from '../src/resolution/frameworks/swift';
  1438. describe('vaporResolver.extract', () => {
  1439. it('extracts route from app.get with use:', () => {
  1440. const src = `app.get("users", use: listUsers)\n`;
  1441. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  1442. expect(nodes[0].name).toBe('GET /users');
  1443. expect(references[0].referenceName).toBe('listUsers');
  1444. });
  1445. it('extracts grouped RouteCollection routes with the group prefix and no path arg', () => {
  1446. const src = `
  1447. func boot(routes: RoutesBuilder) throws {
  1448. let todos = routes.grouped("todos")
  1449. todos.get(use: index)
  1450. todos.post(use: create)
  1451. todos.group(":todoID") { todo in
  1452. todo.delete(use: delete)
  1453. }
  1454. }
  1455. `;
  1456. const { nodes, references } = vaporResolver.extract!('TodoController.swift', src);
  1457. expect(nodes.map((n) => n.name).sort()).toEqual([
  1458. 'DELETE /todos/:todoID',
  1459. 'GET /todos',
  1460. 'POST /todos',
  1461. ]);
  1462. expect(references.map((r) => r.referenceName).sort()).toEqual([
  1463. 'create',
  1464. 'delete',
  1465. 'index',
  1466. ]);
  1467. });
  1468. it('handles use: self.handler and non-string path segments', () => {
  1469. const src = `router.get("users", User.parameter, "edit", use: self.editUserHandler)\n`;
  1470. const { nodes, references } = vaporResolver.extract!('UserController.swift', src);
  1471. expect(nodes[0].name).toBe('GET /users/edit');
  1472. expect(references[0].referenceName).toBe('editUserHandler');
  1473. });
  1474. it('ignores non-route .get calls that lack use: (e.g. Environment.get)', () => {
  1475. const src = `let host = Environment.get("DATABASE_HOST") ?? "localhost"\n`;
  1476. const { nodes } = vaporResolver.extract!('configure.swift', src);
  1477. expect(nodes).toHaveLength(0);
  1478. });
  1479. // A `.METHOD(...)` call with many comma-separated args and no `use:` used to
  1480. // make the route regex backtrack exponentially (60 args hung for minutes).
  1481. it('does not backtrack exponentially on a long arg list without use:', () => {
  1482. const args = Array.from({ length: 60 }, (_, i) => `arg${i}: value${i}`).join(', ');
  1483. const src = `app.get(${args})\n`;
  1484. const start = performance.now();
  1485. const { nodes } = vaporResolver.extract!('routes.swift', src);
  1486. const elapsed = performance.now() - start;
  1487. expect(nodes).toHaveLength(0);
  1488. expect(elapsed).toBeLessThan(250);
  1489. });
  1490. it('still parses every Vapor route shape after the arg-list rewrite', () => {
  1491. const src = `
  1492. admin.get(use: self.list)
  1493. app.get("users", use: listUsers)
  1494. router.post("users", User.parameter, "edit", use: UserController.edit)
  1495. app.patch(":id" , "meta" , use: update)
  1496. app.get(
  1497. "multi",
  1498. "line",
  1499. use: multiLine
  1500. )
  1501. `;
  1502. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  1503. expect(nodes.map((n) => n.name)).toEqual([
  1504. 'GET /',
  1505. 'GET /users',
  1506. 'POST /users/edit',
  1507. 'PATCH /:id/meta',
  1508. 'GET /multi/line',
  1509. ]);
  1510. expect(references.map((r) => r.referenceName)).toEqual([
  1511. 'list',
  1512. 'listUsers',
  1513. 'edit',
  1514. 'update',
  1515. 'multiLine',
  1516. ]);
  1517. });
  1518. });
  1519. import { reactResolver } from '../src/resolution/frameworks/react';
  1520. import { nextjsResolver } from '../src/resolution/frameworks/nextjs';
  1521. import { svelteResolver } from '../src/resolution/frameworks/svelte';
  1522. import { astroResolver } from '../src/resolution/frameworks/astro';
  1523. describe('reactResolver.extract — React Router', () => {
  1524. it('extracts a v6 <Route path element={<Comp/>}>', () => {
  1525. const src = `<Route path="/users" element={<UsersPage/>}/>`;
  1526. const { nodes, references } = reactResolver.extract!('App.tsx', src);
  1527. const route = nodes.find((n) => n.kind === 'route');
  1528. expect(route?.name).toBe('/users');
  1529. expect(references[0]?.referenceName).toBe('UsersPage');
  1530. });
  1531. it('extracts a v5 <Route path component={Comp}> with attributes in any order', () => {
  1532. const src = `<Route exact path="/login" component={Login} />`;
  1533. const { nodes, references } = reactResolver.extract!('App.jsx', src);
  1534. const route = nodes.find((n) => n.kind === 'route');
  1535. expect(route?.name).toBe('/login');
  1536. expect(references[0]?.referenceName).toBe('Login');
  1537. });
  1538. it('does not treat the <Routes> container as a route', () => {
  1539. const src = `<Routes><Route path="/x" element={<X/>}/></Routes>`;
  1540. const routes = reactResolver.extract!('App.tsx', src).nodes.filter((n) => n.kind === 'route');
  1541. expect(routes).toHaveLength(1);
  1542. expect(routes[0]?.name).toBe('/x');
  1543. });
  1544. it('extracts createBrowserRouter object routes ({ path, element/Component })', () => {
  1545. const src = `const router = createBrowserRouter([
  1546. { path: "/dashboard", element: <Dashboard /> },
  1547. { path: "/login", Component: Login },
  1548. ]);`;
  1549. const { nodes, references } = reactResolver.extract!('router.tsx', src);
  1550. const routes = nodes.filter((n) => n.kind === 'route');
  1551. expect(routes.map((n) => n.name).sort()).toEqual(['/dashboard', '/login']);
  1552. expect(references.map((r) => r.referenceName).sort()).toEqual(['Dashboard', 'Login']);
  1553. });
  1554. it('does not treat config files or a nextjs-pages dir as Next.js routes', () => {
  1555. const cfg = nextjsResolver.extract!('apps/nextjs-pages/next.config.mjs', 'export default {}');
  1556. expect(cfg.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1557. const vite = nextjsResolver.extract!('src/pages/vite.config.ts', 'export default {}');
  1558. expect(vite.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1559. // a real page still works — and the React resolver leaves it to the Next one
  1560. const page = nextjsResolver.extract!('src/pages/about.tsx', 'export default function About(){return null}');
  1561. expect(page.nodes.filter((n) => n.kind === 'route').map((n) => n.name)).toEqual(['/about']);
  1562. expect(reactResolver.extract!('src/pages/about.tsx', 'export default function About(){return null}').nodes).toHaveLength(0);
  1563. });
  1564. });
  1565. describe('svelteResolver.extract (smoke)', () => {
  1566. it('returns { nodes, references } shape', () => {
  1567. const result = svelteResolver.extract!('+page.svelte', '');
  1568. expect(result).toHaveProperty('nodes');
  1569. expect(result).toHaveProperty('references');
  1570. });
  1571. });
  1572. describe('astroResolver.extract — src/pages file-based routing', () => {
  1573. const routeNames = (filePath: string): string[] =>
  1574. astroResolver.extract!(filePath, '').nodes.filter((n) => n.kind === 'route').map((n) => n.name);
  1575. it('maps index.astro to /', () => {
  1576. expect(routeNames('src/pages/index.astro')).toEqual(['/']);
  1577. });
  1578. it('maps nested index and plain pages', () => {
  1579. expect(routeNames('src/pages/blog/index.astro')).toEqual(['/blog']);
  1580. expect(routeNames('src/pages/about.astro')).toEqual(['/about']);
  1581. });
  1582. it('converts [param] and [...rest] syntax', () => {
  1583. expect(routeNames('src/pages/blog/[slug].astro')).toEqual(['/blog/:slug']);
  1584. expect(routeNames('src/pages/[...path].astro')).toEqual(['/*path']);
  1585. });
  1586. it('maps .ts endpoints under src/pages to routes', () => {
  1587. expect(routeNames('src/pages/api/posts.ts')).toEqual(['/api/posts']);
  1588. expect(routeNames('src/pages/rss.xml.js')).toEqual(['/rss.xml']);
  1589. });
  1590. it('excludes underscore-prefixed segments and config files', () => {
  1591. expect(routeNames('src/pages/_partial.astro')).toEqual([]);
  1592. expect(routeNames('src/pages/blog/_components/Card.astro')).toEqual([]);
  1593. expect(routeNames('src/pages/vite.config.ts')).toEqual([]);
  1594. });
  1595. it('ignores .astro files outside src/pages', () => {
  1596. expect(routeNames('src/components/Button.astro')).toEqual([]);
  1597. expect(routeNames('docs/pages/guide.astro')).toEqual([]);
  1598. });
  1599. });
  1600. describe('astroResolver.resolve — Astro global and virtual modules', () => {
  1601. const ctx = {} as never;
  1602. const baseRef = {
  1603. fromNodeId: 'component:a',
  1604. line: 1,
  1605. column: 0,
  1606. filePath: 'src/pages/index.astro',
  1607. language: 'astro',
  1608. };
  1609. it('claims Astro.* global references as framework-provided', () => {
  1610. const res = astroResolver.resolve(
  1611. { ...baseRef, referenceName: 'Astro.props', referenceKind: 'references' } as never,
  1612. ctx
  1613. );
  1614. expect(res?.resolvedBy).toBe('framework');
  1615. expect(res?.confidence).toBe(1.0);
  1616. });
  1617. it('claims astro:content virtual module imports', () => {
  1618. const res = astroResolver.resolve(
  1619. { ...baseRef, referenceName: 'astro:content', referenceKind: 'imports' } as never,
  1620. ctx
  1621. );
  1622. expect(res?.resolvedBy).toBe('framework');
  1623. });
  1624. it('leaves ordinary names alone', () => {
  1625. const res = astroResolver.resolve(
  1626. { ...baseRef, referenceName: 'astrolabe', referenceKind: 'calls' } as never,
  1627. { getNodesByName: () => [] } as never
  1628. );
  1629. expect(res).toBeNull();
  1630. });
  1631. });
  1632. // Regression tests: commented-out and docstring route examples must NOT
  1633. // surface as phantom route nodes. These would have failed before the
  1634. // strip-comments wiring (the regex would happily scan comments/docstrings).
  1635. describe('framework extractors ignore commented-out routes', () => {
  1636. it('django: skips line-comment and docstring routes', () => {
  1637. const src = `
  1638. # urls.py example:
  1639. # path('/admin/', AdminPanel.as_view())
  1640. """
  1641. Other routing example:
  1642. path('/users/', UserListView.as_view())
  1643. """
  1644. urlpatterns = [path('/real/', RealView.as_view())]
  1645. `;
  1646. const result = djangoResolver.extract!('app/urls.py', src);
  1647. const urls = result.nodes.map((n) => n.name);
  1648. expect(urls).toEqual(['/real/']);
  1649. });
  1650. it('flask: skips commented-out @app.route', () => {
  1651. const src = `
  1652. # @app.route('/fake')
  1653. # def fake_view():
  1654. # return ''
  1655. @app.route('/real')
  1656. def real_view():
  1657. return ''
  1658. `;
  1659. const { nodes, references } = flaskResolver.extract!('app.py', src);
  1660. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1661. expect(references.map((r) => r.referenceName)).toEqual(['real_view']);
  1662. });
  1663. it('fastapi: skips docstring example routes', () => {
  1664. const src = `
  1665. """
  1666. Example:
  1667. @app.get('/in-docstring')
  1668. async def doc():
  1669. pass
  1670. """
  1671. @app.get('/real')
  1672. async def real_handler():
  1673. return {}
  1674. `;
  1675. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  1676. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1677. expect(references.map((r) => r.referenceName)).toEqual(['real_handler']);
  1678. });
  1679. it('express: skips // and /* */ commented routes', () => {
  1680. const src = `
  1681. // app.get('/fake', fakeHandler);
  1682. /* router.post('/also-fake', otherHandler); */
  1683. app.get('/real', realHandler);
  1684. `;
  1685. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  1686. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1687. expect(references.map((r) => r.referenceName)).toEqual(['realHandler']);
  1688. });
  1689. it('laravel: skips // # and /* */ commented Route::* calls', () => {
  1690. const src = `<?php
  1691. // Route::get('/fake', [FakeController::class, 'index']);
  1692. # Route::get('/also-fake', 'FakeController@show');
  1693. /* Route::post('/another-fake', [X::class, 'y']); */
  1694. Route::get('/real', [RealController::class, 'index']);
  1695. `;
  1696. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  1697. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1698. expect(references.map((r) => r.referenceName)).toEqual(['RealController@index']);
  1699. });
  1700. it('rails: skips =begin/=end and # commented routes', () => {
  1701. const src = `
  1702. # get '/fake', to: 'fake#index'
  1703. =begin
  1704. get '/also-fake', to: 'fake#show'
  1705. =end
  1706. get '/real', to: 'real#index'
  1707. `;
  1708. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  1709. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1710. expect(references.map((r) => r.referenceName)).toEqual(['real#index']);
  1711. });
  1712. it('spring: skips // and /* */ commented @GetMapping', () => {
  1713. const src = `
  1714. // @GetMapping("/fake")
  1715. // public List<X> fake() { return null; }
  1716. /* @PostMapping("/also-fake")
  1717. public void alsoFake() {} */
  1718. @GetMapping("/real")
  1719. public List<User> listUsers() { return users; }
  1720. `;
  1721. const { nodes, references } = springResolver.extract!('UserController.java', src);
  1722. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1723. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1724. });
  1725. it('go: skips // and /* */ commented router.METHOD calls', () => {
  1726. const src = `
  1727. // r.GET("/fake", fakeHandler)
  1728. /* r.POST("/also-fake", anotherHandler) */
  1729. r.GET("/real", listUsers)
  1730. `;
  1731. const { nodes, references } = goResolver.extract!('main.go', src);
  1732. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1733. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1734. });
  1735. it('rust: skips // and nested /* */ commented .route() calls', () => {
  1736. const src = `
  1737. // .route("/fake", get(fake_handler))
  1738. /* outer /* inner .route("/inner-fake", get(x)) */ still .route("/outer-fake", get(y)) */
  1739. let app = Router::new().route("/real", get(list_users));
  1740. `;
  1741. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1742. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1743. expect(references.map((r) => r.referenceName)).toEqual(['list_users']);
  1744. });
  1745. it('aspnet: skips // and /* */ commented [HttpGet] attributes', () => {
  1746. const src = `
  1747. // [HttpGet("/fake")]
  1748. // public IActionResult Fake() { return Ok(); }
  1749. /* [HttpPost("/also-fake")]
  1750. public IActionResult AlsoFake() { return Ok(); } */
  1751. [HttpGet("/real")]
  1752. public IActionResult ListUsers() { return Ok(); }
  1753. `;
  1754. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  1755. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1756. expect(references.map((r) => r.referenceName)).toEqual(['ListUsers']);
  1757. });
  1758. it('vapor: skips // and /* */ commented app.METHOD calls', () => {
  1759. const src = `
  1760. // app.get("fake", use: fakeHandler)
  1761. /* app.post("also-fake", use: anotherHandler) */
  1762. app.get("real", use: listUsers)
  1763. `;
  1764. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  1765. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1766. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1767. });
  1768. it('nestjs: skips // and /* */ commented decorators', () => {
  1769. const src = `
  1770. @Controller('users')
  1771. export class UsersController {
  1772. // @Get('fake')
  1773. // fake() {}
  1774. /* @Post('also-fake')
  1775. alsoFake() {} */
  1776. @Get('real')
  1777. real() {}
  1778. }
  1779. `;
  1780. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  1781. expect(nodes.map((n) => n.name)).toEqual(['GET /users/real']);
  1782. expect(references.map((r) => r.referenceName)).toEqual(['real']);
  1783. });
  1784. });