dsh-ris-ide 1.8.4 → 1.8.5

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/lib/index.js CHANGED
@@ -402,6 +402,8 @@ const DEBUG_PATH = `${ROUTE_PREFIX}/debug`
402
402
  const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
403
403
  /** Pulls a dependency class's source out of its jar (sources → decompiler → javap). */
404
404
  const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
405
+ /** Reports whether the real sources of a dependency class were found or downloaded yet. */
406
+ const DEBUG_SOURCE_STATUS_PATH = `${ROUTE_PREFIX}/debug/source-status`
405
407
  /** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
406
408
  const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
407
409
  /**
@@ -1139,6 +1141,31 @@ function sameWorkspaceRows(left, right) {
1139
1141
  * @param ctx - Host context (`ctx.sessions.get(id)`, workspace registry).
1140
1142
  * @returns {{changed:number, windows:number, dropped:number}} how many entries were refreshed.
1141
1143
  */
1144
+ /** True while `path` names a directory that exists right now. */
1145
+ function isExistingDirectory(path) {
1146
+ if (typeof path !== 'string' || path === '') return false
1147
+ try {
1148
+ return statSync(path).isDirectory()
1149
+ } catch {
1150
+ return false
1151
+ }
1152
+ }
1153
+
1154
+ /**
1155
+ * True while `pid` names a live process on this machine. `EPERM` means the process
1156
+ * belongs to someone else and is still running — only `ESRCH` proves it is gone.
1157
+ * @param pid - Candidate process id.
1158
+ */
1159
+ function isProcessAlive(pid) {
1160
+ if (!Number.isInteger(pid) || pid <= 0) return false
1161
+ try {
1162
+ process.kill(pid, 0)
1163
+ return true
1164
+ } catch (error) {
1165
+ return error !== null && typeof error === 'object' && error.code === 'EPERM'
1166
+ }
1167
+ }
1168
+
1142
1169
  export function refreshDshWindows(ctx) {
1143
1170
  const result = { changed: 0, windows: 0, dropped: 0 }
1144
1171
  try {
@@ -1189,7 +1216,27 @@ export function refreshDshWindows(ctx) {
1189
1216
  // NaN and used to fall through to the pruning branch, review C3-P2-5).
1190
1217
  const rawOwner = Number(row.ownerPid)
1191
1218
  const ownerPid = Number.isInteger(rawOwner) && rawOwner > 0 ? rawOwner : process.pid
1192
- if (ownerPid !== process.pid) { out.push(row); return out }
1219
+ // A workspace can be deleted while dsh still remembers a session on it (or after
1220
+ // it exited). The row is then unopenable, so it must go even though its owner
1221
+ // still looks alive — otherwise the daemon keeps advertising a workspace that
1222
+ // cannot load (m14800).
1223
+ if (!isExistingDirectory(row.cwd)) {
1224
+ dirty = true
1225
+ result.dropped += 1
1226
+ return out
1227
+ }
1228
+ if (ownerPid !== process.pid) {
1229
+ // A live peer prunes its own rows. An exited dsh can never do that, so its
1230
+ // rows would sit in the shared document until the daemon's 7-day retain TTL
1231
+ // and keep showing a workspace nobody serves (m14800).
1232
+ if (!isProcessAlive(ownerPid)) {
1233
+ dirty = true
1234
+ result.dropped += 1
1235
+ return out
1236
+ }
1237
+ out.push(row)
1238
+ return out
1239
+ }
1193
1240
  const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
1194
1241
  // An empty session id cannot be verified (legacy rows); keep it and let the
1195
1242
  // daemon's retain TTL retire it.
@@ -1267,7 +1314,11 @@ function publishDshInstance(now, origin) {
1267
1314
  try {
1268
1315
  const parsed = JSON.parse(readFileSync(join(dir, name), 'utf8'))
1269
1316
  const at = Date.parse(String(parsed?.at ?? ''))
1270
- if (Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS) continue
1317
+ const ownerPid = Number(parsed?.pid)
1318
+ const fresh = Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS
1319
+ // A useful candidate names a live process: a closed dsh leaves a file that the
1320
+ // 24h retain would otherwise keep on the daemon's probe list (m14800).
1321
+ if (fresh && isProcessAlive(ownerPid)) continue
1271
1322
  } catch { /* half-written: nobody can use it */ }
1272
1323
  try { rmSync(join(dir, name), { force: true }) } catch { /* best effort */ }
1273
1324
  }
@@ -1478,6 +1529,14 @@ function dispatchRequest(ctx, req, res, options) {
1478
1529
  serveSafely(res, () => serveDebugSource(ctx, req, res, options))
1479
1530
  return
1480
1531
  }
1532
+ if (pathname === DEBUG_SOURCE_STATUS_PATH) {
1533
+ if (method !== 'GET') {
1534
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1535
+ return
1536
+ }
1537
+ serveSafely(res, () => serveDebugSourceStatus(ctx, req, res, options))
1538
+ return
1539
+ }
1481
1540
  if (pathname === PROXY_PATH) {
1482
1541
  serveSafely(res, () => serveProxy(ctx, req, res, options))
1483
1542
  return
@@ -6267,16 +6326,80 @@ async function programClassPathJars(programDir) {
6267
6326
  return { file, jars }
6268
6327
  }
6269
6328
 
6329
+ /**
6330
+ * `target/cp.txt` files elsewhere in the workspace, newest first.
6331
+ *
6332
+ * `serveDebugSource` resolves a class through the log's OWN program; but a
6333
+ * workspace is a multi-module Maven reactor and only the modules that were
6334
+ * started through the IDE have `target/cp.txt`. For Ctrl/Cmd+click on a jar
6335
+ * class in any other module, any classpath file in the same workspace is a
6336
+ * good enough classpath — so fall back to these (cached; the walk skips
6337
+ * `node_modules`, `.git` and the IDE cache, and is bounded).
6338
+ * @param {string} cwd - workspace root.
6339
+ * @returns {Promise<string[]>} program directories that own a `target/cp.txt`.
6340
+ */
6341
+ const WORKSPACE_CLASS_PATH_CACHE = new Map()
6342
+
6343
+ async function workspaceClassPathDirs(cwd) {
6344
+ const cached = WORKSPACE_CLASS_PATH_CACHE.get(cwd)
6345
+ if (cached !== undefined) return cached
6346
+ const found = []
6347
+ const queue = [{ dir: cwd, depth: 0 }]
6348
+ let visited = 0
6349
+ while (queue.length > 0 && visited < 4000 && found.length < 12) {
6350
+ const item = queue.shift()
6351
+ visited += 1
6352
+ let entries
6353
+ try {
6354
+ entries = await readdir(item.dir, { withFileTypes: true })
6355
+ } catch {
6356
+ continue
6357
+ }
6358
+ const names = new Set(entries.map((entry) => entry.name))
6359
+ if (names.has('target') && item.depth > 0) {
6360
+ try {
6361
+ await stat(join(item.dir, 'target', 'cp.txt'))
6362
+ found.push(item.dir)
6363
+ } catch {
6364
+ void 0
6365
+ }
6366
+ }
6367
+ if (item.depth >= 5) continue
6368
+ for (const entry of entries) {
6369
+ if (!entry.isDirectory()) continue
6370
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.dsh-ris-ide' || entry.name === 'target' || entry.name === 'dist') continue
6371
+ queue.push({ dir: join(item.dir, entry.name), depth: item.depth + 1 })
6372
+ }
6373
+ }
6374
+ WORKSPACE_CLASS_PATH_CACHE.set(cwd, found)
6375
+ return found
6376
+ }
6377
+
6378
+ /**
6379
+ * className → declaring jar. Scanning every classpath jar costs one cached
6380
+ * central-directory read per jar, but a Ctrl/Cmd+click on a dependency class
6381
+ * that is NOT on the classpath (a JDK type, a typo) would otherwise repeat the
6382
+ * full scan on every jump — hence the memo keyed by the `cp.txt` fingerprint.
6383
+ * `null` caches a miss.
6384
+ */
6385
+ const CLASS_JAR_CACHE = new Map()
6386
+
6270
6387
  /** First classpath jar that owns `className`, plus the requested entry. */
6271
6388
  async function findClassJar(programDir, className) {
6272
6389
  const wanted = `${className.split('.').join('/')}.class`
6273
6390
  const { file, jars } = await programClassPathJars(programDir)
6391
+ const cacheKey = `${await fileFingerprint(file)}|${className}`
6392
+ const cached = CLASS_JAR_CACHE.get(cacheKey)
6393
+ if (cached !== undefined) return cached === null ? undefined : cached
6394
+ let found
6274
6395
  for (const jar of jars) {
6275
6396
  const entries = await readZipEntries(jar)
6276
6397
  const entry = entries.find((item) => item.name === wanted)
6277
- if (entry !== undefined) return { jar, entry, classPathFile: file }
6398
+ if (entry !== undefined) { found = { jar, entry, classPathFile: file }; break }
6278
6399
  }
6279
- return undefined
6400
+ if (CLASS_JAR_CACHE.size > 2000) CLASS_JAR_CACHE.clear()
6401
+ CLASS_JAR_CACHE.set(cacheKey, found === undefined ? null : found)
6402
+ return found
6280
6403
  }
6281
6404
 
6282
6405
  /** The sibling `-sources.jar` of a binary jar, when it exists. */
@@ -6431,25 +6554,51 @@ function entryFingerprint(entry) {
6431
6554
  return entry.name + '|' + entry.size + '|' + entry.crc
6432
6555
  }
6433
6556
 
6434
- /** Spawn one command, capture stdout/stderr and its exit code (never throws on spawn failure). */
6435
- function runCapture(command, args, cwd) {
6557
+ /**
6558
+ * Spawn one command, capture stdout/stderr and its exit code (never throws on
6559
+ * spawn failure). `timeoutMs` is the "don't spin forever" guard: a decompiler
6560
+ * jar or a `javap` that wedges used to leave `/debug/source` pending for the
6561
+ * lifetime of the dsh process, and the editor showed a spinner that never
6562
+ * ended. On timeout the child is killed with SIGKILL and
6563
+ * `{ ok: false, timedOut: true }` comes back.
6564
+ */
6565
+ function runCapture(command, args, cwd, timeoutMs) {
6436
6566
  return new Promise((resolvePromise) => {
6437
6567
  let settled = false
6568
+ let timer
6438
6569
  const finish = (value) => {
6439
6570
  if (settled) return
6440
6571
  settled = true
6572
+ if (timer !== undefined) clearTimeout(timer)
6441
6573
  resolvePromise(value)
6442
6574
  }
6443
- const child = spawn(command, args, { cwd: cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
6575
+ let child
6576
+ try {
6577
+ child = spawn(command, args, { cwd: cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
6578
+ } catch (error) {
6579
+ finish({ ok: false, error: error.message, stdout: '', stderr: '' })
6580
+ return
6581
+ }
6444
6582
  let stdout = ''
6445
6583
  let stderr = ''
6446
6584
  child.stdout?.on('data', (chunk) => { stdout += String(chunk) })
6447
6585
  child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
6448
6586
  child.on('error', (error) => finish({ ok: false, error: error.message, stdout, stderr }))
6449
6587
  child.on('close', (code) => finish({ ok: code === 0, code, stdout, stderr }))
6588
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
6589
+ timer = setTimeout(() => {
6590
+ try { child.kill('SIGKILL') } catch (error) { void error }
6591
+ finish({ ok: false, timedOut: true, stdout, stderr })
6592
+ }, timeoutMs)
6593
+ }
6450
6594
  })
6451
6595
  }
6452
6596
 
6597
+ /** How long the user's decompiler jar may run before it is killed. */
6598
+ const DECOMPILE_TIMEOUT_MS = 30 * 1000
6599
+ /** How long `javap` may run before it is killed. */
6600
+ const JAVAP_TIMEOUT_MS = 15 * 1000
6601
+
6453
6602
  /** The user's decompiler choice: `.dsh-ris-ide/settings.json` first, then `.dsh-ris-ide/config.json`. */
6454
6603
  async function readDecompilerConfig(cwd) {
6455
6604
  let settingsText = await readTextIfSmall(resolve(cwd, IDE_SETTINGS_FILENAME))
@@ -6494,7 +6643,7 @@ async function decompileClass(cwd, found, className, config) {
6494
6643
  const expanded = template.map(function (item) {
6495
6644
  return String(item).split('{classfile}').join(classFile).split('{class}').join(className)
6496
6645
  })
6497
- const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd)
6646
+ const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd, DECOMPILE_TIMEOUT_MS)
6498
6647
  if (!run.ok || run.stdout.trim() === '') return undefined
6499
6648
  return run.stdout
6500
6649
  })
@@ -6504,12 +6653,192 @@ async function decompileClass(cwd, found, className, config) {
6504
6653
  async function javapClass(cwd, found, className) {
6505
6654
  const key = ['javap', await fileFingerprint(found.jar), entryFingerprint(found.entry)].join('|')
6506
6655
  return cachedSource(cwd, 'javap', className, '.javap.txt', key, async function () {
6507
- const run = await runCapture('javap', ['-p', '-c', '-l', '-classpath', found.jar, className], cwd)
6656
+ const run = await runCapture('javap', ['-p', '-c', '-l', '-classpath', found.jar, className], cwd, JAVAP_TIMEOUT_MS)
6508
6657
  if (!run.ok || run.stdout.trim() === '') return undefined
6509
6658
  return run.stdout
6510
6659
  })
6511
6660
  }
6512
6661
 
6662
+ /** Artifact id from a jar filename (`spring-beans-6.2.7.jar` → `spring-beans`). */
6663
+ function artifactIdOfJar(jarPath) {
6664
+ const name = String(jarPath).split(/[\\/]/).pop() ?? ''
6665
+ return name.replace(/\.jar$/i, '').replace(/-[0-9][0-9A-Za-z.\-]*$/, '')
6666
+ }
6667
+
6668
+ /**
6669
+ * The real sources of one jar class, when the sibling `-sources.jar` is present.
6670
+ *
6671
+ * This is step 2 of the lookup order (workspace → `~/.m2` → `mvn`): the local Maven
6672
+ * repository usually already has the sources because nexus proxies the public ones.
6673
+ */
6674
+ async function cachedSourcesOf(cwd, className, found) {
6675
+ const sourcesJar = sourcesJarOf(found.jar)
6676
+ if (sourcesJar === undefined) return undefined
6677
+ const sourceName = `${className.split('.').join('/')}.java`
6678
+ const entries = await readZipEntries(sourcesJar)
6679
+ const entry = entries.find((item) => item.name === sourceName)
6680
+ if (entry === undefined) return undefined
6681
+ const key = ['sources', await fileFingerprint(sourcesJar), entryFingerprint(entry)].join('|')
6682
+ const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6683
+ return readZipEntry(sourcesJar, entry)
6684
+ })
6685
+ if (path === undefined) return undefined
6686
+ return { path: path, kind: 'sources', jar: sourcesJar }
6687
+ }
6688
+
6689
+ /** JDK homes we can inspect for a `lib/src.zip` (platform classes). */
6690
+ function javaHomeCandidates() {
6691
+ const homes = []
6692
+ const push = function (home) {
6693
+ if (typeof home !== 'string' || home === '' || homes.includes(home)) return
6694
+ homes.push(home)
6695
+ }
6696
+ if (typeof process.env.JAVA_HOME === 'string' && process.env.JAVA_HOME !== '') push(process.env.JAVA_HOME)
6697
+ const pathEnv = typeof process.env.PATH === 'string' ? process.env.PATH : ''
6698
+ const separator = process.platform === 'win32' ? ';' : ':'
6699
+ for (const dir of pathEnv.split(separator)) {
6700
+ const binary = join(dir, process.platform === 'win32' ? 'java.exe' : 'java')
6701
+ try {
6702
+ // <jdk>/bin/java → <jdk>
6703
+ push(dirname(dirname(realpathSync(binary))))
6704
+ } catch {
6705
+ void 0
6706
+ }
6707
+ }
6708
+ for (const base of ['/usr/lib/jvm', '/usr/java', '/opt/java']) {
6709
+ try {
6710
+ for (const name of readdirSync(base)) push(join(base, name))
6711
+ } catch {
6712
+ void 0
6713
+ }
6714
+ }
6715
+ return homes
6716
+ }
6717
+
6718
+ /** Every existing JDK `src.zip` we can find (first hit is normally the running JDK). */
6719
+ function jdkSourcesArchives() {
6720
+ const archives = []
6721
+ for (const home of javaHomeCandidates()) {
6722
+ const archive = join(home, 'lib', 'src.zip')
6723
+ if (existsSync(archive) && !archives.includes(archive)) archives.push(archive)
6724
+ }
6725
+ return archives
6726
+ }
6727
+
6728
+ /**
6729
+ * Platform ("JDK") classes are not in any `target/cp.txt` jar: `java.lang.*`,
6730
+ * `java.util.*`, `javax.*`… live in the JDK itself. Resolve them from the JDK
6731
+ * `src.zip` when present, else from `javap` (which reads the running module path,
6732
+ * so no classpath is needed). This is what makes Ctrl/Cmd+click work on, e.g.,
6733
+ * `java.lang.annotation.ElementType`.
6734
+ */
6735
+ async function resolveJdkSource(cwd, className) {
6736
+ const fileName = `${className.split('.').join('/')}.java`
6737
+ for (const archive of jdkSourcesArchives()) {
6738
+ try {
6739
+ const entries = await readZipEntries(archive)
6740
+ const entry = entries.find((item) => item.name === fileName || item.name.endsWith('/' + fileName))
6741
+ if (entry === undefined) continue
6742
+ const key = ['sources', 'jdk', await fileFingerprint(archive), entryFingerprint(entry)].join('|')
6743
+ const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6744
+ return readZipEntry(archive, entry)
6745
+ })
6746
+ if (path !== undefined) return { path: path, kind: 'sources', jar: archive }
6747
+ } catch {
6748
+ void 0
6749
+ }
6750
+ }
6751
+ const key = ['javap', 'jdk', className].join('|')
6752
+ const path = await cachedSource(cwd, 'javap', className, '.javap.txt', key, async function () {
6753
+ const run = await runCapture('javap', ['-p', '-c', '-l', className], cwd, JAVAP_TIMEOUT_MS)
6754
+ if (!run.ok || run.stdout.trim() === '') return undefined
6755
+ return run.stdout
6756
+ })
6757
+ if (path === undefined) return undefined
6758
+ return { path: path, kind: 'javap', jar: '' }
6759
+ }
6760
+
6761
+ /** How long `mvn dependency:sources` may run before it is killed. */
6762
+ const SOURCE_FETCH_TIMEOUT_MS = 120 * 1000
6763
+ /** jar path → `{status:'pending'|'ready'|'failed', startedAt, finishedAt, message, artifact}`. */
6764
+ const SOURCE_FETCH_JOBS = new Map()
6765
+
6766
+ /** Finished jobs are kept for ten minutes so the client can read the outcome. */
6767
+ function sourceJobOf(jarPath) {
6768
+ const job = SOURCE_FETCH_JOBS.get(jarPath)
6769
+ if (job === undefined) return undefined
6770
+ if (job.status !== 'pending' && Date.now() - (job.finishedAt ?? job.startedAt) > 10 * 60 * 1000) {
6771
+ SOURCE_FETCH_JOBS.delete(jarPath)
6772
+ return undefined
6773
+ }
6774
+ return job
6775
+ }
6776
+
6777
+ /** The nearest ancestor directory of `startDir` that holds a `pom.xml`. */
6778
+ function nearestPomDir(startDir) {
6779
+ let dir = startDir
6780
+ for (let depth = 0; depth < 8 && typeof dir === 'string' && dir !== ''; depth += 1) {
6781
+ if (existsSync(join(dir, 'pom.xml'))) return dir
6782
+ const parent = dirname(dir)
6783
+ if (parent === dir || parent === '') return ''
6784
+ dir = parent
6785
+ }
6786
+ return ''
6787
+ }
6788
+
6789
+ /**
6790
+ * Step 3: let Maven fetch the sources jar for one dependency.
6791
+ *
6792
+ * The workspace `pom.xml` points Maven at the internal nexus, which already proxies
6793
+ * the public repositories, so `dependency:sources` is the download mechanism — no
6794
+ * hard-coded remote URL. Runs in the background: `/debug/source` answers with the
6795
+ * decompiled text immediately and `/debug/source-status` reports when the real
6796
+ * sources arrive, so the editor never sits on a spinner.
6797
+ */
6798
+ function startSourceFetch(cwd, programDir, jarPath) {
6799
+ const running = sourceJobOf(jarPath)
6800
+ if (running !== undefined && running.status === 'pending') return running
6801
+ const artifact = artifactIdOfJar(jarPath)
6802
+ const job = { status: 'pending', startedAt: Date.now(), jar: jarPath, artifact }
6803
+ SOURCE_FETCH_JOBS.set(jarPath, job)
6804
+ // Maven needs the module's own POM so the sources jar matches the version this
6805
+ // build actually resolves (a transitive dependency's version may only live in
6806
+ // the parent's dependencyManagement). Walk up to the nearest pom, then the
6807
+ // workspace root; the version guard below still rejects a mismatched jar.
6808
+ const mvnDir = nearestPomDir(programDir) || (existsSync(join(cwd, 'pom.xml')) ? cwd : programDir)
6809
+ const mvn = process.platform === 'win32' ? 'mvn.cmd' : 'mvn'
6810
+ const args = ['-q', '-B', 'dependency:sources']
6811
+ if (artifact !== '') args.push(`-DincludeArtifactIds=${artifact}`)
6812
+ runCapture(mvn, args, mvnDir, SOURCE_FETCH_TIMEOUT_MS).then(function (run) {
6813
+ job.finishedAt = Date.now()
6814
+ if (sourcesJarOf(jarPath) !== undefined) {
6815
+ job.status = 'ready'
6816
+ return
6817
+ }
6818
+ job.status = 'failed'
6819
+ if (run.timedOut === true) job.message = 'mvn dependency:sources 超时(120s)'
6820
+ else if (typeof run.error === 'string' && run.error !== '') job.message = `无法运行 mvn:${run.error}`
6821
+ else job.message = 'mvn 没有下载到 sources.jar(仓库里可能没有该依赖的源码)'
6822
+ }).catch(function (error) {
6823
+ job.finishedAt = Date.now()
6824
+ job.status = 'failed'
6825
+ job.message = error instanceof Error ? error.message : String(error)
6826
+ })
6827
+ return job
6828
+ }
6829
+
6830
+ /** The jar that contains one class: the program's own classpath first, then the workspace. */
6831
+ async function findDependencyJar(cwd, programDir, className) {
6832
+ const own = await findClassJar(programDir, className)
6833
+ if (own !== undefined) return own
6834
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
6835
+ if (fallbackDir === programDir) continue
6836
+ const found = await findClassJar(fallbackDir, className)
6837
+ if (found !== undefined) return found
6838
+ }
6839
+ return undefined
6840
+ }
6841
+
6513
6842
  /**
6514
6843
  * Resolve one dependency class to a readable file: sources.jar → decompiler jar
6515
6844
  * → javap disassembly, all cached under the workspace.
@@ -6521,19 +6850,8 @@ async function javapClass(cwd, found, className) {
6521
6850
  export async function resolveDependencySource(cwd, programDir, className) {
6522
6851
  const found = await findClassJar(programDir, className)
6523
6852
  if (found === undefined) return undefined
6524
- const sourcesJar = sourcesJarOf(found.jar)
6525
- if (sourcesJar !== undefined) {
6526
- const sourceName = `${className.split('.').join('/')}.java`
6527
- const entries = await readZipEntries(sourcesJar)
6528
- const entry = entries.find((item) => item.name === sourceName)
6529
- if (entry !== undefined) {
6530
- const key = ['sources', await fileFingerprint(sourcesJar), entryFingerprint(entry)].join('|')
6531
- const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6532
- return readZipEntry(sourcesJar, entry)
6533
- })
6534
- if (path !== undefined) return { path: path, kind: 'sources', jar: sourcesJar }
6535
- }
6536
- }
6853
+ const sources = await cachedSourcesOf(cwd, className, found).catch(() => undefined)
6854
+ if (sources !== undefined) return sources
6537
6855
  const config = await readDecompilerConfig(cwd)
6538
6856
  if (config !== undefined && existsSync(config.jar)) {
6539
6857
  const decompiled = await decompileClass(cwd, found, className, config).catch(() => undefined)
@@ -6544,6 +6862,29 @@ export async function resolveDependencySource(cwd, programDir, className) {
6544
6862
  return undefined
6545
6863
  }
6546
6864
 
6865
+ /**
6866
+ * Resolve one class through several module directories (the log owner first,
6867
+ * then any other `target/cp.txt` in the workspace) and, when no jar has it,
6868
+ * through the JDK itself — platform classes such as
6869
+ * `java.lang.annotation.ElementType` are in no classpath jar at all (m05797).
6870
+ */
6871
+ async function resolveDependencySourceIn(cwd, dirs, className) {
6872
+ for (const dir of dirs) {
6873
+ const resolved = await resolveDependencySource(cwd, dir, className)
6874
+ if (resolved !== undefined) return resolved
6875
+ }
6876
+ return resolveJdkSource(cwd, className)
6877
+ }
6878
+
6879
+ /** The jar that carries `className` in any of `dirs` (null when none does). */
6880
+ async function findDependencyJarIn(dirs, className) {
6881
+ for (const dir of dirs) {
6882
+ const found = await findClassJar(dir, className)
6883
+ if (found !== undefined) return found
6884
+ }
6885
+ return undefined
6886
+ }
6887
+
6547
6888
  /**
6548
6889
  * GET `/dsh-ris-ide/debug/source?className=…&path=<program log>&sessionId=…`:
6549
6890
  * resolve a dependency class to a cached source file, so stepping into a jar
@@ -6558,17 +6899,101 @@ async function serveDebugSource(ctx, req, res, options) {
6558
6899
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6559
6900
  const className = (url.searchParams.get('className') ?? '').trim()
6560
6901
  if (className === '' || !CLASS_NAME_PATTERN.test(className)) throw new TailError('bad-request', 'className is required', 400)
6902
+ // `path` is optional: a class clicked in a module that was never started
6903
+ // through the IDE has no program log to name, so every `target/cp.txt` in the
6904
+ // workspace (and finally the JDK itself) is searched instead (m05797).
6561
6905
  const rawPath = url.searchParams.get('path') ?? ''
6562
- if (rawPath === '') throw new TailError('bad-request', 'path (the program log path) is required', 400)
6563
6906
  const rawDir = url.searchParams.get('dir') ?? ''
6564
6907
  const logsDir = resolvePath(cwd, rawDir !== '' ? rawDir : 'logs', true)
6565
- const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6566
- const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6567
- const program = programs.find((item) => item.logPath === logPath)
6568
- if (program === undefined) throw new TailError('unknown-program', `no program matched log ${rawPath}`, 404)
6569
- const resolved = await resolveDependencySource(cwd, program.dir, className)
6908
+ const dirs = []
6909
+ if (rawPath !== '') {
6910
+ const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6911
+ const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6912
+ const program = programs.find((item) => item.logPath === logPath)
6913
+ if (program !== undefined) dirs.push(program.dir)
6914
+ }
6915
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
6916
+ if (!dirs.includes(fallbackDir)) dirs.push(fallbackDir)
6917
+ }
6918
+ const resolved = await resolveDependencySourceIn(cwd, dirs, className)
6570
6919
  if (resolved === undefined) throw new TailError('no-source', `no source, decompiler or javap output for ${className}`, 404)
6571
- writeJson(res, 200, { ok: true, path: resolved.path, kind: resolved.kind, jar: resolved.jar, cacheDir: join(cwd, IDE_CACHE_DIR) })
6920
+ const payload = { ok: true, path: resolved.path, kind: resolved.kind, jar: resolved.jar, cacheDir: join(cwd, IDE_CACHE_DIR) }
6921
+ if (resolved.kind !== 'sources' && resolved.jar !== '') {
6922
+ // Step 2 missed (no `-sources.jar` in `~/.m2`): answer with the decompiled
6923
+ // text now and let Maven try to fetch the real sources in the background.
6924
+ const found = await findDependencyJarIn(dirs, className).catch(() => undefined)
6925
+ if (found !== undefined) {
6926
+ const classPathDir = typeof found.classPathFile === 'string' ? dirname(dirname(found.classPathFile)) : ''
6927
+ const job = startSourceFetch(cwd, classPathDir !== '' ? classPathDir : (dirs[0] ?? cwd), found.jar)
6928
+ payload.sourcePending = true
6929
+ payload.artifact = job.artifact
6930
+ payload.sourceStatus = job.status
6931
+ payload.sourceStatusPath = DEBUG_SOURCE_STATUS_PATH
6932
+ }
6933
+ }
6934
+ writeJson(res, 200, payload)
6935
+ } catch (error) {
6936
+ writeTailError(res, error)
6937
+ }
6938
+ }
6939
+
6940
+ /**
6941
+ * GET `/dsh-ris-ide/debug/source-status?className=…&path=<program log>&sessionId=…`:
6942
+ * tells the editor whether the real sources of a dependency class showed up (or
6943
+ * were downloaded by the background `mvn dependency:sources` job).
6944
+ */
6945
+ async function serveDebugSourceStatus(ctx, req, res, options) {
6946
+ try {
6947
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6948
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
6949
+ const sessionId = url.searchParams.get('sessionId') ?? ''
6950
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
6951
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6952
+ const className = (url.searchParams.get('className') ?? '').trim()
6953
+ if (className === '' || !CLASS_NAME_PATTERN.test(className)) throw new TailError('bad-request', 'className is required', 400)
6954
+ const rawPath = url.searchParams.get('path') ?? ''
6955
+ const rawDir = url.searchParams.get('dir') ?? ''
6956
+ const logsDir = resolvePath(cwd, rawDir !== '' ? rawDir : 'logs', true)
6957
+ const dirs = []
6958
+ if (rawPath !== '') {
6959
+ const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6960
+ const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6961
+ const program = programs.find((item) => item.logPath === logPath)
6962
+ if (program !== undefined) dirs.push(program.dir)
6963
+ }
6964
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
6965
+ if (!dirs.includes(fallbackDir)) dirs.push(fallbackDir)
6966
+ }
6967
+ const found = await findDependencyJarIn(dirs, className).catch(() => undefined)
6968
+ if (found === undefined) {
6969
+ // Platform classes come straight from the JDK — nothing to download.
6970
+ const jdk = await resolveJdkSource(cwd, className).catch(() => undefined)
6971
+ if (jdk !== undefined) {
6972
+ writeJson(res, 200, { ok: true, ready: true, path: jdk.path, kind: jdk.kind, jar: jdk.jar })
6973
+ return
6974
+ }
6975
+ writeJson(res, 200, { ok: true, ready: false, status: 'missing', message: `no classpath jar contains ${className}` })
6976
+ return
6977
+ }
6978
+ const sources = await cachedSourcesOf(cwd, className, found).catch(() => undefined)
6979
+ if (sources !== undefined) {
6980
+ const job = sourceJobOf(found.jar)
6981
+ if (job !== undefined) {
6982
+ job.status = 'ready'
6983
+ job.finishedAt = job.finishedAt ?? Date.now()
6984
+ }
6985
+ writeJson(res, 200, { ok: true, ready: true, path: sources.path, kind: 'sources', jar: sources.jar })
6986
+ return
6987
+ }
6988
+ const job = sourceJobOf(found.jar)
6989
+ writeJson(res, 200, {
6990
+ ok: true,
6991
+ ready: false,
6992
+ status: job === undefined ? 'idle' : job.status,
6993
+ message: job === undefined ? '' : (job.message ?? ''),
6994
+ artifact: artifactIdOfJar(found.jar),
6995
+ jar: found.jar,
6996
+ })
6572
6997
  } catch (error) {
6573
6998
  writeTailError(res, error)
6574
6999
  }
@@ -11064,6 +11489,10 @@ function renderLogs(value) {
11064
11489
  export const __test = {
11065
11490
  // P4 tests: pretend the plugin is attached to a daemon without booting one.
11066
11491
  setRisdBridge: (bridge) => { risdBridge = bridge },
11492
+ // The dependency pipeline: platform classes come from the JDK itself (m05797).
11493
+ resolveJdkSource,
11494
+ resolveDependencySourceIn,
11495
+ findDependencyJarIn,
11067
11496
  resolvePath,
11068
11497
  refreshDshWindows,
11069
11498
  rememberDshOrigin,
@@ -11229,6 +11658,7 @@ export const __test = {
11229
11658
  normalizeStringArray,
11230
11659
  DEBUG_PATH,
11231
11660
  DEBUG_SOURCE_PATH,
11661
+ DEBUG_SOURCE_STATUS_PATH,
11232
11662
  SETTINGS_PATH,
11233
11663
  IDE_CACHE_DIR,
11234
11664
  CACHE_MAX_BYTES,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-ris-ide",
3
- "version": "1.8.4",
3
+ "version": "1.8.5",
4
4
  "license": "MIT",
5
- "description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. · DSH 右侧栏本地开发面板:日志实时跟随、一键启停本地程序、Java 断点调试、文件树与编辑器、独立 IDE 窗口。",
5
+ "description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. \u00b7 DSH \u53f3\u4fa7\u680f\u672c\u5730\u5f00\u53d1\u9762\u677f\uff1a\u65e5\u5fd7\u5b9e\u65f6\u8ddf\u968f\u3001\u4e00\u952e\u542f\u505c\u672c\u5730\u7a0b\u5e8f\u3001Java \u65ad\u70b9\u8c03\u8bd5\u3001\u6587\u4ef6\u6811\u4e0e\u7f16\u8f91\u5668\u3001\u72ec\u7acb IDE \u7a97\u53e3\u3002",
6
6
  "keywords": [
7
7
  "dsh",
8
8
  "dsh-plugin",
@@ -107,6 +107,9 @@ test('a stale page offers a refresh and never reloads itself', () => {
107
107
  test('the stale-build bar carries a refresh button', () => {
108
108
  const source = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
109
109
  const notice = source.slice(source.indexOf('function showStaleBuildNotice'), source.indexOf('function watchClientBuild'))
110
+ // m06203: dsh端取消 —— the DSH page hosts this panel in its right sidebar, and the
111
+ // banner's only action is a full-page reload there, so it is standalone-only.
112
+ assert.match(notice, /if \(!inStandaloneIdeWindow\(\)\) return/)
110
113
  assert.match(notice, /textContent = '刷新'/)
111
114
  assert.match(notice, /location\.reload\(\)/, 'the reload happens only when the user clicks it')
112
115
  assert.match(notice, /staleNoticeDismissedFor = staleNoticeBuild/)