GitNexus/gitnexus/test/integration/resolvers/express-routes.test.ts
henry201605 8bef64baa1
feat(ingestion/routes): give Route nodes a (method, url) identity (#2289) (#2302)
* feat(ingestion/routes): give Route nodes a (method, url) identity (#2289)

Route node identity was URL-only, so a same-URL multi-verb pair
(GET /x + POST /x) collapsed into a single node and the second verb's
handler and execution flow were silently lost. Route identity is now
(method, url) via routeNodeKey(method, url): a known, specific verb keys
as "METHOD url", while a method-less route (filesystem routes — Next.js /
Expo / PHP — and Laravel resource/apiResource) or a wildcard "*" route
(e.g. Django function views) falls back to URL-only. The fallback is
byte-identical to the previous URL-only ids, so only genuine
declaration-style multi-verb routes split into separate nodes.

The identity key is shared across the three phases that must agree on the
Route node id:
- routes phase: registry key + node id + handler-symbol lookup; the Route
  node still carries the bare URL as its display name.
- call-processor: resolveRouteHandlerSymbols re-keyed by identity so each
  verb resolves its own handler; a verb-less fetch() consumer matches by
  URL and connects to every Route node at that URL (one per verb).
- processes phase: ENTRY_POINT_OF targets the identity-keyed node id.

Bumps INCREMENTAL_SCHEMA_VERSION 4 -> 5: persisted pre-v5 Route nodes use
the old url-only ids, so an incremental top-up would strand them alongside
new composite-keyed nodes — force a full re-analyze instead.

Part of #2280.

* fix(ingestion/routes): address PR #2302 review (P1/P2/P3)

P1 — Schema v5 fast-path bypass (run-analyze.ts):
  Adds a schemaVersion-mismatch guard above the alreadyUpToDate early-return,
  mirroring the pdgModeMismatch slot. Without it, a same-commit re-analyze on
  a pre-v5 stamp returned alreadyUpToDate without ever reaching the
  isIncremental gate, defeating the v5 schema bump's migration intent.
  Regression test covers: analyze (stamps v5) → meta downgrade to v4 → same
  commit re-analyze must NOT early-return and meta restamps to v5.

P2 — ENTRY_POINT_OF handler-aware linking (processes.ts):
  Pre-fix routesByFile fanned every same-file Route to every same-file
  process, cross-wiring same-file GET/POST handlers. Now reads handlerSymbolId
  off the Route graph node (the source of truth routes.ts stamps) into
  routesByHandlerId, with a routesWithoutHandlerByFile fallback — mirrors the
  Tool linking precedent 10 lines below. Two regression tests: weak form
  (only one handler has a process; sibling verb does not get spuriously
  attached) and strong form (both handlers form distinct processes; each
  Route links to exactly its own entryPoint, 2 edges not pre-fix 4).

P2 — Roundtrip composite-id (route-{method,handler-symbol}-roundtrip):
  Both tests now seed the Route node with
  generateId('Route', routeNodeKey('POST', '/api/orders')) and run the
  Cypher MATCH against the composite id, exercising the literal-space-in-id
  through CSV→COPY→HANDLES_ROUTE_QUERY. A space-in-id escape regression
  would surface here instead of being silently swallowed by the extractor's
  catch.

P3 — doc-drift + test if:
  - route-path.ts:4 — header updated to "(method, url) via routeNodeKey"
  - java.ts:684 — drop "Route nodes are URL-keyed"; #2289 closes that gap
  - manifest-extractor.ts:196 — explicit that Route node *id* is composite
    while route.name remains the bare URL
  - multi-verb-route-identity.test.ts:88 — forEachRelationship+if rewritten
    as a .filter().map() chain (no test-level conditional). New
    route-process-linking tests are also if-free.

Validation: tsc clean, prettier clean, 9 touched suites / 43 tests pass.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(ingestion/routes): drop routes.ts re-export, fix CI fast-path tests

Two follow-ups on PR #2302's CHANGES_REQUESTED review:

1. Drop `routes.ts` re-export of `normalizeExtractedRoutePath` /
   `normalizeRouteMethod` / `routeNodeKey` (per @magyargergo's inline
   comment at routes.ts:153 — the symbols already live in
   `route-extractors/route-path.ts` and consumers should import them
   from the source, not via a routes-phase indirection that was kept
   only as a compat shim during the #2289 refactor). Updated the two
   remaining callers (blade-template-routes / spring-route-extractor-
   parity tests) to import directly from `route-extractors/route-path.js`.
   `call-processor.ts` and `processes.ts` already import from the source.

2. Fix two `run-analyze.test.ts` fast-path tests that started failing
   on CI after the schema-version mismatch guard landed (
   "creates .gitnexus/.gitignore on the already-up-to-date fast path"
   and "reports isPrimaryBranch false for an up-to-date non-primary
   branch"). The test fixtures hand-built a RepoMeta with NO
   schemaVersion field; with the guard now checking
   `existingMeta.schemaVersion !== INCREMENTAL_SCHEMA_VERSION`, that
   pre-versioning shape was treated as a mismatch and forced a rebuild,
   short-circuiting the fast path the tests exercise. Stamp the current
   schemaVersion on those fixtures so they reflect the post-#2289 meta
   shape production actually writes (`runFullAnalysis` always stamps
   the field on git repos — see meta save site).

Validation: tsc clean, prettier clean, 11 touched suites / 80 tests pass.

---------

Co-authored-by: henry <zhangwei2017@unipus.cn>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-26 07:59:46 +01:00

64 lines
2.4 KiB
TypeScript

import { describe, it, expect, beforeAll } from 'vitest';
import path from 'path';
import {
FIXTURES,
getRelationships,
getNodesByLabel,
getNodesByLabelFull,
runPipelineFromRepo,
type PipelineResult,
} from './helpers.js';
describe('Express/Hono route detection', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(FIXTURES, 'express-route-mapping'), () => {});
}, 60000);
it('creates Route nodes for Express endpoints in TypeScript', () => {
const routes = getNodesByLabel(result, 'Route');
expect(routes).toContain('/api/users');
expect(routes).toContain('/api/users/:id');
expect(routes).toContain('/api/health');
});
it('creates Route nodes for Express endpoints in JavaScript', () => {
const routes = getNodesByLabel(result, 'Route');
expect(routes).toContain('/api/items');
});
it('creates HANDLES_ROUTE edges from handler files to Route nodes', () => {
const edges = getRelationships(result, 'HANDLES_ROUTE');
expect(edges.length).toBeGreaterThanOrEqual(4);
const usersRoute = edges.find((e) => e.target === '/api/users');
expect(usersRoute).toBeDefined();
expect(usersRoute!.sourceFilePath).toContain('server.ts');
const itemsRoute = edges.find((e) => e.target === '/api/items');
expect(itemsRoute).toBeDefined();
expect(itemsRoute!.sourceFilePath).toContain('app.js');
});
it('splits same-path GET/POST into one Route node per verb (#2289)', () => {
// /api/users carries both GET and POST. Route identity is now `(method, url)`,
// so the pair becomes TWO Route nodes — each keeps `/api/users` as its display
// name and is distinguished by its `method` property. (Pre-#2289 the registry
// deduplicated by URL and collapsed them into a single node.)
const usersNodes = getNodesByLabelFull(result, 'Route').filter((n) => n.name === '/api/users');
expect(usersNodes).toHaveLength(2);
const methods = usersNodes.map((n) => n.properties.method).sort();
expect(methods).toEqual(['GET', 'POST']);
});
it('detects router.get() routes (not just app.get())', () => {
const routes = getNodesByLabel(result, 'Route');
expect(routes).toContain('/api/health');
const edges = getRelationships(result, 'HANDLES_ROUTE');
const healthEdge = edges.find((e) => e.target === '/api/health');
expect(healthEdge).toBeDefined();
expect(healthEdge!.sourceFilePath).toContain('server.ts');
});
});