Repository navigation
Expand file tree
/
Copy pathjava.ts
More file actions
762 lines (715 loc) · 30.5 KB
/
Copy pathjava.ts
File metadata and controls
762 lines (715 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/**
* Java Framework Resolver
*
* Handles Spring Boot and general Java patterns.
*/
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { pickByNameAndKind } from './name-heuristic';
export const springResolver: FrameworkResolver = {
name: 'spring',
languages: ['java', 'kotlin', 'yaml', 'properties'],
claimsReference(name: string): boolean {
// `@ConfigurationProperties(prefix="app.cache")` emits a reference whose
// name carries the `:prefix` sentinel — there's no declared symbol with
// that exact spelling, so the resolver's name-existence pre-filter would
// drop it. Opt those through.
return name.endsWith(':prefix');
},
detect(context: ResolutionContext): boolean {
// Check for pom.xml with Spring
const pomXml = context.readFile('pom.xml');
if (pomXml && (pomXml.includes('spring-boot') || pomXml.includes('springframework'))) {
return true;
}
// Check for build.gradle with Spring
const buildGradle = context.readFile('build.gradle');
if (buildGradle && (buildGradle.includes('spring-boot') || buildGradle.includes('springframework'))) {
return true;
}
const buildGradleKts = context.readFile('build.gradle.kts');
if (buildGradleKts && (buildGradleKts.includes('spring-boot') || buildGradleKts.includes('springframework'))) {
return true;
}
// Check for Spring annotations in Java files
const allFiles = context.getAllFiles();
for (const file of allFiles) {
if (file.endsWith('.java')) {
const content = context.readFile(file);
if (content && (
content.includes('@SpringBootApplication') ||
content.includes('@RestController') ||
content.includes('@Service') ||
content.includes('@Repository')
)) {
return true;
}
}
}
return false;
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// A route's handler is the method its mapping annotation is written on,
// told apart from an overload by position: under a tall `@Operation` /
// `@ApiResponses` stack, the next overload's declaration can be nearer the
// annotation than the method it annotates (#851).
const handler = routeHandlerAt(ref, context);
if (handler) return { original: ref, targetNodeId: handler.id, confidence: 0.95, resolvedBy: 'framework' };
// Spring config-key references — `@Value("${key}")` (single leaf) and
// `@ConfigurationProperties(prefix="X")` (entire subtree, marked with the
// `:prefix` suffix in extractSpringValueBindings). Lookup goes through
// Spring's relaxed binding (kebab/camel/snake → canonical lowercase).
if (ref.referenceName.endsWith(':prefix')) {
const prefix = ref.referenceName.slice(0, -':prefix'.length);
const canonPrefix = canonicalConfigKey(prefix);
// Prefer an exact prefix match (one node = the prefix subtree). Without
// node-level subtree representation we map to the closest matching key.
const candidates = context.getNodesByKind('constant').filter(
(n) => (n.language === 'yaml' || n.language === 'properties')
&& canonicalConfigKey(n.qualifiedName).startsWith(canonPrefix),
);
if (candidates.length === 0) return null;
// Pick the SHORTEST canonical name — it's the closest binding point
// (`app.cache` over `app.cache.name.user-token` for prefix=`app.cache`).
const best = candidates.reduce((a, b) =>
canonicalConfigKey(a.qualifiedName).length <= canonicalConfigKey(b.qualifiedName).length ? a : b,
);
return { original: ref, targetNodeId: best.id, confidence: 0.85, resolvedBy: 'framework' };
}
if (ref.referenceName.includes('.') && ref.language !== 'java' && ref.language !== 'kotlin') {
// Spring config dotted key — only when the source language is Java/Kotlin
// (the bindings come from `@Value`). Skip non-Spring refs that happen to
// have dots in them.
}
// Spring config-key resolution: `@Value("${a.b.c}")` and
// `@ConfigurationProperties`. Gate on the `references` kind — those bindings
// are emitted as `references` by extractSpringValueBindings, whereas the far
// more numerous method-call refs (`list.add()`, `builder.build()`, every
// `receiver.method()`) are `calls`. A config key is NEVER a `calls` ref, so
// this loses no resolution. Without the gate, every dotted `calls` ref fell
// into the uncached getNodesByKind('constant') scan below — an
// O(dotted-calls × constant-nodes) cost that dominated resolution and made a
// full index take ~1h on large Java/Kotlin (Spring) monorepos (#1180). The
// old `split('.').length >= 2` heuristic couldn't separate keys from calls;
// the kind check does it exactly.
if (
ref.referenceKind === 'references' &&
(ref.language === 'java' || ref.language === 'kotlin') &&
ref.referenceName.includes('.') &&
!ref.referenceName.includes('::')
) {
const canonRef = canonicalConfigKey(ref.referenceName);
const candidates = context.getNodesByKind('constant').filter(
(n) => n.kind === 'constant'
&& (n.language === 'yaml' || n.language === 'properties')
&& canonicalConfigKey(n.qualifiedName) === canonRef,
);
if (candidates.length === 1) {
return { original: ref, targetNodeId: candidates[0]!.id, confidence: 0.9, resolvedBy: 'framework' };
}
if (candidates.length > 1) {
// Multiple profile-specific files (application-dev.yml +
// application-prod.yml) can define the same key. Prefer the one with
// the shortest profile suffix (the base `application.yml` wins over
// profile variants when both exist), then by alphabetical path so the
// pick is deterministic across reindexes.
const score = (n: Node) => {
const base = n.filePath.split('/').pop() ?? '';
const isBase = /^(application|bootstrap)\.(yml|yaml|properties)$/i.test(base);
return (isBase ? 0 : 1) * 1000 + base.length;
};
const best = candidates.reduce((a, b) => (score(a) <= score(b) ? a : b));
return { original: ref, targetNodeId: best.id, confidence: 0.75, resolvedBy: 'framework' };
}
}
// The DI/convention patterns below (1–5) are Spring-specific heuristics:
// they must only fire on Java/Kotlin refs, and never on inheritance refs.
// Without these gates a Scala `extends ExtCustomer` (Spring detected via a
// sibling Java module) was hijacked by Pattern 4's bare-name fallback to an
// unrelated same-named test class — `extends`/`implements` must resolve via
// imports/name matching, not directory heuristics.
if (ref.language !== 'java' && ref.language !== 'kotlin') return null;
if (ref.referenceKind === 'extends' || ref.referenceKind === 'implements') return null;
// Pattern 1: Service references (dependency injection)
if (ref.referenceName.endsWith('Service')) {
const result = resolveByNameAndKind(ref, SERVICE_KINDS, SERVICE_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.85,
resolvedBy: 'framework',
};
}
}
// Pattern 2: Repository references
if (ref.referenceName.endsWith('Repository')) {
const result = resolveByNameAndKind(ref, SERVICE_KINDS, REPO_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.85,
resolvedBy: 'framework',
};
}
}
// Pattern 3: Controller references
if (ref.referenceName.endsWith('Controller')) {
const result = resolveByNameAndKind(ref, CLASS_KINDS, CONTROLLER_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.85,
resolvedBy: 'framework',
};
}
}
// Pattern 4: Entity/Model references
if (/^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
const result = resolveByNameAndKind(ref, CLASS_KINDS, ENTITY_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.7,
resolvedBy: 'framework',
};
}
}
// Pattern 5: Component references
if (ref.referenceName.endsWith('Component') || ref.referenceName.endsWith('Config')) {
const result = resolveByNameAndKind(ref, CLASS_KINDS, COMPONENT_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
}
return null;
},
extract(filePath, content) {
// Spring config files (application.yml / application.properties /
// bootstrap.yml + per-profile variants) are extracted on the framework
// path, not in the language extractor, so the keys become first-class
// nodes a `@Value("${k}")` reference can resolve to.
if (isSpringConfigFile(filePath)) {
return extractSpringConfig(filePath, content);
}
// Spring Boot is used from both Java and Kotlin (identical @GetMapping etc.
// annotations); the difference is method syntax — Kotlin `fun name(...)` vs
// Java `public X name(...)` — handled in the method regex below.
if (!filePath.endsWith('.java') && !filePath.endsWith('.kt')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const lang: 'java' | 'kotlin' = filePath.endsWith('.kt') ? 'kotlin' : 'java';
const safe = stripCommentsForRegex(content, 'java');
const consts = new Map<string, string>();
for (const m of safe.matchAll(/\bstatic\s+final\s+String\s+(\w+)\s*=\s*"([^"]*)"\s*;/g)) {
consts.set(m[1]!, m[2]!);
}
// Class-level @RequestMapping prefix (an @RequestMapping whose tail leads to a
// `class`). Joined onto each method's path — and, crucially, NOT treated as a
// route itself (the old regex did, creating one bogus class route and missing
// every BARE method mapping like `@PostMapping` with the path on the class).
const cls = /@RequestMapping\s*\(([^)]*)\)\s*(?:@[\w.]+(?:\([^)]*\))?\s*)*(?:public\s+|final\s+|abstract\s+|open\s+|data\s+|sealed\s+)*class\b/.exec(safe);
const classPrefixes = cls ? parseMappingPaths(cls[1]!, consts) : [''];
const VERB: Record<string, string> = {
GetMapping: 'GET', PostMapping: 'POST', PutMapping: 'PUT', PatchMapping: 'PATCH', DeleteMapping: 'DELETE',
};
// Verb-specific method mappings — always method-level, BARE or with a path.
const mappingRegex = /@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping)\b/g;
let match: RegExpExecArray | null;
while ((match = mappingRegex.exec(safe)) !== null) {
const annotation = readAnnotation(safe, match.index, lang);
if (!annotation) continue;
const method = VERB[match[1]!]!;
const paths = parseMappingPaths(annotation.args, consts);
const line = safe.slice(0, match.index).split('\n').length;
// The method it decorates: the declaration it is written on (#851).
const handler = annotatedMethodName(safe, match.index, lang);
for (const routePath of classPrefixes.flatMap(prefix => paths.map(sub => joinPath(prefix, sub)))) {
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: annotation.end - match.index,
language: lang,
updatedAt: now,
};
nodes.push(routeNode);
if (handler) {
references.push({
fromNodeId: routeNode.id,
referenceName: handler,
referenceKind: 'references',
line,
column: 0,
filePath,
language: lang,
});
}
}
}
// Method-level @RequestMapping (older style: `@RequestMapping(value="/x",
// method=RequestMethod.GET)` on a method). The class-level @RequestMapping is
// the prefix (handled above) — skip it here so it isn't double-counted.
const reqRe = /@RequestMapping\b/g;
while ((match = reqRe.exec(safe)) !== null) {
const annotation = readAnnotation(safe, match.index, lang);
if (!annotation) continue;
const args = annotation.args;
const after = safe.slice(annotation.end, annotation.end + 600);
if (/^\s*(?:@[\w.]+(?:\([^)]*\))?\s*)*(?:public\s+|final\s+|abstract\s+|open\s+|data\s+|sealed\s+)*class\b/.test(after)) continue; // class-level prefix
// Only on a method: the declaration it is written on (#851).
const handler = annotatedMethodName(safe, match.index, lang);
if (!handler) continue;
const verbM = args.match(/method\s*=\s*[{\[]?\s*(?:RequestMethod\.)?(\w+)/);
const method = verbM ? verbM[1]!.toUpperCase() : 'ANY';
const paths = parseMappingPaths(args, consts);
const line = safe.slice(0, match.index).split('\n').length;
for (const routePath of classPrefixes.flatMap(prefix => paths.map(sub => joinPath(prefix, sub)))) {
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath, startLine: line, endLine: line, startColumn: 0, endColumn: annotation.end - match.index, language: lang, updatedAt: now,
};
nodes.push(routeNode);
references.push({
fromNodeId: routeNode.id,
referenceName: handler,
referenceKind: 'references',
line, column: 0, filePath, language: lang,
});
}
}
// @Value("${key}") and @ConfigurationProperties(prefix="...") — bind
// Spring config-key references in Java/Kotlin source. The reference target
// is the corresponding YAML/properties leaf-key node emitted by
// extractSpringConfig; springResolver.resolve looks it up with relaxed
// binding (kebab/camel/snake collapse).
extractSpringValueBindings(filePath, safe, lang, now, nodes, references);
return { nodes, references };
},
};
/** Spring config file patterns: application(-profile)?.{yml,yaml,properties} +
* bootstrap variants. Matches the basename, not the path, so a project that
* vendors `application.yml` under `src/main/resources` and one under `src/test/
* resources` are both picked up. */
function isSpringConfigFile(filePath: string): boolean {
const base = filePath.split('/').pop() ?? '';
return /^(application|bootstrap)(-[\w.-]+)?\.(yml|yaml|properties)$/i.test(base);
}
/**
* Parse a Spring config file (YAML or .properties) and emit one `constant`
* node per LEAF key, with `qualifiedName` = the dotted path. Leaf keys are
* what `@Value("${k}")` references hit; intermediate keys aren't bound by
* Spring's `@Value` (a `@ConfigurationProperties` class binds a SUBTREE, and
* those references are resolved at lookup time by prefix-suffix matching).
*/
function extractSpringConfig(
filePath: string,
content: string,
): { nodes: Node[]; references: UnresolvedRef[] } {
const nodes: Node[] = [];
const isProperties = /\.properties$/i.test(filePath);
const lang = isProperties ? 'properties' : 'yaml';
const now = Date.now();
const emitLeaf = (dottedKey: string, line: number, valueText: string) => {
if (!dottedKey) return;
nodes.push({
id: `spring-config:${filePath}:${line}:${dottedKey}`,
kind: 'constant',
name: dottedKey.split('.').pop() ?? dottedKey,
qualifiedName: dottedKey,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: valueText.length,
language: lang,
signature: dottedKey,
// SECURITY (#383): store the KEY only, never the value. Config files
// routinely hold secrets (DB passwords, API keys, JDBC URLs with embedded
// credentials), and surfacing the value here pushes it into agent context
// unbidden (it lands in codegraph_node/explore output via the docstring).
// The key is all `@Value`/`@ConfigurationProperties` resolution needs; an
// agent that genuinely needs a value can read the file directly.
updatedAt: now,
});
};
if (isProperties) {
// Properties format: `k1.k2.k3 = value` (or `:` separator, or no value).
// Lines starting with `#`/`!` are comments. Backslash continuations are
// valid but rare; we don't try to join them (a continued value is still
// a value of the same key).
const lines = content.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const raw = lines[i] ?? '';
const trimmed = raw.trim();
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) continue;
const sep = (() => {
for (let j = 0; j < raw.length; j++) {
const ch = raw[j];
if (ch === '=' || ch === ':') return j;
if (ch === '\\' && raw[j + 1]) { j++; continue; }
}
return -1;
})();
if (sep < 0) continue;
const key = raw.slice(0, sep).trim();
const val = raw.slice(sep + 1).trim();
emitLeaf(key, i + 1, val);
}
return { nodes, references: [] };
}
// YAML: indent-based. We track a stack of (indent, key) so the dotted path
// is built by joining ancestor keys with `.`. A leaf is a line with a value
// on the same line (after `:`). List items, flow-style scalars, and `---`
// separators are ignored — they don't bind to `@Value` anyway.
const stack: Array<{ indent: number; key: string }> = [];
const yamlLines = content.split(/\r?\n/);
for (let i = 0; i < yamlLines.length; i++) {
const raw = yamlLines[i] ?? '';
const trimmed = raw.trim();
if (!trimmed || trimmed.startsWith('#') || trimmed === '---' || trimmed.startsWith('- ')) continue;
const indent = raw.length - raw.replace(/^[\t ]+/, '').length;
const colonIdx = (() => {
let inStr: string | null = null;
for (let j = 0; j < raw.length; j++) {
const ch = raw[j];
if (inStr) { if (ch === inStr && raw[j - 1] !== '\\') inStr = null; continue; }
if (ch === '"' || ch === "'") { inStr = ch; continue; }
if (ch === ':') return j;
}
return -1;
})();
if (colonIdx < 0) continue;
const key = raw.slice(indent, colonIdx).trim();
if (!key) continue;
const after = raw.slice(colonIdx + 1).trim();
while (stack.length > 0 && stack[stack.length - 1]!.indent >= indent) stack.pop();
const dotted = [...stack.map((s) => s.key), key].join('.');
if (after === '' || after.startsWith('#')) {
stack.push({ indent, key });
} else {
// A leaf with an inline value (or a flow-mapping like `{ a: 1 }` — we
// emit it as a leaf, not as a subtree; precision is fine for `@Value`).
const valStripped = after.replace(/^["']|["']$/g, '');
emitLeaf(dotted, i + 1, valStripped);
}
}
return { nodes, references: [] };
}
/** Append `@Value("${k}")` and `@ConfigurationProperties(prefix=...)`
* references discovered in `safe` (comments stripped) into the caller's
* `nodes`/`references` arrays. */
function extractSpringValueBindings(
filePath: string,
safe: string,
lang: 'java' | 'kotlin',
now: number,
nodes: Node[],
references: UnresolvedRef[],
): void {
const valueRe = /@Value\s*\(\s*["']\$\{([^}:]+)(?::[^}]*)?\}["']\s*\)/g;
let m: RegExpExecArray | null;
while ((m = valueRe.exec(safe)) !== null) {
const key = m[1]!.trim();
if (!key) continue;
const line = safe.slice(0, m.index).split('\n').length;
const bindNode: Node = {
id: `spring-value:${filePath}:${line}:${key}`,
kind: 'constant',
name: key,
qualifiedName: `${filePath}::@Value:${key}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: m[0].length,
language: lang,
signature: `@Value("${key}")`,
updatedAt: now,
};
nodes.push(bindNode);
references.push({
fromNodeId: bindNode.id,
referenceName: key,
referenceKind: 'references',
line,
column: 0,
filePath,
language: lang,
});
}
const cpRe = /@ConfigurationProperties\s*\(\s*(?:prefix\s*=\s*)?["']([^"']+)["']/g;
while ((m = cpRe.exec(safe)) !== null) {
const prefix = m[1]!.trim();
if (!prefix) continue;
const line = safe.slice(0, m.index).split('\n').length;
const bindNode: Node = {
id: `spring-cp:${filePath}:${line}:${prefix}`,
kind: 'constant',
name: prefix,
qualifiedName: `${filePath}::@ConfigurationProperties:${prefix}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: m[0].length,
language: lang,
signature: `@ConfigurationProperties("${prefix}")`,
updatedAt: now,
};
nodes.push(bindNode);
references.push({
fromNodeId: bindNode.id,
// Mark the reference with a `:prefix` suffix so springResolver.resolve
// knows to expand it into the SUBTREE rather than a single key.
referenceName: `${prefix}:prefix`,
referenceKind: 'references',
line,
column: 0,
filePath,
language: lang,
});
}
}
/** Spring's relaxed binding (`cache-list` ↔ `cacheList` ↔ `cache_list` ↔
* `CACHE_LIST`) collapses on lowercase + dash/underscore removal. We compare
* candidate keys to a reference in this canonical form. */
function canonicalConfigKey(key: string): string {
return key.toLowerCase().replace(/[-_]/g, '');
}
// Directory patterns
const SERVICE_DIRS = ['/service/', '/services/'];
const REPO_DIRS = ['/repository/', '/repositories/'];
const CONTROLLER_DIRS = ['/controller/', '/controllers/'];
const ENTITY_DIRS = ['/entity/', '/entities/', '/model/', '/models/', '/domain/'];
const COMPONENT_DIRS = ['/component/', '/components/', '/config/'];
const CLASS_KINDS = new Set(['class']);
const SERVICE_KINDS = new Set(['class', 'interface']);
/** All declared paths; [''] for an omitted path, [] for an unresolved one. */
function parseMappingPaths(args: string, consts: Map<string, string>): string[] {
const paths: string[] = [];
let hasPaths = false;
// Keep Java/Kotlin arrays and quoted URI variables together when separating
// attributes. Strings in produces/consumes/etc. are never mapping paths.
const argRe = /(?:^|,)\s*(?:(\w+)\s*=\s*)?(\{(?:[^"'}]|"[^"]*"|'[^']*')*\}|\[(?:[^"'\]]|"[^"]*"|'[^']*')*\]|"[^"]*"|'[^']*'|[^,]+)/g;
for (const arg of args.matchAll(argRe)) {
if (arg[1] && arg[1] !== 'value' && arg[1] !== 'path') continue;
hasPaths = true;
const scope = arg[2]!.trim().replace(/^[{\[]|[}\]]$/g, '').trim();
if (!scope) paths.push(''); // An explicitly empty path array also inherits the prefix.
for (const value of scope.matchAll(/(?:^|,)\s*(?:"([^"]*)"|'([^']*)'|([\w.]+))\s*(?=,|$)/g)) {
const path = value[1] ?? value[2] ?? consts.get(value[3]!.split('.').pop()!);
if (path !== undefined) paths.push(path);
}
}
return hasPaths ? [...new Set(paths)] : [''];
}
/** Join a class-level prefix and a method sub-path into one normalized `/path`. */
function joinPath(prefix: string, sub: string): string {
const parts = [prefix, sub].map((p) => p.replace(/^\/+|\/+$/g, '')).filter(Boolean);
return '/' + parts.join('/');
}
/** Java modifiers a method may carry before its type parameters and return type. */
const JAVA_METHOD_MODIFIERS = new Set([
'public', 'protected', 'private', 'static', 'final', 'abstract', 'synchronized', 'native', 'strictfp', 'default',
]);
/** Kotlin modifiers a function may carry before `fun`. */
const KOTLIN_FUN_MODIFIERS = new Set([
'public', 'protected', 'private', 'internal', 'open', 'override', 'final', 'abstract',
'suspend', 'inline', 'operator', 'infix', 'tailrec', 'external', 'actual', 'expect',
]);
/** Words that begin a declaration other than a method where a Java return type would stand. */
const NOT_A_RETURN_TYPE = new Set(['class', 'interface', 'enum', 'record']);
const IDENTIFIER = /[A-Za-z_$][\w$]*/y;
function readIdentifier(s: string, i: number): string | null {
IDENTIFIER.lastIndex = i;
return IDENTIFIER.exec(s)?.[0] ?? null;
}
function skipSpace(s: string, i: number): number {
while (i < s.length && /\s/.test(s[i]!)) i++;
return i;
}
/** The index past the string or char literal (or `"""` text block) opening at `i`; -1 when it never closes. */
function skipQuoted(s: string, i: number): number {
const quote = s[i]!;
if (s.startsWith('"""', i)) {
const end = s.indexOf('"""', i + 3);
return end < 0 ? -1 : end + 3;
}
for (let j = i + 1; j < s.length; j++) {
if (s[j] === '\\') j++;
else if (s[j] === quote) return j + 1;
else if (s[j] === '\n') return -1;
}
return -1;
}
/** The index past the bracketed group opening at `i` — nested groups and literals inside it included; -1 when it never closes. */
function skipGroup(s: string, i: number): number {
const open = s[i]!;
const close = open === '(' ? ')' : open === '[' ? ']' : open === '{' ? '}' : '>';
let depth = 0;
for (let j = i; j < s.length; j++) {
const c = s[j]!;
if (c === '"' || (c === "'" && open !== '<')) {
const end = skipQuoted(s, j);
if (end < 0) return -1;
j = end - 1;
} else if (c === open) {
depth++;
} else if (c === close && --depth === 0) {
return j + 1;
}
}
return -1;
}
/**
* The annotation at `at` — `@Name`, `@a.b.Name`, Kotlin's `@field:Name` or
* `@[A B]` — with its arguments read as a balanced group, so a `)` in a string
* or a nested annotation doesn't end it. `end` is past the arguments, or past
* the whitespace after a bare name. Null when no annotation is there, or its
* arguments never close.
*/
function readAnnotation(s: string, at: number, lang: 'java' | 'kotlin'): { args: string; end: number } | null {
if (s[at] !== '@') return null;
let i = at + 1;
if (lang === 'kotlin' && s[i] === '[') {
const end = skipGroup(s, i);
return end < 0 ? null : { args: '', end };
}
const readName = (from: number): number => {
let j = from;
for (;;) {
const part = readIdentifier(s, j);
if (!part) return -1;
j += part.length;
if (s[j] !== '.') return j;
j++;
}
};
i = readName(i);
if (i < 0) return null;
// A Kotlin use-site target: `@field:Name`, `@get:Name`.
if (lang === 'kotlin' && s[i] === ':') {
i = readName(i + 1);
if (i < 0) return null;
}
const next = skipSpace(s, i);
if (s[next] !== '(') return { args: '', end: next };
const end = skipGroup(s, next);
return end < 0 ? null : { args: s.slice(next + 1, end - 1), end };
}
/**
* The name of the method the annotation at `at` is written on (#851): read
* past it and every annotation stacked with it, the modifiers — none at all
* for a package-private Java method — the type parameters and the return type
* (`void`, a primitive, a qualified or nested generic type, an array) to
* `name(`; for Kotlin, past the modifiers to `fun`, its type parameters, and
* `name(`. Null when what the annotation is written on is no method: a field,
* a constructor, a class.
*/
function annotatedMethodName(s: string, at: number, lang: 'java' | 'kotlin'): string | null {
const modifiers = lang === 'kotlin' ? KOTLIN_FUN_MODIFIERS : JAVA_METHOD_MODIFIERS;
// Annotations and modifiers come in any order (`public @ResponseBody String x()`).
const skipAnnotationsAndModifiers = (from: number): number => {
let i = from;
for (;;) {
i = skipSpace(s, i);
if (s[i] === '@') {
const annotation = readAnnotation(s, i, lang);
if (!annotation) return -1;
i = annotation.end;
continue;
}
const word = readIdentifier(s, i);
if (!word || !modifiers.has(word)) return i;
i += word.length;
}
};
let i = skipAnnotationsAndModifiers(at);
if (i < 0) return null;
if (lang === 'kotlin') {
if (readIdentifier(s, i) !== 'fun') return null;
i = skipSpace(s, i + 3);
if (s[i] === '<') {
i = skipGroup(s, i);
if (i < 0) return null;
i = skipSpace(s, i);
}
} else {
if (s[i] === '<') {
i = skipGroup(s, i);
if (i < 0) return null;
}
// Annotations on the return type: `<T> @Nullable T x()`.
i = skipAnnotationsAndModifiers(i);
if (i < 0) return null;
const type = readIdentifier(s, i);
if (!type || NOT_A_RETURN_TYPE.has(type)) return null;
i += type.length;
// Its qualifiers, type arguments and array dimensions.
for (;;) {
const j = skipSpace(s, i);
if (s[j] === '<') {
i = skipGroup(s, j);
if (i < 0) return null;
} else if (s[j] === '.') {
const k = skipSpace(s, j + 1);
const part = readIdentifier(s, k);
if (!part) return null;
i = k + part.length;
} else if (s[j] === '[' && s[skipSpace(s, j + 1)] === ']') {
i = skipSpace(s, j + 1) + 1;
} else {
break;
}
}
i = skipSpace(s, i);
}
const name = readIdentifier(s, i);
if (!name) return null;
return s[skipSpace(s, i + name.length)] === '(' ? name : null;
}
/**
* The method a Spring route's handler reference names, found where the
* route's mapping annotation is written: the innermost method of that name
* whose span — which starts at its first annotation — holds the annotation's
* line. Null for any other reference, and when no such method is indexed.
*/
function routeHandlerAt(ref: UnresolvedRef, context: ResolutionContext): Node | null {
if (ref.referenceKind !== 'references' || (ref.language !== 'java' && ref.language !== 'kotlin')) return null;
if (!ref.fromNodeId.startsWith(`route:${ref.filePath}:${ref.line}:`)) return null;
let handler: Node | null = null;
for (const node of context.getNodesInFile(ref.filePath)) {
if ((node.kind !== 'method' && node.kind !== 'function') || node.name !== ref.referenceName) continue;
if (node.startLine > ref.line || node.endLine < ref.line) continue;
if (!handler || node.startLine > handler.startLine) handler = node;
}
return handler;
}
/** A framework name heuristic's pick (see name-heuristic.ts), preferring these folders. */
function resolveByNameAndKind(
ref: UnresolvedRef,
kinds: Set<string>,
preferredDirPatterns: string[],
context: ResolutionContext,
): string | null {
return pickByNameAndKind(ref, kinds, (f) => preferredDirPatterns.some((d) => f.includes(d)), context);
}