dsh-ris-ide 1.6.11 → 1.7.0

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
@@ -204,6 +204,16 @@ const CONFIG_PATH = `${ROUTE_PREFIX}/config`
204
204
  const OPENS_PATH = `${ROUTE_PREFIX}/opens`
205
205
  /** Workspace filename search that honours every git repo's .gitignore. */
206
206
  const SEARCH_PATH = `${ROUTE_PREFIX}/search`
207
+ /**
208
+ * Workspace CONTENT search: `git grep` inside every repo root under the cwd, with
209
+ * a plain filesystem walk when there is no git (or git is not installed).
210
+ */
211
+ const CONTENT_SEARCH_PATH = `${ROUTE_PREFIX}/search-content`
212
+ /**
213
+ * Run ONE Maven test (`-Dtest=<name>`) in one module and keep its console in
214
+ * memory, so the IDE can start it and poll without a fake terminal.
215
+ */
216
+ const RUN_TEST_PATH = `${ROUTE_PREFIX}/run-test`
207
217
  /** One directory level for the IDE tree: gitignore-filtered + compact chains folded. */
208
218
  const TREE_PATH = `${ROUTE_PREFIX}/tree`
209
219
  /** Deleted entries park here so the tree's Ctrl+Z can bring them back. */
@@ -505,6 +515,14 @@ function dispatchRequest(ctx, req, res, options) {
505
515
  serveSafely(res, () => serveStart(ctx, req, res, options))
506
516
  return
507
517
  }
518
+ if (pathname === RUN_TEST_PATH) {
519
+ if (method !== 'GET' && method !== 'POST') {
520
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET or POST only' })
521
+ return
522
+ }
523
+ serveSafely(res, () => (method === 'POST' ? serveRunTestStart(ctx, req, res, options) : serveRunTestStatus(ctx, req, res, options)))
524
+ return
525
+ }
508
526
  if (pathname === DEBUGS_PATH) {
509
527
  if (method !== 'GET') {
510
528
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -549,6 +567,14 @@ function dispatchRequest(ctx, req, res, options) {
549
567
  serveSafely(res, () => serveSearch(ctx, req, res, options))
550
568
  return
551
569
  }
570
+ if (pathname === CONTENT_SEARCH_PATH) {
571
+ if (method !== 'GET') {
572
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
573
+ return
574
+ }
575
+ serveSafely(res, () => serveContentSearch(ctx, req, res, options))
576
+ return
577
+ }
552
578
  if (pathname === OPENS_PATH) {
553
579
  if (method !== 'GET') {
554
580
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -598,8 +624,9 @@ function runGit(args, cwd, input) {
598
624
  child.on('close', (code) => {
599
625
  if (settled) return
600
626
  settled = true
601
- // `git check-ignore` exits 1 when nothing matched; that is a valid answer.
602
- if (code === 0 || (code === 1 && args[0] === 'check-ignore')) resolvePromise(stdout)
627
+ // `git check-ignore` exits 1 when nothing matched, and `git grep` exits 1
628
+ // when the pattern has no match; both are valid answers, not failures.
629
+ if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) resolvePromise(stdout)
603
630
  else rejectPromise(new Error(stderr || `git exited with ${code}`))
604
631
  })
605
632
  })
@@ -743,6 +770,182 @@ async function serveSearch(ctx, req, res, options) {
743
770
  }
744
771
  }
745
772
 
773
+ /** Content-search clamp: hits returned by one request (`limit`, default 300). */
774
+ const CONTENT_SEARCH_MAX_HITS = 1000
775
+ /** Content-search clamp: matches taken from one file (`perFile`, default 8). */
776
+ const CONTENT_SEARCH_MAX_PER_FILE = 50
777
+ /** Files the no-git fallback walks at most (bounded so a search can never hang). */
778
+ const CONTENT_SEARCH_FALLBACK_MAX_FILES = 2000
779
+ /** Files at least this large are skipped by the no-git fallback. */
780
+ const CONTENT_SEARCH_FALLBACK_MAX_BYTES = 1024 * 1024
781
+ /** Bytes inspected for a NUL byte when deciding whether a fallback file is binary. */
782
+ const CONTENT_SEARCH_BINARY_PROBE_BYTES = 8 * 1024
783
+
784
+ /**
785
+ * Whether `candidate` is `root` itself or lexically inside it. Used on the
786
+ * `path:line:text` records `git grep` prints, whose "path" is repo-relative:
787
+ * a `..` segment (or a quoted/odd name) must never produce a hit outside the
788
+ * repo root the search was scoped to.
789
+ * @param root - absolute repo root.
790
+ * @param candidate - absolute path to test.
791
+ * @returns `true` when the candidate stays inside the root.
792
+ */
793
+ function isContainedIn(root, candidate) {
794
+ const base = resolve(root)
795
+ const target = resolve(candidate)
796
+ return target === base || target.startsWith(base.endsWith(sep) ? base : `${base}${sep}`)
797
+ }
798
+
799
+ /**
800
+ * Parse one `git grep -n` stdout line (`<path>:<line>:<text>`) into a hit.
801
+ * Malformed lines and paths escaping the root are dropped, never thrown.
802
+ * @param root - absolute repo root the grep ran in.
803
+ * @param raw - one stdout line.
804
+ * @returns `{ path, line, text }`, or `undefined` when the line is not a hit.
805
+ */
806
+ function parseGitGrepLine(root, raw) {
807
+ if (typeof raw !== 'string' || raw === '') return undefined
808
+ // Non-greedy: the first `:<digits>:` pair separates path from line number, so
809
+ // a path that itself contains a colon still parses as long as it has no `:1:`.
810
+ const match = /^(.*?):(\d+):(.*)$/.exec(raw)
811
+ if (match === null) return undefined
812
+ const relativePath = match[1]
813
+ if (relativePath === '') return undefined
814
+ const absolutePath = resolve(root, relativePath)
815
+ if (!isContainedIn(root, absolutePath)) return undefined
816
+ const line = Number(match[2])
817
+ if (!Number.isSafeInteger(line) || line <= 0) return undefined
818
+ return { path: absolutePath, line, text: match[3].replace(/\r$/, '').trimEnd() }
819
+ }
820
+
821
+ /**
822
+ * Filesystem fallback for content search: no git repo, or no `git` binary. Walk
823
+ * the workspace ({@link listRawFiles}), read small files, and substring-match
824
+ * case-insensitively (`git grep` itself is case-sensitive unless `-i` is passed;
825
+ * this fallback deliberately leans the other way so it still finds things).
826
+ * @param cwd - workspace root.
827
+ * @param query - the search text (non-empty).
828
+ * @param limit - max hits returned.
829
+ * @param perFile - max hits taken from one file.
830
+ * @returns `{ hits, truncated, files }`.
831
+ */
832
+ async function searchContentRaw(cwd, query, limit, perFile) {
833
+ const needle = String(query).toLowerCase()
834
+ const hits = []
835
+ let files = 0
836
+ const all = await listRawFiles(cwd)
837
+ for (const path of all) {
838
+ if (files >= CONTENT_SEARCH_FALLBACK_MAX_FILES) return { hits, truncated: true, files }
839
+ files += 1
840
+ const info = await stat(path).catch(() => undefined)
841
+ if (info === undefined || !info.isFile()) continue
842
+ if (info.size >= CONTENT_SEARCH_FALLBACK_MAX_BYTES) continue
843
+ let bytes
844
+ try {
845
+ bytes = await readFile(path)
846
+ } catch {
847
+ continue // unreadable (permissions, a race with a delete): skip, never fail the search
848
+ }
849
+ if (bytes.subarray(0, CONTENT_SEARCH_BINARY_PROBE_BYTES).includes(0)) continue
850
+ const text = bytes.toString('utf8')
851
+ let lineNumber = 0
852
+ let perFileCount = 0
853
+ for (const line of text.split('\n')) {
854
+ lineNumber += 1
855
+ if (perFileCount >= perFile) break
856
+ const plain = line.replace(/\r$/, '')
857
+ if (plain.toLowerCase().indexOf(needle) === -1) continue
858
+ hits.push({ path, line: lineNumber, text: plain.trimEnd() })
859
+ perFileCount += 1
860
+ if (hits.length >= limit) return { hits, truncated: true, files }
861
+ }
862
+ }
863
+ return { hits, truncated: false, files }
864
+ }
865
+
866
+ /**
867
+ * Workspace CONTENT search (the IDE's "在文件中查找").
868
+ *
869
+ * One `git grep` per repo root under `cwd` — the only implementation that gets
870
+ * .gitignore, submodule and binary handling right, and it is fast (a repo-wide
871
+ * literal search is a few hundred ms). `-m <perFile>` caps matches per file and
872
+ * `-I` skips binaries; `-F` makes the pattern a fixed string (no regex
873
+ * compilation of user input, no `.`/`*` surprises).
874
+ * Without git (no repo anywhere, or no git binary) it falls back to walking
875
+ * files, which keeps the panel useful on a bare directory.
876
+ * @param cwd - workspace root.
877
+ * @param query - the literal text to look for (non-empty; validated by the route).
878
+ * @param limit - max hits returned (already clamped by the route).
879
+ * @param perFile - max hits per file (already clamped by the route).
880
+ * @returns `{ hits: [{path, line, text}], truncated, roots, files }`.
881
+ */
882
+ async function searchWorkspaceContent(cwd, query, limit, perFile) {
883
+ const needle = String(query ?? '')
884
+ const roots = await searchRoots(cwd)
885
+ if (needle === '') return { hits: [], truncated: false, roots, files: 0 }
886
+ if (roots.length === 0 || gitMissing) {
887
+ return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
888
+ }
889
+ const hits = []
890
+ const paths = new Set()
891
+ let truncated = false
892
+ for (const root of roots) {
893
+ let stdout
894
+ try {
895
+ stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle], root)
896
+ } catch {
897
+ // A root whose git call failed is not fatal (and git may have disappeared
898
+ // mid-search): fall back to the filesystem walk for the whole request.
899
+ if (gitMissing) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
900
+ continue
901
+ }
902
+ for (const raw of stdout.split('\n')) {
903
+ if (hits.length >= limit) {
904
+ truncated = true
905
+ break
906
+ }
907
+ const hit = parseGitGrepLine(root, raw)
908
+ if (hit === undefined) continue
909
+ hits.push(hit)
910
+ paths.add(hit.path)
911
+ }
912
+ if (hits.length >= limit) {
913
+ truncated = true
914
+ break
915
+ }
916
+ }
917
+ return { hits, truncated, roots, files: paths.size }
918
+ }
919
+
920
+ /**
921
+ * One content-search request. Query parameters: `sessionId` (required),
922
+ * `cwd`, `q` (required, non-empty), `limit` (default 300, clamped 1..1000) and
923
+ * `perFile` (default 8, clamped 1..50).
924
+ * @param ctx - Host context (session cwd lookup).
925
+ * @param req - Node request face.
926
+ * @param res - Node response face.
927
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
928
+ */
929
+ async function serveContentSearch(ctx, req, res, options) {
930
+ try {
931
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
932
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
933
+ const sessionId = url.searchParams.get('sessionId') ?? ''
934
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
935
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
936
+ const query = url.searchParams.get('q') ?? ''
937
+ if (query.trim() === '') throw new TailError('bad-request', 'q (the text to search for) is required', 400)
938
+ const rawLimit = Number(url.searchParams.get('limit') ?? '300')
939
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), CONTENT_SEARCH_MAX_HITS) : 300
940
+ const rawPerFile = Number(url.searchParams.get('perFile') ?? '8')
941
+ const perFile = Number.isFinite(rawPerFile) ? Math.min(Math.max(1, Math.floor(rawPerFile)), CONTENT_SEARCH_MAX_PER_FILE) : 8
942
+ const result = await searchWorkspaceContent(cwd, query, limit, perFile)
943
+ writeJson(res, 200, { ok: true, root: cwd, ...result })
944
+ } catch (error) {
945
+ writeTailError(res, error)
946
+ }
947
+ }
948
+
746
949
  /** Cache of one repo root's allowed file paths (gitignore-aware), 5s TTL. */
747
950
  const TREE_ALLOWED_CACHE = new Map()
748
951
  /** Repo listing caches invalidated in the last second (coalesces save storms). */
@@ -3635,13 +3838,19 @@ async function serveDebug(ctx, req, res, options) {
3635
3838
  }
3636
3839
 
3637
3840
  /**
3638
- * One request: start one discovered program. The body is
3639
- * `{ sessionId, id, cwd?, dir? }` — only the program id identifies what to run,
3640
- * and the host re-scans before composing the command.
3841
+ * One request: start (or restart) one discovered program. The body is
3842
+ * `{ sessionId, id, cwd?, dir?, restart? }` — only the program id identifies
3843
+ * what to run, and the host re-scans before composing the command.
3844
+ *
3845
+ * `restart: true` is the panel's "重启" button: stop whatever owns this program's
3846
+ * log first (with the SAME stop grace as `/stop`), then start it again and report
3847
+ * `restarted` so the caller knows a stop really happened. A program that is not
3848
+ * running is simply started (there is no pidfile to honour, and treating that as
3849
+ * a failed restart would make the button useless on a stopped row).
3641
3850
  * @param ctx - Host context (session cwd lookup).
3642
3851
  * @param req - Node request face (POST).
3643
3852
  * @param res - Node response face.
3644
- * @param options - `{ restrictToCwd }` (see {@link apply}).
3853
+ * @param options - `{ restrictToCwd, stopGraceMs }` (see {@link apply}).
3645
3854
  */
3646
3855
  async function serveStart(ctx, req, res, options) {
3647
3856
  try {
@@ -3659,6 +3868,15 @@ async function serveStart(ctx, req, res, options) {
3659
3868
  if (program === undefined) {
3660
3869
  throw new TailError('unknown-program', `no runnable program "${id}" was found under ${cwd}`, 404)
3661
3870
  }
3871
+ if (body.restart === true) {
3872
+ const wasRunning = program.running !== null && program.running !== undefined && program.running.alive === true
3873
+ if (wasRunning) await stopLogPath(program.logPath, options?.stopGraceMs)
3874
+ // A stale `running` row must not make startProgram answer `alreadyRunning`
3875
+ // for a process we just stopped (or never found).
3876
+ const started = await startProgram(cwd, logsDir, Object.assign({}, program, { running: null }), options)
3877
+ writeJson(res, 200, { ok: true, restarted: wasRunning, ...started })
3878
+ return
3879
+ }
3662
3880
  writeJson(res, 200, { ok: true, ...await startProgram(cwd, logsDir, program, options) })
3663
3881
  } catch (error) {
3664
3882
  writeTailError(res, error)
@@ -3841,6 +4059,314 @@ export async function stopLogPath(logPath, fallbackGraceMs) {
3841
4059
  return outcome
3842
4060
  }
3843
4061
 
4062
+ /** One captured run's console: keep the first 4 KiB (mvn's real error often comes
4063
+ * first) plus the LAST 400k characters (the failing test's stack trace). */
4064
+ const RUN_TEST_HEAD_CHARS = 4096
4065
+ const RUN_TEST_TAIL_CHARS = 400000
4066
+ /** A single-test run is killed (TERM, then KILL) after this long. */
4067
+ const RUN_TEST_TIMEOUT_MS = 900000
4068
+ /** Grace between SIGTERM and SIGKILL when a run times out. */
4069
+ const RUN_TEST_KILL_GRACE_MS = 2000
4070
+ /** In-memory run records kept; the oldest is dropped past this (see {@link rememberRunTest}). */
4071
+ const RUN_TEST_MAX_RECORDS = 10
4072
+ /** Characters allowed in a Maven profile id / `-Dtest` selector / one module segment. */
4073
+ const RUN_TEST_NAME_RE = /^[A-Za-z0-9_.\-$#]+$/
4074
+ /** id → run record (bounded, oldest dropped). */
4075
+ const RUN_TEST_RECORDS = new Map()
4076
+ /** Monotonic suffix so two runs in the same millisecond still get distinct ids. */
4077
+ let runTestSequence = 0
4078
+
4079
+ /** Allocate a short, unique, human-scannable run id. */
4080
+ function nextRunTestId() {
4081
+ runTestSequence += 1
4082
+ return `rt-${Date.now().toString(36)}-${runTestSequence.toString(36)}`
4083
+ }
4084
+
4085
+ /**
4086
+ * Validate one Maven module path: relative, `/`-separated segments of the same
4087
+ * safe charset. `..` is refused outright (containment is enforced again by
4088
+ * {@link resolvePath}), and `.` means "the cwd itself".
4089
+ * @param value - the request's `module`.
4090
+ * @returns the normalized relative module path.
4091
+ * @throws {TailError} `bad-request` when it is missing, absolute, or unsafe.
4092
+ */
4093
+ function validateRunTestModule(value) {
4094
+ if (typeof value !== 'string' || value.trim() === '') {
4095
+ throw new TailError('bad-request', 'module is required (a path relative to cwd)', 400)
4096
+ }
4097
+ const raw = value.trim()
4098
+ if (isAbsolute(raw)) {
4099
+ throw new TailError('bad-request', 'module must be a path relative to cwd, not an absolute path', 400)
4100
+ }
4101
+ const segments = raw.split('/').filter((segment) => segment !== '' && segment !== '.')
4102
+ if (segments.length === 0) return '.'
4103
+ for (const segment of segments) {
4104
+ if (segment === '..' || !RUN_TEST_NAME_RE.test(segment)) {
4105
+ throw new TailError('bad-request', `module segment "${segment}" is not a safe Maven module name`, 400)
4106
+ }
4107
+ }
4108
+ return segments.join('/')
4109
+ }
4110
+
4111
+ /**
4112
+ * Validate one `-Dtest` selector. `shell: false` already makes injection
4113
+ * impossible, but a stray `;`, space or `(` is a caller bug worth a clear 400.
4114
+ * @param value - the request's `test`.
4115
+ * @returns the selector.
4116
+ * @throws {TailError} `bad-request` when it is missing or unsafe.
4117
+ */
4118
+ function validateRunTestSelector(value) {
4119
+ if (typeof value !== 'string' || value === '' || !RUN_TEST_NAME_RE.test(value)) {
4120
+ throw new TailError('bad-request', 'test must match /^[A-Za-z0-9_.\\-$#]+$/ (a Maven -Dtest selector)', 400)
4121
+ }
4122
+ return value
4123
+ }
4124
+
4125
+ /**
4126
+ * The Maven profile for one run: `-Pdev` unless the caller named one.
4127
+ * @param body - the parsed request body.
4128
+ * @returns the validated profile id.
4129
+ * @throws {TailError} `bad-request` for a profile that is not a plain id.
4130
+ */
4131
+ function runTestProfile(body) {
4132
+ const raw = typeof body.profile === 'string' ? body.profile.trim() : ''
4133
+ if (raw === '') return 'dev'
4134
+ if (!RUN_TEST_NAME_RE.test(raw)) {
4135
+ throw new TailError('bad-request', 'profile must be a Maven profile id (letters, digits, _ . - $ #)', 400)
4136
+ }
4137
+ return raw
4138
+ }
4139
+
4140
+ /** `mvn` is a `.cmd` shim on Windows; `spawn` with `shell: false` needs that name. */
4141
+ function mavenExecutable() {
4142
+ return IS_WINDOWS ? 'mvn.cmd' : 'mvn'
4143
+ }
4144
+
4145
+ /**
4146
+ * Append one console chunk while BOTH ends stay bounded: the head is kept as
4147
+ * the first {@link RUN_TEST_HEAD_CHARS} characters, the tail as the last
4148
+ * {@link RUN_TEST_TAIL_CHARS}. `total` remembers how much was dropped.
4149
+ * @param record - the run record being filled.
4150
+ * @param chunk - a stdout/stderr chunk (Buffer or string).
4151
+ */
4152
+ function appendRunTestOutput(record, chunk) {
4153
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8')
4154
+ record.total += text.length
4155
+ if (record.head.length < RUN_TEST_HEAD_CHARS) {
4156
+ record.head += text.slice(0, RUN_TEST_HEAD_CHARS - record.head.length)
4157
+ }
4158
+ record.tail += text
4159
+ if (record.tail.length > RUN_TEST_TAIL_CHARS) {
4160
+ record.tail = record.tail.slice(record.tail.length - RUN_TEST_TAIL_CHARS)
4161
+ }
4162
+ }
4163
+
4164
+ /**
4165
+ * The console text handed back to the panel: whole output when it fits, and
4166
+ * `head + "…(省略 N 字符)…" + tail` when the caps had to bite.
4167
+ * @param record - the run record.
4168
+ * @returns the (possibly elided) console text.
4169
+ */
4170
+ function runTestOutput(record) {
4171
+ if (record.total <= RUN_TEST_HEAD_CHARS) return record.head
4172
+ if (record.total <= RUN_TEST_TAIL_CHARS) return record.tail
4173
+ const tailStart = record.total - record.tail.length
4174
+ if (tailStart <= RUN_TEST_HEAD_CHARS) return record.head.slice(0, tailStart) + record.tail
4175
+ const dropped = tailStart - record.head.length
4176
+ return `${record.head}…(省略 ${dropped} 字符)…${record.tail}`
4177
+ }
4178
+
4179
+ /**
4180
+ * Remember one run, dropping the oldest past {@link RUN_TEST_MAX_RECORDS}.
4181
+ * @param record - the record to store (its `id` is the key).
4182
+ */
4183
+ function rememberRunTest(record) {
4184
+ RUN_TEST_RECORDS.set(record.id, record)
4185
+ while (RUN_TEST_RECORDS.size > RUN_TEST_MAX_RECORDS) {
4186
+ const oldest = RUN_TEST_RECORDS.keys().next().value
4187
+ if (oldest === undefined) break
4188
+ RUN_TEST_RECORDS.delete(oldest)
4189
+ }
4190
+ }
4191
+
4192
+ /**
4193
+ * Finalize one run exactly once (the close handler and the timeout race for it).
4194
+ * @param record - the run record.
4195
+ * @param code - the child's exit code, when it exited normally.
4196
+ * @param status - `done` | `failed` | `timeout`.
4197
+ * @param extra - optional console text appended first (a spawn failure note).
4198
+ */
4199
+ function finishRunTest(record, code, status, extra) {
4200
+ if (record.status !== 'running') return
4201
+ if (record.timer !== null) {
4202
+ clearTimeout(record.timer)
4203
+ record.timer = null
4204
+ }
4205
+ if (typeof extra === 'string' && extra !== '') appendRunTestOutput(record, extra)
4206
+ record.status = status
4207
+ record.exitCode = Number.isInteger(code) ? code : null
4208
+ record.durationMs = Date.now() - record.startedAt
4209
+ }
4210
+
4211
+ /**
4212
+ * Kill a timed-out `mvn` and its children: on POSIX the group TERM→KILL (the
4213
+ * spawn was detached, so `mvn → java → surefire` share one pgid), on Windows
4214
+ * `taskkill /T`. Same escalation the service stop path uses.
4215
+ * @param record - the run record holding the child.
4216
+ */
4217
+ function killRunTestTree(record) {
4218
+ const child = record.child
4219
+ if (child === null || child === undefined) return
4220
+ if (IS_WINDOWS) {
4221
+ if (Number.isInteger(child.pid)) void taskkillTree(child.pid)
4222
+ return
4223
+ }
4224
+ const pgid = Number.isInteger(child.pid) ? child.pid : undefined
4225
+ const signal = (name) => {
4226
+ try {
4227
+ if (pgid !== undefined) process.kill(-pgid, name)
4228
+ else child.kill(name)
4229
+ } catch {
4230
+ // already gone
4231
+ }
4232
+ }
4233
+ signal('SIGTERM')
4234
+ record.killTimer = setTimeout(() => signal('SIGKILL'), RUN_TEST_KILL_GRACE_MS)
4235
+ record.killTimer.unref?.()
4236
+ }
4237
+
4238
+ /**
4239
+ * One POST: start `mvn -P<profile> -q -pl <module> test -Dtest=<test>` and answer
4240
+ * at once; the console is polled through {@link serveRunTestStatus}.
4241
+ *
4242
+ * `cwd` is the Maven reactor root (the directory holding the top `pom.xml`):
4243
+ * Maven resolves `-pl` relative to it, so a nested module such as
4244
+ * `ris-model/ris-model-biz` is addressed from the reactor root, not from itself.
4245
+ * @param ctx - Host context (session cwd lookup).
4246
+ * @param req - Node request face (POST).
4247
+ * @param res - Node response face.
4248
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
4249
+ */
4250
+ async function serveRunTestStart(ctx, req, res, options) {
4251
+ try {
4252
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
4253
+ const body = await readJsonBody(req)
4254
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
4255
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
4256
+ const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
4257
+ const module = validateRunTestModule(body.module)
4258
+ const test = validateRunTestSelector(body.test)
4259
+ const profile = runTestProfile(body)
4260
+ // The module has to be a real Maven module INSIDE the session cwd: strict
4261
+ // containment even when the plugin runs unrestricted, because this value
4262
+ // ends up in a spawn argument.
4263
+ const moduleDir = resolvePath(cwd, module, true)
4264
+ const pom = await stat(join(moduleDir, 'pom.xml')).catch(() => undefined)
4265
+ if (pom === undefined || !pom.isFile()) {
4266
+ throw new TailError('unknown-module', `no pom.xml under "${module}" (not a Maven module of ${cwd})`, 404)
4267
+ }
4268
+ const args = [`-P${profile}`, '-q', '-pl', module, 'test', `-Dtest=${test}`, '-DfailIfNoTests=false', '-DskipITs']
4269
+ const command = `mvn ${args.map((arg) => quoteShell(arg)).join(' ')}`
4270
+ const record = {
4271
+ id: nextRunTestId(),
4272
+ status: 'running',
4273
+ exitCode: null,
4274
+ startedAt: Date.now(),
4275
+ durationMs: 0,
4276
+ command,
4277
+ module,
4278
+ test,
4279
+ profile,
4280
+ child: null,
4281
+ timer: null,
4282
+ killTimer: null,
4283
+ head: '',
4284
+ tail: '',
4285
+ total: 0,
4286
+ }
4287
+ rememberRunTest(record)
4288
+ let child
4289
+ try {
4290
+ child = spawn(mavenExecutable(), args, {
4291
+ cwd,
4292
+ windowsHide: true,
4293
+ shell: false,
4294
+ stdio: ['ignore', 'pipe', 'pipe'],
4295
+ // POSIX: its own process group, so a timeout can stop the whole tree.
4296
+ detached: !IS_WINDOWS,
4297
+ })
4298
+ } catch (error) {
4299
+ const reason = error instanceof Error ? error.message : String(error)
4300
+ finishRunTest(record, null, 'failed', `\n[spawn failed] ${reason}\n`)
4301
+ writeJson(res, 200, { ok: true, id: record.id, command, startedAt: record.startedAt })
4302
+ return
4303
+ }
4304
+ record.child = child
4305
+ child.stdout?.on('data', (chunk) => appendRunTestOutput(record, chunk))
4306
+ // Interleaved on purpose: Maven writes errors and the test log to two
4307
+ // streams, and the user reads them as one console.
4308
+ child.stderr?.on('data', (chunk) => appendRunTestOutput(record, chunk))
4309
+ child.on('error', (error) => {
4310
+ const reason = isMissingExecutable(error)
4311
+ ? 'mvn not found on PATH (install Maven, or put mvn/mvn.cmd on the PATH the host was started with)'
4312
+ : (error instanceof Error ? error.message : String(error))
4313
+ finishRunTest(record, null, 'failed', `\n[spawn failed] ${reason}\n`)
4314
+ })
4315
+ child.on('close', (code) => {
4316
+ // The timeout path finalizes first; a late close must not rewrite it.
4317
+ if (record.status !== 'running') return
4318
+ finishRunTest(record, code, code === 0 ? 'done' : 'failed')
4319
+ })
4320
+ record.timer = setTimeout(() => {
4321
+ if (record.status !== 'running') return
4322
+ killRunTestTree(record)
4323
+ finishRunTest(record, child.exitCode, 'timeout')
4324
+ }, RUN_TEST_TIMEOUT_MS)
4325
+ record.timer.unref?.()
4326
+ writeJson(res, 200, { ok: true, id: record.id, command, startedAt: record.startedAt })
4327
+ } catch (error) {
4328
+ writeTailError(res, error)
4329
+ }
4330
+ }
4331
+
4332
+ /**
4333
+ * One GET: the state and (capped) console of one run. Query parameters
4334
+ * `sessionId`, `cwd`, `id`.
4335
+ * @param ctx - Host context (session cwd lookup).
4336
+ * @param req - Node request face (GET).
4337
+ * @param res - Node response face.
4338
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
4339
+ */
4340
+ async function serveRunTestStatus(ctx, req, res, options) {
4341
+ try {
4342
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
4343
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
4344
+ const sessionId = url.searchParams.get('sessionId') ?? ''
4345
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
4346
+ // Resolved only to validate the session (records are host-wide, keyed by id).
4347
+ resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
4348
+ const id = url.searchParams.get('id') ?? ''
4349
+ if (id === '') throw new TailError('bad-request', 'id is required', 400)
4350
+ const record = RUN_TEST_RECORDS.get(id)
4351
+ if (record === undefined) {
4352
+ throw new TailError('not-found', `no run-test record "${id}" (a host restart clears them, and only the last ${RUN_TEST_MAX_RECORDS} are kept)`, 404)
4353
+ }
4354
+ const running = record.status === 'running'
4355
+ writeJson(res, 200, {
4356
+ ok: true,
4357
+ id: record.id,
4358
+ status: record.status,
4359
+ exitCode: record.exitCode,
4360
+ output: runTestOutput(record),
4361
+ startedAt: record.startedAt,
4362
+ durationMs: running ? Date.now() - record.startedAt : record.durationMs,
4363
+ running,
4364
+ })
4365
+ } catch (error) {
4366
+ writeTailError(res, error)
4367
+ }
4368
+ }
4369
+
3844
4370
  /**
3845
4371
  * Scan one workspace root for runnable programs.
3846
4372
  *
@@ -5956,6 +6482,19 @@ export const __test = {
5956
6482
  LOG_ROTATE_BYTES,
5957
6483
  searchRoots,
5958
6484
  searchWorkspaceFiles,
6485
+ // git-grep CONTENT search (workspace fallback is a plain substring scan)
6486
+ CONTENT_SEARCH_PATH,
6487
+ searchWorkspaceContent,
6488
+ serveContentSearch,
6489
+ // one-module `mvn test` runner (poll the console through GET ?id=)
6490
+ RUN_TEST_PATH,
6491
+ serveRunTestStart,
6492
+ serveRunTestStatus,
6493
+ RUN_TEST_MAX_RECORDS,
6494
+ RUN_TEST_TIMEOUT_MS,
6495
+ RUN_TEST_HEAD_CHARS,
6496
+ RUN_TEST_TAIL_CHARS,
6497
+ runTestOutput,
5959
6498
  // gitignore-aware, compact-chain-folding tree level
5960
6499
  findGitRoot,
5961
6500
  repoAllowedPaths,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ris-ide",
3
- "version": "1.6.11",
3
+ "version": "1.7.0",
4
4
  "license": "MIT",
5
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 窗口。",
6
6
  "keywords": [