dsh-ris-ide 1.8.3 → 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
@@ -3969,9 +4028,11 @@ function describe(error) {
3969
4028
  /**
3970
4029
  * Resolve the URL "open in browser" should use for one program.
3971
4030
  *
3972
- * Two sources, in this order: the dev-server URL the program printed into its own
3973
- * log (webpack/vite always do), then dsh-ris-yds' injecting proxy — which is only
3974
- * used when that plugin answers, so ris-ide keeps working without it.
4031
+ * The dev-server URL the program printed into its own log (webpack/vite always do)
4032
+ * is the answer. dsh-ris-yds may then wrap it — but ONLY when the program is one of
4033
+ * the yds front-ends the workspace declares, and it is told which one (m00555);
4034
+ * otherwise the page opens directly (m00462). A missing/failing yds plugin never
4035
+ * blocks the button: ris-ide keeps working without it.
3975
4036
  */
3976
4037
  async function serveOpenTarget(ctx, req, res, options) {
3977
4038
  try {
@@ -3994,19 +4055,20 @@ async function serveOpenTarget(ctx, req, res, options) {
3994
4055
  })
3995
4056
  return
3996
4057
  }
3997
- // Preferred path for a yds project: yds starts its private debugging browser
3998
- // (extension preloaded, CDP on). The page there carries rdbga, so its requests
3999
- // reach the local backend; the old loopback proxy only rewrites the bundles.
4000
- const debug = await askYdsToWrap(req, cwd, devUrl, { mode: 'debug' })
4001
- if (debug !== null && debug.ok === true && debug.mode === 'debug') {
4002
- writeJson(res, 200, debug)
4003
- return
4004
- }
4005
- const wrapped = await askYdsToWrap(req, cwd, devUrl)
4006
- if (wrapped !== null) {
4007
- if (wrapped.ok === true) writeJson(res, 200, wrapped)
4008
- else writeJson(res, 200, { ok: false, code: wrapped.code ?? 'yds', message: wrapped.reason ?? 'dsh-ris-yds 无法代理这个地址' })
4009
- return
4058
+ // The 🌐 button opens the dev-server page the program printed. That page is
4059
+ // enough on its own; dsh-ris-yds is asked ONLY for a program that IS a yds
4060
+ // frontend, and it is told WHICH frontend: `yds.webConfig` declares one entry
4061
+ // per front-end project with its own port, and injecting another entry's rules
4062
+ // opens a page that talks to the wrong dev server (m00555). A plain npm app, a
4063
+ // spring program, or an unlisted frontend opens directly — no proxy, no
4064
+ // private browser (m00462), and a yds refusal is not an error.
4065
+ const frontend = program.kind === 'frontend' ? await ydsFrontendOf(req, cwd, program) : null
4066
+ if (frontend !== null) {
4067
+ const wrapped = await askYdsToWrap(req, cwd, devUrl, frontend)
4068
+ if (wrapped !== null && wrapped.ok === true && typeof wrapped.url === 'string') {
4069
+ writeJson(res, 200, { ...wrapped, source: 'yds' })
4070
+ return
4071
+ }
4010
4072
  }
4011
4073
  writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4012
4074
  } catch (error) {
@@ -4027,10 +4089,62 @@ async function findProgramById(cwd, logsDir, ref) {
4027
4089
  }
4028
4090
 
4029
4091
  /**
4030
- * Ask dsh-ris-yds to serve this URL through its injecting proxy.
4092
+ * The yds front-end project identity of one program, or null when it is not one.
4093
+ *
4094
+ * `yds.webConfig` is keyed by the front-end project's directory name, and the
4095
+ * program's own directory basename is that project. Asking the probe first keeps
4096
+ * the rule honest: a plain npm app, the backend module, or a frontend the
4097
+ * workspace never declared as a yds frontend must NOT be proxied at all.
4098
+ * @returns {Promise<{code: string, name: string, relDir: string}|null>}
4099
+ */
4100
+ async function ydsFrontendOf(req, cwd, program) {
4101
+ const dir = typeof program.dir === 'string' ? program.dir : ''
4102
+ if (dir === '') return null
4103
+ const code = basename(dir)
4104
+ if (code === '') return null
4105
+ const probe = await askYdsProbe(req, cwd)
4106
+ if (probe === null || probe.yds !== true) return null
4107
+ const frontends = Array.isArray(probe.frontends) ? probe.frontends : []
4108
+ if (frontends.indexOf(code) === -1) return null
4109
+ return {
4110
+ code,
4111
+ name: typeof program.name === 'string' && program.name !== '' ? program.name : code,
4112
+ relDir: typeof program.relDir === 'string' ? program.relDir : '',
4113
+ }
4114
+ }
4115
+
4116
+ /** One short JSON answer from a sibling plugin route, or null when it is not there. */
4117
+ async function askPluginJson(req, path, timeoutMs) {
4118
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4119
+ if (host === '') return null
4120
+ const controller = new AbortController()
4121
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
4122
+ try {
4123
+ const response = await fetch(`http://${host}${path}`, {
4124
+ headers: { accept: 'application/json' },
4125
+ signal: controller.signal,
4126
+ })
4127
+ if (response.status === 404) return null
4128
+ const parsed = await response.json().catch(() => null)
4129
+ return parsed === null || typeof parsed !== 'object' ? null : parsed
4130
+ } catch {
4131
+ return null
4132
+ } finally {
4133
+ clearTimeout(timer)
4134
+ }
4135
+ }
4136
+
4137
+ /** Ask dsh-ris-yds which front-ends this workspace declares (`null` = plugin absent). */
4138
+ async function askYdsProbe(req, cwd) {
4139
+ return askPluginJson(req, `/dsh-ris-yds/probe?workspace=${encodeURIComponent(cwd)}`, 5000)
4140
+ }
4141
+
4142
+ /**
4143
+ * Ask dsh-ris-yds to serve this URL through its injecting proxy for ONE frontend.
4144
+ * @param {object} frontend - `{code, name, relDir}` of the yds front-end program.
4031
4145
  * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4032
4146
  */
4033
- async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4147
+ async function askYdsToWrap(req, cwd, devUrl, frontend) {
4034
4148
  const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4035
4149
  if (host === '') return null
4036
4150
  const controller = new AbortController()
@@ -4039,7 +4153,7 @@ async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4039
4153
  const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4040
4154
  method: 'POST',
4041
4155
  headers: { 'content-type': 'application/json' },
4042
- body: JSON.stringify({ workspace: cwd, devUrl, ...(options.mode === 'debug' ? { mode: 'debug' } : {}) }),
4156
+ body: JSON.stringify({ workspace: cwd, devUrl, frontend }),
4043
4157
  signal: controller.signal,
4044
4158
  })
4045
4159
  if (response.status === 404) return null
@@ -6212,16 +6326,80 @@ async function programClassPathJars(programDir) {
6212
6326
  return { file, jars }
6213
6327
  }
6214
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
+
6215
6387
  /** First classpath jar that owns `className`, plus the requested entry. */
6216
6388
  async function findClassJar(programDir, className) {
6217
6389
  const wanted = `${className.split('.').join('/')}.class`
6218
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
6219
6395
  for (const jar of jars) {
6220
6396
  const entries = await readZipEntries(jar)
6221
6397
  const entry = entries.find((item) => item.name === wanted)
6222
- if (entry !== undefined) return { jar, entry, classPathFile: file }
6398
+ if (entry !== undefined) { found = { jar, entry, classPathFile: file }; break }
6223
6399
  }
6224
- 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
6225
6403
  }
6226
6404
 
6227
6405
  /** The sibling `-sources.jar` of a binary jar, when it exists. */
@@ -6376,25 +6554,51 @@ function entryFingerprint(entry) {
6376
6554
  return entry.name + '|' + entry.size + '|' + entry.crc
6377
6555
  }
6378
6556
 
6379
- /** Spawn one command, capture stdout/stderr and its exit code (never throws on spawn failure). */
6380
- 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) {
6381
6566
  return new Promise((resolvePromise) => {
6382
6567
  let settled = false
6568
+ let timer
6383
6569
  const finish = (value) => {
6384
6570
  if (settled) return
6385
6571
  settled = true
6572
+ if (timer !== undefined) clearTimeout(timer)
6386
6573
  resolvePromise(value)
6387
6574
  }
6388
- 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
+ }
6389
6582
  let stdout = ''
6390
6583
  let stderr = ''
6391
6584
  child.stdout?.on('data', (chunk) => { stdout += String(chunk) })
6392
6585
  child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
6393
6586
  child.on('error', (error) => finish({ ok: false, error: error.message, stdout, stderr }))
6394
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
+ }
6395
6594
  })
6396
6595
  }
6397
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
+
6398
6602
  /** The user's decompiler choice: `.dsh-ris-ide/settings.json` first, then `.dsh-ris-ide/config.json`. */
6399
6603
  async function readDecompilerConfig(cwd) {
6400
6604
  let settingsText = await readTextIfSmall(resolve(cwd, IDE_SETTINGS_FILENAME))
@@ -6439,7 +6643,7 @@ async function decompileClass(cwd, found, className, config) {
6439
6643
  const expanded = template.map(function (item) {
6440
6644
  return String(item).split('{classfile}').join(classFile).split('{class}').join(className)
6441
6645
  })
6442
- const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd)
6646
+ const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd, DECOMPILE_TIMEOUT_MS)
6443
6647
  if (!run.ok || run.stdout.trim() === '') return undefined
6444
6648
  return run.stdout
6445
6649
  })
@@ -6449,10 +6653,190 @@ async function decompileClass(cwd, found, className, config) {
6449
6653
  async function javapClass(cwd, found, className) {
6450
6654
  const key = ['javap', await fileFingerprint(found.jar), entryFingerprint(found.entry)].join('|')
6451
6655
  return cachedSource(cwd, 'javap', className, '.javap.txt', key, async function () {
6452
- 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)
6657
+ if (!run.ok || run.stdout.trim() === '') return undefined
6658
+ return run.stdout
6659
+ })
6660
+ }
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)
6453
6754
  if (!run.ok || run.stdout.trim() === '') return undefined
6454
6755
  return run.stdout
6455
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
6456
6840
  }
6457
6841
 
6458
6842
  /**
@@ -6466,19 +6850,8 @@ async function javapClass(cwd, found, className) {
6466
6850
  export async function resolveDependencySource(cwd, programDir, className) {
6467
6851
  const found = await findClassJar(programDir, className)
6468
6852
  if (found === undefined) return undefined
6469
- const sourcesJar = sourcesJarOf(found.jar)
6470
- if (sourcesJar !== undefined) {
6471
- const sourceName = `${className.split('.').join('/')}.java`
6472
- const entries = await readZipEntries(sourcesJar)
6473
- const entry = entries.find((item) => item.name === sourceName)
6474
- if (entry !== undefined) {
6475
- const key = ['sources', await fileFingerprint(sourcesJar), entryFingerprint(entry)].join('|')
6476
- const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6477
- return readZipEntry(sourcesJar, entry)
6478
- })
6479
- if (path !== undefined) return { path: path, kind: 'sources', jar: sourcesJar }
6480
- }
6481
- }
6853
+ const sources = await cachedSourcesOf(cwd, className, found).catch(() => undefined)
6854
+ if (sources !== undefined) return sources
6482
6855
  const config = await readDecompilerConfig(cwd)
6483
6856
  if (config !== undefined && existsSync(config.jar)) {
6484
6857
  const decompiled = await decompileClass(cwd, found, className, config).catch(() => undefined)
@@ -6489,6 +6862,29 @@ export async function resolveDependencySource(cwd, programDir, className) {
6489
6862
  return undefined
6490
6863
  }
6491
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
+
6492
6888
  /**
6493
6889
  * GET `/dsh-ris-ide/debug/source?className=…&path=<program log>&sessionId=…`:
6494
6890
  * resolve a dependency class to a cached source file, so stepping into a jar
@@ -6503,17 +6899,101 @@ async function serveDebugSource(ctx, req, res, options) {
6503
6899
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6504
6900
  const className = (url.searchParams.get('className') ?? '').trim()
6505
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).
6506
6905
  const rawPath = url.searchParams.get('path') ?? ''
6507
- if (rawPath === '') throw new TailError('bad-request', 'path (the program log path) is required', 400)
6508
6906
  const rawDir = url.searchParams.get('dir') ?? ''
6509
6907
  const logsDir = resolvePath(cwd, rawDir !== '' ? rawDir : 'logs', true)
6510
- const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6511
- const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6512
- const program = programs.find((item) => item.logPath === logPath)
6513
- if (program === undefined) throw new TailError('unknown-program', `no program matched log ${rawPath}`, 404)
6514
- 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)
6515
6919
  if (resolved === undefined) throw new TailError('no-source', `no source, decompiler or javap output for ${className}`, 404)
6516
- 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
+ })
6517
6997
  } catch (error) {
6518
6998
  writeTailError(res, error)
6519
6999
  }
@@ -11009,6 +11489,10 @@ function renderLogs(value) {
11009
11489
  export const __test = {
11010
11490
  // P4 tests: pretend the plugin is attached to a daemon without booting one.
11011
11491
  setRisdBridge: (bridge) => { risdBridge = bridge },
11492
+ // The dependency pipeline: platform classes come from the JDK itself (m05797).
11493
+ resolveJdkSource,
11494
+ resolveDependencySourceIn,
11495
+ findDependencyJarIn,
11012
11496
  resolvePath,
11013
11497
  refreshDshWindows,
11014
11498
  rememberDshOrigin,
@@ -11174,6 +11658,7 @@ export const __test = {
11174
11658
  normalizeStringArray,
11175
11659
  DEBUG_PATH,
11176
11660
  DEBUG_SOURCE_PATH,
11661
+ DEBUG_SOURCE_STATUS_PATH,
11177
11662
  SETTINGS_PATH,
11178
11663
  IDE_CACHE_DIR,
11179
11664
  CACHE_MAX_BYTES,