dsh-ris-ide 1.7.0 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/lib/client-codemirror.js +18 -0
- package/lib/client.js +1192 -123
- package/lib/index.js +1555 -52
- package/lib/standalone/window.html +89 -14
- package/package.json +1 -1
- package/skills/dsh-ris-ide-debug/SKILL.md +2 -2
- package/test/client-viewer.test.mjs +589 -33
- package/test/clipboard.test.mjs +254 -0
- package/test/host-search.test.mjs +125 -1
- package/test/host-tail.test.mjs +198 -21
- package/test/windows.test.mjs +198 -0
package/lib/index.js
CHANGED
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
*
|
|
51
51
|
* @module dsh-ris-ide
|
|
52
52
|
*/
|
|
53
|
-
import { appendFile, copyFile, cp, mkdir, open, readdir, readFile, rename, rm, stat, truncate, writeFile } from 'node:fs/promises'
|
|
53
|
+
import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
|
|
54
54
|
import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
55
55
|
import { watch } from 'node:fs'
|
|
56
56
|
import { createHash } from 'node:crypto'
|
|
@@ -168,6 +168,63 @@ const FS_IMPORT_PATH = `${ROUTE_PREFIX}/fs/import`
|
|
|
168
168
|
const FS_UPLOAD_PATH = `${ROUTE_PREFIX}/fs/upload`
|
|
169
169
|
/** Upload cap: generous for screenshots/zips, small enough to stream, not buffer. */
|
|
170
170
|
const FS_UPLOAD_MAX_BYTES = 128 * 1024 * 1024
|
|
171
|
+
/** Mirror a tree copy onto the SYSTEM clipboard, so the OS file manager can paste it. */
|
|
172
|
+
const CLIPBOARD_FILES_PATH = `${ROUTE_PREFIX}/clipboard/files`
|
|
173
|
+
/** One copy gesture; a folder of 1000 files is a mistake, not a clipboard write. */
|
|
174
|
+
const CLIPBOARD_MAX_ENTRIES = 200
|
|
175
|
+
/** Upper bound on the "one path per line" stdin payload the backends accept. */
|
|
176
|
+
const CLIPBOARD_MAX_PAYLOAD = 256 * 1024
|
|
177
|
+
/**
|
|
178
|
+
* `GET /dsh-ris-ide/windows` — which standalone IDE windows are alive.
|
|
179
|
+
*
|
|
180
|
+
* A page cannot enumerate other windows, so the host keeps the list: every IDE
|
|
181
|
+
* window's stream declares `window=1`, the connection IS the liveness (a closed
|
|
182
|
+
* window drops its stream, and a `dsh web` restart reconnects it a moment later).
|
|
183
|
+
* That is what lets the ⧉ button focus the window the user already has instead
|
|
184
|
+
* of stacking a second one, and what makes it find that window again after a
|
|
185
|
+
* restart without anyone announcing anything.
|
|
186
|
+
*/
|
|
187
|
+
const WINDOWS_PATH = `${ROUTE_PREFIX}/windows`
|
|
188
|
+
/** A window whose stream has been gone this long counts as closed. */
|
|
189
|
+
const IDE_WINDOW_GRACE_MS = 90 * 1000
|
|
190
|
+
/** Live IDE windows, keyed by workspace cwd (one IDE window per workspace). */
|
|
191
|
+
const IDE_WINDOWS = new Map()
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* ONE hidden folder for everything the IDE keeps inside a workspace
|
|
195
|
+
* (`<workspace>/.dsh-ris-ide/`): `trash/` for deletes the tree can undo,
|
|
196
|
+
* `cache/` for extracted sources, `stage/` for clipboard publish mirrors.
|
|
197
|
+
* Older builds wrote those as three sibling dot-folders; `ensureIdeStateDir()`
|
|
198
|
+
* folds such leftovers in the first time this workspace is touched.
|
|
199
|
+
*/
|
|
200
|
+
export const IDE_STATE_DIR = '.dsh-ris-ide'
|
|
201
|
+
/**
|
|
202
|
+
* Hidden staging area for a COPY publish (`<workspace>/.dsh-ris-ide/stage`).
|
|
203
|
+
*
|
|
204
|
+
* Explorer is free to interpret a cross-`\\wsl.localhost` paste as a MOVE: the
|
|
205
|
+
* files then leave the workspace even though the page published DROPEFFECT_COPY.
|
|
206
|
+
* Publishing a STAGED copy instead keeps the originals out of Explorer's hands —
|
|
207
|
+
* a plain file is hard-linked (O(1), same inode), a directory is copied under a
|
|
208
|
+
* size budget. `cut` still publishes the real paths: a cut IS a move.
|
|
209
|
+
*/
|
|
210
|
+
const CLIPBOARD_STAGE_DIR = `${IDE_STATE_DIR}/stage`
|
|
211
|
+
/** Directories are copied for real; this is the budget one copy gesture may spend. */
|
|
212
|
+
const CLIPBOARD_STAGE_MAX_BYTES = 64 * 1024 * 1024
|
|
213
|
+
/** How many recent staging batches survive (older ones are pruned on publish). */
|
|
214
|
+
const CLIPBOARD_STAGE_KEEP_BATCHES = 3
|
|
215
|
+
/** A batch older than this is pruned even when it is one of the recent few. */
|
|
216
|
+
const CLIPBOARD_STAGE_TTL_MS = 24 * 60 * 60 * 1000
|
|
217
|
+
/** Batch record: staged path -> original path, so a read can translate back. */
|
|
218
|
+
const CLIPBOARD_STAGE_MANIFEST = 'manifest.json'
|
|
219
|
+
/**
|
|
220
|
+
* Read the SYSTEM clipboard back (`GET /dsh-ris-ide/clipboard/read`).
|
|
221
|
+
*
|
|
222
|
+
* A page cannot do this either: in WSL a copy made in Explorer never reaches
|
|
223
|
+
* Chromium (WSLg does not bridge the Windows `CF_HDROP` flavour), so the paste
|
|
224
|
+
* event arrives with an EMPTY payload while the clipboard really holds files.
|
|
225
|
+
* Only the Host can look; the route is read-only and writes nothing.
|
|
226
|
+
*/
|
|
227
|
+
const CLIPBOARD_READ_PATH = `${ROUTE_PREFIX}/clipboard/read`
|
|
171
228
|
/**
|
|
172
229
|
* Lazily-built client chunks (see `tsdown.config.mjs`). Only these names are
|
|
173
230
|
* served; the file is read from beside this module on every request so a rebuilt
|
|
@@ -209,6 +266,25 @@ const SEARCH_PATH = `${ROUTE_PREFIX}/search`
|
|
|
209
266
|
* a plain filesystem walk when there is no git (or git is not installed).
|
|
210
267
|
*/
|
|
211
268
|
const CONTENT_SEARCH_PATH = `${ROUTE_PREFIX}/search-content`
|
|
269
|
+
/**
|
|
270
|
+
* Streaming twins of the two searches: ONE NDJSON response, one frame per page,
|
|
271
|
+
* so the dropdown paints the first matches while the other repo roots are still
|
|
272
|
+
* being listed. The non-streaming routes stay (compatibility + fallback when a
|
|
273
|
+
* browser lacks readable streams).
|
|
274
|
+
*/
|
|
275
|
+
const SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search/stream`
|
|
276
|
+
const CONTENT_SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search-content/stream`
|
|
277
|
+
/** Rows per streamed page when the client does not ask for a size. */
|
|
278
|
+
export const SEARCH_STREAM_PAGE_DEFAULT = 40
|
|
279
|
+
/** Largest page a client may ask for. */
|
|
280
|
+
export const SEARCH_STREAM_PAGE_MAX = 500
|
|
281
|
+
/**
|
|
282
|
+
* How many repo roots may run `git` at the same time. The roots are independent
|
|
283
|
+
* processes and this workspace has 32 of them: sequential `ls-files` measured
|
|
284
|
+
* 1.0 s, the same calls with all roots in flight 0.09 s — the wall clock is
|
|
285
|
+
* spawn latency, not file count, so running them together is the whole fix.
|
|
286
|
+
*/
|
|
287
|
+
export const SEARCH_STREAM_CONCURRENCY = 6
|
|
212
288
|
/**
|
|
213
289
|
* Run ONE Maven test (`-Dtest=<name>`) in one module and keep its console in
|
|
214
290
|
* memory, so the IDE can start it and poll without a fake terminal.
|
|
@@ -217,11 +293,11 @@ const RUN_TEST_PATH = `${ROUTE_PREFIX}/run-test`
|
|
|
217
293
|
/** One directory level for the IDE tree: gitignore-filtered + compact chains folded. */
|
|
218
294
|
const TREE_PATH = `${ROUTE_PREFIX}/tree`
|
|
219
295
|
/** Deleted entries park here so the tree's Ctrl+Z can bring them back. */
|
|
220
|
-
export const TREE_TRASH_DIR =
|
|
296
|
+
export const TREE_TRASH_DIR = `${IDE_STATE_DIR}/trash`
|
|
221
297
|
/** Path segments whose churn is never interesting to the file tree. */
|
|
222
298
|
const TREE_WATCH_IGNORED = new Set([
|
|
223
299
|
'node_modules', 'target', 'build', 'dist', 'out', 'coverage', '.git',
|
|
224
|
-
'logs', '.dsh', '.dsh-ris-ide
|
|
300
|
+
'logs', '.dsh', '.dsh-ris-ide', '.gradle', '.idea', '.mvn',
|
|
225
301
|
])
|
|
226
302
|
|
|
227
303
|
/**
|
|
@@ -241,12 +317,14 @@ const DEBUG_PATH = `${ROUTE_PREFIX}/debug`
|
|
|
241
317
|
const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
|
|
242
318
|
/** Pulls a dependency class's source out of its jar (sources → decompiler → javap). */
|
|
243
319
|
const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
|
|
244
|
-
/** Read/write the IDE-specific settings kept
|
|
320
|
+
/** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
|
|
245
321
|
const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
|
|
246
322
|
/** Workspace cache holding extracted sources / decompiled files. */
|
|
247
|
-
export const IDE_CACHE_DIR =
|
|
323
|
+
export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
|
|
248
324
|
/** Where the visual settings dialog persists the decompiler jar. */
|
|
249
|
-
const IDE_SETTINGS_FILENAME =
|
|
325
|
+
export const IDE_SETTINGS_FILENAME = `${IDE_STATE_DIR}/settings.json`
|
|
326
|
+
/** Older builds kept the settings beside the workspace root: read, never write. */
|
|
327
|
+
const LEGACY_SETTINGS_FILENAME = '.dsh-ris-ide.settings.json'
|
|
250
328
|
const CLASS_NAME_PATTERN = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/
|
|
251
329
|
const ZIP_EOCD_SIGNATURE = 0x06054b50
|
|
252
330
|
const ZIP_CENTRAL_SIGNATURE = 0x02014b50
|
|
@@ -254,8 +332,10 @@ const ZIP_LOCAL_SIGNATURE = 0x04034b50
|
|
|
254
332
|
const SOURCE_ENTRY_MAX_BYTES = 4 * 1024 * 1024
|
|
255
333
|
/** One JDWP session per program, shared by the routes, the tool and the workbench UI. */
|
|
256
334
|
const debugSessions = createDebugSessions()
|
|
257
|
-
/** The user-editable program config,
|
|
258
|
-
const CONFIG_FILENAME =
|
|
335
|
+
/** The user-editable program config, inside the workspace state folder. */
|
|
336
|
+
export const CONFIG_FILENAME = `${IDE_STATE_DIR}/config.json`
|
|
337
|
+
/** Older builds kept the config as a hidden file beside the root: read, never write. */
|
|
338
|
+
const LEGACY_CONFIG_FILENAME = '.dsh-ris-ide.json'
|
|
259
339
|
/** Header written into a generated config file (JSONC: `parseJsonc` tolerates it). */
|
|
260
340
|
const CONFIG_HEADER = `// dsh-ris-ide 程序配置(JSONC:允许注释与尾逗号)
|
|
261
341
|
//
|
|
@@ -316,6 +396,13 @@ const DEFAULT_STOP_GRACE_MS = 5000
|
|
|
316
396
|
const MAX_STOP_GRACE_MS = 60000
|
|
317
397
|
/** Cap on one JSON request body (the stop request carries two short strings). */
|
|
318
398
|
const MAX_BODY_BYTES = 64 * 1024
|
|
399
|
+
/**
|
|
400
|
+
* Cap on one `POST /fs/write` body: an editor save carries the WHOLE file, so the
|
|
401
|
+
* generic 64 KB JSON cap rejected every save of a file above ~64 KB ("request body
|
|
402
|
+
* too large"). Text edits are opened whole below `FS_MAX_TEXT_BYTES` (512 KB) and
|
|
403
|
+
* chunked above it, so 8 MB covers every editable document with room to spare.
|
|
404
|
+
*/
|
|
405
|
+
const FS_WRITE_MAX_BODY_BYTES = 8 * 1024 * 1024
|
|
319
406
|
|
|
320
407
|
/** One routable failure with a machine code and an HTTP status. */
|
|
321
408
|
export class TailError extends Error {
|
|
@@ -405,6 +492,14 @@ export function handleRequest(ctx, req, res, options) {
|
|
|
405
492
|
function dispatchRequest(ctx, req, res, options) {
|
|
406
493
|
const method = req.method ?? 'GET'
|
|
407
494
|
const pathname = requestPathname(req)
|
|
495
|
+
if (pathname === WINDOWS_PATH) {
|
|
496
|
+
if (method !== 'GET') {
|
|
497
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
serveSafely(res, () => serveWindows(ctx, req, res))
|
|
501
|
+
return
|
|
502
|
+
}
|
|
408
503
|
if (pathname === WINDOW_PAGE_PATH) {
|
|
409
504
|
if (method !== 'GET') {
|
|
410
505
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
@@ -470,6 +565,22 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
470
565
|
serveSafely(res, () => serveFsImport(ctx, req, res, options))
|
|
471
566
|
return
|
|
472
567
|
}
|
|
568
|
+
if (pathname === CLIPBOARD_FILES_PATH) {
|
|
569
|
+
if (method !== 'POST') {
|
|
570
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
|
|
571
|
+
return
|
|
572
|
+
}
|
|
573
|
+
serveSafely(res, () => serveClipboardFiles(ctx, req, res, options))
|
|
574
|
+
return
|
|
575
|
+
}
|
|
576
|
+
if (pathname === CLIPBOARD_READ_PATH) {
|
|
577
|
+
if (method !== 'GET') {
|
|
578
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
579
|
+
return
|
|
580
|
+
}
|
|
581
|
+
serveSafely(res, () => serveClipboardRead(ctx, req, res))
|
|
582
|
+
return
|
|
583
|
+
}
|
|
473
584
|
if (pathname === FS_READ_PATH || pathname === FS_WRITE_PATH || pathname === FS_FILE_PATH || pathname === FS_WINDOW_PATH) {
|
|
474
585
|
if (pathname !== FS_WRITE_PATH) {
|
|
475
586
|
if (method !== 'GET') {
|
|
@@ -575,6 +686,15 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
575
686
|
serveSafely(res, () => serveContentSearch(ctx, req, res, options))
|
|
576
687
|
return
|
|
577
688
|
}
|
|
689
|
+
if (pathname === SEARCH_STREAM_PATH || pathname === CONTENT_SEARCH_STREAM_PATH) {
|
|
690
|
+
if (method !== 'GET') {
|
|
691
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
692
|
+
return
|
|
693
|
+
}
|
|
694
|
+
// Not serveSafely: the handler streams and owns its own error frames.
|
|
695
|
+
void serveSearchStream(ctx, req, res, options, pathname === CONTENT_SEARCH_STREAM_PATH)
|
|
696
|
+
return
|
|
697
|
+
}
|
|
578
698
|
if (pathname === OPENS_PATH) {
|
|
579
699
|
if (method !== 'GET') {
|
|
580
700
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
@@ -722,7 +842,7 @@ async function searchWorkspaceFiles(cwd, query, limit) {
|
|
|
722
842
|
for (const root of roots) {
|
|
723
843
|
let listing
|
|
724
844
|
try {
|
|
725
|
-
listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
|
|
845
|
+
listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
|
|
726
846
|
} catch {
|
|
727
847
|
// git is absent/broken here: walk this root so filename search still answers.
|
|
728
848
|
const all = await listRawFiles(root)
|
|
@@ -892,7 +1012,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
|
|
|
892
1012
|
for (const root of roots) {
|
|
893
1013
|
let stdout
|
|
894
1014
|
try {
|
|
895
|
-
stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle], root)
|
|
1015
|
+
stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root)
|
|
896
1016
|
} catch {
|
|
897
1017
|
// A root whose git call failed is not fatal (and git may have disappeared
|
|
898
1018
|
// mid-search): fall back to the filesystem walk for the whole request.
|
|
@@ -946,6 +1066,355 @@ async function serveContentSearch(ctx, req, res, options) {
|
|
|
946
1066
|
}
|
|
947
1067
|
}
|
|
948
1068
|
|
|
1069
|
+
/**
|
|
1070
|
+
* Spawn one git command and hand its stdout to `onText` as it arrives — the
|
|
1071
|
+
* streaming twin of {@link runGit}. `git grep`/`git ls-files` exit 1 for "no
|
|
1072
|
+
* match", which is an answer, not a failure. A client that navigated away leaves
|
|
1073
|
+
* `stream.aborted` set: the child is killed and no more text is delivered.
|
|
1074
|
+
* @param args - git arguments.
|
|
1075
|
+
* @param cwd - working directory (one repo root).
|
|
1076
|
+
* @param onText - called with each stdout chunk.
|
|
1077
|
+
* @param stream - `{ aborted, children }` control object (see serveSearchStream).
|
|
1078
|
+
* @returns {Promise<void>} resolves when the child is gone.
|
|
1079
|
+
*/
|
|
1080
|
+
function streamGitStdout(args, cwd, onText, stream) {
|
|
1081
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1082
|
+
const child = spawn('git', args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
1083
|
+
if (stream !== undefined) stream.children.add(child)
|
|
1084
|
+
let stderr = ''
|
|
1085
|
+
let settled = false
|
|
1086
|
+
child.stdout?.setEncoding('utf8')
|
|
1087
|
+
child.stdout?.on('data', (chunk) => {
|
|
1088
|
+
if (stream !== undefined && stream.aborted === true) return
|
|
1089
|
+
onText(chunk)
|
|
1090
|
+
})
|
|
1091
|
+
child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
|
|
1092
|
+
const settle = (error) => {
|
|
1093
|
+
if (settled) return
|
|
1094
|
+
settled = true
|
|
1095
|
+
if (stream !== undefined) stream.children.delete(child)
|
|
1096
|
+
if (error === undefined) resolvePromise()
|
|
1097
|
+
else rejectPromise(error)
|
|
1098
|
+
}
|
|
1099
|
+
child.on('error', (error) => {
|
|
1100
|
+
if (isMissingExecutable(error)) gitMissing = true
|
|
1101
|
+
settle(error)
|
|
1102
|
+
})
|
|
1103
|
+
child.on('close', (code) => {
|
|
1104
|
+
// Killed on purpose (row budget spent / client gone) is an ANSWER, not an
|
|
1105
|
+
// error: treating it as one made every fallback walk the whole root again.
|
|
1106
|
+
if (child.killed === true) settle(undefined)
|
|
1107
|
+
else if (stream !== undefined && stream.aborted === true) settle(undefined)
|
|
1108
|
+
else if (code === 0 || code === 1) settle(undefined)
|
|
1109
|
+
else settle(new Error(stderr || `git exited with ${code}`))
|
|
1110
|
+
})
|
|
1111
|
+
})
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* SIGTERM every git child of one streamed search. Called when the row budget is
|
|
1116
|
+
* spent (nobody waits for the rest) and when the client disconnects.
|
|
1117
|
+
* @param stream - `{ children: Set<ChildProcess> }`, or undefined in unit tests.
|
|
1118
|
+
*/
|
|
1119
|
+
function killStreamChildren(stream) {
|
|
1120
|
+
if (stream === undefined || stream === null) return
|
|
1121
|
+
for (const child of stream.children) {
|
|
1122
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Emit streamed matches in ROOT ORDER while the roots are searched concurrently.
|
|
1128
|
+
*
|
|
1129
|
+
* The sequential search visits the workspace root first and then the child repos
|
|
1130
|
+
* alphabetically; buffering per root and only flushing the head root keeps that
|
|
1131
|
+
* ranking exactly, so pages never reshuffle the dropdown. A page leaves as soon
|
|
1132
|
+
* as `pageSize` rows of the emitting root are buffered — the first page therefore
|
|
1133
|
+
* arrives after the fastest root instead of after the slowest.
|
|
1134
|
+
*
|
|
1135
|
+
* `maxItems` (the caller's `limit`) is counted on the EMITTED order, not on the
|
|
1136
|
+
* arrival order: roots answer concurrently, so a root late in the ranking must
|
|
1137
|
+
* not steal the budget from an earlier one. Hitting it closes the emitter and
|
|
1138
|
+
* fires `onFull` (the caller kills the git children there).
|
|
1139
|
+
* @param rootCount - number of roots (one buffer each).
|
|
1140
|
+
* @param pageSize - rows per emitted page.
|
|
1141
|
+
* @param emit - receives one page (non-empty array).
|
|
1142
|
+
* @param [options] - `{ maxItems, onFull }`.
|
|
1143
|
+
* @returns `{ push, finish, close, isClosed, isFull, total }`.
|
|
1144
|
+
*/
|
|
1145
|
+
function createOrderedPages(rootCount, pageSize, emit, options = {}) {
|
|
1146
|
+
const maxItems = Number.isFinite(options.maxItems) && options.maxItems > 0 ? options.maxItems : Infinity
|
|
1147
|
+
const onFull = typeof options.onFull === 'function' ? options.onFull : () => {}
|
|
1148
|
+
const buffers = []
|
|
1149
|
+
const finished = []
|
|
1150
|
+
for (let index = 0; index < rootCount; index += 1) { buffers.push([]); finished.push(false) }
|
|
1151
|
+
let head = 0
|
|
1152
|
+
let total = 0
|
|
1153
|
+
let full = false
|
|
1154
|
+
let closed = false
|
|
1155
|
+
/** Deliver `items` as pages, never more than the remaining budget. */
|
|
1156
|
+
function deliver(items) {
|
|
1157
|
+
let offset = 0
|
|
1158
|
+
while (offset < items.length && full !== true) {
|
|
1159
|
+
const take = Math.min(pageSize, items.length - offset, maxItems - total)
|
|
1160
|
+
if (take <= 0) break
|
|
1161
|
+
const page = items.slice(offset, offset + take)
|
|
1162
|
+
offset += take
|
|
1163
|
+
total += take
|
|
1164
|
+
emit(page)
|
|
1165
|
+
if (total >= maxItems) full = true
|
|
1166
|
+
}
|
|
1167
|
+
if (full === true && closed !== true) {
|
|
1168
|
+
closed = true
|
|
1169
|
+
onFull()
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function flush() {
|
|
1173
|
+
while (!closed && head < rootCount) {
|
|
1174
|
+
const buffer = buffers[head]
|
|
1175
|
+
while (buffer.length >= pageSize) deliver(buffer.splice(0, pageSize))
|
|
1176
|
+
if (finished[head] !== true) return
|
|
1177
|
+
if (buffer.length > 0) deliver(buffer.splice(0, buffer.length))
|
|
1178
|
+
head += 1
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return {
|
|
1182
|
+
push(index, items) {
|
|
1183
|
+
if (closed) return
|
|
1184
|
+
const buffer = buffers[index]
|
|
1185
|
+
for (const item of items) buffer.push(item)
|
|
1186
|
+
flush()
|
|
1187
|
+
},
|
|
1188
|
+
finish(index) {
|
|
1189
|
+
if (closed) return
|
|
1190
|
+
finished[index] = true
|
|
1191
|
+
flush()
|
|
1192
|
+
},
|
|
1193
|
+
close() {
|
|
1194
|
+
if (closed) return
|
|
1195
|
+
// Abort path: flush what was already accepted (in root order) so a caller
|
|
1196
|
+
// that closed early still sees the rows it asked for, then stop.
|
|
1197
|
+
for (let index = head; index < rootCount; index += 1) {
|
|
1198
|
+
const buffer = buffers[index]
|
|
1199
|
+
while (buffer.length > 0 && full !== true) deliver(buffer.splice(0, Math.min(pageSize, buffer.length)))
|
|
1200
|
+
}
|
|
1201
|
+
closed = true
|
|
1202
|
+
},
|
|
1203
|
+
isClosed() { return closed },
|
|
1204
|
+
isFull() { return full },
|
|
1205
|
+
total() { return total },
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* Run `worker(root, index)` for every root with at most `concurrency` in flight.
|
|
1211
|
+
* A worker must handle its own errors — one broken repo must not cancel the rest.
|
|
1212
|
+
* @param roots - repo roots.
|
|
1213
|
+
* @param concurrency - maximum simultaneous workers.
|
|
1214
|
+
* @param worker - async `(root, index)`.
|
|
1215
|
+
* @returns {Promise<void>} resolves when every root was visited.
|
|
1216
|
+
*/
|
|
1217
|
+
async function forEachRootInParallel(roots, concurrency, worker) {
|
|
1218
|
+
let next = 0
|
|
1219
|
+
async function lane() {
|
|
1220
|
+
while (next < roots.length) {
|
|
1221
|
+
const index = next
|
|
1222
|
+
next += 1
|
|
1223
|
+
await worker(roots[index], index)
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
const lanes = []
|
|
1227
|
+
const width = Math.max(1, Math.min(concurrency, roots.length))
|
|
1228
|
+
for (let index = 0; index < width; index += 1) lanes.push(lane())
|
|
1229
|
+
await Promise.all(lanes)
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* Streaming filename search: the same matches, ignore rules and ordering as
|
|
1234
|
+
* {@link searchWorkspaceFiles}, delivered page by page while the roots are
|
|
1235
|
+
* listed in parallel.
|
|
1236
|
+
* @param cwd - workspace root (only for the no-git fallback).
|
|
1237
|
+
* @param roots - repo roots from {@link searchRoots}.
|
|
1238
|
+
* @param query - case-insensitive substring of the path or basename.
|
|
1239
|
+
* @param options - `{ limit, pageSize, onPage, stream }`.
|
|
1240
|
+
* @returns `{ files, count, truncated }` when the walk is complete.
|
|
1241
|
+
*/
|
|
1242
|
+
async function searchWorkspaceFilesStream(cwd, roots, query, options) {
|
|
1243
|
+
const { limit, pageSize, onPage, stream } = options
|
|
1244
|
+
const needle = String(query ?? '').toLowerCase()
|
|
1245
|
+
let files = 0
|
|
1246
|
+
let truncated = false
|
|
1247
|
+
// The `limit` is counted on the EMITTED (root-ordered) rows: see createOrderedPages.
|
|
1248
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1249
|
+
maxItems: limit,
|
|
1250
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1251
|
+
})
|
|
1252
|
+
const take = (index, path) => {
|
|
1253
|
+
files += 1
|
|
1254
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
|
|
1255
|
+
emitter.push(index, [path])
|
|
1256
|
+
}
|
|
1257
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1258
|
+
// No repo anywhere (or no git binary): walk and page the fallback listing.
|
|
1259
|
+
const all = await listRawFiles(cwd)
|
|
1260
|
+
const matches = []
|
|
1261
|
+
for (const path of all) {
|
|
1262
|
+
files += 1
|
|
1263
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) continue
|
|
1264
|
+
matches.push(path)
|
|
1265
|
+
if (matches.length >= limit) { truncated = true; break }
|
|
1266
|
+
}
|
|
1267
|
+
for (let offset = 0; offset < matches.length; offset += pageSize) onPage(matches.slice(offset, offset + pageSize))
|
|
1268
|
+
return { files, count: matches.length, truncated }
|
|
1269
|
+
}
|
|
1270
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1271
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1272
|
+
let rest = ''
|
|
1273
|
+
const consume = (relativePath) => {
|
|
1274
|
+
if (relativePath === '' || emitter.isClosed()) return
|
|
1275
|
+
take(index, join(root, relativePath))
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
await streamGitStdout(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root, (chunk) => {
|
|
1279
|
+
const parts = `${rest}${chunk}`.split('\0')
|
|
1280
|
+
rest = parts.pop() ?? ''
|
|
1281
|
+
for (const relativePath of parts) consume(relativePath)
|
|
1282
|
+
}, stream)
|
|
1283
|
+
} catch {
|
|
1284
|
+
// git disappeared mid-search: walking this root keeps the answer usable.
|
|
1285
|
+
const all = await listRawFiles(root)
|
|
1286
|
+
for (const path of all) {
|
|
1287
|
+
if (emitter.isClosed()) break
|
|
1288
|
+
take(index, path)
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
consume(rest)
|
|
1292
|
+
emitter.finish(index)
|
|
1293
|
+
})
|
|
1294
|
+
return { files, count: emitter.total(), truncated }
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/**
|
|
1298
|
+
* Streaming content search: one `git grep` per repo root, run in parallel, with
|
|
1299
|
+
* the same literal matching / per-file cap / ordering as
|
|
1300
|
+
* {@link searchWorkspaceContent}.
|
|
1301
|
+
* @param cwd - workspace root (fallback walk).
|
|
1302
|
+
* @param roots - repo roots.
|
|
1303
|
+
* @param query - literal text.
|
|
1304
|
+
* @param options - `{ limit, perFile, pageSize, onPage, stream }`.
|
|
1305
|
+
* @returns `{ files, count, truncated }` when every root answered.
|
|
1306
|
+
*/
|
|
1307
|
+
async function searchWorkspaceContentStream(cwd, roots, query, options) {
|
|
1308
|
+
const { limit, perFile, pageSize, onPage, stream } = options
|
|
1309
|
+
const needle = String(query ?? '')
|
|
1310
|
+
const paths = new Set()
|
|
1311
|
+
let truncated = false
|
|
1312
|
+
// Same rule as the filename search: the limit applies to the emitted root order.
|
|
1313
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1314
|
+
maxItems: limit,
|
|
1315
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1316
|
+
})
|
|
1317
|
+
const take = (index, hit) => {
|
|
1318
|
+
paths.add(hit.path)
|
|
1319
|
+
emitter.push(index, [hit])
|
|
1320
|
+
}
|
|
1321
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1322
|
+
const fallback = await searchContentRaw(cwd, needle, limit, perFile)
|
|
1323
|
+
const hits = fallback.hits
|
|
1324
|
+
for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
|
|
1325
|
+
return { files: fallback.files, count: hits.length, truncated: fallback.truncated }
|
|
1326
|
+
}
|
|
1327
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1328
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1329
|
+
let rest = ''
|
|
1330
|
+
const consume = (raw) => {
|
|
1331
|
+
if (raw === '' || emitter.isClosed()) return
|
|
1332
|
+
const hit = parseGitGrepLine(root, raw)
|
|
1333
|
+
if (hit !== undefined) take(index, hit)
|
|
1334
|
+
}
|
|
1335
|
+
try {
|
|
1336
|
+
await streamGitStdout(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root, (chunk) => {
|
|
1337
|
+
const lines = `${rest}${chunk}`.split('\n')
|
|
1338
|
+
rest = lines.pop() ?? ''
|
|
1339
|
+
for (const raw of lines) consume(raw)
|
|
1340
|
+
}, stream)
|
|
1341
|
+
} catch {
|
|
1342
|
+
// A failing root is skipped, never fatal (same rule as the batch search).
|
|
1343
|
+
}
|
|
1344
|
+
consume(rest)
|
|
1345
|
+
emitter.finish(index)
|
|
1346
|
+
})
|
|
1347
|
+
return { files: paths.size, count: emitter.total(), truncated }
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* One STREAMED search: NDJSON frames over a chunked response.
|
|
1352
|
+
*
|
|
1353
|
+
* Frames: `{type:'start',root,roots}` then `{type:'page',items:[...]}` (one per
|
|
1354
|
+
* page, in root order) and finally `{type:'done',files,matches,truncated}` —
|
|
1355
|
+
* or `{type:'error',code,message}` when the search failed after the headers.
|
|
1356
|
+
* A client disconnect aborts the git children of this request.
|
|
1357
|
+
* @param ctx - Host context (session cwd lookup).
|
|
1358
|
+
* @param req - Node request face.
|
|
1359
|
+
* @param res - Node response face.
|
|
1360
|
+
* @param options - `{ restrictToCwd }` (see {@link apply}).
|
|
1361
|
+
* @param content - `true` for content hits, `false` for filenames.
|
|
1362
|
+
*/
|
|
1363
|
+
async function serveSearchStream(ctx, req, res, options, content) {
|
|
1364
|
+
let finished = false
|
|
1365
|
+
const stream = { aborted: false, children: new Set() }
|
|
1366
|
+
const write = (payload) => {
|
|
1367
|
+
if (finished === true || res.writableEnded === true) return
|
|
1368
|
+
res.write(`${JSON.stringify(payload)}\n`)
|
|
1369
|
+
}
|
|
1370
|
+
const finish = (payload) => {
|
|
1371
|
+
if (finished === true) return
|
|
1372
|
+
finished = true
|
|
1373
|
+
if (res.writableEnded === true) return
|
|
1374
|
+
res.end(`${JSON.stringify(payload)}\n`)
|
|
1375
|
+
}
|
|
1376
|
+
try {
|
|
1377
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
1378
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
1379
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
1380
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
1381
|
+
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
|
|
1382
|
+
const query = url.searchParams.get('q') ?? ''
|
|
1383
|
+
if (content && query.trim() === '') throw new TailError('bad-request', 'q (the text to search for) is required', 400)
|
|
1384
|
+
const rawLimit = Number(url.searchParams.get('limit') ?? '300')
|
|
1385
|
+
const limit = content
|
|
1386
|
+
? (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), CONTENT_SEARCH_MAX_HITS) : 300)
|
|
1387
|
+
: (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), 2000) : 300)
|
|
1388
|
+
const rawPerFile = Number(url.searchParams.get('perFile') ?? '8')
|
|
1389
|
+
const perFile = Number.isFinite(rawPerFile) ? Math.min(Math.max(1, Math.floor(rawPerFile)), CONTENT_SEARCH_MAX_PER_FILE) : 8
|
|
1390
|
+
const rawPageSize = Number(url.searchParams.get('pageSize') ?? String(SEARCH_STREAM_PAGE_DEFAULT))
|
|
1391
|
+
const pageSize = Number.isFinite(rawPageSize) ? Math.min(Math.max(1, Math.floor(rawPageSize)), SEARCH_STREAM_PAGE_MAX) : SEARCH_STREAM_PAGE_DEFAULT
|
|
1392
|
+
const roots = await searchRoots(cwd)
|
|
1393
|
+
res.writeHead(200, {
|
|
1394
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
1395
|
+
'cache-control': 'no-store',
|
|
1396
|
+
'x-accel-buffering': 'no',
|
|
1397
|
+
})
|
|
1398
|
+
res.on('close', () => {
|
|
1399
|
+
if (finished === true) return
|
|
1400
|
+
stream.aborted = true
|
|
1401
|
+
for (const child of stream.children) {
|
|
1402
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1403
|
+
}
|
|
1404
|
+
})
|
|
1405
|
+
write({ type: 'start', root: cwd, repoCount: roots.length })
|
|
1406
|
+
const onPage = (items) => write({ type: 'page', items })
|
|
1407
|
+
const result = content
|
|
1408
|
+
? await searchWorkspaceContentStream(cwd, roots, query, { limit, perFile, pageSize, onPage, stream })
|
|
1409
|
+
: await searchWorkspaceFilesStream(cwd, roots, query, { limit, pageSize, onPage, stream })
|
|
1410
|
+
finish({ type: 'done', files: result.files, matches: result.count, truncated: result.truncated })
|
|
1411
|
+
} catch (error) {
|
|
1412
|
+
if (finished === true) return
|
|
1413
|
+
if (res.writableEnded !== true && res.headersSent !== true) { writeTailError(res, error); return }
|
|
1414
|
+
finish({ type: 'error', code: error?.code ?? 'error', message: error?.message ?? 'search failed' })
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
949
1418
|
/** Cache of one repo root's allowed file paths (gitignore-aware), 5s TTL. */
|
|
950
1419
|
const TREE_ALLOWED_CACHE = new Map()
|
|
951
1420
|
/** Repo listing caches invalidated in the last second (coalesces save storms). */
|
|
@@ -1063,7 +1532,7 @@ function relativePathOf(cwd, absolute) {
|
|
|
1063
1532
|
}
|
|
1064
1533
|
|
|
1065
1534
|
/** Path segments the watcher always drops (git never reports these as changes). */
|
|
1066
|
-
const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git',
|
|
1535
|
+
const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git', IDE_STATE_DIR])
|
|
1067
1536
|
|
|
1068
1537
|
/**
|
|
1069
1538
|
* Whether a rel path is one the tree never shows for structural reasons.
|
|
@@ -1175,7 +1644,7 @@ async function repoAllowedPaths(root) {
|
|
|
1175
1644
|
const dirs = new Set([root])
|
|
1176
1645
|
let listing
|
|
1177
1646
|
try {
|
|
1178
|
-
listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
|
|
1647
|
+
listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
|
|
1179
1648
|
} catch {
|
|
1180
1649
|
// Any failure (most often "git is not installed") degrades to no filtering.
|
|
1181
1650
|
TREE_ALLOWED_CACHE.set(root, { at: Date.now(), value: undefined })
|
|
@@ -1241,6 +1710,9 @@ async function compactChain(full, allowed, repo) {
|
|
|
1241
1710
|
for (const child of children) {
|
|
1242
1711
|
const childPath = join(current, child.name)
|
|
1243
1712
|
if (child.isDirectory()) {
|
|
1713
|
+
// A filtered tree hides `.git` too (see listIdeTree): it is metadata, and
|
|
1714
|
+
// it would otherwise count as a visible sibling and block package folding.
|
|
1715
|
+
if (allowed !== undefined && TREE_WATCH_ALWAYS_IGNORED.has(child.name)) continue
|
|
1244
1716
|
const isRepo = await stat(join(childPath, '.git')).then(() => true).catch(() => false)
|
|
1245
1717
|
if (isRepo) return { path: current, segments }
|
|
1246
1718
|
if (allowed !== undefined && !allowed.dirs.has(childPath)) {
|
|
@@ -1298,6 +1770,76 @@ async function ignoredTreeDirs(repo, relatives) {
|
|
|
1298
1770
|
return ignored
|
|
1299
1771
|
}
|
|
1300
1772
|
|
|
1773
|
+
/** Workspaces whose `.dsh-ris-ide/` folder was already prepared in this process. */
|
|
1774
|
+
const IDE_STATE_READY = new Set()
|
|
1775
|
+
|
|
1776
|
+
/** Legacy config files an older build wrote beside the workspace root. */
|
|
1777
|
+
const LEGACY_STATE_FILES = [
|
|
1778
|
+
['.dsh-ris-ide.json', 'config.json'],
|
|
1779
|
+
['.dsh-ris-ide.settings.json', 'settings.json'],
|
|
1780
|
+
]
|
|
1781
|
+
|
|
1782
|
+
/** Legacy sibling folders an older build wrote straight into the workspace root. */
|
|
1783
|
+
const LEGACY_STATE_DIRS = [
|
|
1784
|
+
['.dsh-ris-ide-trash', 'trash'],
|
|
1785
|
+
['.dsh-ris-ide-cache', 'cache'],
|
|
1786
|
+
['.dsh-ris-ide-stage', 'stage'],
|
|
1787
|
+
]
|
|
1788
|
+
|
|
1789
|
+
/**
|
|
1790
|
+
* Create `<root>/.dsh-ris-ide/` and fold any legacy dot-folders into it, once per
|
|
1791
|
+
* workspace per process. Earlier builds scattered three sibling folders across the
|
|
1792
|
+
* workspace root (`-trash`, `-cache`, `-stage`), each of which the tree had to hide
|
|
1793
|
+
* by name; one folder is easier to explain and to gitignore. Contents are moved,
|
|
1794
|
+
* not dropped: a parked delete must stay restorable and a cache entry reusable.
|
|
1795
|
+
* @param {string} root - the workspace root.
|
|
1796
|
+
* @returns {Promise<string|undefined>} the state folder, or undefined without a root.
|
|
1797
|
+
*/
|
|
1798
|
+
async function ensureIdeStateDir(root) {
|
|
1799
|
+
if (root === undefined || root === null || root === '') return undefined
|
|
1800
|
+
const stateDir = join(root, IDE_STATE_DIR)
|
|
1801
|
+
const key = resolve(stateDir)
|
|
1802
|
+
if (IDE_STATE_READY.has(key)) return stateDir
|
|
1803
|
+
IDE_STATE_READY.add(key)
|
|
1804
|
+
try {
|
|
1805
|
+
await mkdir(stateDir, { recursive: true }).catch(() => undefined)
|
|
1806
|
+
for (const [legacyName, childName] of LEGACY_STATE_DIRS) {
|
|
1807
|
+
const from = join(root, legacyName)
|
|
1808
|
+
const info = await stat(from).catch(() => undefined)
|
|
1809
|
+
if (info === undefined || !info.isDirectory()) continue
|
|
1810
|
+
const target = join(stateDir, childName)
|
|
1811
|
+
await mkdir(target, { recursive: true }).catch(() => undefined)
|
|
1812
|
+
// Parked deletes live in the legacy trash: a folder that could not be
|
|
1813
|
+
// emptied completely must stay where it is, or the failed move becomes a
|
|
1814
|
+
// silent delete of somebody's files.
|
|
1815
|
+
let moved = true
|
|
1816
|
+
for (const name of await readdir(from).catch(() => [])) {
|
|
1817
|
+
const to = join(target, name)
|
|
1818
|
+
const taken = await stat(to).then(() => true).catch(() => false)
|
|
1819
|
+
// Never overwrite same-named leftovers: keep both, the newcomer wins the
|
|
1820
|
+
// plain name and the legacy entry is parked with a suffix.
|
|
1821
|
+
const destination = taken ? join(target, `${name}-legacy-${Date.now()}`) : to
|
|
1822
|
+
await rename(join(from, name), destination).catch(() => { moved = false })
|
|
1823
|
+
}
|
|
1824
|
+
if (moved === true) await rm(from, { recursive: true, force: true }).catch(() => undefined)
|
|
1825
|
+
}
|
|
1826
|
+
for (const [legacyName, childName] of LEGACY_STATE_FILES) {
|
|
1827
|
+
const from = join(root, legacyName)
|
|
1828
|
+
const info = await stat(from).catch(() => undefined)
|
|
1829
|
+
if (info === undefined || !info.isFile()) continue
|
|
1830
|
+
const to = join(stateDir, childName)
|
|
1831
|
+
// A file already at the new place wins: never overwrite the newer config.
|
|
1832
|
+
const taken = await stat(to).then(() => true).catch(() => false)
|
|
1833
|
+
if (!taken) await rename(from, to).catch(() => undefined)
|
|
1834
|
+
}
|
|
1835
|
+
return stateDir
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
// Let a later call retry the migration instead of remembering a failed one.
|
|
1838
|
+
IDE_STATE_READY.delete(key)
|
|
1839
|
+
throw error
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1301
1843
|
/**
|
|
1302
1844
|
* One directory level for the IDE tree.
|
|
1303
1845
|
* @param {string} target - absolute directory.
|
|
@@ -1305,6 +1847,7 @@ async function ignoredTreeDirs(repo, relatives) {
|
|
|
1305
1847
|
* @returns {Promise<{entries: object[], truncated: boolean}>}
|
|
1306
1848
|
*/
|
|
1307
1849
|
async function listIdeTree(target, cwd, options) {
|
|
1850
|
+
await ensureIdeStateDir(cwd)
|
|
1308
1851
|
const repo = await findGitRoot(target, cwd)
|
|
1309
1852
|
// `filter: 'all'` is the tree's "show everything" mode: the gitignore filter is
|
|
1310
1853
|
// deliberately bypassed, but the plugin's own bookkeeping folders stay hidden.
|
|
@@ -1316,7 +1859,7 @@ async function listIdeTree(target, cwd, options) {
|
|
|
1316
1859
|
const unknownDirs = []
|
|
1317
1860
|
if (repo !== undefined && allowed !== undefined) {
|
|
1318
1861
|
for (const dirent of dirents) {
|
|
1319
|
-
if (!dirent.isDirectory() || dirent.name
|
|
1862
|
+
if (!dirent.isDirectory() || TREE_WATCH_ALWAYS_IGNORED.has(dirent.name)) continue
|
|
1320
1863
|
const full = join(target, dirent.name)
|
|
1321
1864
|
if (allowed.dirs.has(full)) continue
|
|
1322
1865
|
const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
|
|
@@ -1327,9 +1870,21 @@ async function listIdeTree(target, cwd, options) {
|
|
|
1327
1870
|
const ignoredDirs = await ignoredTreeDirs(repo ?? '', unknownDirs)
|
|
1328
1871
|
const entries = []
|
|
1329
1872
|
for (const dirent of dirents) {
|
|
1330
|
-
//
|
|
1331
|
-
//
|
|
1332
|
-
|
|
1873
|
+
// A chunked save stages the document in `<file>.dsh-ris-ide-saving` next to
|
|
1874
|
+
// its target (same directory ⇒ the rename is atomic). It exists for a few
|
|
1875
|
+
// milliseconds, and after a crash it may linger: never show it as a tree row.
|
|
1876
|
+
if (dirent.name.endsWith(FS_WRITE_TEMP_SUFFIX)) continue
|
|
1877
|
+
// `.dsh-ris-ide/` holds the undo trash, the dependency-source cache and the
|
|
1878
|
+
// clipboard staging batches: implementation details, never tree rows — and
|
|
1879
|
+
// hidden in BOTH filter modes, like the trash row it replaced.
|
|
1880
|
+
if (dirent.name === IDE_STATE_DIR) continue
|
|
1881
|
+
// `.git` is repository metadata, not project content: a filtered tree hides it
|
|
1882
|
+
// exactly like TREE_WATCH_ALWAYS_IGNORED hides its watch events. `git ls-files`
|
|
1883
|
+
// never lists it and `check-ignore` never reports it, so without this line it
|
|
1884
|
+
// would be the one ignored-looking folder the .gitignore filter still showed
|
|
1885
|
+
// (every repo root has one, and a nested repo's `.git` file is the same noise).
|
|
1886
|
+
// "显示所有文件" keeps it visible, like every other hidden entry.
|
|
1887
|
+
if (allowed !== undefined && TREE_WATCH_ALWAYS_IGNORED.has(dirent.name)) continue
|
|
1333
1888
|
const full = join(target, dirent.name)
|
|
1334
1889
|
if (dirent.isDirectory()) {
|
|
1335
1890
|
const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
|
|
@@ -1478,7 +2033,7 @@ export async function assertEnoughMemory(minFreeBytes) {
|
|
|
1478
2033
|
if (free === 0 || free >= floor) return
|
|
1479
2034
|
throw new TailError(
|
|
1480
2035
|
'low-memory',
|
|
1481
|
-
`可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
|
|
2036
|
+
`可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide/config.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
|
|
1482
2037
|
507,
|
|
1483
2038
|
)
|
|
1484
2039
|
}
|
|
@@ -2030,12 +2585,12 @@ function delay(ms) {
|
|
|
2030
2585
|
* @param req - Node request face (async iterable).
|
|
2031
2586
|
* @returns the parsed object (empty object for an empty body).
|
|
2032
2587
|
*/
|
|
2033
|
-
async function readJsonBody(req) {
|
|
2588
|
+
async function readJsonBody(req, limitBytes = MAX_BODY_BYTES, tooLargeMessage = 'request body too large') {
|
|
2034
2589
|
let size = 0
|
|
2035
2590
|
const chunks = []
|
|
2036
2591
|
for await (const chunk of req) {
|
|
2037
2592
|
size += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length
|
|
2038
|
-
if (size >
|
|
2593
|
+
if (size > limitBytes) throw new TailError('bad-request', tooLargeMessage, 413)
|
|
2039
2594
|
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
|
2040
2595
|
}
|
|
2041
2596
|
if (size === 0) return {}
|
|
@@ -2576,18 +3131,38 @@ async function serveFsOp(ctx, req, res, options) {
|
|
|
2576
3131
|
const notRoot = (target, action) => {
|
|
2577
3132
|
if (target === root) throw new TailError('bad-request', `不能对工作区根目录执行${action}`, 409)
|
|
2578
3133
|
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Every mutation stays INSIDE the tree root.
|
|
3136
|
+
*
|
|
3137
|
+
* A path is only a string from the page: `/fs/remove` with `"../../../home"`
|
|
3138
|
+
* would otherwise recurse out of the tree and delete what it never listed.
|
|
3139
|
+
* The lexical check is enough because {@link resolvePath} already normalized
|
|
3140
|
+
* `.`/`..`, and `fs.rm` never follows a symlink to a directory.
|
|
3141
|
+
*/
|
|
3142
|
+
const insideRoot = (target, action) => {
|
|
3143
|
+
notRoot(target, action)
|
|
3144
|
+
const base = root.endsWith(sep) ? root : `${root}${sep}`
|
|
3145
|
+
if (!target.startsWith(base)) throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
|
|
3146
|
+
}
|
|
2579
3147
|
const exists = async (target) => stat(target).then(() => true).catch(() => false)
|
|
3148
|
+
/** A destination given as a FILE means its directory, same rule as a paste. */
|
|
3149
|
+
const asFolder = async (target) => {
|
|
3150
|
+
const info = await stat(target).catch(() => undefined)
|
|
3151
|
+
return info !== undefined && !info.isDirectory() ? dirname(target) : target
|
|
3152
|
+
}
|
|
2580
3153
|
|
|
2581
3154
|
if (url.pathname === FS_MKDIR_PATH) {
|
|
2582
3155
|
const target = one(body.path, 'path')
|
|
2583
|
-
|
|
3156
|
+
insideRoot(target, '新建文件夹')
|
|
3157
|
+
checkLeafName(basename(target))
|
|
2584
3158
|
await mkdir(target, { recursive: true })
|
|
2585
3159
|
writeJson(res, 200, { ok: true, path: target, created: true })
|
|
2586
3160
|
return
|
|
2587
3161
|
}
|
|
2588
3162
|
if (url.pathname === FS_CREATE_PATH) {
|
|
2589
3163
|
const target = one(body.path, 'path')
|
|
2590
|
-
|
|
3164
|
+
insideRoot(target, '新建文件')
|
|
3165
|
+
checkLeafName(basename(target))
|
|
2591
3166
|
if (await exists(target)) throw new TailError('exists', `「${basename(target)}」已存在`, 409)
|
|
2592
3167
|
await mkdir(dirname(target), { recursive: true })
|
|
2593
3168
|
await writeFile(target, typeof body.content === 'string' ? body.content : '', { flag: 'wx' })
|
|
@@ -2596,13 +3171,11 @@ async function serveFsOp(ctx, req, res, options) {
|
|
|
2596
3171
|
}
|
|
2597
3172
|
if (url.pathname === FS_COPY_PATH || url.pathname === FS_MOVE_PATH) {
|
|
2598
3173
|
const from = one(body.from, 'from')
|
|
2599
|
-
|
|
2600
|
-
const toDir = one(body.toDir !== undefined ? body.toDir : body.to, 'toDir')
|
|
2601
|
-
const requested = typeof body.name === 'string' ? body.name
|
|
2602
|
-
if (requested.includes('/') || requested.includes('\\') || requested === '.' || requested === '..') {
|
|
2603
|
-
throw new TailError('bad-request', '非法的目标文件名', 400)
|
|
2604
|
-
}
|
|
3174
|
+
insideRoot(from, '复制或移动')
|
|
3175
|
+
const toDir = await asFolder(one(body.toDir !== undefined ? body.toDir : body.to, 'toDir'))
|
|
3176
|
+
const requested = leafName(typeof body.name === 'string' ? body.name : '')
|
|
2605
3177
|
const target = join(toDir, requested === '' ? basename(from) : requested)
|
|
3178
|
+
insideRoot(target, '复制或移动')
|
|
2606
3179
|
if (target === from) throw new TailError('bad-request', '目标与源相同', 409)
|
|
2607
3180
|
if (target.startsWith(from.endsWith(sep) ? from : `${from}${sep}`)) {
|
|
2608
3181
|
throw new TailError('bad-request', '不能把目录复制/移动到它自己内部', 409)
|
|
@@ -2627,7 +3200,7 @@ async function serveFsOp(ctx, req, res, options) {
|
|
|
2627
3200
|
}
|
|
2628
3201
|
if (url.pathname === FS_REMOVE_PATH) {
|
|
2629
3202
|
const target = one(body.path, 'path')
|
|
2630
|
-
|
|
3203
|
+
insideRoot(target, '删除')
|
|
2631
3204
|
const info = await stat(target).catch(() => undefined)
|
|
2632
3205
|
if (info === undefined) throw new TailError('not-found', `「${basename(target)}」不存在`, 404)
|
|
2633
3206
|
const recursive = body.recursive === true
|
|
@@ -2648,12 +3221,44 @@ async function serveFsOp(ctx, req, res, options) {
|
|
|
2648
3221
|
/** Text files bigger than this are refused by the read route (matches the old sidebar). */
|
|
2649
3222
|
const FS_MAX_TEXT_BYTES = 512 * 1024
|
|
2650
3223
|
|
|
2651
|
-
/**
|
|
2652
|
-
|
|
3224
|
+
/** Longest leaf name the tree accepts (most Linux filesystems stop at 255 bytes). */
|
|
3225
|
+
const FS_MAX_NAME_LENGTH = 255
|
|
3226
|
+
|
|
3227
|
+
/**
|
|
3228
|
+
* Refuse a leaf name no sane filesystem/UX round-trips: control characters would
|
|
3229
|
+
* break logs and every line-oriented protocol downstream, and 255 is the usual
|
|
3230
|
+
* filesystem cap.
|
|
3231
|
+
* @param name - one path component.
|
|
3232
|
+
*/
|
|
3233
|
+
function checkLeafName(name) {
|
|
3234
|
+
if (/[\u0000-\u001f\u007f]/.test(name)) throw new TailError('bad-request', '文件名里不能有控制字符', 400)
|
|
3235
|
+
if (name.length > FS_MAX_NAME_LENGTH) throw new TailError('bad-request', '文件名太长', 400)
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
/**
|
|
3239
|
+
* One sanitized leaf name — never a path, never a control character.
|
|
3240
|
+
*
|
|
3241
|
+
* Names are only ever path components: every external command gets its paths as
|
|
3242
|
+
* argv/stdin and no shell is involved, so `'; rm -rf /'` is a file name and
|
|
3243
|
+
* nothing else. A newline or NUL would still corrupt logs, clipboard flavours and
|
|
3244
|
+
* any line-oriented protocol downstream, so those are refused at the door.
|
|
3245
|
+
* @param raw - requested name ('' means "keep the source name").
|
|
3246
|
+
* @returns the trimmed name, possibly ''.
|
|
3247
|
+
*/
|
|
3248
|
+
function leafName(raw) {
|
|
2653
3249
|
const name = String(raw === undefined || raw === null ? '' : raw).trim()
|
|
2654
|
-
if (name === ''
|
|
3250
|
+
if (name === '') return ''
|
|
3251
|
+
if (name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
|
|
2655
3252
|
throw new TailError('bad-request', '非法的文件名', 400)
|
|
2656
3253
|
}
|
|
3254
|
+
checkLeafName(name)
|
|
3255
|
+
return name
|
|
3256
|
+
}
|
|
3257
|
+
|
|
3258
|
+
/** One sanitized leaf name for an import target (never a path, never empty). */
|
|
3259
|
+
function importEntryName(raw) {
|
|
3260
|
+
const name = leafName(raw)
|
|
3261
|
+
if (name === '') throw new TailError('bad-request', '非法的文件名', 400)
|
|
2657
3262
|
return name
|
|
2658
3263
|
}
|
|
2659
3264
|
|
|
@@ -2681,6 +3286,54 @@ async function pathExists(target) {
|
|
|
2681
3286
|
* @param res - Node response face.
|
|
2682
3287
|
* @param options - `{ restrictToCwd }` from the plugin config.
|
|
2683
3288
|
*/
|
|
3289
|
+
/**
|
|
3290
|
+
* The folder a paste lands in.
|
|
3291
|
+
*
|
|
3292
|
+
* Callers may hand over a FILE as the destination: the tree selection can be a
|
|
3293
|
+
* file row, and 「粘贴」/Ctrl+V on it means "put it NEXT TO this file". Rather
|
|
3294
|
+
* than failing with 「粘贴目标不是目录」, a file target resolves to its own
|
|
3295
|
+
* directory. A target that does not exist at all is still an error.
|
|
3296
|
+
* @param {string} cwd - session working directory.
|
|
3297
|
+
* @param {string} raw - requested destination (absolute or cwd-relative).
|
|
3298
|
+
* @param {boolean} restrict - keep the destination inside `cwd`.
|
|
3299
|
+
* @returns {Promise<string>} an existing directory.
|
|
3300
|
+
*/
|
|
3301
|
+
async function resolvePasteDirectory(cwd, raw, restrict) {
|
|
3302
|
+
const root = resolve(cwd)
|
|
3303
|
+
const target = resolvePath(cwd, raw, restrict)
|
|
3304
|
+
const info = await stat(target).catch(() => undefined)
|
|
3305
|
+
if (info === undefined) throw new TailError('bad-request', `粘贴目标「${raw}」不存在`, 400)
|
|
3306
|
+
if (info.isDirectory()) {
|
|
3307
|
+
insideRootDirectory(root, target, raw)
|
|
3308
|
+
return target
|
|
3309
|
+
}
|
|
3310
|
+
const folder = dirname(target)
|
|
3311
|
+
const folderInfo = await stat(folder).catch(() => undefined)
|
|
3312
|
+
if (folderInfo === undefined || !folderInfo.isDirectory()) {
|
|
3313
|
+
throw new TailError('bad-request', '粘贴目标不是目录', 400)
|
|
3314
|
+
}
|
|
3315
|
+
insideRootDirectory(root, folder, raw)
|
|
3316
|
+
return folder
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
/**
|
|
3320
|
+
* A paste only ever lands INSIDE the tree root.
|
|
3321
|
+
*
|
|
3322
|
+
* `dir` arrives as a string from the page; without this check an overwrite paste
|
|
3323
|
+
* (`rm -rf` of the colliding entry) could be aimed at any absolute directory on
|
|
3324
|
+
* the machine. The tree only ever lists its own root, so nothing legitimate is
|
|
3325
|
+
* lost by refusing the rest.
|
|
3326
|
+
* @param root - absolute tree root (the session cwd).
|
|
3327
|
+
* @param dir - resolved destination directory.
|
|
3328
|
+
* @param raw - the requested value, for the error message.
|
|
3329
|
+
*/
|
|
3330
|
+
function insideRootDirectory(root, dir, raw) {
|
|
3331
|
+
const base = root.endsWith(sep) ? root : `${root}${sep}`
|
|
3332
|
+
if (dir !== root && !dir.startsWith(base)) {
|
|
3333
|
+
throw new TailError('outside-workspace', `粘贴目标「${raw}」不在工作区里`, 403)
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
|
|
2684
3337
|
async function serveFsImport(ctx, req, res, options) {
|
|
2685
3338
|
try {
|
|
2686
3339
|
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
@@ -2690,9 +3343,7 @@ async function serveFsImport(ctx, req, res, options) {
|
|
|
2690
3343
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
2691
3344
|
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
|
|
2692
3345
|
const name = importEntryName(url.searchParams.get('name') ?? '')
|
|
2693
|
-
const dir =
|
|
2694
|
-
const info = await stat(dir).catch(() => undefined)
|
|
2695
|
-
if (info === undefined || !info.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
|
|
3346
|
+
const dir = await resolvePasteDirectory(cwd, url.searchParams.get('dir') ?? '', options?.restrictToCwd === true)
|
|
2696
3347
|
const target = join(dir, name)
|
|
2697
3348
|
const overwrite = url.searchParams.get('overwrite') === '1'
|
|
2698
3349
|
if (!overwrite && await pathExists(target)) throw new TailError('exists', `「${name}」已存在`, 409)
|
|
@@ -2730,9 +3381,7 @@ async function serveFsImport(ctx, req, res, options) {
|
|
|
2730
3381
|
const source = isAbsolute(rawFrom) ? resolve(rawFrom) : resolvePath(cwd, rawFrom, restrict)
|
|
2731
3382
|
const sourceInfo = await stat(source).catch(() => undefined)
|
|
2732
3383
|
if (sourceInfo === undefined) throw new TailError('not-found', `找不到「${rawFrom}」`, 404)
|
|
2733
|
-
const dir =
|
|
2734
|
-
const dirInfo = await stat(dir).catch(() => undefined)
|
|
2735
|
-
if (dirInfo === undefined || !dirInfo.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
|
|
3384
|
+
const dir = await resolvePasteDirectory(cwd, typeof body.dir === 'string' ? body.dir : '', restrict)
|
|
2736
3385
|
const name = importEntryName(typeof body.name === 'string' && body.name.trim() !== '' ? body.name : basename(source))
|
|
2737
3386
|
const target = join(dir, name)
|
|
2738
3387
|
if (target === source || target.startsWith(`${source}${sep}`) || source.startsWith(`${target}${sep}`)) {
|
|
@@ -2751,6 +3400,562 @@ async function serveFsImport(ctx, req, res, options) {
|
|
|
2751
3400
|
}
|
|
2752
3401
|
}
|
|
2753
3402
|
|
|
3403
|
+
/**
|
|
3404
|
+
* Is this Linux really WSL? Then the Windows clipboard is reachable through
|
|
3405
|
+
* interop, which is the ONLY way a web page can hand files to Explorer/desktop:
|
|
3406
|
+
* Chromium refuses `text/uri-list` (and `x-special/gnome-copied-files`) on
|
|
3407
|
+
* `Clipboard.write`, so the browser cannot publish a file list itself.
|
|
3408
|
+
* @returns whether the platform is WSL.
|
|
3409
|
+
*/
|
|
3410
|
+
export function isWsl() {
|
|
3411
|
+
if (IS_WINDOWS) return false
|
|
3412
|
+
try {
|
|
3413
|
+
return existsSync('/proc/version') && readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')
|
|
3414
|
+
} catch {
|
|
3415
|
+
return false
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
|
|
3419
|
+
/**
|
|
3420
|
+
* PowerShell that puts a FILE LIST on the Windows clipboard (CF_HDROP), with the
|
|
3421
|
+
* copy/move intent Explorer reads from `Preferred DropEffect`. Clipboard.SetDataObject
|
|
3422
|
+
* needs an STA thread, so callers pass `-STA`.
|
|
3423
|
+
*
|
|
3424
|
+
* The paths are NOT part of this text: they arrive on STDIN, one per line, so a
|
|
3425
|
+
* filename can never become PowerShell code (`'; rm -rf /; '` is just a name).
|
|
3426
|
+
* The only interpolated value is the DropEffect integer, chosen from a boolean.
|
|
3427
|
+
* @param cut - `true` for a MOVE intent (Explorer deletes the source on paste).
|
|
3428
|
+
* @returns the script text.
|
|
3429
|
+
*/
|
|
3430
|
+
export function windowsClipboardScript(cut) {
|
|
3431
|
+
const effect = cut ? 2 : 1
|
|
3432
|
+
return [
|
|
3433
|
+
// Node writes UTF-8 bytes; decode them here so Windows PowerShell's console
|
|
3434
|
+
// input encoding cannot mangle non-ASCII file names.
|
|
3435
|
+
'$stdin = [Console]::OpenStandardInput()',
|
|
3436
|
+
'$buffer = New-Object System.IO.MemoryStream',
|
|
3437
|
+
'$stdin.CopyTo($buffer)',
|
|
3438
|
+
'$raw = [Text.Encoding]::UTF8.GetString($buffer.ToArray())',
|
|
3439
|
+
// One path per line (CRLF tolerated); a path never contains a line break — the
|
|
3440
|
+
// route rejects those before this script runs.
|
|
3441
|
+
"$lines = @($raw -split \"`n\" | ForEach-Object { $_.TrimEnd(\"`r\") } | Where-Object { $_ -ne '' })",
|
|
3442
|
+
'if ($lines.Count -eq 0) { exit 2 }',
|
|
3443
|
+
'Add-Type -AssemblyName System.Windows.Forms',
|
|
3444
|
+
'$data = New-Object System.Windows.Forms.DataObject',
|
|
3445
|
+
"$data.SetData('FileDrop', [string[]]$lines)",
|
|
3446
|
+
`$data.SetData('Preferred DropEffect', [byte[]]@(${effect},0,0,0))`,
|
|
3447
|
+
'[System.Windows.Forms.Clipboard]::SetDataObject($data, $true)',
|
|
3448
|
+
].join('\n')
|
|
3449
|
+
}
|
|
3450
|
+
|
|
3451
|
+
/**
|
|
3452
|
+
* Run one child process, collecting its output as text.
|
|
3453
|
+
*
|
|
3454
|
+
* `command` and `args` are always fixed program names and flags — request data
|
|
3455
|
+
* travels on stdin, never through a shell, so nothing a user names can be read
|
|
3456
|
+
* as code or as another flag. A hard timeout kills a stuck helper (a clipboard
|
|
3457
|
+
* tool that waits for a display can hang forever).
|
|
3458
|
+
* @param command - executable name or path.
|
|
3459
|
+
* @param args - argument vector.
|
|
3460
|
+
* @param input - optional stdin payload.
|
|
3461
|
+
* @param timeoutMs - give up (and kill) after this long.
|
|
3462
|
+
* @returns `{ ok, stdout, stderr }`; `ok` is `code === 0`.
|
|
3463
|
+
*/
|
|
3464
|
+
function runTool(command, args, input, timeoutMs = 15000) {
|
|
3465
|
+
return new Promise((resolvePromise) => {
|
|
3466
|
+
let settled = false
|
|
3467
|
+
const settle = (result) => {
|
|
3468
|
+
if (settled) return
|
|
3469
|
+
settled = true
|
|
3470
|
+
clearTimeout(timer)
|
|
3471
|
+
resolvePromise(result)
|
|
3472
|
+
}
|
|
3473
|
+
let child
|
|
3474
|
+
try {
|
|
3475
|
+
child = spawn(command, args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], windowsHide: true })
|
|
3476
|
+
} catch (error) {
|
|
3477
|
+
settle({ ok: false, stdout: '', stderr: messageOf(error) })
|
|
3478
|
+
return
|
|
3479
|
+
}
|
|
3480
|
+
let stdout = ''
|
|
3481
|
+
let stderr = ''
|
|
3482
|
+
const timer = setTimeout(() => {
|
|
3483
|
+
child.kill('SIGKILL')
|
|
3484
|
+
settle({ ok: false, stdout, stderr: `${stderr}${stderr === '' ? '' : '\n'}${command} 超时(${Math.round(timeoutMs / 1000)}s)` })
|
|
3485
|
+
}, timeoutMs)
|
|
3486
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk })
|
|
3487
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk })
|
|
3488
|
+
child.on('error', (error) => settle({ ok: false, stdout, stderr: messageOf(error) }))
|
|
3489
|
+
child.on('close', (code) => settle({ ok: code === 0, stdout, stderr }))
|
|
3490
|
+
if (input !== undefined) {
|
|
3491
|
+
child.stdin?.on('error', () => {})
|
|
3492
|
+
child.stdin?.end(input)
|
|
3493
|
+
}
|
|
3494
|
+
})
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
/**
|
|
3498
|
+
* Translate one WSL path into the Windows path the clipboard must carry
|
|
3499
|
+
* (`\\wsl.localhost\<distro>\…`). `wslpath` knows better than any guess.
|
|
3500
|
+
* @param path - absolute Linux path.
|
|
3501
|
+
* @returns the Windows path, or `undefined` when `wslpath` refused.
|
|
3502
|
+
*/
|
|
3503
|
+
async function wslWindowsPath(path) {
|
|
3504
|
+
const result = await runTool('wslpath', ['-w', path])
|
|
3505
|
+
const converted = result.ok ? result.stdout.trim() : ''
|
|
3506
|
+
return converted === '' ? undefined : converted
|
|
3507
|
+
}
|
|
3508
|
+
|
|
3509
|
+
/**
|
|
3510
|
+
* Put `paths` on the SYSTEM clipboard as a file list, per platform.
|
|
3511
|
+
* @param paths - absolute native paths (files and/or directories).
|
|
3512
|
+
* @param cut - `true` for a MOVE intent.
|
|
3513
|
+
* @returns `{ method }` naming the backend that took it.
|
|
3514
|
+
* @throws TailError `unsupported` when the platform has no way to do it.
|
|
3515
|
+
*/
|
|
3516
|
+
export async function writeSystemFileClipboard(paths, cut = false) {
|
|
3517
|
+
if (process.platform === 'win32' || isWsl()) {
|
|
3518
|
+
let windowsPaths = paths
|
|
3519
|
+
if (!IS_WINDOWS) {
|
|
3520
|
+
const converted = await Promise.all(paths.map((path) => wslWindowsPath(path)))
|
|
3521
|
+
if (converted.some((path) => path === undefined)) {
|
|
3522
|
+
throw new TailError('clipboard-failed', '无法把 WSL 路径转换成 Windows 路径(wslpath 不可用)', 500)
|
|
3523
|
+
}
|
|
3524
|
+
windowsPaths = converted
|
|
3525
|
+
}
|
|
3526
|
+
const encoded = Buffer.from(windowsClipboardScript(cut === true), 'utf16le').toString('base64')
|
|
3527
|
+
// The list rides on STDIN — see windowsClipboardScript(): no path is ever
|
|
3528
|
+
// spliced into a command line or a script.
|
|
3529
|
+
const result = await runTool('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded], `${windowsPaths.join('\n')}\n`)
|
|
3530
|
+
if (!result.ok) {
|
|
3531
|
+
throw new TailError('clipboard-failed', `PowerShell 写剪贴板失败:${(result.stderr || result.stdout).trim().split('\n')[0] || '未知错误'}`, 500)
|
|
3532
|
+
}
|
|
3533
|
+
return { method: IS_WINDOWS ? 'windows-powershell' : 'wsl-powershell' }
|
|
3534
|
+
}
|
|
3535
|
+
if (process.platform === 'darwin') {
|
|
3536
|
+
// Paths are argv here too: no path text is parsed as JXA source.
|
|
3537
|
+
const script = [
|
|
3538
|
+
'function run(argv) {',
|
|
3539
|
+
' ObjC.import("AppKit")',
|
|
3540
|
+
' var pb = $.NSPasteboard.generalPasteboard',
|
|
3541
|
+
' pb.clearContents',
|
|
3542
|
+
' pb.writeObjects($(argv.map(function (path) { return $.NSURL.fileURLWithPath(path) })))',
|
|
3543
|
+
' return ""',
|
|
3544
|
+
'}',
|
|
3545
|
+
].join('\n')
|
|
3546
|
+
const result = await runTool('osascript', ['-l', 'JavaScript', '-e', script, ...paths])
|
|
3547
|
+
if (!result.ok) {
|
|
3548
|
+
throw new TailError('clipboard-failed', `osascript 写剪贴板失败:${result.stderr.trim() || '未知错误'}`, 500)
|
|
3549
|
+
}
|
|
3550
|
+
return { method: 'macos-appkit' }
|
|
3551
|
+
}
|
|
3552
|
+
// Linux desktop: GNOME wants x-special/gnome-copied-files (it carries copy|cut),
|
|
3553
|
+
// wl-clipboard only offers text/uri-list — both are understood by file managers.
|
|
3554
|
+
// The payload is data on stdin: it is never an argument and never shell-parsed.
|
|
3555
|
+
const urls = paths.map((path) => `file://${encodeURI(path)}`)
|
|
3556
|
+
const gnomePayload = `${cut === true ? 'cut' : 'copy'}\n${urls.join('\n')}\n`
|
|
3557
|
+
const xclip = await runTool('xclip', ['-selection', 'clipboard', '-t', 'x-special/gnome-copied-files', '-i'], gnomePayload)
|
|
3558
|
+
if (xclip.ok) return { method: 'linux-xclip' }
|
|
3559
|
+
const uriList = `${urls.join('\r\n')}\r\n`
|
|
3560
|
+
const wlCopy = await runTool('wl-copy', ['--type', 'text/uri-list'], uriList)
|
|
3561
|
+
if (wlCopy.ok) return { method: 'linux-wl-copy' }
|
|
3562
|
+
throw new TailError('unsupported', '这台机器没有 xclip / wl-copy,浏览器也无法直接写文件剪贴板', 501)
|
|
3563
|
+
}
|
|
3564
|
+
|
|
3565
|
+
/**
|
|
3566
|
+
* Create `target` as a mirror of `source` using HARD LINKS wherever one is
|
|
3567
|
+
* possible: a staged directory costs inodes, not bytes, and Explorer moving a
|
|
3568
|
+
* staged link out of the stage never touches the original path.
|
|
3569
|
+
*
|
|
3570
|
+
* Links only fail across filesystems (`EXDEV`); then — and only then — the entry
|
|
3571
|
+
* is copied for real, which is still safe (a copy of the original) and is charged
|
|
3572
|
+
* against the byte budget of one copy gesture.
|
|
3573
|
+
* @param {string} source - entry to mirror (file, directory or symlink).
|
|
3574
|
+
* @param {string} target - staged path to create.
|
|
3575
|
+
* @param {{budget: number}} meter - remaining bytes for real copies.
|
|
3576
|
+
*/
|
|
3577
|
+
async function mirrorStagedEntry(source, target, meter) {
|
|
3578
|
+
const info = await lstat(source)
|
|
3579
|
+
if (info.isSymbolicLink()) {
|
|
3580
|
+
await symlink(await readlink(source), target)
|
|
3581
|
+
return
|
|
3582
|
+
}
|
|
3583
|
+
if (info.isDirectory()) {
|
|
3584
|
+
await mkdir(target, { recursive: true })
|
|
3585
|
+
const entries = await readdir(source, { withFileTypes: true })
|
|
3586
|
+
for (const entry of entries) {
|
|
3587
|
+
await mirrorStagedEntry(join(source, entry.name), join(target, entry.name), meter)
|
|
3588
|
+
}
|
|
3589
|
+
return
|
|
3590
|
+
}
|
|
3591
|
+
try {
|
|
3592
|
+
await link(source, target)
|
|
3593
|
+
} catch (error) {
|
|
3594
|
+
if (error === null || error === undefined || error.code !== 'EXDEV') throw error
|
|
3595
|
+
meter.budget -= info.size
|
|
3596
|
+
if (meter.budget < 0) throw clipboardStageTooLarge()
|
|
3597
|
+
await copyFile(source, target)
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
|
|
3601
|
+
/** Delete staging batches that are old or beyond the keep window. */
|
|
3602
|
+
async function pruneClipboardStage(root) {
|
|
3603
|
+
await ensureIdeStateDir(root)
|
|
3604
|
+
const base = join(root, CLIPBOARD_STAGE_DIR)
|
|
3605
|
+
const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
|
|
3606
|
+
const batches = []
|
|
3607
|
+
for (const entry of entries) {
|
|
3608
|
+
if (!entry.isDirectory()) continue
|
|
3609
|
+
const path = join(base, entry.name)
|
|
3610
|
+
const info = await stat(path).catch(() => undefined)
|
|
3611
|
+
if (info !== undefined) batches.push({ path, at: info.mtimeMs })
|
|
3612
|
+
}
|
|
3613
|
+
batches.sort((left, right) => right.at - left.at)
|
|
3614
|
+
const now = Date.now()
|
|
3615
|
+
for (let index = 0; index < batches.length; index += 1) {
|
|
3616
|
+
if (index < CLIPBOARD_STAGE_KEEP_BATCHES && now - batches[index].at < CLIPBOARD_STAGE_TTL_MS) continue
|
|
3617
|
+
await rm(batches[index].path, { recursive: true, force: true }).catch(() => {})
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
|
|
3621
|
+
/** The staged copy cannot be expressed within the budget. Never fall back to the originals. */
|
|
3622
|
+
function clipboardStageTooLarge() {
|
|
3623
|
+
const megabytes = Math.round(CLIPBOARD_STAGE_MAX_BYTES / (1024 * 1024))
|
|
3624
|
+
// Short on purpose: this string ends up in a toast.
|
|
3625
|
+
return new TailError('too-large', `超过 ${megabytes} MB,已取消复制到系统剪贴板`, 413)
|
|
3626
|
+
}
|
|
3627
|
+
|
|
3628
|
+
/**
|
|
3629
|
+
* Stage a COPY publish: every entry gets its own numbered folder inside a fresh
|
|
3630
|
+
* batch, so two same-named files from different folders do not collide and the
|
|
3631
|
+
* names Explorer pastes are the original ones. Entries are hard-link mirrors — a
|
|
3632
|
+
* staged path is a different NAME for the same inode, so the originals stay put
|
|
3633
|
+
* whatever Explorer does with the pasted files.
|
|
3634
|
+
*
|
|
3635
|
+
* A failure is an ERROR, never a quiet "publish the originals instead": silently
|
|
3636
|
+
* handing the real paths to Explorer is exactly how files disappear.
|
|
3637
|
+
* @returns {Promise<{staged: string[], originals: string[], batchDir: string}>} the staged paths.
|
|
3638
|
+
*/
|
|
3639
|
+
async function stageClipboardCopy(root, paths) {
|
|
3640
|
+
await ensureIdeStateDir(root)
|
|
3641
|
+
const base = join(root, CLIPBOARD_STAGE_DIR)
|
|
3642
|
+
const batch = `${Date.now()}-${process.pid.toString(36)}${Math.random().toString(36).slice(2, 8)}`
|
|
3643
|
+
const batchDir = join(base, batch)
|
|
3644
|
+
const staged = []
|
|
3645
|
+
const originals = []
|
|
3646
|
+
const meter = { budget: CLIPBOARD_STAGE_MAX_BYTES }
|
|
3647
|
+
try {
|
|
3648
|
+
await mkdir(batchDir, { recursive: true })
|
|
3649
|
+
for (let index = 0; index < paths.length; index += 1) {
|
|
3650
|
+
const source = paths[index]
|
|
3651
|
+
const entryDir = join(batchDir, String(index))
|
|
3652
|
+
await mkdir(entryDir, { recursive: true })
|
|
3653
|
+
const target = join(entryDir, basename(source))
|
|
3654
|
+
await mirrorStagedEntry(source, target, meter)
|
|
3655
|
+
staged.push(target)
|
|
3656
|
+
originals.push(resolve(source))
|
|
3657
|
+
}
|
|
3658
|
+
await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged }), 'utf8')
|
|
3659
|
+
return { staged, originals, batchDir }
|
|
3660
|
+
} catch (error) {
|
|
3661
|
+
await rm(batchDir, { recursive: true, force: true }).catch(() => {})
|
|
3662
|
+
if (error instanceof TailError) throw error
|
|
3663
|
+
throw new TailError('clipboard-failed', `暂存这批内容失败:${messageOf(error)}`, 500)
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
3666
|
+
|
|
3667
|
+
/** staged path → original path for every batch still on disk. */
|
|
3668
|
+
async function clipboardStageMapping(root) {
|
|
3669
|
+
await ensureIdeStateDir(root)
|
|
3670
|
+
const base = join(root, CLIPBOARD_STAGE_DIR)
|
|
3671
|
+
const mapping = new Map()
|
|
3672
|
+
const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
|
|
3673
|
+
for (const entry of entries) {
|
|
3674
|
+
if (!entry.isDirectory()) continue
|
|
3675
|
+
const manifest = await readFile(join(base, entry.name, CLIPBOARD_STAGE_MANIFEST), 'utf8').catch(() => undefined)
|
|
3676
|
+
if (manifest === undefined) continue
|
|
3677
|
+
let parsed
|
|
3678
|
+
try {
|
|
3679
|
+
parsed = JSON.parse(manifest)
|
|
3680
|
+
} catch {
|
|
3681
|
+
continue
|
|
3682
|
+
}
|
|
3683
|
+
if (parsed === null || typeof parsed !== 'object') continue
|
|
3684
|
+
const staged = Array.isArray(parsed.staged) ? parsed.staged : []
|
|
3685
|
+
const originals = Array.isArray(parsed.originals) ? parsed.originals : []
|
|
3686
|
+
for (let index = 0; index < staged.length; index += 1) {
|
|
3687
|
+
if (typeof staged[index] === 'string' && typeof originals[index] === 'string') {
|
|
3688
|
+
mapping.set(resolve(staged[index]), originals[index])
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
}
|
|
3692
|
+
return mapping
|
|
3693
|
+
}
|
|
3694
|
+
|
|
3695
|
+
/** Workspace root for one clipboard call, or undefined when the scope is unknown. */
|
|
3696
|
+
function clipboardRoot(ctx, sessionId, cwd) {
|
|
3697
|
+
if (typeof sessionId !== 'string' || sessionId === '') return undefined
|
|
3698
|
+
try {
|
|
3699
|
+
return resolveCwd(ctx, sessionId, typeof cwd === 'string' && cwd !== '' ? cwd : undefined)
|
|
3700
|
+
} catch {
|
|
3701
|
+
return undefined
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
|
|
3705
|
+
/**
|
|
3706
|
+
* Read the workspace scope of a clipboard request.
|
|
3707
|
+
*
|
|
3708
|
+
* The page sends it as a QUERY string (`?sessionId=…&cwd=…`), same as every other
|
|
3709
|
+
* tree route; the POST body may carry the same two fields for old clients. Reading
|
|
3710
|
+
* only one of them is what made copy answer "复制到系统剪贴板需要 sessionId".
|
|
3711
|
+
* @param {object} body - the parsed JSON body (may be empty).
|
|
3712
|
+
* @param {URL} url - the request URL.
|
|
3713
|
+
* @returns {{sessionId: string, cwd: string}} whatever the request actually carried.
|
|
3714
|
+
*/
|
|
3715
|
+
export function clipboardScope(body, url) {
|
|
3716
|
+
const pick = (key) => {
|
|
3717
|
+
const fromBody = body !== null && typeof body === 'object' && typeof body[key] === 'string' ? body[key] : ''
|
|
3718
|
+
if (fromBody !== '') return fromBody
|
|
3719
|
+
return url.searchParams.get(key) ?? ''
|
|
3720
|
+
}
|
|
3721
|
+
return { sessionId: pick('sessionId'), cwd: pick('cwd') }
|
|
3722
|
+
}
|
|
3723
|
+
|
|
3724
|
+
/**
|
|
3725
|
+
* `POST /dsh-ris-ide/clipboard/files` — the tree's copy/cut mirrors the selection
|
|
3726
|
+
* onto the SYSTEM clipboard so it can be pasted into an OS file manager. The page
|
|
3727
|
+
* cannot do this itself (see {@link isWsl}); the Host owns the platform call.
|
|
3728
|
+
*/
|
|
3729
|
+
async function serveClipboardFiles(ctx, req, res, options) {
|
|
3730
|
+
try {
|
|
3731
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
3732
|
+
const body = await readJsonBody(req)
|
|
3733
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
3734
|
+
const scope = clipboardScope(body, url)
|
|
3735
|
+
const raw = Array.isArray(body.paths) ? body.paths : []
|
|
3736
|
+
const requested = raw.filter((path) => typeof path === 'string' && path.trim() !== '')
|
|
3737
|
+
if (requested.length === 0) throw new TailError('bad-request', 'paths is required', 400)
|
|
3738
|
+
// The OS clipboard can only describe REAL locations: a relative path has no
|
|
3739
|
+
// meaning outside the tree, so refuse it instead of stat-ing the plugin's cwd.
|
|
3740
|
+
const paths = requested.map((path) => (isAbsolute(path) ? resolve(path) : ''))
|
|
3741
|
+
if (paths.some((path) => path === '')) throw new TailError('bad-request', '复制到系统剪贴板需要绝对路径', 400)
|
|
3742
|
+
if (paths.length > CLIPBOARD_MAX_ENTRIES) throw new TailError('bad-request', `一次最多复制 ${CLIPBOARD_MAX_ENTRIES} 项`, 400)
|
|
3743
|
+
// The backends carry the list as "one path per line" data (never as code or as
|
|
3744
|
+
// flags). A name containing a line break or a NUL cannot be expressed that way,
|
|
3745
|
+
// and silently splitting it into two entries would put a wrong path on the
|
|
3746
|
+
// clipboard — refuse it instead.
|
|
3747
|
+
if (paths.some((path) => /[\u0000\r\n]/.test(path))) {
|
|
3748
|
+
throw new TailError('bad-request', '复制到系统剪贴板不支持路径里的换行或控制字符', 400)
|
|
3749
|
+
}
|
|
3750
|
+
if (Buffer.byteLength(`${paths.join('\n')}\n`, 'utf8') > CLIPBOARD_MAX_PAYLOAD) {
|
|
3751
|
+
throw new TailError('bad-request', '一次复制的路径总长度超出上限', 400)
|
|
3752
|
+
}
|
|
3753
|
+
for (const path of paths) {
|
|
3754
|
+
const info = await stat(path).catch(() => undefined)
|
|
3755
|
+
if (info === undefined) throw new TailError('not-found', `找不到「${path}」`, 404)
|
|
3756
|
+
}
|
|
3757
|
+
// A COPY goes out as a staged HARD-LINK mirror (see CLIPBOARD_STAGE_DIR): the
|
|
3758
|
+
// clipboard hands Explorer a different name for the same inode, so whatever it
|
|
3759
|
+
// does with the pasted files, the originals stay where they are. A CUT keeps
|
|
3760
|
+
// the real paths — cut means move, not "move a link".
|
|
3761
|
+
//
|
|
3762
|
+
// When the copy cannot be staged the route FAILS. Publishing the originals
|
|
3763
|
+
// instead would be a silent downgrade to exactly the behavior that lost files.
|
|
3764
|
+
const root = clipboardRoot(ctx, scope.sessionId, scope.cwd)
|
|
3765
|
+
let published = paths
|
|
3766
|
+
let staged = false
|
|
3767
|
+
if (body.cut !== true) {
|
|
3768
|
+
if (root === undefined) {
|
|
3769
|
+
throw new TailError('bad-request', '复制到系统剪贴板需要 sessionId', 400)
|
|
3770
|
+
}
|
|
3771
|
+
const rootInfo = await stat(root).catch(() => undefined)
|
|
3772
|
+
if (rootInfo === undefined || !rootInfo.isDirectory()) {
|
|
3773
|
+
throw new TailError('bad-request', `工作区不是目录:「${root}」`, 400)
|
|
3774
|
+
}
|
|
3775
|
+
const stage = await stageClipboardCopy(root, paths)
|
|
3776
|
+
published = stage.staged
|
|
3777
|
+
staged = true
|
|
3778
|
+
await pruneClipboardStage(root)
|
|
3779
|
+
}
|
|
3780
|
+
const result = await writeSystemFileClipboard(published, body.cut === true)
|
|
3781
|
+
writeJson(res, 200, { ok: true, count: published.length, method: result.method, staged, paths: published })
|
|
3782
|
+
} catch (error) {
|
|
3783
|
+
writeTailError(res, error)
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
|
|
3787
|
+
/**
|
|
3788
|
+
* PowerShell that PRINTS the clipboard's file list and text flavour — the reverse
|
|
3789
|
+
* of {@link windowsClipboardScript}. The output is line based (`F:<path>` per
|
|
3790
|
+
* file, one `T:<base64 utf8>` line), so nothing has to be re-escaped as code.
|
|
3791
|
+
*/
|
|
3792
|
+
export function windowsClipboardReadScript() {
|
|
3793
|
+
return [
|
|
3794
|
+
'[Console]::OutputEncoding = [Text.Encoding]::UTF8',
|
|
3795
|
+
'Add-Type -AssemblyName System.Windows.Forms',
|
|
3796
|
+
'$data = [System.Windows.Forms.Clipboard]::GetDataObject()',
|
|
3797
|
+
'$files = @()',
|
|
3798
|
+
'$text = ""',
|
|
3799
|
+
'if ($data -ne $null -and $data.GetDataPresent("FileDrop")) { $files = @($data.GetData("FileDrop")) }',
|
|
3800
|
+
'if ($data -ne $null -and $data.GetDataPresent("UnicodeText")) { $text = [string]$data.GetData("UnicodeText") }',
|
|
3801
|
+
'foreach ($file in $files) { [Console]::Out.WriteLine("F:" + [string]$file) }',
|
|
3802
|
+
'[Console]::Out.WriteLine("T:" + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$text)))',
|
|
3803
|
+
].join('\n')
|
|
3804
|
+
}
|
|
3805
|
+
|
|
3806
|
+
/**
|
|
3807
|
+
* Split {@link windowsClipboardReadScript}'s stdout into paths and text.
|
|
3808
|
+
* @param stdout - the script output.
|
|
3809
|
+
* @returns `{ files, text }` (paths are the raw Windows strings).
|
|
3810
|
+
*/
|
|
3811
|
+
export function parseClipboardRead(stdout) {
|
|
3812
|
+
const files = []
|
|
3813
|
+
let text = ''
|
|
3814
|
+
for (const rawLine of String(stdout ?? '').split('\n')) {
|
|
3815
|
+
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
|
|
3816
|
+
if (line.startsWith('F:')) files.push(line.slice(2))
|
|
3817
|
+
else if (line.startsWith('T:')) text = Buffer.from(line.slice(2), 'base64').toString('utf8')
|
|
3818
|
+
}
|
|
3819
|
+
return { files, text }
|
|
3820
|
+
}
|
|
3821
|
+
|
|
3822
|
+
/**
|
|
3823
|
+
* Map Windows clipboard paths onto this WSL filesystem — `/fs/import` needs a
|
|
3824
|
+
* real Linux path. Entries that cannot be mapped are dropped, never guessed.
|
|
3825
|
+
* @param rawPaths - paths as Windows wrote them (`\\wsl.localhost\…`, `C:\…`).
|
|
3826
|
+
* @param options - `distro` overrides `$WSL_DISTRO_NAME` (tests).
|
|
3827
|
+
* @returns absolute Linux paths, de-duplicated and capped.
|
|
3828
|
+
*/
|
|
3829
|
+
export function clipboardPathsToLinux(rawPaths, options = {}) {
|
|
3830
|
+
if (!Array.isArray(rawPaths)) return []
|
|
3831
|
+
const distro = String(options.distro ?? process.env.WSL_DISTRO_NAME ?? '').toLowerCase()
|
|
3832
|
+
const mapped = []
|
|
3833
|
+
const seen = new Set()
|
|
3834
|
+
for (const raw of rawPaths) {
|
|
3835
|
+
if (typeof raw !== 'string') continue
|
|
3836
|
+
const value = raw.trim()
|
|
3837
|
+
if (value === '') continue
|
|
3838
|
+
let path
|
|
3839
|
+
if (value.startsWith('/')) path = value
|
|
3840
|
+
else {
|
|
3841
|
+
const wsl = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)\\(.*)$/i.exec(value)
|
|
3842
|
+
const drive = /^([A-Za-z]):\\(.*)$/.exec(value)
|
|
3843
|
+
if (wsl !== null) {
|
|
3844
|
+
// A different distro's filesystem is not visible from here.
|
|
3845
|
+
if (distro !== '' && wsl[1].toLowerCase() !== distro) continue
|
|
3846
|
+
path = '/' + wsl[2].replace(/\\/g, '/')
|
|
3847
|
+
} else if (drive !== null) {
|
|
3848
|
+
path = '/mnt/' + drive[1].toLowerCase() + '/' + drive[2].replace(/\\/g, '/')
|
|
3849
|
+
} else continue
|
|
3850
|
+
}
|
|
3851
|
+
if (seen.has(path)) continue
|
|
3852
|
+
seen.add(path)
|
|
3853
|
+
mapped.push(path)
|
|
3854
|
+
if (mapped.length >= CLIPBOARD_MAX_ENTRIES) break
|
|
3855
|
+
}
|
|
3856
|
+
return mapped
|
|
3857
|
+
}
|
|
3858
|
+
|
|
3859
|
+
/** Extract `file://` URIs from a gnome-copied-files / text/uri-list payload. */
|
|
3860
|
+
function fileUrlsToPaths(text) {
|
|
3861
|
+
const files = []
|
|
3862
|
+
for (const rawLine of String(text ?? '').split('\n')) {
|
|
3863
|
+
const line = rawLine.trim()
|
|
3864
|
+
if (line === '' || line === 'copy' || line === 'cut') continue
|
|
3865
|
+
if (!line.startsWith('file://')) continue
|
|
3866
|
+
try {
|
|
3867
|
+
const url = new URL(line)
|
|
3868
|
+
if (url.protocol !== 'file:') continue
|
|
3869
|
+
files.push(decodeURIComponent(url.pathname))
|
|
3870
|
+
} catch {
|
|
3871
|
+
// An unparsable line is not a file; the next line still is.
|
|
3872
|
+
}
|
|
3873
|
+
if (files.length >= CLIPBOARD_MAX_ENTRIES) break
|
|
3874
|
+
}
|
|
3875
|
+
return files
|
|
3876
|
+
}
|
|
3877
|
+
|
|
3878
|
+
/**
|
|
3879
|
+
* Read the SYSTEM clipboard: the file list it carries plus its text flavour.
|
|
3880
|
+
* @returns `{ files, text, method }` — `files` are native (Linux) absolute paths.
|
|
3881
|
+
*/
|
|
3882
|
+
export async function readSystemFileClipboard() {
|
|
3883
|
+
if (process.platform === 'win32' || isWsl()) {
|
|
3884
|
+
const encoded = Buffer.from(windowsClipboardReadScript(), 'utf16le').toString('base64')
|
|
3885
|
+
const result = await runTool('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded])
|
|
3886
|
+
if (!result.ok) {
|
|
3887
|
+
throw new TailError('clipboard-failed', `PowerShell 读剪贴板失败:${(result.stderr || result.stdout).trim().split('\n')[0] || '未知错误'}`, 500)
|
|
3888
|
+
}
|
|
3889
|
+
const parsed = parseClipboardRead(result.stdout)
|
|
3890
|
+
return {
|
|
3891
|
+
files: IS_WINDOWS ? parsed.files : clipboardPathsToLinux(parsed.files),
|
|
3892
|
+
text: parsed.text,
|
|
3893
|
+
method: IS_WINDOWS ? 'windows-powershell' : 'wsl-powershell',
|
|
3894
|
+
}
|
|
3895
|
+
}
|
|
3896
|
+
if (process.platform === 'darwin') {
|
|
3897
|
+
// JXA: the file list is whatever NSURL objects the pasteboard exposes.
|
|
3898
|
+
const script = [
|
|
3899
|
+
'function run() {',
|
|
3900
|
+
' ObjC.import("AppKit")',
|
|
3901
|
+
' var pasteboard = $.NSPasteboard.generalPasteboard',
|
|
3902
|
+
' var files = []',
|
|
3903
|
+
' var urls = pasteboard.readObjectsForClassesOptions($([$.NSURL]), $({}))',
|
|
3904
|
+
' var count = urls ? Number(urls.count) : 0',
|
|
3905
|
+
' for (var index = 0; index < count; index += 1) { files.push(ObjC.unwrap(urls.objectAtIndex(index).path)) }',
|
|
3906
|
+
' var text = ObjC.unwrap(pasteboard.stringForType("public.utf8-plain-text"))',
|
|
3907
|
+
' return JSON.stringify({ files: files, text: text || "" })',
|
|
3908
|
+
'}',
|
|
3909
|
+
].join('\n')
|
|
3910
|
+
const result = await runTool('osascript', ['-l', 'JavaScript', '-e', script], undefined, 8000)
|
|
3911
|
+
if (!result.ok) {
|
|
3912
|
+
throw new TailError('clipboard-failed', `osascript 读剪贴板失败:${result.stderr.trim() || '未知错误'}`, 500)
|
|
3913
|
+
}
|
|
3914
|
+
let parsed = { files: [], text: '' }
|
|
3915
|
+
try {
|
|
3916
|
+
parsed = JSON.parse(result.stdout.trim() || '{}')
|
|
3917
|
+
} catch {
|
|
3918
|
+
parsed = { files: [], text: '' }
|
|
3919
|
+
}
|
|
3920
|
+
return {
|
|
3921
|
+
files: Array.isArray(parsed.files) ? parsed.files.filter((path) => typeof path === 'string' && path !== '') : [],
|
|
3922
|
+
text: typeof parsed.text === 'string' ? parsed.text : '',
|
|
3923
|
+
method: 'macos-appkit',
|
|
3924
|
+
}
|
|
3925
|
+
}
|
|
3926
|
+
// Linux desktop: xclip / wl-paste expose the SAME flavours the writer sets.
|
|
3927
|
+
const xclip = await runTool('xclip', ['-selection', 'clipboard', '-o', '-t', 'x-special/gnome-copied-files'], undefined, 8000)
|
|
3928
|
+
if (xclip.ok) return { files: fileUrlsToPaths(xclip.stdout), text: '', method: 'linux-xclip' }
|
|
3929
|
+
const wlPaste = await runTool('wl-paste', ['--type', 'text/uri-list'], undefined, 8000)
|
|
3930
|
+
if (wlPaste.ok) return { files: fileUrlsToPaths(wlPaste.stdout), text: '', method: 'linux-wl-paste' }
|
|
3931
|
+
return { files: [], text: '', method: 'unsupported' }
|
|
3932
|
+
}
|
|
3933
|
+
|
|
3934
|
+
/**
|
|
3935
|
+
* `GET /dsh-ris-ide/clipboard/read` — what the SYSTEM clipboard holds right now.
|
|
3936
|
+
* Read-only: it never writes the clipboard and never touches the filesystem.
|
|
3937
|
+
*/
|
|
3938
|
+
async function serveClipboardRead(ctx, req, res) {
|
|
3939
|
+
try {
|
|
3940
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
3941
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
3942
|
+
const root = clipboardRoot(ctx, url.searchParams.get('sessionId') ?? '', url.searchParams.get('cwd') ?? '')
|
|
3943
|
+
const state = await readSystemFileClipboard()
|
|
3944
|
+
// A copy the tree published sits on the clipboard as a STAGED path. Translate
|
|
3945
|
+
// it back: the page compares against what the tree copied, so a round-trip must
|
|
3946
|
+
// look like the original selection (otherwise Ctrl+C → Ctrl+V would import a
|
|
3947
|
+
// second copy of files the tree already has).
|
|
3948
|
+
let files = state.files
|
|
3949
|
+
if (root !== undefined) {
|
|
3950
|
+
const mapping = await clipboardStageMapping(root)
|
|
3951
|
+
if (mapping.size > 0) files = files.map((path) => mapping.get(resolve(path)) ?? path)
|
|
3952
|
+
}
|
|
3953
|
+
writeJson(res, 200, { ok: true, files, text: state.text, method: state.method })
|
|
3954
|
+
} catch (error) {
|
|
3955
|
+
writeTailError(res, error)
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
|
|
2754
3959
|
/** Content types the media route can serve inline (`<img>`, `<iframe>`). */
|
|
2755
3960
|
const FS_MEDIA_TYPES = {
|
|
2756
3961
|
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
|
|
@@ -2840,6 +4045,42 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
2840
4045
|
writeJson(res, 200, { ok: true, kind: 'text-window', offset: from, next, eof: next >= info.size, size: info.size, mtimeMs: info.mtimeMs, text })
|
|
2841
4046
|
}
|
|
2842
4047
|
|
|
4048
|
+
/** Suffix of the sibling file a chunked save is staged in before the rename. */
|
|
4049
|
+
const FS_WRITE_TEMP_SUFFIX = '.dsh-ris-ide-saving'
|
|
4050
|
+
|
|
4051
|
+
/**
|
|
4052
|
+
* Write ONE chunk of a chunked `POST /fs/write`.
|
|
4053
|
+
*
|
|
4054
|
+
* The chunks land in `<target>.dsh-ris-ide-saving` at their byte offset (so a
|
|
4055
|
+
* retried chunk overwrites itself instead of appending twice) and only the chunk
|
|
4056
|
+
* with `final !== false` truncates to `offset + bytes` and renames the temp file
|
|
4057
|
+
* over the target. A reader therefore sees the old file or the new one, never a
|
|
4058
|
+
* half-written mixed document, and a failed save leaves the target untouched.
|
|
4059
|
+
*
|
|
4060
|
+
* @param target - absolute path the editor is saving.
|
|
4061
|
+
* @param body - `{content, offset, final}` from the request.
|
|
4062
|
+
*/
|
|
4063
|
+
async function writeChunk(target, body) {
|
|
4064
|
+
const offset = body.offset
|
|
4065
|
+
if (!Number.isInteger(offset) || offset < 0) throw new TailError('bad-request', 'offset must be a non-negative integer', 400)
|
|
4066
|
+
const buffer = Buffer.from(body.content, 'utf8')
|
|
4067
|
+
const staging = `${target}${FS_WRITE_TEMP_SUFFIX}`
|
|
4068
|
+
if (offset === 0) await writeFile(staging, '')
|
|
4069
|
+
// Chunks must be contiguous: a lost chunk would otherwise leave zero bytes in
|
|
4070
|
+
// the middle of the document, which is worse than refusing the save.
|
|
4071
|
+
const present = offset === 0 ? { size: 0 } : await stat(staging).catch(() => undefined)
|
|
4072
|
+
if (present === undefined) throw new TailError('chunk-out-of-order', 'the previous chunk never arrived; save again', 409)
|
|
4073
|
+
if (present.size !== offset) throw new TailError('chunk-out-of-order', 'a chunk is missing; save again', 409)
|
|
4074
|
+
const handle = await open(staging, 'r+')
|
|
4075
|
+
try {
|
|
4076
|
+
await handle.write(buffer, 0, buffer.length, offset)
|
|
4077
|
+
if (body.final !== false) await handle.truncate(offset + buffer.length)
|
|
4078
|
+
} finally {
|
|
4079
|
+
await handle.close()
|
|
4080
|
+
}
|
|
4081
|
+
if (body.final !== false) await rename(staging, target)
|
|
4082
|
+
}
|
|
4083
|
+
|
|
2843
4084
|
/**
|
|
2844
4085
|
* The IDE's own workspace file API — no `dsh-better-sidebar` involved.
|
|
2845
4086
|
*
|
|
@@ -2847,6 +4088,9 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
2847
4088
|
* or `{ok:true, kind:'binary'|'too-large', size, message}` (the caller decides
|
|
2848
4089
|
* how to render those).
|
|
2849
4090
|
* - `POST /fs/write` `{sessionId, path, cwd?, content}` → `{ok, mtimeMs}`.
|
|
4091
|
+
* With `{offset, final}` it is ONE CHUNK of a chunked save: the bytes are written
|
|
4092
|
+
* at `offset` into a sibling temp file and the LAST chunk renames it over the
|
|
4093
|
+
* target, so a save is never seen half-written and has no practical size cap.
|
|
2850
4094
|
* - `GET /fs/file?sessionId&path` → raw bytes with the media content-type.
|
|
2851
4095
|
*
|
|
2852
4096
|
* All three are loopback-fenced and resolve the path exactly like `/tail` does.
|
|
@@ -2857,7 +4101,12 @@ async function serveFs(ctx, req, res, options) {
|
|
|
2857
4101
|
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
2858
4102
|
const pathname = url.pathname
|
|
2859
4103
|
if (pathname === FS_WRITE_PATH) {
|
|
2860
|
-
|
|
4104
|
+
// A save carries the entire document: give this one route its own (much
|
|
4105
|
+
// larger) cap and say so in Chinese when even that is exceeded.
|
|
4106
|
+
const writeCap = typeof options?.maxWriteBytes === 'number' && options.maxWriteBytes > 0
|
|
4107
|
+
? options.maxWriteBytes
|
|
4108
|
+
: FS_WRITE_MAX_BODY_BYTES
|
|
4109
|
+
const body = await readJsonBody(req, writeCap, `文件太大(超过 ${Math.floor(writeCap / (1024 * 1024))} MB),不能在这里保存;请改用其他编辑器`)
|
|
2861
4110
|
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
2862
4111
|
const raw = typeof body.path === 'string' ? body.path : ''
|
|
2863
4112
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
@@ -2867,6 +4116,21 @@ async function serveFs(ctx, req, res, options) {
|
|
|
2867
4116
|
const target = resolvePath(cwd, raw, options?.restrictToCwd === true)
|
|
2868
4117
|
const info = await stat(target).catch(() => undefined)
|
|
2869
4118
|
if (info !== undefined && !info.isFile()) throw new TailError('not-a-file', `"${target}" is not a regular file`, 400)
|
|
4119
|
+
// Chunked saves are marked by `offset`; every other request keeps the old
|
|
4120
|
+
// one-shot behaviour. Both paths end with a rename-free / rename-based
|
|
4121
|
+
// write of exactly the bytes the editor held.
|
|
4122
|
+
if (typeof body.offset === 'number' && Number.isFinite(body.offset)) {
|
|
4123
|
+
await writeChunk(target, body)
|
|
4124
|
+
const afterChunk = await stat(target).catch(() => undefined)
|
|
4125
|
+
writeJson(res, 200, {
|
|
4126
|
+
ok: true,
|
|
4127
|
+
path: target,
|
|
4128
|
+
chunked: true,
|
|
4129
|
+
final: body.final !== false,
|
|
4130
|
+
mtimeMs: afterChunk === undefined ? undefined : afterChunk.mtimeMs,
|
|
4131
|
+
})
|
|
4132
|
+
return
|
|
4133
|
+
}
|
|
2870
4134
|
await writeFile(target, body.content, 'utf8')
|
|
2871
4135
|
const after = await stat(target).catch(() => undefined)
|
|
2872
4136
|
writeJson(res, 200, { ok: true, path: target, mtimeMs: after === undefined ? undefined : after.mtimeMs })
|
|
@@ -2971,6 +4235,141 @@ async function readFileRange(path, start, end) {
|
|
|
2971
4235
|
* grows, `: ping` comments keep proxies quiet. EventSource reconnects by itself,
|
|
2972
4236
|
* so a restart of `dsh web` self-heals; the JSON routes remain as fallbacks.
|
|
2973
4237
|
*/
|
|
4238
|
+
/**
|
|
4239
|
+
* Drop window entries whose stream has been gone for a while. A plain reload
|
|
4240
|
+
* closes and reopens the stream within a second, so the grace period keeps the
|
|
4241
|
+
* entry alive across it instead of flickering "no window".
|
|
4242
|
+
* @param now - current epoch ms (tests pass a fixed clock).
|
|
4243
|
+
*/
|
|
4244
|
+
function sweepIdeWindows(now = Date.now()) {
|
|
4245
|
+
for (const [key, entry] of IDE_WINDOWS) {
|
|
4246
|
+
if (entry.streams <= 0 && now - entry.at > IDE_WINDOW_GRACE_MS) IDE_WINDOWS.delete(key)
|
|
4247
|
+
}
|
|
4248
|
+
}
|
|
4249
|
+
|
|
4250
|
+
/** The registry key of one IDE window: its name when the page knows it, else its cwd. */
|
|
4251
|
+
function ideWindowKey(name, cwd) {
|
|
4252
|
+
if (typeof name === 'string' && name !== '') return `name:${name}`
|
|
4253
|
+
if (typeof cwd === 'string' && cwd !== '') return `cwd:${resolve(cwd)}`
|
|
4254
|
+
return undefined
|
|
4255
|
+
}
|
|
4256
|
+
|
|
4257
|
+
/** One IDE window's stream opened: remember it (the stream IS the liveness). */
|
|
4258
|
+
function ideWindowOpened(key, info) {
|
|
4259
|
+
if (typeof key !== 'string' || key === '') return
|
|
4260
|
+
const previous = IDE_WINDOWS.get(key)
|
|
4261
|
+
IDE_WINDOWS.set(key, {
|
|
4262
|
+
key,
|
|
4263
|
+
name: typeof info?.name === 'string' ? info.name : previous !== undefined ? previous.name : '',
|
|
4264
|
+
cwd: typeof info?.cwd === 'string' ? info.cwd : previous !== undefined ? previous.cwd : undefined,
|
|
4265
|
+
sessionId: typeof info?.sessionId === 'string' && info.sessionId !== ''
|
|
4266
|
+
? info.sessionId
|
|
4267
|
+
: previous !== undefined ? previous.sessionId : '',
|
|
4268
|
+
at: Date.now(),
|
|
4269
|
+
streams: (previous !== undefined ? previous.streams : 0) + 1,
|
|
4270
|
+
})
|
|
4271
|
+
}
|
|
4272
|
+
|
|
4273
|
+
/** One IDE window's stream closed (the entry survives until the grace expires). */
|
|
4274
|
+
function ideWindowClosed(key) {
|
|
4275
|
+
if (typeof key !== 'string' || key === '') return
|
|
4276
|
+
const entry = IDE_WINDOWS.get(key)
|
|
4277
|
+
if (entry === undefined) return
|
|
4278
|
+
entry.streams = Math.max(0, entry.streams - 1)
|
|
4279
|
+
entry.at = Date.now()
|
|
4280
|
+
}
|
|
4281
|
+
|
|
4282
|
+
/**
|
|
4283
|
+
* List live IDE windows, optionally only one window name or one workspace.
|
|
4284
|
+
* @param {{name?: string, cwd?: string}} [filter] - narrow by window name and/or cwd.
|
|
4285
|
+
* @returns `[{ name, cwd, sessionId, alive, idleMs }]`, most recently seen first.
|
|
4286
|
+
*/
|
|
4287
|
+
export function listIdeWindows(filter) {
|
|
4288
|
+
sweepIdeWindows()
|
|
4289
|
+
const wantedName = typeof filter?.name === 'string' && filter.name !== '' ? filter.name : undefined
|
|
4290
|
+
const wantedCwd = typeof filter?.cwd === 'string' && filter.cwd !== '' ? resolve(filter.cwd) : undefined
|
|
4291
|
+
const now = Date.now()
|
|
4292
|
+
const out = []
|
|
4293
|
+
for (const entry of IDE_WINDOWS.values()) {
|
|
4294
|
+
if (wantedName !== undefined && entry.name !== wantedName) continue
|
|
4295
|
+
if (wantedCwd !== undefined && entry.cwd !== wantedCwd) continue
|
|
4296
|
+
out.push({
|
|
4297
|
+
name: entry.name,
|
|
4298
|
+
cwd: entry.cwd,
|
|
4299
|
+
sessionId: entry.sessionId,
|
|
4300
|
+
alive: entry.streams > 0,
|
|
4301
|
+
idleMs: now - entry.at,
|
|
4302
|
+
})
|
|
4303
|
+
}
|
|
4304
|
+
out.sort((a, b) => a.idleMs - b.idleMs)
|
|
4305
|
+
return out
|
|
4306
|
+
}
|
|
4307
|
+
|
|
4308
|
+
/**
|
|
4309
|
+
* The DSH session a workspace currently belongs to: the newest LIVE session whose
|
|
4310
|
+
* header cwd is that workspace. A window that outlived its session (or the host
|
|
4311
|
+
* restart) uses this to hop onto the current one instead of staying on a dead id.
|
|
4312
|
+
* @param ctx - the Host context (`ctx.sessions` is the session store).
|
|
4313
|
+
* @param cwd - the workspace.
|
|
4314
|
+
* @returns `{ id }`, or `null` when no live session sits in that workspace.
|
|
4315
|
+
*/
|
|
4316
|
+
export function liveSessionFor(ctx, cwd) {
|
|
4317
|
+
if (typeof cwd !== 'string' || cwd === '') return null
|
|
4318
|
+
let live
|
|
4319
|
+
try {
|
|
4320
|
+
live = ctx?.sessions?.list?.()
|
|
4321
|
+
} catch {
|
|
4322
|
+
return null
|
|
4323
|
+
}
|
|
4324
|
+
if (!Array.isArray(live)) return null
|
|
4325
|
+
const root = resolve(cwd)
|
|
4326
|
+
// The IDE is workspace-level: a window opened inside a program folder still
|
|
4327
|
+
// belongs to the workspace's session, so an ancestor cwd matches too — but an
|
|
4328
|
+
// exact match always wins over an ancestor one.
|
|
4329
|
+
let ancestor
|
|
4330
|
+
for (let index = live.length - 1; index >= 0; index -= 1) {
|
|
4331
|
+
const session = live[index]
|
|
4332
|
+
const sessionCwd = session?.header?.cwd
|
|
4333
|
+
if (typeof sessionCwd !== 'string' || sessionCwd === '') continue
|
|
4334
|
+
const base = resolve(sessionCwd)
|
|
4335
|
+
if (base === root) return { id: session.id }
|
|
4336
|
+
if (ancestor === undefined && root.startsWith(base.endsWith('/') ? base : `${base}/`)) ancestor = { id: session.id }
|
|
4337
|
+
}
|
|
4338
|
+
return ancestor ?? null
|
|
4339
|
+
}
|
|
4340
|
+
|
|
4341
|
+
/** Whether `id` is still a live session here (a stale window id stops being one). */
|
|
4342
|
+
function isLiveSession(ctx, id) {
|
|
4343
|
+
if (typeof id !== 'string' || id === '') return false
|
|
4344
|
+
try {
|
|
4345
|
+
return ctx?.sessions?.get?.(id) !== undefined
|
|
4346
|
+
} catch {
|
|
4347
|
+
// A detached id throws instead of answering: treat it as gone.
|
|
4348
|
+
return false
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
|
|
4352
|
+
/** `GET /dsh-ris-ide/windows` — the live windows, and the session of one workspace. */
|
|
4353
|
+
async function serveWindows(ctx, req, res) {
|
|
4354
|
+
try {
|
|
4355
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
4356
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
4357
|
+
const rawCwd = url.searchParams.get('cwd') ?? ''
|
|
4358
|
+
if (rawCwd !== '' && !isAbsolute(expandHome(rawCwd))) {
|
|
4359
|
+
throw new TailError('bad-request', 'cwd must be an absolute workspace path', 400)
|
|
4360
|
+
}
|
|
4361
|
+
const cwd = rawCwd === '' ? undefined : resolve(expandHome(rawCwd))
|
|
4362
|
+
const name = (url.searchParams.get('name') ?? '').trim()
|
|
4363
|
+
writeJson(res, 200, {
|
|
4364
|
+
ok: true,
|
|
4365
|
+
windows: listIdeWindows({ name: name === '' ? undefined : name, cwd }),
|
|
4366
|
+
session: cwd === undefined ? null : liveSessionFor(ctx, cwd),
|
|
4367
|
+
})
|
|
4368
|
+
} catch (error) {
|
|
4369
|
+
writeTailError(res, error)
|
|
4370
|
+
}
|
|
4371
|
+
}
|
|
4372
|
+
|
|
2974
4373
|
async function serveStream(ctx, req, res, options) {
|
|
2975
4374
|
let url
|
|
2976
4375
|
try {
|
|
@@ -3015,7 +4414,38 @@ async function serveStream(ctx, req, res, options) {
|
|
|
3015
4414
|
})
|
|
3016
4415
|
res.flushHeaders?.()
|
|
3017
4416
|
|
|
4417
|
+
// A standalone IDE window keeps ONE stream for its whole lifetime, so that
|
|
4418
|
+
// connection IS its liveness: `dsh web` restarts, the page reconnects, the
|
|
4419
|
+
// window re-registers by itself — no heartbeat, no stored state to go stale.
|
|
4420
|
+
const isIdeWindow = url.searchParams.get('window') === '1'
|
|
4421
|
+
// The window's workspace does NOT depend on the requested topics: a window whose
|
|
4422
|
+
// first connection only asks for `hello` never needs a resolved cwd, yet it must
|
|
4423
|
+
// still register (otherwise the ⧉ button sees no window and opens a second one).
|
|
4424
|
+
const rawWindowCwd = isIdeWindow ? (url.searchParams.get('cwd') ?? '').trim() : ''
|
|
4425
|
+
const windowCwd = isIdeWindow
|
|
4426
|
+
? (typeof cwd === 'string' ? cwd : (rawWindowCwd !== '' && isAbsolute(rawWindowCwd) ? resolve(rawWindowCwd) : undefined))
|
|
4427
|
+
: undefined
|
|
4428
|
+
const helloCwd = typeof cwd === 'string' ? cwd : windowCwd
|
|
4429
|
+
const streamWindowName = (url.searchParams.get('wname') ?? '').trim()
|
|
4430
|
+
const windowKey = windowCwd !== undefined ? ideWindowKey(streamWindowName, windowCwd) : undefined
|
|
4431
|
+
if (windowKey !== undefined) {
|
|
4432
|
+
ideWindowOpened(windowKey, {
|
|
4433
|
+
name: streamWindowName,
|
|
4434
|
+
cwd: windowCwd,
|
|
4435
|
+
sessionId: (url.searchParams.get('sessionId') ?? '').trim(),
|
|
4436
|
+
})
|
|
4437
|
+
}
|
|
4438
|
+
|
|
3018
4439
|
let closed = false
|
|
4440
|
+
// The window entry must be released exactly once: an aborted SSE connection may
|
|
4441
|
+
// report 'error' and then 'close' (and a clean reload only reports 'close'), and
|
|
4442
|
+
// double-decrementing would hide a real second stream.
|
|
4443
|
+
let windowSettled = false
|
|
4444
|
+
const settleWindow = () => {
|
|
4445
|
+
if (windowSettled === true) return
|
|
4446
|
+
windowSettled = true
|
|
4447
|
+
if (windowKey !== undefined) ideWindowClosed(windowKey)
|
|
4448
|
+
}
|
|
3019
4449
|
const cleanups = []
|
|
3020
4450
|
const send = (event, payload) => {
|
|
3021
4451
|
if (closed) return false
|
|
@@ -3032,7 +4462,22 @@ async function serveStream(ctx, req, res, options) {
|
|
|
3032
4462
|
return false
|
|
3033
4463
|
}
|
|
3034
4464
|
}
|
|
3035
|
-
|
|
4465
|
+
const streamSession = (url.searchParams.get('sessionId') ?? '').trim()
|
|
4466
|
+
send('hello', {
|
|
4467
|
+
ok: true,
|
|
4468
|
+
version: PKG_VERSION,
|
|
4469
|
+
root: cwd,
|
|
4470
|
+
topics,
|
|
4471
|
+
window: windowCwd !== undefined,
|
|
4472
|
+
// The session this workspace is on RIGHT NOW. A window left open across a
|
|
4473
|
+
// `dsh web` restart reads this and follows the new session instead of
|
|
4474
|
+
// keeping the dead id it was opened with.
|
|
4475
|
+
session: helloCwd === undefined ? null : liveSessionFor(ctx, helloCwd),
|
|
4476
|
+
// Whether the id this stream asked for is still a live session here: false
|
|
4477
|
+
// means "the page may switch to `session`", null means it never had one.
|
|
4478
|
+
windowSession: streamSession === '' ? null
|
|
4479
|
+
: { id: streamSession, live: isLiveSession(ctx, streamSession) },
|
|
4480
|
+
})
|
|
3036
4481
|
|
|
3037
4482
|
const heartbeat = setInterval(() => {
|
|
3038
4483
|
if (closed) return
|
|
@@ -3046,12 +4491,16 @@ async function serveStream(ctx, req, res, options) {
|
|
|
3046
4491
|
|
|
3047
4492
|
res.on('error', () => {
|
|
3048
4493
|
// An aborted SSE connection emits 'error'; without a listener Node would
|
|
3049
|
-
// treat it as an uncaught exception.
|
|
4494
|
+
// treat it as an uncaught exception. The stream is gone either way, so free
|
|
4495
|
+
// the window registration here too (a window stuck "alive" would make the next
|
|
4496
|
+
// ⧉ wait out its close handshake against a window that is not there).
|
|
3050
4497
|
closed = true
|
|
4498
|
+
settleWindow()
|
|
3051
4499
|
})
|
|
3052
4500
|
res.on('close', () => {
|
|
3053
4501
|
closed = true
|
|
3054
4502
|
clearInterval(heartbeat)
|
|
4503
|
+
settleWindow()
|
|
3055
4504
|
for (const cleanup of cleanups) {
|
|
3056
4505
|
try {
|
|
3057
4506
|
cleanup()
|
|
@@ -3384,7 +4833,7 @@ function sourcesJarOf(jar) {
|
|
|
3384
4833
|
}
|
|
3385
4834
|
|
|
3386
4835
|
/**
|
|
3387
|
-
* The dependency-source cache (`<cwd>/.dsh-ris-ide
|
|
4836
|
+
* The dependency-source cache (`<cwd>/.dsh-ris-ide/cache/`) is keyed by a
|
|
3388
4837
|
* FINGERPRINT of its inputs (jar path+size+mtime and the entry's name/size/crc,
|
|
3389
4838
|
* plus the decompiler jar+args), not by file age: a rebuilt jar invalidates its
|
|
3390
4839
|
* derived files immediately. `manifest.json` remembers those fingerprints, and a
|
|
@@ -3458,7 +4907,7 @@ async function cacheFiles(root) {
|
|
|
3458
4907
|
/**
|
|
3459
4908
|
* Drop aged files first, then the least-recently-written ones until the cache
|
|
3460
4909
|
* fits its size/file budget. Rate-limited so a burst of resolves prunes once.
|
|
3461
|
-
* @param {string} root - the `.dsh-ris-ide
|
|
4910
|
+
* @param {string} root - the `.dsh-ris-ide/cache` directory.
|
|
3462
4911
|
* @param {{maxBytes?: number, maxFiles?: number, maxAgeMs?: number, force?: boolean}} [options]
|
|
3463
4912
|
*/
|
|
3464
4913
|
export async function pruneIdeCache(root, options) {
|
|
@@ -3507,6 +4956,7 @@ export async function pruneIdeCache(root, options) {
|
|
|
3507
4956
|
* still exists, otherwise produced and written (then the cache GC may run).
|
|
3508
4957
|
*/
|
|
3509
4958
|
async function cachedSource(cwd, kind, className, suffix, key, produce) {
|
|
4959
|
+
await ensureIdeStateDir(cwd)
|
|
3510
4960
|
const root = join(cwd, IDE_CACHE_DIR)
|
|
3511
4961
|
const rel = kind + '/' + className + suffix
|
|
3512
4962
|
const target = join(root, rel)
|
|
@@ -3546,10 +4996,10 @@ function runCapture(command, args, cwd) {
|
|
|
3546
4996
|
})
|
|
3547
4997
|
}
|
|
3548
4998
|
|
|
3549
|
-
/** The user's decompiler choice: `.dsh-ris-ide
|
|
4999
|
+
/** The user's decompiler choice: `.dsh-ris-ide/settings.json` first, then `.dsh-ris-ide/config.json`. */
|
|
3550
5000
|
async function readDecompilerConfig(cwd) {
|
|
3551
|
-
|
|
3552
|
-
|
|
5001
|
+
let settingsText = await readTextIfSmall(resolve(cwd, IDE_SETTINGS_FILENAME))
|
|
5002
|
+
if (settingsText === undefined) settingsText = await readTextIfSmall(resolve(cwd, LEGACY_SETTINGS_FILENAME))
|
|
3553
5003
|
if (settingsText !== undefined) {
|
|
3554
5004
|
const parsed = parseJsonc(settingsText)
|
|
3555
5005
|
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
@@ -3559,7 +5009,8 @@ async function readDecompilerConfig(cwd) {
|
|
|
3559
5009
|
}
|
|
3560
5010
|
}
|
|
3561
5011
|
}
|
|
3562
|
-
|
|
5012
|
+
let configText = await readTextIfSmall(resolve(cwd, CONFIG_FILENAME))
|
|
5013
|
+
if (configText === undefined) configText = await readTextIfSmall(resolve(cwd, LEGACY_CONFIG_FILENAME))
|
|
3563
5014
|
if (configText === undefined) return undefined
|
|
3564
5015
|
const parsed = parseJsonc(configText)
|
|
3565
5016
|
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
|
@@ -3671,7 +5122,7 @@ async function serveDebugSource(ctx, req, res, options) {
|
|
|
3671
5122
|
|
|
3672
5123
|
/**
|
|
3673
5124
|
* `/dsh-ris-ide/settings`: GET returns the visual debug settings, POST saves the
|
|
3674
|
-
* decompiler jar into `.dsh-ris-ide
|
|
5125
|
+
* decompiler jar into `.dsh-ris-ide/settings.json` (the program config stays
|
|
3675
5126
|
* untouched — rewriting JSONC would drop the user's comments).
|
|
3676
5127
|
*/
|
|
3677
5128
|
async function serveSettings(ctx, req, res, options) {
|
|
@@ -3685,6 +5136,7 @@ async function serveSettings(ctx, req, res, options) {
|
|
|
3685
5136
|
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
3686
5137
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
3687
5138
|
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5139
|
+
await ensureIdeStateDir(cwd)
|
|
3688
5140
|
const path = settingsPathOf(cwd)
|
|
3689
5141
|
const existingText = await readTextIfSmall(path)
|
|
3690
5142
|
const existing = existingText === undefined ? {} : parseJsonc(existingText)
|
|
@@ -3700,6 +5152,7 @@ async function serveSettings(ctx, req, res, options) {
|
|
|
3700
5152
|
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
3701
5153
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
3702
5154
|
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
|
|
5155
|
+
await ensureIdeStateDir(cwd)
|
|
3703
5156
|
const config = await readDecompilerConfig(cwd)
|
|
3704
5157
|
writeJson(res, 200, {
|
|
3705
5158
|
ok: true,
|
|
@@ -4789,7 +6242,7 @@ export function buildStartSpec(program, context) {
|
|
|
4789
6242
|
? program.mainClass
|
|
4790
6243
|
: (launchMainClass ?? program.mainClass)
|
|
4791
6244
|
const args = resolveSpringArgs(program, workspace)
|
|
4792
|
-
// User JVM flags (memory, GC, agents) come from `.dsh-ris-ide.json`; they sit
|
|
6245
|
+
// User JVM flags (memory, GC, agents) come from `.dsh-ris-ide/config.json`; they sit
|
|
4793
6246
|
// after the plugin's required -D flags so a deliberate override still wins.
|
|
4794
6247
|
const jvmArgs = normalizeStringArray(program.jvmArgs) ?? []
|
|
4795
6248
|
// Debug mode adds the JDWP agent before the user's own JVM flags.
|
|
@@ -5182,7 +6635,7 @@ export function parseJsonc(text) {
|
|
|
5182
6635
|
|
|
5183
6636
|
// ── User program config (generated from a scan, then user-maintained) ────────
|
|
5184
6637
|
//
|
|
5185
|
-
// The panel can write `<workspace>/.dsh-ris-ide.json` from what it discovered.
|
|
6638
|
+
// The panel can write `<workspace>/.dsh-ris-ide/config.json` from what it discovered.
|
|
5186
6639
|
// After that the file belongs to the user: entries override discovered programs
|
|
5187
6640
|
// by id (then dir, then name), entries that match nothing become user-added
|
|
5188
6641
|
// programs, `disabled: true` hides a row, and `startCommand` replaces the
|
|
@@ -5195,8 +6648,16 @@ export function parseJsonc(text) {
|
|
|
5195
6648
|
* @returns `{ path, exists, entries, error }`; `entries` only holds valid rows.
|
|
5196
6649
|
*/
|
|
5197
6650
|
export async function readProgramConfig(cwd) {
|
|
5198
|
-
|
|
5199
|
-
|
|
6651
|
+
let path = resolve(cwd, CONFIG_FILENAME)
|
|
6652
|
+
let text = await readTextIfSmall(path)
|
|
6653
|
+
if (text === undefined) {
|
|
6654
|
+
const legacy = resolve(cwd, LEGACY_CONFIG_FILENAME)
|
|
6655
|
+
const legacyText = await readTextIfSmall(legacy)
|
|
6656
|
+
if (legacyText !== undefined) {
|
|
6657
|
+
path = legacy
|
|
6658
|
+
text = legacyText
|
|
6659
|
+
}
|
|
6660
|
+
}
|
|
5200
6661
|
if (text === undefined) return { path, exists: false, entries: [], error: undefined }
|
|
5201
6662
|
const parsed = parseJsonc(text)
|
|
5202
6663
|
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
@@ -5475,6 +6936,7 @@ export function buildConfigDocument(programs, workspace) {
|
|
|
5475
6936
|
/** Write the generated config (refuses to clobber an existing file unless asked). */
|
|
5476
6937
|
async function writeProgramConfig(cwd, logsDir, mode, fresh = false) {
|
|
5477
6938
|
if (fresh) discoveryCache.delete(resolve(cwd))
|
|
6939
|
+
await ensureIdeStateDir(cwd)
|
|
5478
6940
|
const path = resolve(cwd, CONFIG_FILENAME)
|
|
5479
6941
|
const exists = existsSync(path)
|
|
5480
6942
|
if (exists && mode !== 'update' && mode !== 'overwrite') {
|
|
@@ -5773,7 +7235,7 @@ export function registerAgentTools(ctx, options) {
|
|
|
5773
7235
|
description: 'Start one discovered program (Spring Boot: mvn -Pdev compile then exec java; frontend: exec <pm> run <script>), wrapped by run-with-log.sh so it gets a log file, a pidfile and the sidebar stop button. '
|
|
5774
7236
|
+ 'Resolve the program with ris_dev_programs and check ris_dev_status first; give its id, or a unique name fragment. '
|
|
5775
7237
|
+ 'Starting an already-running program is NOT an error: it returns alreadyRunning=true without touching it; use ris_dev_restart to restart it. '
|
|
5776
|
-
+ 'JVM options (memory, GC) come from the workspace config `.dsh-ris-ide.json` (`defaults.jvmArgs` / per-program `jvmArgs`), not from this call.',
|
|
7238
|
+
+ 'JVM options (memory, GC) come from the workspace config `.dsh-ris-ide/config.json` (`defaults.jvmArgs` / per-program `jvmArgs`), not from this call.',
|
|
5777
7239
|
parameters: {
|
|
5778
7240
|
type: 'object',
|
|
5779
7241
|
additionalProperties: false,
|
|
@@ -6486,6 +7948,17 @@ export const __test = {
|
|
|
6486
7948
|
CONTENT_SEARCH_PATH,
|
|
6487
7949
|
searchWorkspaceContent,
|
|
6488
7950
|
serveContentSearch,
|
|
7951
|
+
// streamed (paged) variants: NDJSON frames while the repo roots are searched in parallel
|
|
7952
|
+
SEARCH_STREAM_PATH,
|
|
7953
|
+
CONTENT_SEARCH_STREAM_PATH,
|
|
7954
|
+
SEARCH_STREAM_PAGE_DEFAULT,
|
|
7955
|
+
SEARCH_STREAM_PAGE_MAX,
|
|
7956
|
+
SEARCH_STREAM_CONCURRENCY,
|
|
7957
|
+
searchWorkspaceFilesStream,
|
|
7958
|
+
searchWorkspaceContentStream,
|
|
7959
|
+
serveSearchStream,
|
|
7960
|
+
createOrderedPages,
|
|
7961
|
+
streamGitStdout,
|
|
6489
7962
|
// one-module `mvn test` runner (poll the console through GET ?id=)
|
|
6490
7963
|
RUN_TEST_PATH,
|
|
6491
7964
|
serveRunTestStart,
|
|
@@ -6618,6 +8091,12 @@ export const __test = {
|
|
|
6618
8091
|
STREAM_PATH,
|
|
6619
8092
|
BUNDLE_PATH,
|
|
6620
8093
|
WINDOW_PAGE_PATH,
|
|
8094
|
+
WINDOWS_PATH,
|
|
8095
|
+
serveWindows,
|
|
8096
|
+
listIdeWindows,
|
|
8097
|
+
liveSessionFor,
|
|
8098
|
+
ideWindowOpened,
|
|
8099
|
+
ideWindowClosed,
|
|
6621
8100
|
WINDOW_APP_PATH,
|
|
6622
8101
|
WINDOW_VENDOR_PREFIX,
|
|
6623
8102
|
WINDOW_VENDOR_FILES,
|
|
@@ -6633,6 +8112,27 @@ export const __test = {
|
|
|
6633
8112
|
FS_UPLOAD_MAX_BYTES,
|
|
6634
8113
|
serveFsOp,
|
|
6635
8114
|
serveFsImport,
|
|
8115
|
+
// the tree's copy mirrored onto the OS clipboard (paste in Explorer/Finder/…)
|
|
8116
|
+
CLIPBOARD_FILES_PATH,
|
|
8117
|
+
CLIPBOARD_MAX_ENTRIES,
|
|
8118
|
+
CLIPBOARD_MAX_PAYLOAD,
|
|
8119
|
+
CLIPBOARD_STAGE_DIR,
|
|
8120
|
+
CLIPBOARD_STAGE_MAX_BYTES,
|
|
8121
|
+
stageClipboardCopy,
|
|
8122
|
+
pruneClipboardStage,
|
|
8123
|
+
clipboardStageMapping,
|
|
8124
|
+
serveClipboardFiles,
|
|
8125
|
+
writeSystemFileClipboard,
|
|
8126
|
+
windowsClipboardScript,
|
|
8127
|
+
isWsl,
|
|
8128
|
+
// …and reading it back (Desktop → tree pastes: WSLg hides CF_HDROP from the page)
|
|
8129
|
+
CLIPBOARD_READ_PATH,
|
|
8130
|
+
clipboardScope,
|
|
8131
|
+
serveClipboardRead,
|
|
8132
|
+
readSystemFileClipboard,
|
|
8133
|
+
windowsClipboardReadScript,
|
|
8134
|
+
parseClipboardRead,
|
|
8135
|
+
clipboardPathsToLinux,
|
|
6636
8136
|
CLIENT_CHUNKS,
|
|
6637
8137
|
serveBundle,
|
|
6638
8138
|
FS_READ_PATH,
|
|
@@ -6653,6 +8153,9 @@ export const __test = {
|
|
|
6653
8153
|
ROUTE_PREFIX,
|
|
6654
8154
|
DEFAULT_BYTES,
|
|
6655
8155
|
HARD_MAX_BYTES,
|
|
8156
|
+
FS_WRITE_MAX_BODY_BYTES,
|
|
8157
|
+
FS_WRITE_TEMP_SUFFIX,
|
|
8158
|
+
writeChunk,
|
|
6656
8159
|
MIN_BYTES,
|
|
6657
8160
|
PID_SUFFIX,
|
|
6658
8161
|
DEFAULT_STOP_GRACE_MS,
|