@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.
Files changed (69) hide show
  1. package/README.md +147 -261
  2. package/dist/analyzer/ApiDiff.d.ts +35 -0
  3. package/dist/analyzer/ApiDiff.d.ts.map +1 -0
  4. package/dist/analyzer/ApiDiff.js +199 -0
  5. package/dist/analyzer/ApiDiff.js.map +1 -0
  6. package/dist/analyzer/JavaClassAnalyzer.d.ts +16 -0
  7. package/dist/analyzer/JavaClassAnalyzer.d.ts.map +1 -1
  8. package/dist/analyzer/JavaClassAnalyzer.js +64 -10
  9. package/dist/analyzer/JavaClassAnalyzer.js.map +1 -1
  10. package/dist/analyzer/JdkSourceService.d.ts +17 -0
  11. package/dist/analyzer/JdkSourceService.d.ts.map +1 -0
  12. package/dist/analyzer/JdkSourceService.js +138 -0
  13. package/dist/analyzer/JdkSourceService.js.map +1 -0
  14. package/dist/cache/ProjectCache.d.ts +14 -1
  15. package/dist/cache/ProjectCache.d.ts.map +1 -1
  16. package/dist/cache/ProjectCache.js +122 -12
  17. package/dist/cache/ProjectCache.js.map +1 -1
  18. package/dist/decompiler/DecompilerService.d.ts +9 -2
  19. package/dist/decompiler/DecompilerService.d.ts.map +1 -1
  20. package/dist/decompiler/DecompilerService.js +114 -17
  21. package/dist/decompiler/DecompilerService.js.map +1 -1
  22. package/dist/index.d.ts +96 -18
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1146 -606
  25. package/dist/index.js.map +1 -1
  26. package/dist/scanner/ArtifactService.d.ts +168 -0
  27. package/dist/scanner/ArtifactService.d.ts.map +1 -0
  28. package/dist/scanner/ArtifactService.js +828 -0
  29. package/dist/scanner/ArtifactService.js.map +1 -0
  30. package/dist/scanner/BackgroundScanner.d.ts.map +1 -1
  31. package/dist/scanner/BackgroundScanner.js +38 -26
  32. package/dist/scanner/BackgroundScanner.js.map +1 -1
  33. package/dist/scanner/ClassFileMetadataReader.d.ts +31 -0
  34. package/dist/scanner/ClassFileMetadataReader.d.ts.map +1 -0
  35. package/dist/scanner/ClassFileMetadataReader.js +215 -0
  36. package/dist/scanner/ClassFileMetadataReader.js.map +1 -0
  37. package/dist/scanner/DependencyScanner.d.ts +80 -0
  38. package/dist/scanner/DependencyScanner.d.ts.map +1 -1
  39. package/dist/scanner/DependencyScanner.js +401 -41
  40. package/dist/scanner/DependencyScanner.js.map +1 -1
  41. package/dist/scanner/JarIndexer.d.ts +73 -0
  42. package/dist/scanner/JarIndexer.d.ts.map +1 -0
  43. package/dist/scanner/JarIndexer.js +445 -0
  44. package/dist/scanner/JarIndexer.js.map +1 -0
  45. package/dist/scanner/JarScanCoordinator.d.ts +32 -0
  46. package/dist/scanner/JarScanCoordinator.d.ts.map +1 -0
  47. package/dist/scanner/JarScanCoordinator.js +124 -0
  48. package/dist/scanner/JarScanCoordinator.js.map +1 -0
  49. package/dist/scanner/LazyResolver.js +1 -1
  50. package/dist/scanner/LazyResolver.js.map +1 -1
  51. package/dist/scanner/ProjectDiscovery.d.ts +13 -0
  52. package/dist/scanner/ProjectDiscovery.d.ts.map +1 -0
  53. package/dist/scanner/ProjectDiscovery.js +84 -0
  54. package/dist/scanner/ProjectDiscovery.js.map +1 -0
  55. package/dist/utils/cachePaths.d.ts +3 -0
  56. package/dist/utils/cachePaths.d.ts.map +1 -1
  57. package/dist/utils/cachePaths.js +9 -0
  58. package/dist/utils/cachePaths.js.map +1 -1
  59. package/dist/utils/javaOutline.d.ts +70 -0
  60. package/dist/utils/javaOutline.d.ts.map +1 -0
  61. package/dist/utils/javaOutline.js +444 -0
  62. package/dist/utils/javaOutline.js.map +1 -0
  63. package/dist/utils/methodExtractor.d.ts +7 -0
  64. package/dist/utils/methodExtractor.d.ts.map +1 -1
  65. package/dist/utils/methodExtractor.js +50 -0
  66. package/dist/utils/methodExtractor.js.map +1 -1
  67. package/lib/vineflower-1.12.0.jar +0 -0
  68. package/package.json +8 -5
  69. package/lib/vineflower-1.11.2.jar +0 -0
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
+ import * as os from 'os';
3
4
  import * as path from 'path';
4
5
  import fs from 'fs-extra';
5
6
  import { projectCache } from '../cache/ProjectCache.js';
@@ -8,12 +9,74 @@ import { lazyResolver } from './LazyResolver.js';
8
9
  import { getProjectCacheDir } from '../utils/cachePaths.js';
9
10
  import { Logger } from '../utils/Logger.js';
10
11
  import { CrossProcessLock } from '../utils/CrossProcessLock.js';
12
+ import { buildToolOf } from './ProjectDiscovery.js';
11
13
  const execFileAsync = promisify(execFile);
14
+ /** Parse the text output of `mvn dependency:tree -DoutputFile=...` (one module per file). */
15
+ export function parseDependencyTree(text) {
16
+ const lines = text.split(/\r?\n/).filter(line => line.trim());
17
+ if (!lines.length)
18
+ return null;
19
+ const parse = (token) => {
20
+ const parts = token.split(':');
21
+ if (parts.length < 4)
22
+ return null;
23
+ const [groupId, artifactId, type] = parts;
24
+ if (parts.length === 4)
25
+ return { groupId, artifactId, type, version: parts[3] };
26
+ if (parts.length === 5)
27
+ return { groupId, artifactId, type, version: parts[3], scope: parts[4] };
28
+ return { groupId, artifactId, type, classifier: parts[3], version: parts[4], scope: parts[5] };
29
+ };
30
+ const root = parse(lines[0].trim().split(/\s+/)[0]);
31
+ if (!root)
32
+ return null;
33
+ const module = `${root.groupId}:${root.artifactId}:${root.version}`;
34
+ const stack = [`${root.groupId}:${root.artifactId}`];
35
+ const dependencies = [];
36
+ for (const line of lines.slice(1)) {
37
+ const prefix = line.match(/^[| +\\-]*/)?.[0] ?? '';
38
+ const depth = Math.max(1, Math.round(prefix.length / 3));
39
+ const body = line.substring(prefix.length).trim();
40
+ const node = parse(body.split(/\s+/)[0]);
41
+ if (!node)
42
+ continue;
43
+ stack.length = depth;
44
+ dependencies.push({ ...node, depth, via: stack[depth - 1], ...(/\(optional\)/.test(body) ? { optional: true } : {}) });
45
+ stack[depth] = `${node.groupId}:${node.artifactId}`;
46
+ }
47
+ return { module, dependencies };
48
+ }
49
+ const GRADLE_INIT_SCRIPT = `
50
+ allprojects { p ->
51
+ p.tasks.register('javaInspectorClasspath') {
52
+ doLast {
53
+ def outDir = new File(System.getProperty('javaInspector.out'))
54
+ def files = new LinkedHashSet<File>()
55
+ ['compileClasspath', 'runtimeClasspath', 'testCompileClasspath', 'testRuntimeClasspath'].each { name ->
56
+ def conf = p.configurations.findByName(name)
57
+ if (conf != null && conf.canBeResolved) {
58
+ try {
59
+ files.addAll(conf.incoming.artifactView { lenient = true }.files.files)
60
+ } catch (Exception e) {
61
+ p.logger.warn("java-inspector: could not resolve " + p.path + ":" + name + ": " + e.message)
62
+ }
63
+ }
64
+ }
65
+ def safe = p.path.replaceAll('[^A-Za-z0-9_.-]', '_')
66
+ new File(outDir, "cp-" + (safe ?: 'root') + ".txt").text = files.collect { it.absolutePath }.join('\\n')
67
+ }
68
+ }
69
+ }
70
+ `;
12
71
  export class DependencyScanner {
72
+ /** Projects whose last classpath came from recoverReactorClasspath with JARs missing. */
73
+ partialClasspaths = new Set();
13
74
  static instance;
14
75
  classpathPromises = new Map();
15
76
  mavenCommand = null;
16
77
  scanErrors = new Map();
78
+ activeClasspathResolutions = 0;
79
+ classpathResolutionQueue = [];
17
80
  // Track scan.lock release functions so we can release when scan completes
18
81
  scanLockReleases = new Map();
19
82
  static getInstance() {
@@ -64,7 +127,7 @@ export class DependencyScanner {
64
127
  classCount: 0,
65
128
  sampleEntries: [],
66
129
  status: 'in_progress',
67
- message: `Previous scan failed: ${storedError}. Call scan_dependencies with forceRefresh=true to retry.`,
130
+ message: `Previous scan failed: ${storedError}. Call scan_project with forceRefresh=true to retry.`,
68
131
  };
69
132
  }
70
133
  // Check for complete index
@@ -81,24 +144,6 @@ export class DependencyScanner {
81
144
  };
82
145
  }
83
146
  }
84
- // Cross-process check: is another process currently scanning?
85
- const isLockedByOther = await CrossProcessLock.check(projectPath, 'scan');
86
- if (isLockedByOther) {
87
- logger.info('[SCAN] Another process is currently scanning this project.');
88
- const progress = await projectCache.getScanProgress(projectPath) ?? undefined;
89
- const progressText = progress
90
- ? `${progress.processed}/${progress.total} JARs processed`
91
- : 'scanning in progress';
92
- await onProgress?.(`Another process is scanning: ${progressText}`, progress ? Math.floor((progress.processed / progress.total) * 100) : 0, 100);
93
- return {
94
- jarCount: progress?.total ?? 0,
95
- classCount: 0,
96
- sampleEntries: [],
97
- status: 'in_progress',
98
- progress,
99
- message: 'Another process is currently scanning this project. Please wait or call again later.',
100
- };
101
- }
102
147
  // Check if classpath resolution is already in progress (in-process)
103
148
  if (this.classpathPromises.has(projectPath)) {
104
149
  await onProgress?.('Maven classpath resolution in progress...', 5, 100);
@@ -107,7 +152,7 @@ export class DependencyScanner {
107
152
  classCount: 0,
108
153
  sampleEntries: [],
109
154
  status: 'in_progress',
110
- message: 'Maven classpath is being resolved in the background. This may take a few minutes for large projects (e.g. Spring Boot). Call scan_dependencies again to check progress.',
155
+ message: 'Maven classpath is being resolved in the background. This may take a few minutes for large projects (e.g. Spring Boot). Call scan_project again to check progress; other tools already work on the partial index.',
111
156
  };
112
157
  }
113
158
  // Check if background scan is already running (in-process)
@@ -123,6 +168,24 @@ export class DependencyScanner {
123
168
  progress,
124
169
  };
125
170
  }
171
+ // Cross-process check: is another process currently scanning?
172
+ const isLockedByOther = await CrossProcessLock.check(projectPath, 'scan');
173
+ if (isLockedByOther) {
174
+ logger.info('[SCAN] Another process is currently scanning this project.');
175
+ const progress = await projectCache.getScanProgress(projectPath) ?? undefined;
176
+ const progressText = progress
177
+ ? `${progress.processed}/${progress.total} JARs processed`
178
+ : 'scanning in progress';
179
+ await onProgress?.(`Another process is scanning: ${progressText}`, progress ? Math.floor((progress.processed / progress.total) * 100) : 0, 100);
180
+ return {
181
+ jarCount: progress?.total ?? 0,
182
+ classCount: 0,
183
+ sampleEntries: [],
184
+ status: 'in_progress',
185
+ progress,
186
+ message: 'Another process is currently scanning this project. Please wait or call again later.',
187
+ };
188
+ }
126
189
  // Check if we already have classpath cached (scan may have finished or been interrupted)
127
190
  const cachedClasspath = await projectCache.getClasspath(projectPath);
128
191
  if (cachedClasspath && cachedClasspath.length > 0) {
@@ -151,7 +214,7 @@ export class DependencyScanner {
151
214
  classCount: 0,
152
215
  sampleEntries: [],
153
216
  status: 'in_progress',
154
- message: 'Maven classpath resolution started in the background. This may take a few minutes for large projects (e.g. Spring Boot). Call scan_dependencies again to check progress.',
217
+ message: 'Maven classpath resolution started in the background. This may take a few minutes for large projects (e.g. Spring Boot). Call scan_project again to check progress; other tools already work on the partial index.',
155
218
  };
156
219
  }
157
220
  /**
@@ -194,18 +257,29 @@ export class DependencyScanner {
194
257
  */
195
258
  async resolveClasspathAndStartScan(projectPath, onProgress) {
196
259
  const logger = Logger.get(projectPath);
197
- const promise = this.getBuildClasspath(projectPath, onProgress);
260
+ const promise = this.withClasspathResolutionSlot(() => this.getBuildClasspath(projectPath, onProgress));
198
261
  this.classpathPromises.set(projectPath, promise);
199
262
  try {
200
263
  const jarPaths = await promise;
201
264
  this.classpathPromises.delete(projectPath);
202
265
  if (jarPaths.length === 0) {
203
266
  logger.warn('[MAVEN] No dependency JARs found after classpath resolution.');
267
+ const pomHash = await projectCache.getPomHash(projectPath);
268
+ const classpathHash = projectCache.getClasspathHash([]);
269
+ await projectCache.saveClasspath(projectPath, [], pomHash);
270
+ await projectCache.saveClassIndex(projectPath, {
271
+ jarCount: 0,
272
+ classCount: 0,
273
+ sampleEntries: [],
274
+ }, pomHash, classpathHash);
204
275
  return;
205
276
  }
206
277
  const pomHash = await projectCache.getPomHash(projectPath);
207
278
  const classpathHash = projectCache.getClasspathHash(jarPaths);
208
- await projectCache.saveClasspath(projectPath, jarPaths, pomHash);
279
+ const partial = this.partialClasspaths.delete(projectPath);
280
+ await projectCache.saveClasspath(projectPath, jarPaths, pomHash, partial);
281
+ if (partial)
282
+ logger.warn('[MAVEN] Classpath is partial (some dependencies are not in the local repository); it will be resolved again in 10 minutes.');
209
283
  logger.info(`[MAVEN] Classpath resolved. ${jarPaths.length} JARs found. Starting background scan...`);
210
284
  await onProgress?.(`Classpath resolved: ${jarPaths.length} JARs. Starting background scan...`, 10, 100);
211
285
  await this.acquireScanLockAndStart(projectPath, jarPaths, pomHash, classpathHash, onProgress);
@@ -222,18 +296,29 @@ export class DependencyScanner {
222
296
  * Use Maven to get the dependency classpath.
223
297
  */
224
298
  async getBuildClasspath(projectPath, onProgress) {
299
+ if (await buildToolOf(projectPath) === 'gradle')
300
+ return this.getGradleClasspath(projectPath, onProgress);
225
301
  const logger = Logger.get(projectPath);
226
302
  const mavenCmd = await this.resolveMavenCommand(projectPath);
227
303
  const cacheDir = getProjectCacheDir(projectPath);
228
304
  await fs.ensureDir(cacheDir);
229
- const outputFile = path.join(cacheDir, 'maven-cp.txt');
305
+ // One output file per reactor module. A single shared -Dmdep.outputFile is overwritten by every
306
+ // module of a multi-module build (only the last module would survive), and -Dmdep.appendOutput
307
+ // is not reliable across plugin versions. Maven interpolates ${project.*} in the CLI property.
308
+ const outputDir = path.join(cacheDir, 'maven-cp');
309
+ await fs.remove(outputDir).catch(() => { });
310
+ await fs.ensureDir(outputDir);
311
+ const outputFile = path.join(outputDir, 'cp-${project.groupId}__${project.artifactId}.txt');
230
312
  const isDebug = process.env.NODE_ENV === 'development';
231
313
  logger.info(`[MAVEN] Running: ${mavenCmd} dependency:build-classpath...`);
232
314
  logger.debug(`[MAVEN] Config: cwd=${projectPath}, timeout=300000ms, shell=${process.platform === 'win32'}, maxBuffer=1MB, outputFile=${outputFile}`);
233
315
  await onProgress?.(`Running Maven: ${mavenCmd} dependency:build-classpath...`, 5, 100);
234
316
  const start = performance.now();
317
+ let recovered = null;
235
318
  try {
236
- const { stdout, stderr } = await execFileAsync(mavenCmd, ['dependency:build-classpath', `-Dmdep.outputFile=${outputFile}`, '-q'], {
319
+ const { stdout, stderr } = await execFileAsync(mavenCmd,
320
+ // -B: never block on interactive prompts.
321
+ ['-B', '-q', 'dependency:build-classpath', `-Dmdep.outputFile=${outputFile}`], {
237
322
  cwd: projectPath,
238
323
  timeout: 300000, // 5 minutes for large projects (e.g. Spring Boot)
239
324
  shell: process.platform === 'win32',
@@ -258,25 +343,27 @@ export class DependencyScanner {
258
343
  if (error.code)
259
344
  details += `\nexit code: ${error.code}`;
260
345
  logger.error(`[MAVEN] Command failed after ${duration}s: ${error.message}${details}`);
261
- throw new Error(`Maven command failed: ${error.message}${details}`);
346
+ recovered = await this.recoverReactorClasspath(projectPath, mavenCmd, outputFile, details);
347
+ if (!recovered)
348
+ throw new Error(`Maven command failed: ${error.message}${details}`);
262
349
  }
263
- if (!(await fs.pathExists(outputFile))) {
350
+ const outputFiles = (await fs.readdir(outputDir)).filter(name => name.endsWith('.txt')).sort();
351
+ if (outputFiles.length === 0 && !recovered?.length) {
264
352
  throw new Error('Maven did not produce classpath output file');
265
353
  }
266
- const content = await fs.readFile(outputFile, 'utf-8');
267
- // Remove the temp file
268
- try {
269
- await fs.remove(outputFile);
270
- }
271
- catch {
272
- // ignore cleanup errors
273
- }
274
- // Classpath entries are separated by path.delimiter (: on Unix, ; on Windows)
275
- const jarPaths = content
276
- .trim()
277
- .split(path.delimiter)
278
- .map(p => p.trim())
279
- .filter(p => p.length > 0 && p.endsWith('.jar'));
354
+ const contents = [];
355
+ for (const name of outputFiles)
356
+ contents.push(await fs.readFile(path.join(outputDir, name), 'utf-8'));
357
+ await fs.remove(outputDir).catch(() => { });
358
+ // Classpath entries are separated by path.delimiter (: on Unix, ; on Windows); the same JAR
359
+ // usually appears in several modules.
360
+ const jarPaths = [...new Set(contents
361
+ .flatMap(content => content.split(/\r?\n/))
362
+ .flatMap(line => line.split(path.delimiter))
363
+ .map(p => p.trim())
364
+ .filter(p => p.length > 0 && p.endsWith('.jar'))
365
+ .concat(recovered ?? []))];
366
+ logger.info(`[MAVEN] Read classpath of ${outputFiles.length} module(s).`);
280
367
  // Validate paths exist
281
368
  const validPaths = [];
282
369
  for (const jar of jarPaths) {
@@ -296,6 +383,49 @@ export class DependencyScanner {
296
383
  isResolvingClasspath(projectPath) {
297
384
  return this.classpathPromises.has(projectPath);
298
385
  }
386
+ /**
387
+ * Wait (bounded) for a classpath that is being resolved by this process or, via scan.lock,
388
+ * by another server process. Returns null if it is still unavailable when the time is up.
389
+ * Single-class lookups use this so a cold start does not answer "class not found" while
390
+ * Maven is still running.
391
+ */
392
+ /** The last classpath/scan failure of a project, without clearing it (scanProject reports and clears it). */
393
+ peekScanError(projectPath) {
394
+ return this.scanErrors.get(projectPath);
395
+ }
396
+ async waitForClasspath(projectPath, timeoutMs, onWait) {
397
+ const deadline = Date.now() + Math.max(0, timeoutMs);
398
+ const started = Date.now();
399
+ while (true) {
400
+ const cached = await projectCache.getClasspath(projectPath).catch(() => null);
401
+ if (cached !== null)
402
+ return cached;
403
+ const remaining = deadline - Date.now();
404
+ if (remaining <= 0)
405
+ return null;
406
+ const inProcess = this.classpathPromises.get(projectPath);
407
+ if (inProcess) {
408
+ let timer;
409
+ const result = await Promise.race([
410
+ inProcess.then(paths => paths, () => null),
411
+ new Promise(resolve => { timer = setTimeout(() => resolve(undefined), Math.min(remaining, 2_000)); }),
412
+ ]);
413
+ if (timer)
414
+ clearTimeout(timer);
415
+ if (result === null)
416
+ return null; // resolution failed; the error is reported by scanProject
417
+ if (result !== undefined)
418
+ return result;
419
+ }
420
+ else if (await CrossProcessLock.check(projectPath, 'scan')) {
421
+ await new Promise(resolve => setTimeout(resolve, Math.min(remaining, 500)));
422
+ }
423
+ else {
424
+ return null;
425
+ }
426
+ await onWait?.(Date.now() - started);
427
+ }
428
+ }
299
429
  /**
300
430
  * Find corresponding JAR package path by class name.
301
431
  * Uses cache + lazy on-demand scanning.
@@ -333,6 +463,236 @@ export class DependencyScanner {
333
463
  async getClasspath(projectPath) {
334
464
  return projectCache.getClasspath(projectPath);
335
465
  }
466
+ async explainDependency(projectPath, coordinates) {
467
+ if (await buildToolOf(projectPath) === 'gradle')
468
+ throw new Error(`explain_dependency supports Maven only; for this Gradle build run \`gradle dependencyInsight --dependency ${coordinates}\`.`);
469
+ if (!coordinates || /[&|;<>$()]/.test(coordinates)) {
470
+ throw new Error('coordinates is required and may not contain shell metacharacters');
471
+ }
472
+ const mavenCmd = await this.resolveMavenCommand(projectPath);
473
+ const { stdout, stderr } = await execFileAsync(mavenCmd, ['-B', 'dependency:tree', `-Dincludes=${coordinates}`, '-Dverbose'], {
474
+ cwd: projectPath,
475
+ timeout: 120000,
476
+ shell: process.platform === 'win32',
477
+ maxBuffer: 10 * 1024 * 1024,
478
+ });
479
+ return [stdout, stderr].filter(value => value?.trim()).join('\n');
480
+ }
481
+ /**
482
+ * Download the -sources.jar of one artifact into the local repository (`mvn dependency:get`).
483
+ * Opt-in: it reaches the network. Returns Maven's error output on failure.
484
+ */
485
+ async downloadSources(projectPath, coordinates) {
486
+ return this.downloadArtifact(projectPath, coordinates, 'sources');
487
+ }
488
+ /** `mvn dependency:get` for one artifact (no transitives) into the local repository. Opt-in: it reaches the network. */
489
+ async downloadArtifact(projectPath, coordinates, classifier) {
490
+ const gav = `${coordinates.groupId}:${coordinates.artifactId}:${coordinates.version}`;
491
+ if (!/^[\w.\-]+:[\w.\-]+:[\w.\-+]+$/.test(gav))
492
+ return { ok: false, message: `Invalid coordinates: ${gav}` };
493
+ const mavenCmd = await this.resolveMavenCommand(projectPath);
494
+ const logger = Logger.get(projectPath);
495
+ logger.info(`[MAVEN] Downloading ${gav}${classifier ? `:${classifier}` : ''}`);
496
+ try {
497
+ await execFileAsync(mavenCmd, ['-B', '-q', 'dependency:get', `-Dartifact=${gav}:jar${classifier ? `:${classifier}` : ''}`, '-Dtransitive=false'], {
498
+ cwd: projectPath,
499
+ timeout: 120000,
500
+ shell: process.platform === 'win32',
501
+ maxBuffer: 10 * 1024 * 1024,
502
+ });
503
+ return { ok: true };
504
+ }
505
+ catch (error) {
506
+ const output = `${error?.stdout ?? ''}\n${error?.stderr ?? ''}`.split('\n').filter(line => /ERROR|Could not/.test(line)).slice(0, 3).join(' ').trim();
507
+ logger.info(`[MAVEN] Download failed for ${gav}: ${output || error?.message}`);
508
+ return { ok: false, message: output || String(error?.message ?? error) };
509
+ }
510
+ }
511
+ /**
512
+ * Gradle: an init script adds a task to every project that writes the resolved compile/runtime/test
513
+ * classpath files (lenient, so one unresolvable dependency does not lose the rest) to one file per project.
514
+ */
515
+ async getGradleClasspath(projectPath, onProgress) {
516
+ const logger = Logger.get(projectPath);
517
+ const gradleCmd = await this.resolveGradleCommand(projectPath);
518
+ const outputDir = path.join(getProjectCacheDir(projectPath), `gradle-cp-${process.pid}`);
519
+ await fs.remove(outputDir).catch(() => { });
520
+ await fs.ensureDir(outputDir);
521
+ const initScript = path.join(outputDir, 'java-inspector-init.gradle');
522
+ await fs.writeFile(initScript, GRADLE_INIT_SCRIPT, 'utf-8');
523
+ logger.info(`[GRADLE] Running: ${gradleCmd} javaInspectorClasspath`);
524
+ await onProgress?.(`Running Gradle: ${gradleCmd} (resolving classpath)...`, 5, 100);
525
+ const start = performance.now();
526
+ try {
527
+ await execFileAsync(gradleCmd, ['-q', '--console=plain', '--no-configuration-cache', '--init-script', initScript, `-DjavaInspector.out=${outputDir}`, 'javaInspectorClasspath'], {
528
+ cwd: projectPath,
529
+ timeout: 300000,
530
+ shell: process.platform === 'win32',
531
+ maxBuffer: 10 * 1024 * 1024,
532
+ });
533
+ const contents = await Promise.all((await fs.readdir(outputDir)).filter(name => name.endsWith('.txt')).map(name => fs.readFile(path.join(outputDir, name), 'utf-8')));
534
+ if (!contents.length)
535
+ throw new Error('Gradle did not produce classpath output (no Java projects?)');
536
+ const jars = [...new Set(contents.flatMap(content => content.split(/\r?\n/)).map(line => line.trim()).filter(line => line.endsWith('.jar')))];
537
+ const existing = [];
538
+ for (const jar of jars)
539
+ if (await fs.pathExists(jar))
540
+ existing.push(jar);
541
+ logger.info(`[GRADLE] Classpath of ${contents.length} project(s) resolved in ${((performance.now() - start) / 1000).toFixed(1)}s: ${existing.length} JARs.`);
542
+ return existing;
543
+ }
544
+ catch (error) {
545
+ const details = [error?.stdout, error?.stderr].filter(Boolean).join('\n').split('\n').filter(line => line.trim()).slice(0, 15).join('\n');
546
+ logger.error(`[GRADLE] Classpath resolution failed: ${error?.message}\n${details}`);
547
+ throw new Error(`Gradle command failed: ${String(error?.message ?? error).split('\n')[0]}${details ? `\n${details}` : ''}`);
548
+ }
549
+ finally {
550
+ await fs.remove(outputDir).catch(() => { });
551
+ }
552
+ }
553
+ /** GRADLE_CMD, then the project's wrapper (gradlew), then GRADLE_HOME/bin/gradle, then gradle on PATH. */
554
+ async resolveGradleCommand(projectPath) {
555
+ if (process.env.GRADLE_CMD) {
556
+ if (/[&|;<>$()]/.test(process.env.GRADLE_CMD))
557
+ throw new Error('Invalid GRADLE_CMD: Shell metacharacters are not allowed.');
558
+ return process.env.GRADLE_CMD;
559
+ }
560
+ const wrapper = path.join(projectPath, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew');
561
+ if (await fs.pathExists(wrapper))
562
+ return wrapper;
563
+ return process.env.GRADLE_HOME ? path.join(process.env.GRADLE_HOME, 'bin', 'gradle') : 'gradle';
564
+ }
565
+ /**
566
+ * A multi-module checkout whose modules depend on each other fails `dependency:build-classpath` on Maven 3
567
+ * until the sibling modules are installed ("Could not resolve dependencies ... demo:a:jar"). Recover by
568
+ * re-running with --fail-at-end (modules that resolve still write their file) and adding the external
569
+ * dependencies of the dependency tree (which only needs poms) that exist in the local repository.
570
+ */
571
+ async recoverReactorClasspath(projectPath, mavenCmd, outputFile, details) {
572
+ if (!/Could not resolve dependencies|was not found in|Could not find artifact/.test(details))
573
+ return null;
574
+ const logger = Logger.get(projectPath);
575
+ const reactorPoms = await this.reactorCoordinates(projectPath);
576
+ // Only an unresolved *reactor module* is recoverable; a missing external artifact (network or
577
+ // repository problem) must stay an error instead of becoming a silently incomplete classpath.
578
+ const unresolved = details.replace(/for project \S+/g, '');
579
+ if (![...reactorPoms].some(ga => unresolved.includes(`${ga}:`)))
580
+ return null;
581
+ logger.info('[MAVEN] Classpath resolution failed on a module dependency; retrying with --fail-at-end and dependency:tree (unbuilt sibling modules?)');
582
+ await execFileAsync(mavenCmd, ['-B', '-q', '-fae', 'dependency:build-classpath', `-Dmdep.outputFile=${outputFile}`], {
583
+ cwd: projectPath, timeout: 300000, shell: process.platform === 'win32', maxBuffer: 10 * 1024 * 1024,
584
+ }).catch(() => { });
585
+ let modules;
586
+ try {
587
+ modules = await this.runDependencyTree(projectPath, mavenCmd);
588
+ }
589
+ catch (error) {
590
+ logger.error(`[MAVEN] dependency:tree fallback failed: ${error instanceof Error ? error.message : String(error)}`);
591
+ return null;
592
+ }
593
+ const reactor = new Set(modules.map(module => module.module.split(':').slice(0, 2).join(':')));
594
+ const repository = path.resolve(process.env.MAVEN_REPO || path.join(os.homedir(), '.m2', 'repository'));
595
+ const jars = [];
596
+ let missing = 0;
597
+ for (const dep of modules.flatMap(module => module.dependencies)) {
598
+ if (reactor.has(`${dep.groupId}:${dep.artifactId}`) || (dep.type !== 'jar' && dep.type !== 'bundle' && dep.type !== 'test-jar'))
599
+ continue;
600
+ const classifier = dep.classifier ?? (dep.type === 'test-jar' ? 'tests' : undefined);
601
+ const jar = path.join(repository, ...dep.groupId.split('.'), dep.artifactId, dep.version, `${dep.artifactId}-${dep.version}${classifier ? `-${classifier}` : ''}.jar`);
602
+ if (await fs.pathExists(jar))
603
+ jars.push(jar);
604
+ else
605
+ missing++;
606
+ }
607
+ logger.info(`[MAVEN] Recovered ${jars.length} JAR(s) from the dependency tree of ${modules.length} module(s)${missing ? `; ${missing} not downloaded yet` : ''}. Reactor modules are skipped (their code is in the workspace).`);
608
+ if (missing)
609
+ this.partialClasspaths.add(projectPath);
610
+ else
611
+ this.partialClasspaths.delete(projectPath);
612
+ return jars;
613
+ }
614
+ /** groupId:artifactId of every module pom under the project (parent groupId when the module has none). */
615
+ async reactorCoordinates(projectPath) {
616
+ const result = new Set();
617
+ const visit = async (directory, depth) => {
618
+ const pom = await fs.readFile(path.join(directory, 'pom.xml'), 'utf-8').catch(() => null);
619
+ if (pom === null)
620
+ return;
621
+ const withoutParent = pom.replace(/<parent>[\s\S]*?<\/parent>/, '').replace(/<(dependencies|dependencyManagement|build|profiles|plugins)>[\s\S]*$/, '');
622
+ const parentGroup = pom.match(/<parent>[\s\S]*?<groupId>\s*([^<\s]+)\s*<\/groupId>/)?.[1];
623
+ const groupId = withoutParent.match(/<groupId>\s*([^<\s]+)\s*<\/groupId>/)?.[1] ?? parentGroup;
624
+ const artifactId = withoutParent.match(/<artifactId>\s*([^<\s]+)\s*<\/artifactId>/)?.[1];
625
+ if (groupId && artifactId)
626
+ result.add(`${groupId}:${artifactId}`);
627
+ if (depth >= 6)
628
+ return;
629
+ for (const module of pom.matchAll(/<module>\s*([^<]+?)\s*<\/module>/g))
630
+ await visit(path.resolve(directory, module[1]), depth + 1);
631
+ };
632
+ await visit(projectPath, 0);
633
+ return result;
634
+ }
635
+ async runDependencyTree(projectPath, mavenCmd) {
636
+ const outputDir = path.join(getProjectCacheDir(projectPath), `maven-tree-${process.pid}-${Date.now()}`);
637
+ await fs.ensureDir(outputDir);
638
+ const outputFile = path.join(outputDir, 'tree-${project.groupId}__${project.artifactId}.txt');
639
+ try {
640
+ try {
641
+ await execFileAsync(mavenCmd, ['-B', '-q', 'dependency:tree', `-DoutputFile=${outputFile}`, '-DoutputType=text'], {
642
+ cwd: projectPath, timeout: 300000, shell: process.platform === 'win32', maxBuffer: 10 * 1024 * 1024,
643
+ });
644
+ }
645
+ catch (error) {
646
+ const details = `${error?.stdout ?? ''}\n${error?.stderr ?? ''}`.split('\n').filter(line => /ERROR/.test(line)).slice(0, 5).join('\n');
647
+ throw new Error(`mvn dependency:tree failed: ${error?.message?.split('\n')[0] ?? error}${details ? `\n${details}` : ''}`);
648
+ }
649
+ const modules = [];
650
+ for (const name of (await fs.readdir(outputDir)).filter(file => file.endsWith('.txt')).sort()) {
651
+ const parsed = parseDependencyTree(await fs.readFile(path.join(outputDir, name), 'utf-8'));
652
+ if (parsed)
653
+ modules.push(parsed);
654
+ }
655
+ if (!modules.length)
656
+ throw new Error('Maven did not produce dependency:tree output');
657
+ return modules;
658
+ }
659
+ finally {
660
+ await fs.remove(outputDir).catch(() => { });
661
+ }
662
+ }
663
+ /**
664
+ * Resolved dependency tree of every reactor module (`mvn dependency:tree`, one output file per module).
665
+ * Cached per project until pom.xml or the resolved classpath changes.
666
+ */
667
+ async listDependencies(projectPath) {
668
+ if (await buildToolOf(projectPath) === 'gradle')
669
+ throw new Error('list_dependencies supports Maven only; for this Gradle build run `gradle dependencies`. Classes, sources and the other tools work for Gradle projects.');
670
+ const key = `${await projectCache.getPomHash(projectPath).catch(() => '')}:${projectCache.getClasspathHash((await projectCache.getClasspath(projectPath).catch(() => null)) ?? [])}`;
671
+ const cacheFile = path.join(getProjectCacheDir(projectPath), 'dependency-tree.json');
672
+ const cached = await fs.readJson(cacheFile).catch(() => null);
673
+ if (cached?.key === key && Array.isArray(cached.modules))
674
+ return { modules: cached.modules, cached: true };
675
+ const logger = Logger.get(projectPath);
676
+ const start = performance.now();
677
+ logger.info('[MAVEN] Running dependency:tree for list_dependencies');
678
+ const modules = await this.runDependencyTree(projectPath, await this.resolveMavenCommand(projectPath));
679
+ logger.info(`[MAVEN] Dependency tree of ${modules.length} module(s) in ${((performance.now() - start) / 1000).toFixed(1)}s`);
680
+ await fs.writeJson(cacheFile, { key, modules }).catch(() => { });
681
+ return { modules, cached: false };
682
+ }
683
+ async withClasspathResolutionSlot(task) {
684
+ if (this.activeClasspathResolutions >= 2) {
685
+ await new Promise(resolve => this.classpathResolutionQueue.push(resolve));
686
+ }
687
+ this.activeClasspathResolutions++;
688
+ try {
689
+ return await task();
690
+ }
691
+ finally {
692
+ this.activeClasspathResolutions--;
693
+ this.classpathResolutionQueue.shift()?.();
694
+ }
695
+ }
336
696
  /**
337
697
  * Resolve the Maven command to use.
338
698
  * Preference order: