@mustafagoksever/java-inspector 2.4.0 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -261
- package/dist/analyzer/ApiDiff.d.ts +35 -0
- package/dist/analyzer/ApiDiff.d.ts.map +1 -0
- package/dist/analyzer/ApiDiff.js +199 -0
- package/dist/analyzer/ApiDiff.js.map +1 -0
- package/dist/analyzer/JavaClassAnalyzer.d.ts +16 -0
- package/dist/analyzer/JavaClassAnalyzer.d.ts.map +1 -1
- package/dist/analyzer/JavaClassAnalyzer.js +64 -10
- package/dist/analyzer/JavaClassAnalyzer.js.map +1 -1
- package/dist/analyzer/JdkSourceService.d.ts +17 -0
- package/dist/analyzer/JdkSourceService.d.ts.map +1 -0
- package/dist/analyzer/JdkSourceService.js +138 -0
- package/dist/analyzer/JdkSourceService.js.map +1 -0
- package/dist/cache/ProjectCache.d.ts +14 -1
- package/dist/cache/ProjectCache.d.ts.map +1 -1
- package/dist/cache/ProjectCache.js +122 -12
- package/dist/cache/ProjectCache.js.map +1 -1
- package/dist/decompiler/DecompilerService.d.ts +9 -2
- package/dist/decompiler/DecompilerService.d.ts.map +1 -1
- package/dist/decompiler/DecompilerService.js +114 -17
- package/dist/decompiler/DecompilerService.js.map +1 -1
- package/dist/index.d.ts +96 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1146 -606
- package/dist/index.js.map +1 -1
- package/dist/scanner/ArtifactService.d.ts +168 -0
- package/dist/scanner/ArtifactService.d.ts.map +1 -0
- package/dist/scanner/ArtifactService.js +828 -0
- package/dist/scanner/ArtifactService.js.map +1 -0
- package/dist/scanner/BackgroundScanner.d.ts.map +1 -1
- package/dist/scanner/BackgroundScanner.js +38 -26
- package/dist/scanner/BackgroundScanner.js.map +1 -1
- package/dist/scanner/ClassFileMetadataReader.d.ts +31 -0
- package/dist/scanner/ClassFileMetadataReader.d.ts.map +1 -0
- package/dist/scanner/ClassFileMetadataReader.js +215 -0
- package/dist/scanner/ClassFileMetadataReader.js.map +1 -0
- package/dist/scanner/DependencyScanner.d.ts +80 -0
- package/dist/scanner/DependencyScanner.d.ts.map +1 -1
- package/dist/scanner/DependencyScanner.js +401 -41
- package/dist/scanner/DependencyScanner.js.map +1 -1
- package/dist/scanner/JarIndexer.d.ts +73 -0
- package/dist/scanner/JarIndexer.d.ts.map +1 -0
- package/dist/scanner/JarIndexer.js +445 -0
- package/dist/scanner/JarIndexer.js.map +1 -0
- package/dist/scanner/JarScanCoordinator.d.ts +32 -0
- package/dist/scanner/JarScanCoordinator.d.ts.map +1 -0
- package/dist/scanner/JarScanCoordinator.js +124 -0
- package/dist/scanner/JarScanCoordinator.js.map +1 -0
- package/dist/scanner/LazyResolver.js +1 -1
- package/dist/scanner/LazyResolver.js.map +1 -1
- package/dist/scanner/ProjectDiscovery.d.ts +13 -0
- package/dist/scanner/ProjectDiscovery.d.ts.map +1 -0
- package/dist/scanner/ProjectDiscovery.js +84 -0
- package/dist/scanner/ProjectDiscovery.js.map +1 -0
- package/dist/utils/cachePaths.d.ts +3 -0
- package/dist/utils/cachePaths.d.ts.map +1 -1
- package/dist/utils/cachePaths.js +9 -0
- package/dist/utils/cachePaths.js.map +1 -1
- package/dist/utils/javaOutline.d.ts +70 -0
- package/dist/utils/javaOutline.d.ts.map +1 -0
- package/dist/utils/javaOutline.js +444 -0
- package/dist/utils/javaOutline.js.map +1 -0
- package/dist/utils/methodExtractor.d.ts +7 -0
- package/dist/utils/methodExtractor.d.ts.map +1 -1
- package/dist/utils/methodExtractor.js +50 -0
- package/dist/utils/methodExtractor.js.map +1 -1
- package/lib/vineflower-1.12.0.jar +0 -0
- package/package.json +8 -5
- package/lib/vineflower-1.11.2.jar +0 -0
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as os from 'os';
|
|
4
|
+
import fs from 'fs-extra';
|
|
5
|
+
import { projectCache } from '../cache/ProjectCache.js';
|
|
6
|
+
import { getJarIndexesDir } from '../utils/cachePaths.js';
|
|
7
|
+
import { projectDiscovery } from './ProjectDiscovery.js';
|
|
8
|
+
import { jarIndexer } from './JarIndexer.js';
|
|
9
|
+
import { jarScanCoordinator } from './JarScanCoordinator.js';
|
|
10
|
+
import { DependencyScanner } from './DependencyScanner.js';
|
|
11
|
+
export class ArtifactService {
|
|
12
|
+
scanner;
|
|
13
|
+
constructor(scanner = DependencyScanner.getInstance()) {
|
|
14
|
+
this.scanner = scanner;
|
|
15
|
+
}
|
|
16
|
+
async getContextPaths(workspacePath) {
|
|
17
|
+
return projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
18
|
+
}
|
|
19
|
+
async findJars(selector, match = 'prefix', limit = 20, timeBudgetMs = 5000) {
|
|
20
|
+
if (selector.jarPath) {
|
|
21
|
+
const resolved = path.resolve(selector.jarPath);
|
|
22
|
+
await jarIndexer.fingerprint(resolved);
|
|
23
|
+
return { results: [{ jarPath: resolved, jarName: path.basename(resolved), origin: 'direct' }], complete: true, errors: [] };
|
|
24
|
+
}
|
|
25
|
+
const rawQuery = selector.jarNamePrefix || this.artifactIdFromCoordinates(selector.coordinates) || '';
|
|
26
|
+
const query = rawQuery.toLowerCase();
|
|
27
|
+
const matches = (name) => {
|
|
28
|
+
const lower = name.toLowerCase();
|
|
29
|
+
if (!query)
|
|
30
|
+
return true;
|
|
31
|
+
if (match === 'exact')
|
|
32
|
+
return lower === query || lower === `${query}.jar`;
|
|
33
|
+
if (match === 'contains')
|
|
34
|
+
return lower.includes(query);
|
|
35
|
+
return lower.startsWith(query);
|
|
36
|
+
};
|
|
37
|
+
const results = [];
|
|
38
|
+
const errors = [];
|
|
39
|
+
let mavenPending = false;
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
const add = (candidate) => {
|
|
42
|
+
const resolved = path.resolve(candidate.jarPath);
|
|
43
|
+
if (seen.has(resolved) || !matches(candidate.jarName) || results.length >= limit)
|
|
44
|
+
return;
|
|
45
|
+
seen.add(resolved);
|
|
46
|
+
results.push({ ...candidate, jarPath: resolved });
|
|
47
|
+
};
|
|
48
|
+
if (selector.coordinates) {
|
|
49
|
+
for (const jarPath of await this.findCoordinateJars(selector.coordinates)) {
|
|
50
|
+
add({ jarPath, jarName: path.basename(jarPath), origin: 'maven' });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (selector.workspacePath) {
|
|
54
|
+
for (const contextPath of await this.getContextPaths(selector.workspacePath)) {
|
|
55
|
+
const classpath = await this.getMavenClasspath(contextPath, selector);
|
|
56
|
+
mavenPending ||= classpath.pending;
|
|
57
|
+
if (classpath.error)
|
|
58
|
+
errors.push(classpath.error);
|
|
59
|
+
for (const jarPath of classpath.jarPaths) {
|
|
60
|
+
add({ jarPath, jarName: path.basename(jarPath), origin: 'maven', contextPath });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (results.length >= limit)
|
|
65
|
+
return { results, complete: false, errors };
|
|
66
|
+
const searchRoot = selector.jarDirectory || selector.workspacePath;
|
|
67
|
+
if (!searchRoot)
|
|
68
|
+
return { results, complete: !mavenPending && errors.length === 0, errors };
|
|
69
|
+
const root = path.resolve(searchRoot);
|
|
70
|
+
const deadline = Date.now() + Math.max(100, timeBudgetMs);
|
|
71
|
+
const conventional = selector.jarDirectory
|
|
72
|
+
? [root]
|
|
73
|
+
: ['lib', 'libs', 'target', path.join('build', 'libs'), path.join('WEB-INF', 'lib')]
|
|
74
|
+
.map(relative => path.join(root, relative));
|
|
75
|
+
const queue = [];
|
|
76
|
+
for (const candidate of conventional) {
|
|
77
|
+
if (await fs.pathExists(candidate))
|
|
78
|
+
queue.push(candidate);
|
|
79
|
+
}
|
|
80
|
+
if (!selector.jarDirectory)
|
|
81
|
+
queue.push(root);
|
|
82
|
+
const visited = new Set();
|
|
83
|
+
let complete = !mavenPending && errors.length === 0;
|
|
84
|
+
while (queue.length > 0 && results.length < limit) {
|
|
85
|
+
if (Date.now() >= deadline) {
|
|
86
|
+
complete = false;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
const directory = queue.shift();
|
|
90
|
+
const normalized = path.resolve(directory);
|
|
91
|
+
if (visited.has(normalized))
|
|
92
|
+
continue;
|
|
93
|
+
visited.add(normalized);
|
|
94
|
+
let entries;
|
|
95
|
+
try {
|
|
96
|
+
entries = await fs.readdir(normalized, { withFileTypes: true });
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
102
|
+
if (Date.now() >= deadline || results.length >= limit) {
|
|
103
|
+
complete = false;
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
const fullPath = path.join(normalized, entry.name);
|
|
107
|
+
if (entry.isFile() && entry.name.toLowerCase().endsWith('.jar')) {
|
|
108
|
+
add({ jarPath: fullPath, jarName: entry.name, origin: 'local' });
|
|
109
|
+
}
|
|
110
|
+
else if (entry.isDirectory() && !entry.isSymbolicLink() && !['.git', 'node_modules', '.idea', '.gradle'].includes(entry.name)) {
|
|
111
|
+
queue.push(fullPath);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { results, complete, errors };
|
|
116
|
+
}
|
|
117
|
+
async inspectJar(selector) {
|
|
118
|
+
const found = await this.findJars(selector, 'prefix', 21);
|
|
119
|
+
if (found.results.length === 0 && found.errors.length > 0) {
|
|
120
|
+
throw new Error(found.errors.map(error => error.message).join('; '));
|
|
121
|
+
}
|
|
122
|
+
if (found.results.length !== 1)
|
|
123
|
+
return { candidates: found.results };
|
|
124
|
+
const candidate = found.results[0];
|
|
125
|
+
const context = selector.workspacePath || candidate.contextPath || path.dirname(candidate.jarPath);
|
|
126
|
+
const index = await jarScanCoordinator.scanLight(candidate.jarPath, context, 'foreground');
|
|
127
|
+
return { index };
|
|
128
|
+
}
|
|
129
|
+
async searchClasses(query, selector, limit = 20, maxNewJars = 20) {
|
|
130
|
+
const dollar = query.indexOf('$');
|
|
131
|
+
if (dollar > 0 && !/\s/.test(query.trim()))
|
|
132
|
+
return this.searchNestedClasses(query.trim(), dollar, selector, limit, maxNewJars);
|
|
133
|
+
const results = new Map();
|
|
134
|
+
const useWorkspaceClasspath = Boolean(selector.workspacePath && !selector.jarPath && !selector.jarDirectory && !selector.coordinates);
|
|
135
|
+
const contexts = useWorkspaceClasspath ? await this.getContextPaths(selector.workspacePath) : [];
|
|
136
|
+
const errors = [];
|
|
137
|
+
const classpaths = new Map();
|
|
138
|
+
let mavenPending = false;
|
|
139
|
+
for (const context of contexts) {
|
|
140
|
+
const classpath = await this.getMavenClasspath(context, selector);
|
|
141
|
+
classpaths.set(context, classpath.jarPaths);
|
|
142
|
+
mavenPending ||= classpath.pending;
|
|
143
|
+
if (classpath.error)
|
|
144
|
+
errors.push(classpath.error);
|
|
145
|
+
}
|
|
146
|
+
const scoreAndAdd = (entry, origin, contextPath) => {
|
|
147
|
+
const score = this.classScore(entry, query);
|
|
148
|
+
if (score <= 0)
|
|
149
|
+
return;
|
|
150
|
+
const key = `${entry.className}::${path.resolve(entry.jarPath)}`;
|
|
151
|
+
results.set(key, { ...entry, score, origin, contextPath });
|
|
152
|
+
};
|
|
153
|
+
for (const context of contexts) {
|
|
154
|
+
for (const entry of await projectCache.getAllEntriesWithDuplicates(context)) {
|
|
155
|
+
scoreAndAdd(entry, 'maven', context);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
let jarCandidates = [];
|
|
159
|
+
const hasExplicitJarSelector = Boolean(selector.jarPath || selector.jarNamePrefix || selector.jarDirectory || selector.coordinates);
|
|
160
|
+
if (hasExplicitJarSelector) {
|
|
161
|
+
const found = await this.findJars(selector, selector.jarPath ? 'exact' : 'prefix', 50);
|
|
162
|
+
jarCandidates = found.results;
|
|
163
|
+
mavenPending ||= !found.complete;
|
|
164
|
+
errors.push(...found.errors);
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
for (const context of contexts) {
|
|
168
|
+
for (const jarPath of classpaths.get(context) ?? []) {
|
|
169
|
+
jarCandidates.push({ jarPath, jarName: path.basename(jarPath), origin: 'maven', contextPath: context });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (jarCandidates.length === 0 && selector.workspacePath) {
|
|
173
|
+
const found = await this.findJars({ workspacePath: selector.workspacePath }, 'contains', maxNewJars, 5000);
|
|
174
|
+
jarCandidates = found.results;
|
|
175
|
+
mavenPending ||= !found.complete;
|
|
176
|
+
errors.push(...found.errors);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
jarCandidates = [...new Map(jarCandidates.map(candidate => [path.resolve(candidate.jarPath), candidate])).values()];
|
|
180
|
+
const processed = new Set();
|
|
181
|
+
for (const context of contexts) {
|
|
182
|
+
const state = await projectCache.getScanState(context);
|
|
183
|
+
for (const jar of state?.processedJars ?? [])
|
|
184
|
+
processed.add(path.resolve(jar));
|
|
185
|
+
}
|
|
186
|
+
// Unprocessed JARs first; for a qualified class name, JARs whose Maven path/name matches the
|
|
187
|
+
// package (org.apache.commons.lang3 -> org/apache/commons/commons-lang3) are opened first, so an
|
|
188
|
+
// exact lookup usually needs one JAR read even while the background index is incomplete.
|
|
189
|
+
const relevance = this.packageRelevance(query);
|
|
190
|
+
jarCandidates.sort((a, b) => Number(processed.has(path.resolve(a.jarPath))) - Number(processed.has(path.resolve(b.jarPath)))
|
|
191
|
+
|| relevance(b.jarPath) - relevance(a.jarPath));
|
|
192
|
+
let scannedJarCount = 0;
|
|
193
|
+
let nestedRemaining = 0;
|
|
194
|
+
const attempted = new Set();
|
|
195
|
+
for (const candidate of jarCandidates) {
|
|
196
|
+
if (scannedJarCount >= maxNewJars)
|
|
197
|
+
break;
|
|
198
|
+
if (!hasExplicitJarSelector && processed.has(path.resolve(candidate.jarPath)))
|
|
199
|
+
continue;
|
|
200
|
+
const context = selector.workspacePath || candidate.contextPath || path.dirname(candidate.jarPath);
|
|
201
|
+
const resolvedJar = path.resolve(candidate.jarPath);
|
|
202
|
+
attempted.add(resolvedJar);
|
|
203
|
+
try {
|
|
204
|
+
const index = await jarScanCoordinator.scanLight(candidate.jarPath, context, 'foreground');
|
|
205
|
+
scannedJarCount++;
|
|
206
|
+
for (const entry of index.classes.filter(item => !item.isInner)) {
|
|
207
|
+
scoreAndAdd({ ...entry, jarPath: index.jarPath }, candidate.origin, context);
|
|
208
|
+
}
|
|
209
|
+
let exactFound = this.isExactClassMatch(query, index.classes);
|
|
210
|
+
if (!exactFound && index.nestedJars.length > 0) {
|
|
211
|
+
let nestedAttempted = 0;
|
|
212
|
+
for (const nestedEntry of index.nestedJars) {
|
|
213
|
+
if (scannedJarCount >= maxNewJars)
|
|
214
|
+
break;
|
|
215
|
+
nestedAttempted++;
|
|
216
|
+
try {
|
|
217
|
+
const nestedPath = await this.extractNestedJar(candidate.jarPath, nestedEntry, context);
|
|
218
|
+
const nestedIndex = await jarScanCoordinator.scanLight(nestedPath, context, 'foreground');
|
|
219
|
+
scannedJarCount++;
|
|
220
|
+
for (const entry of nestedIndex.classes.filter(item => !item.isInner)) {
|
|
221
|
+
scoreAndAdd({ ...entry, jarPath: nestedPath }, 'nested', context);
|
|
222
|
+
}
|
|
223
|
+
exactFound = this.isExactClassMatch(query, nestedIndex.classes);
|
|
224
|
+
if (exactFound)
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
scannedJarCount++;
|
|
229
|
+
errors.push({ jarPath: candidate.jarPath, contextPath: context, message: `Nested JAR ${nestedEntry}: ${this.errorMessage(error)}` });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (!exactFound)
|
|
233
|
+
nestedRemaining += Math.max(0, index.nestedJars.length - nestedAttempted);
|
|
234
|
+
}
|
|
235
|
+
if (exactFound && !query.includes(' '))
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
scannedJarCount++;
|
|
240
|
+
const scanError = { jarPath: candidate.jarPath, contextPath: context, message: this.errorMessage(error) };
|
|
241
|
+
if (selector.jarPath)
|
|
242
|
+
throw new Error(`Unable to scan ${candidate.jarPath}: ${scanError.message}`);
|
|
243
|
+
errors.push(scanError);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const sorted = [...results.values()]
|
|
247
|
+
.sort((a, b) => b.score - a.score || a.className.localeCompare(b.className) || a.jarPath.localeCompare(b.jarPath))
|
|
248
|
+
.slice(0, Math.max(1, limit));
|
|
249
|
+
const remainingJarCount = jarCandidates.filter(candidate => {
|
|
250
|
+
const resolvedJar = path.resolve(candidate.jarPath);
|
|
251
|
+
return !processed.has(resolvedJar) && !attempted.has(resolvedJar);
|
|
252
|
+
}).length + nestedRemaining;
|
|
253
|
+
return {
|
|
254
|
+
query,
|
|
255
|
+
results: sorted,
|
|
256
|
+
complete: !mavenPending && remainingJarCount === 0 && errors.length === 0,
|
|
257
|
+
scannedJarCount,
|
|
258
|
+
remainingJarCount,
|
|
259
|
+
errors,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Nested classes (Outer$Inner) are not part of the class index; resolve the outer class first,
|
|
264
|
+
* then read the nested entry from the outer class's JAR. On a miss the outer class's nested
|
|
265
|
+
* classes are returned as candidates so the caller can suggest them.
|
|
266
|
+
*/
|
|
267
|
+
async searchNestedClasses(query, dollar, selector, limit, maxNewJars) {
|
|
268
|
+
const outerName = query.substring(0, dollar);
|
|
269
|
+
const outer = await this.searchClasses(outerName, selector, 50, maxNewJars);
|
|
270
|
+
const qualified = outerName.includes('.');
|
|
271
|
+
const outerMatches = outer.results.filter(item => qualified ? item.className === outerName : item.simpleName === outerName);
|
|
272
|
+
const lower = query.toLowerCase();
|
|
273
|
+
const exact = [];
|
|
274
|
+
const related = [];
|
|
275
|
+
const errors = [...outer.errors];
|
|
276
|
+
const seen = new Set();
|
|
277
|
+
for (const match of outerMatches) {
|
|
278
|
+
const jarKey = path.resolve(match.jarPath);
|
|
279
|
+
if (seen.has(jarKey))
|
|
280
|
+
continue;
|
|
281
|
+
seen.add(jarKey);
|
|
282
|
+
try {
|
|
283
|
+
const index = await jarScanCoordinator.scanLight(match.jarPath, match.contextPath, 'foreground');
|
|
284
|
+
const prefix = `${match.className}$`;
|
|
285
|
+
for (const entry of index.classes) {
|
|
286
|
+
if (!entry.isInner || !entry.className.startsWith(prefix))
|
|
287
|
+
continue;
|
|
288
|
+
const full = entry.className.toLowerCase();
|
|
289
|
+
const simple = entry.simpleName.toLowerCase();
|
|
290
|
+
const candidate = { ...entry, jarPath: match.jarPath, origin: match.origin, contextPath: match.contextPath, score: 0 };
|
|
291
|
+
if (full === lower || simple === lower)
|
|
292
|
+
exact.push({ ...candidate, score: full === lower ? 120 : 110 });
|
|
293
|
+
else
|
|
294
|
+
related.push({ ...candidate, score: full.includes(lower) || simple.includes(lower) ? 70 : 30 });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
errors.push({ jarPath: match.jarPath, contextPath: match.contextPath, message: this.errorMessage(error) });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const byName = (a, b) => b.score - a.score || a.className.localeCompare(b.className);
|
|
302
|
+
const unique = (items) => [...new Map(items.map(item => [`${item.className}::${path.resolve(item.jarPath)}`, item])).values()];
|
|
303
|
+
const results = (exact.length ? unique(exact) : unique(related)).sort(byName).slice(0, Math.max(1, limit));
|
|
304
|
+
return { ...outer, query, results, errors, complete: outer.complete && errors.length === outer.errors.length };
|
|
305
|
+
}
|
|
306
|
+
async resolveClass(className, selector) {
|
|
307
|
+
// A fully qualified lookup is cheap with package-relevance ordering, so allow more JARs.
|
|
308
|
+
return this.searchClasses(className, selector, 50, className.includes('.') ? 60 : 20);
|
|
309
|
+
}
|
|
310
|
+
async searchCode(query, kind, selector, limit = 20, maxNewJars = 5) {
|
|
311
|
+
const candidates = await this.candidateJarsForDeepSearch(selector, 10_000);
|
|
312
|
+
const jars = candidates.jars;
|
|
313
|
+
const errors = [...candidates.errors];
|
|
314
|
+
const matches = [];
|
|
315
|
+
let newlyScanned = 0;
|
|
316
|
+
let remainingUnindexed = 0;
|
|
317
|
+
let skippedAfterLimit = 0;
|
|
318
|
+
const lower = query.toLowerCase();
|
|
319
|
+
const ordered = await this.orderForDeepSearch(jars, selector, kind === 'reference' ? query.split('#')[0] : query);
|
|
320
|
+
for (const { candidate, context, cached } of ordered) {
|
|
321
|
+
if (!cached && newlyScanned >= maxNewJars) {
|
|
322
|
+
remainingUnindexed++;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (matches.length >= limit) {
|
|
326
|
+
skippedAfterLimit++;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const deep = await jarScanCoordinator.scanDeep(candidate.jarPath, context, 'foreground');
|
|
331
|
+
if (!cached)
|
|
332
|
+
newlyScanned++;
|
|
333
|
+
for (const clazz of deep.classes) {
|
|
334
|
+
if (kind === 'method') {
|
|
335
|
+
for (const method of clazz.methods.filter(item => item.name.toLowerCase().includes(lower))) {
|
|
336
|
+
matches.push({ jarPath: candidate.jarPath, className: clazz.className, kind, member: method.name, descriptor: method.descriptor });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
else if (kind === 'field') {
|
|
340
|
+
for (const field of clazz.fields.filter(item => item.name.toLowerCase().includes(lower))) {
|
|
341
|
+
matches.push({ jarPath: candidate.jarPath, className: clazz.className, kind, member: field.name, descriptor: field.descriptor });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else if (kind === 'annotation') {
|
|
345
|
+
for (const annotation of clazz.annotationCandidates.filter(item => item.toLowerCase().includes(lower))) {
|
|
346
|
+
matches.push({ jarPath: candidate.jarPath, className: clazz.className, kind, value: annotation });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
else if (kind === 'string') {
|
|
350
|
+
for (const value of clazz.stringConstants.filter(item => item.toLowerCase().includes(lower))) {
|
|
351
|
+
matches.push({ jarPath: candidate.jarPath, className: clazz.className, kind, value });
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
for (const reference of clazz.references.filter(item => `${item.owner}#${item.name} ${item.owner}.${item.name} ${item.name}`.toLowerCase().includes(lower))) {
|
|
356
|
+
matches.push({
|
|
357
|
+
jarPath: candidate.jarPath,
|
|
358
|
+
className: clazz.className,
|
|
359
|
+
kind,
|
|
360
|
+
member: reference.name,
|
|
361
|
+
owner: reference.owner,
|
|
362
|
+
descriptor: reference.descriptor,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (matches.length >= limit)
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
if (!cached)
|
|
372
|
+
newlyScanned++;
|
|
373
|
+
const scanError = { jarPath: candidate.jarPath, contextPath: context, message: this.errorMessage(error) };
|
|
374
|
+
if (selector.jarPath)
|
|
375
|
+
throw new Error(`Unable to deep-scan ${candidate.jarPath}: ${scanError.message}`);
|
|
376
|
+
errors.push(scanError);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return { matches: matches.slice(0, limit), complete: !candidates.pending && remainingUnindexed === 0 && skippedAfterLimit === 0 && errors.length === 0, scannedJarCount: newlyScanned, remainingJarCount: remainingUnindexed + skippedAfterLimit, errors };
|
|
380
|
+
}
|
|
381
|
+
async findImplementations(targetClass, selector, transitive = true, limit = 50, maxNewJars = 5) {
|
|
382
|
+
const candidates = await this.candidateJarsForDeepSearch(selector, 10_000);
|
|
383
|
+
const jars = candidates.jars;
|
|
384
|
+
const errors = [...candidates.errors];
|
|
385
|
+
const allClasses = new Map();
|
|
386
|
+
let newlyScanned = 0;
|
|
387
|
+
let remainingUnindexed = 0;
|
|
388
|
+
for (const { candidate, context, cached } of await this.orderForDeepSearch(jars, selector, targetClass)) {
|
|
389
|
+
if (!cached && newlyScanned >= maxNewJars) {
|
|
390
|
+
remainingUnindexed++;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
const deep = await jarScanCoordinator.scanDeep(candidate.jarPath, context, 'foreground');
|
|
395
|
+
if (!cached)
|
|
396
|
+
newlyScanned++;
|
|
397
|
+
for (const clazz of deep.classes) {
|
|
398
|
+
allClasses.set(clazz.className, { jarPath: candidate.jarPath, superClass: clazz.superClass, interfaces: clazz.interfaces, accessFlags: clazz.accessFlags });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
if (!cached)
|
|
403
|
+
newlyScanned++;
|
|
404
|
+
const scanError = { jarPath: candidate.jarPath, contextPath: context, message: this.errorMessage(error) };
|
|
405
|
+
if (selector.jarPath)
|
|
406
|
+
throw new Error(`Unable to deep-scan ${candidate.jarPath}: ${scanError.message}`);
|
|
407
|
+
errors.push(scanError);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const isSubtype = (name, seen = new Set()) => {
|
|
411
|
+
const metadata = allClasses.get(name);
|
|
412
|
+
if (!metadata || seen.has(name))
|
|
413
|
+
return false;
|
|
414
|
+
seen.add(name);
|
|
415
|
+
const parents = [metadata.superClass, ...metadata.interfaces].filter(Boolean);
|
|
416
|
+
if (parents.includes(targetClass))
|
|
417
|
+
return true;
|
|
418
|
+
return transitive && parents.some(parent => isSubtype(parent, seen));
|
|
419
|
+
};
|
|
420
|
+
const implementations = [];
|
|
421
|
+
for (const [className, metadata] of allClasses) {
|
|
422
|
+
if (className !== targetClass && isSubtype(className)) {
|
|
423
|
+
implementations.push({ jarPath: metadata.jarPath, className, kind: 'implementation' });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
implementations.sort((a, b) => a.className.localeCompare(b.className));
|
|
427
|
+
return {
|
|
428
|
+
implementations: implementations.slice(0, limit),
|
|
429
|
+
complete: !candidates.pending && remainingUnindexed === 0 && errors.length === 0,
|
|
430
|
+
scannedJarCount: newlyScanned,
|
|
431
|
+
remainingJarCount: remainingUnindexed,
|
|
432
|
+
errors,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
async searchResources(selector, pathQuery = '', contentQuery, limit = 20) {
|
|
436
|
+
// Previously capped at the first 20 classpath JARs, so a workspace-wide search could never see the rest.
|
|
437
|
+
const candidates = await this.candidateJarsForDeepSearch(selector, 10_000);
|
|
438
|
+
const jars = candidates.jars;
|
|
439
|
+
const errors = [...candidates.errors];
|
|
440
|
+
const results = [];
|
|
441
|
+
const deadline = Date.now() + 20_000;
|
|
442
|
+
const lowerPath = pathQuery.toLowerCase();
|
|
443
|
+
const lowerContent = contentQuery?.toLowerCase();
|
|
444
|
+
for (const candidate of jars) {
|
|
445
|
+
if (Date.now() > deadline)
|
|
446
|
+
return { results, complete: false, errors };
|
|
447
|
+
const context = selector.workspacePath || candidate.contextPath || path.dirname(candidate.jarPath);
|
|
448
|
+
let index;
|
|
449
|
+
try {
|
|
450
|
+
index = await jarScanCoordinator.scanLight(candidate.jarPath, context, 'foreground');
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
const scanError = { jarPath: candidate.jarPath, contextPath: context, message: this.errorMessage(error) };
|
|
454
|
+
if (selector.jarPath)
|
|
455
|
+
throw new Error(`Unable to scan resources in ${candidate.jarPath}: ${scanError.message}`);
|
|
456
|
+
errors.push(scanError);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
for (const resource of index.resources) {
|
|
460
|
+
if (lowerPath && !resource.path.toLowerCase().includes(lowerPath))
|
|
461
|
+
continue;
|
|
462
|
+
if (lowerContent) {
|
|
463
|
+
if (!resource.isText || resource.size > 1024 * 1024)
|
|
464
|
+
continue;
|
|
465
|
+
const text = (await jarIndexer.readEntry(candidate.jarPath, resource.path, 1024 * 1024)).toString('utf8');
|
|
466
|
+
const position = text.toLowerCase().indexOf(lowerContent);
|
|
467
|
+
if (position < 0)
|
|
468
|
+
continue;
|
|
469
|
+
results.push({
|
|
470
|
+
jarPath: candidate.jarPath,
|
|
471
|
+
resourcePath: resource.path,
|
|
472
|
+
size: resource.size,
|
|
473
|
+
contentMatch: text.substring(Math.max(0, position - 80), Math.min(text.length, position + lowerContent.length + 80)),
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
results.push({ jarPath: candidate.jarPath, resourcePath: resource.path, size: resource.size });
|
|
478
|
+
}
|
|
479
|
+
if (results.length >= limit)
|
|
480
|
+
return { results, complete: false, errors };
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return { results, complete: !candidates.pending && errors.length === 0, errors };
|
|
484
|
+
}
|
|
485
|
+
async readResource(selector, resourcePath, offset = 1, limit = 200) {
|
|
486
|
+
const inspection = await this.inspectJar(selector);
|
|
487
|
+
if (!inspection.index)
|
|
488
|
+
throw new Error(`JAR selector is ambiguous. Candidates: ${(inspection.candidates ?? []).map(item => item.jarPath).join(', ')}`);
|
|
489
|
+
const resource = inspection.index.resources.find(item => item.path === resourcePath);
|
|
490
|
+
if (!resource)
|
|
491
|
+
throw new Error(`Resource not found: ${resourcePath}`);
|
|
492
|
+
if (!resource.isText)
|
|
493
|
+
throw new Error(`Binary resource content is not supported: ${resourcePath}`);
|
|
494
|
+
const bytes = await jarIndexer.readEntry(inspection.index.jarPath, resourcePath, 2 * 1024 * 1024);
|
|
495
|
+
const lines = bytes.toString('utf8').split(/\r?\n/);
|
|
496
|
+
const start = Math.max(1, offset);
|
|
497
|
+
const pageSize = Math.min(1000, Math.max(1, limit));
|
|
498
|
+
const end = Math.min(lines.length, start - 1 + pageSize);
|
|
499
|
+
return {
|
|
500
|
+
jarPath: inspection.index.jarPath,
|
|
501
|
+
resourcePath,
|
|
502
|
+
text: lines.slice(start - 1, end).join('\n'),
|
|
503
|
+
totalLines: lines.length,
|
|
504
|
+
startLine: start,
|
|
505
|
+
endLine: end,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
async extractNestedJar(parentJar, nestedEntry, contextPath) {
|
|
509
|
+
const parentFingerprint = await jarIndexer.fingerprint(parentJar);
|
|
510
|
+
const entryKey = createHash('sha256').update(nestedEntry).digest('hex').substring(0, 12);
|
|
511
|
+
const target = path.join(getJarIndexesDir(contextPath), 'nested', parentFingerprint.key, `${entryKey}-${path.basename(nestedEntry)}`);
|
|
512
|
+
if (!(await fs.pathExists(target))) {
|
|
513
|
+
const bytes = await jarIndexer.readEntry(parentJar, nestedEntry, 250 * 1024 * 1024);
|
|
514
|
+
await fs.outputFile(target, bytes);
|
|
515
|
+
}
|
|
516
|
+
return target;
|
|
517
|
+
}
|
|
518
|
+
async candidateJarsForDeepSearch(selector, limit) {
|
|
519
|
+
const hasSelector = Boolean(selector.jarPath || selector.jarNamePrefix || selector.jarDirectory || selector.coordinates);
|
|
520
|
+
if (hasSelector) {
|
|
521
|
+
const found = await this.findJars(selector, selector.jarPath ? 'exact' : 'prefix', limit);
|
|
522
|
+
return { jars: found.results, pending: !found.complete, errors: found.errors };
|
|
523
|
+
}
|
|
524
|
+
const results = [];
|
|
525
|
+
const errors = [];
|
|
526
|
+
let pending = false;
|
|
527
|
+
if (selector.workspacePath) {
|
|
528
|
+
for (const contextPath of await this.getContextPaths(selector.workspacePath)) {
|
|
529
|
+
const classpath = await this.getMavenClasspath(contextPath, selector);
|
|
530
|
+
pending ||= classpath.pending;
|
|
531
|
+
if (classpath.error)
|
|
532
|
+
errors.push(classpath.error);
|
|
533
|
+
for (const jarPath of classpath.jarPaths) {
|
|
534
|
+
results.push({ jarPath, jarName: path.basename(jarPath), origin: 'maven', contextPath });
|
|
535
|
+
if (results.length >= limit)
|
|
536
|
+
return { jars: results, pending: true, errors };
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (results.length === 0) {
|
|
540
|
+
const found = await this.findJars({ workspacePath: selector.workspacePath }, 'contains', limit);
|
|
541
|
+
return { jars: found.results, pending: pending || !found.complete, errors: [...errors, ...found.errors] };
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
const jars = [...new Map(results.map(candidate => [path.resolve(candidate.jarPath), candidate])).values()];
|
|
545
|
+
return { jars, pending, errors };
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Already deep-indexed JARs first (free), then JARs whose Maven path matches the query's package
|
|
549
|
+
* (e.g. org.springframework.context.ApplicationListener -> spring-context), so the per-call budget
|
|
550
|
+
* of new deep scans is spent where matches are most likely.
|
|
551
|
+
*/
|
|
552
|
+
async orderForDeepSearch(jars, selector, relevanceQuery) {
|
|
553
|
+
const relevance = this.packageRelevance(relevanceQuery.replace(/[#(].*$/, '').replace(/\$/g, '.'));
|
|
554
|
+
const ordered = [];
|
|
555
|
+
for (const candidate of jars) {
|
|
556
|
+
const context = selector.workspacePath || candidate.contextPath || path.dirname(candidate.jarPath);
|
|
557
|
+
ordered.push({ candidate, context, cached: await jarIndexer.hasDeepIndex(candidate.jarPath, context), relevance: relevance(candidate.jarPath) });
|
|
558
|
+
}
|
|
559
|
+
return ordered
|
|
560
|
+
.map((item, position) => ({ ...item, position }))
|
|
561
|
+
.sort((a, b) => Number(b.cached) - Number(a.cached) || b.relevance - a.relevance || a.position - b.position);
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Classes present in more than one classpath JAR (split packages, relocated/shaded copies,
|
|
565
|
+
* two versions of one artifact). Uses the background class index plus on-demand light scans of
|
|
566
|
+
* JARs the background scan has not reached yet.
|
|
567
|
+
*/
|
|
568
|
+
async findDuplicateClasses(selector, options = {}) {
|
|
569
|
+
const limit = options.limit ?? 50;
|
|
570
|
+
const classLimit = options.classLimit ?? 10;
|
|
571
|
+
const maxNewJars = options.maxNewJars ?? 200;
|
|
572
|
+
const deadline = Date.now() + (options.deadlineMs ?? 20_000);
|
|
573
|
+
const query = (options.query ?? '').trim().toLowerCase();
|
|
574
|
+
const errors = [];
|
|
575
|
+
const hasSelector = Boolean(selector.jarPath || selector.jarNamePrefix || selector.jarDirectory || selector.coordinates);
|
|
576
|
+
const scopes = [];
|
|
577
|
+
let pending = false;
|
|
578
|
+
if (hasSelector) {
|
|
579
|
+
const found = await this.findJars(selector, selector.jarPath ? 'exact' : 'prefix', 10_000);
|
|
580
|
+
pending ||= !found.complete;
|
|
581
|
+
errors.push(...found.errors);
|
|
582
|
+
const contextPath = selector.workspacePath || selector.jarDirectory || (found.results[0] ? path.dirname(found.results[0].jarPath) : process.cwd());
|
|
583
|
+
scopes.push({ contextPath, jars: found.results.map(item => item.jarPath), indexed: new Map(), processed: new Set() });
|
|
584
|
+
}
|
|
585
|
+
else if (selector.workspacePath) {
|
|
586
|
+
for (const contextPath of await this.getContextPaths(selector.workspacePath)) {
|
|
587
|
+
const classpath = await this.getMavenClasspath(contextPath, selector);
|
|
588
|
+
pending ||= classpath.pending;
|
|
589
|
+
if (classpath.error)
|
|
590
|
+
errors.push(classpath.error);
|
|
591
|
+
const indexed = new Map();
|
|
592
|
+
for (const entry of await projectCache.getAllEntriesWithDuplicates(contextPath)) {
|
|
593
|
+
if (!indexed.has(entry.className))
|
|
594
|
+
indexed.set(entry.className, new Set());
|
|
595
|
+
indexed.get(entry.className).add(path.resolve(entry.jarPath));
|
|
596
|
+
}
|
|
597
|
+
const state = await projectCache.getScanState(contextPath);
|
|
598
|
+
scopes.push({ contextPath, jars: classpath.jarPaths, indexed, processed: new Set((state?.processedJars ?? []).map(jar => path.resolve(jar))) });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
let scannedJarCount = 0;
|
|
602
|
+
let remainingJarCount = 0;
|
|
603
|
+
const groups = new Map();
|
|
604
|
+
for (const scope of scopes) {
|
|
605
|
+
const owners = scope.indexed;
|
|
606
|
+
for (const jarPath of scope.jars) {
|
|
607
|
+
const resolved = path.resolve(jarPath);
|
|
608
|
+
if (scope.processed.has(resolved))
|
|
609
|
+
continue;
|
|
610
|
+
if (scannedJarCount >= maxNewJars || Date.now() > deadline) {
|
|
611
|
+
remainingJarCount++;
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
try {
|
|
615
|
+
const index = await jarScanCoordinator.scanLight(jarPath, scope.contextPath, 'foreground');
|
|
616
|
+
scannedJarCount++;
|
|
617
|
+
for (const entry of index.classes) {
|
|
618
|
+
if (entry.isInner || entry.isSource)
|
|
619
|
+
continue;
|
|
620
|
+
if (!owners.has(entry.className))
|
|
621
|
+
owners.set(entry.className, new Set());
|
|
622
|
+
owners.get(entry.className).add(resolved);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
scannedJarCount++;
|
|
627
|
+
errors.push({ jarPath, contextPath: scope.contextPath, message: this.errorMessage(error) });
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const onClasspath = new Set(scope.jars.map(jar => path.resolve(jar)));
|
|
631
|
+
for (const [className, jarSet] of owners) {
|
|
632
|
+
const jarsForClass = [...jarSet].filter(jar => onClasspath.size === 0 || onClasspath.has(jar)).sort();
|
|
633
|
+
if (jarsForClass.length < 2)
|
|
634
|
+
continue;
|
|
635
|
+
if (query && !className.toLowerCase().includes(query))
|
|
636
|
+
continue;
|
|
637
|
+
const key = `${scope.contextPath}\n${jarsForClass.join('\n')}`;
|
|
638
|
+
let group = groups.get(key);
|
|
639
|
+
if (!group) {
|
|
640
|
+
const artifacts = jarsForClass.map(jar => ({ jarPath: jar, ...this.coordinatesFromJarPath(jar) }));
|
|
641
|
+
const artifactIds = new Set(artifacts.map(item => item.groupId && item.artifactId ? `${item.groupId}:${item.artifactId}` : path.basename(item.jarPath)));
|
|
642
|
+
group = {
|
|
643
|
+
contextPath: scope.contextPath,
|
|
644
|
+
jars: artifacts,
|
|
645
|
+
kind: artifactIds.size === 1 ? 'same-artifact-multiple-versions' : 'different-artifacts',
|
|
646
|
+
classCount: 0,
|
|
647
|
+
packages: [],
|
|
648
|
+
sampleClasses: [],
|
|
649
|
+
};
|
|
650
|
+
groups.set(key, group);
|
|
651
|
+
}
|
|
652
|
+
group.classCount++;
|
|
653
|
+
const pkg = className.includes('.') ? className.substring(0, className.lastIndexOf('.')) : '';
|
|
654
|
+
if (!group.packages.includes(pkg) && group.packages.length < 20)
|
|
655
|
+
group.packages.push(pkg);
|
|
656
|
+
if (group.sampleClasses.length < classLimit)
|
|
657
|
+
group.sampleClasses.push(className);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const sorted = [...groups.values()]
|
|
661
|
+
.map(group => ({ ...group, packages: group.packages.sort(), sampleClasses: group.sampleClasses.sort() }))
|
|
662
|
+
.sort((a, b) => Number(b.kind === 'same-artifact-multiple-versions') - Number(a.kind === 'same-artifact-multiple-versions') || b.classCount - a.classCount);
|
|
663
|
+
return {
|
|
664
|
+
groups: sorted.slice(0, Math.max(1, limit)),
|
|
665
|
+
totalGroups: sorted.length,
|
|
666
|
+
totalDuplicateClasses: sorted.reduce((sum, group) => sum + group.classCount, 0),
|
|
667
|
+
complete: !pending && remainingJarCount === 0 && errors.length === 0,
|
|
668
|
+
scannedJarCount,
|
|
669
|
+
remainingJarCount,
|
|
670
|
+
errors,
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
/** groupId/artifactId/version from a Maven repository layout path (.../g/r/o/u/p/artifact/version/artifact-version.jar). */
|
|
674
|
+
coordinatesFromJarPath(jarPath) {
|
|
675
|
+
const parts = path.resolve(jarPath).split(/[\\/]/);
|
|
676
|
+
// Gradle cache: .../files-2.1/<group>/<artifact>/<version>/<sha1>/<file>.jar
|
|
677
|
+
const gradleIndex = parts.lastIndexOf('files-2.1');
|
|
678
|
+
if (gradleIndex >= 0 && parts.length - gradleIndex === 6) {
|
|
679
|
+
return { groupId: parts[gradleIndex + 1], artifactId: parts[gradleIndex + 2], version: parts[gradleIndex + 3] };
|
|
680
|
+
}
|
|
681
|
+
const file = parts[parts.length - 1];
|
|
682
|
+
const version = parts[parts.length - 2];
|
|
683
|
+
const artifactId = parts[parts.length - 3];
|
|
684
|
+
if (!file || !version || !artifactId || !file.startsWith(`${artifactId}-${version}`))
|
|
685
|
+
return {};
|
|
686
|
+
// Prefer the configured local repository root (MAVEN_REPO may not end in "repository", and a groupId
|
|
687
|
+
// may itself contain a "repository" segment); fall back to the last "repository" directory.
|
|
688
|
+
const repositoryRoot = path.resolve(process.env.MAVEN_REPO || path.join(os.homedir(), '.m2', 'repository')).split(/[\\/]/).filter(Boolean);
|
|
689
|
+
const absolute = parts.filter(Boolean);
|
|
690
|
+
const underRoot = repositoryRoot.length < absolute.length - 3 && repositoryRoot.every((segment, index) => absolute[index] === segment);
|
|
691
|
+
const repoIndex = parts.lastIndexOf('repository');
|
|
692
|
+
const groupParts = underRoot
|
|
693
|
+
? absolute.slice(repositoryRoot.length, absolute.length - 3)
|
|
694
|
+
: repoIndex >= 0 ? parts.slice(repoIndex + 1, parts.length - 3) : [];
|
|
695
|
+
return { groupId: groupParts.length ? groupParts.join('.') : undefined, artifactId, version };
|
|
696
|
+
}
|
|
697
|
+
async getMavenClasspath(contextPath, options = {}) {
|
|
698
|
+
const cached = await projectCache.getClasspath(contextPath).catch(() => null);
|
|
699
|
+
if (cached !== null)
|
|
700
|
+
return { jarPaths: cached, pending: false };
|
|
701
|
+
if (!this.scanner.isResolvingClasspath(contextPath)) {
|
|
702
|
+
try {
|
|
703
|
+
const result = await this.scanner.scanProject(contextPath, false);
|
|
704
|
+
if (result.message?.startsWith('Previous scan failed:')) {
|
|
705
|
+
return { jarPaths: [], pending: false, error: { contextPath, message: result.message } };
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
return { jarPaths: [], pending: false, error: { contextPath, message: this.errorMessage(error) } };
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
let refreshed = await projectCache.getClasspath(contextPath).catch(() => null);
|
|
713
|
+
if (refreshed === null && options.classpathWaitMs) {
|
|
714
|
+
await options.onWait?.('Waiting for Maven classpath resolution (first run for this project)...');
|
|
715
|
+
refreshed = await this.scanner.waitForClasspath(contextPath, options.classpathWaitMs, async (elapsed) => {
|
|
716
|
+
await options.onWait?.(`Still resolving Maven classpath (${Math.round(elapsed / 1000)}s)...`);
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
if (refreshed === null && !this.scanner.isResolvingClasspath(contextPath)) {
|
|
720
|
+
// Resolution finished without a classpath: report Maven's/Gradle's error instead of "still resolving".
|
|
721
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
722
|
+
const failure = this.scanner.peekScanError(contextPath);
|
|
723
|
+
if (failure)
|
|
724
|
+
return { jarPaths: [], pending: false, error: { contextPath, message: `Classpath resolution failed: ${this.summarizeBuildError(failure)}` } };
|
|
725
|
+
}
|
|
726
|
+
return { jarPaths: refreshed ?? [], pending: refreshed === null };
|
|
727
|
+
}
|
|
728
|
+
/** First [ERROR] lines of a Maven/Gradle failure; the full output is in the server log. */
|
|
729
|
+
summarizeBuildError(message) {
|
|
730
|
+
const errors = [...new Set(message.split('\n').map(line => line.trim()).filter(line => /^\[ERROR\]\s+\S/.test(line) && !/\[Help \d+\]|re-run Maven|Re-run Maven|For more information|After correcting|mvn <args>|full stack trace/i.test(line)))].slice(0, 4);
|
|
731
|
+
const first = message.split('\n')[0].substring(0, 300);
|
|
732
|
+
return errors.length ? `${first}\n${errors.join('\n')}` : message.substring(0, 800);
|
|
733
|
+
}
|
|
734
|
+
errorMessage(error) {
|
|
735
|
+
return error instanceof Error ? error.message : String(error);
|
|
736
|
+
}
|
|
737
|
+
classScore(entry, query) {
|
|
738
|
+
const normalized = query.toLowerCase().trim();
|
|
739
|
+
if (!normalized)
|
|
740
|
+
return 0;
|
|
741
|
+
const full = entry.className.toLowerCase();
|
|
742
|
+
const simple = entry.simpleName.toLowerCase();
|
|
743
|
+
if (full === normalized)
|
|
744
|
+
return 120;
|
|
745
|
+
if (simple === normalized)
|
|
746
|
+
return 110;
|
|
747
|
+
if (simple.endsWith(normalized))
|
|
748
|
+
return 80;
|
|
749
|
+
if (simple.includes(normalized))
|
|
750
|
+
return 60;
|
|
751
|
+
if (full.includes(normalized))
|
|
752
|
+
return 50;
|
|
753
|
+
const parts = normalized.split(/[\s.]+/).filter(Boolean);
|
|
754
|
+
if (parts.length > 1 && parts.every(part => full.includes(part)))
|
|
755
|
+
return 40 + parts.length * 5;
|
|
756
|
+
return 0;
|
|
757
|
+
}
|
|
758
|
+
packageRelevance(query) {
|
|
759
|
+
const trimmed = query.trim();
|
|
760
|
+
if (!/^[\w$]+(\.[\w$]+)+$/.test(trimmed))
|
|
761
|
+
return () => 0;
|
|
762
|
+
const generic = new Set(['org', 'com', 'io', 'net', 'java', 'javax', 'jakarta', 'internal', 'impl', 'api', 'util', 'core']);
|
|
763
|
+
const segments = trimmed.toLowerCase().split('.').slice(0, -1);
|
|
764
|
+
return (jarPath) => {
|
|
765
|
+
const parts = new Set(jarPath.toLowerCase().split(/[\\/._-]+/));
|
|
766
|
+
let score = 0;
|
|
767
|
+
segments.forEach((segment, index) => {
|
|
768
|
+
if (!parts.has(segment))
|
|
769
|
+
return;
|
|
770
|
+
// Leading package segments match the Maven groupId directories; distinctive ones weigh more.
|
|
771
|
+
score += (generic.has(segment) ? 1 : 3) + (index < 4 ? 1 : 0);
|
|
772
|
+
});
|
|
773
|
+
return score;
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
isExactClassMatch(query, classes) {
|
|
777
|
+
const lower = query.toLowerCase();
|
|
778
|
+
return classes.some(entry => !entry.isInner && (entry.className.toLowerCase() === lower || entry.simpleName.toLowerCase() === lower));
|
|
779
|
+
}
|
|
780
|
+
artifactIdFromCoordinates(coordinates) {
|
|
781
|
+
if (!coordinates)
|
|
782
|
+
return '';
|
|
783
|
+
return coordinates.split(':')[1] || coordinates;
|
|
784
|
+
}
|
|
785
|
+
/** The -sources.jar of a binary JAR: next to it (Maven repository) or in a sibling hash directory (Gradle cache). */
|
|
786
|
+
async findSourcesJar(jarPath) {
|
|
787
|
+
const sibling = jarPath.replace(/\.jar$/i, '-sources.jar');
|
|
788
|
+
if (sibling !== jarPath && await fs.pathExists(sibling))
|
|
789
|
+
return sibling;
|
|
790
|
+
const parts = path.resolve(jarPath).split(/[\\/]/);
|
|
791
|
+
const gradleIndex = parts.lastIndexOf('files-2.1');
|
|
792
|
+
if (gradleIndex < 0 || parts.length - gradleIndex !== 6)
|
|
793
|
+
return null;
|
|
794
|
+
const versionDir = path.dirname(path.dirname(path.resolve(jarPath)));
|
|
795
|
+
const fileName = path.basename(sibling);
|
|
796
|
+
for (const hash of await fs.readdir(versionDir).catch(() => [])) {
|
|
797
|
+
const candidate = path.join(versionDir, hash, fileName);
|
|
798
|
+
if (await fs.pathExists(candidate))
|
|
799
|
+
return candidate;
|
|
800
|
+
}
|
|
801
|
+
return null;
|
|
802
|
+
}
|
|
803
|
+
async findCoordinateJars(coordinates) {
|
|
804
|
+
const [groupId, artifactId, version, classifier] = coordinates.split(':');
|
|
805
|
+
if (!groupId || !artifactId)
|
|
806
|
+
return [];
|
|
807
|
+
const repository = path.resolve(process.env.MAVEN_REPO || path.join(os.homedir(), '.m2', 'repository'));
|
|
808
|
+
const artifactRoot = path.join(repository, ...groupId.split('.'), artifactId);
|
|
809
|
+
if (!(await fs.pathExists(artifactRoot)))
|
|
810
|
+
return [];
|
|
811
|
+
const versions = version
|
|
812
|
+
? [version]
|
|
813
|
+
: (await fs.readdir(artifactRoot, { withFileTypes: true }))
|
|
814
|
+
.filter(entry => entry.isDirectory())
|
|
815
|
+
.map(entry => entry.name)
|
|
816
|
+
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
|
|
817
|
+
const results = [];
|
|
818
|
+
for (const selectedVersion of versions) {
|
|
819
|
+
const suffix = classifier ? `-${classifier}` : '';
|
|
820
|
+
const jarPath = path.join(artifactRoot, selectedVersion, `${artifactId}-${selectedVersion}${suffix}.jar`);
|
|
821
|
+
if (await fs.pathExists(jarPath))
|
|
822
|
+
results.push(jarPath);
|
|
823
|
+
}
|
|
824
|
+
return results;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
export const artifactService = new ArtifactService();
|
|
828
|
+
//# sourceMappingURL=ArtifactService.js.map
|