dsh-remote 1.0.1 → 1.1.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.
@@ -0,0 +1,66 @@
1
+ // Vendored unchanged from jsdiff 8.0.4; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
2
+ import Diff from './base.js';
3
+ import { generateOptions } from '../util/params.js';
4
+ class LineDiff extends Diff {
5
+ constructor() {
6
+ super(...arguments);
7
+ this.tokenize = tokenize;
8
+ }
9
+ equals(left, right, options) {
10
+ // If we're ignoring whitespace, we need to normalise lines by stripping
11
+ // whitespace before checking equality. (This has an annoying interaction
12
+ // with newlineIsToken that requires special handling: if newlines get their
13
+ // own token, then we DON'T want to trim the *newline* tokens down to empty
14
+ // strings, since this would cause us to treat whitespace-only line content
15
+ // as equal to a separator between lines, which would be weird and
16
+ // inconsistent with the documented behavior of the options.)
17
+ if (options.ignoreWhitespace) {
18
+ if (!options.newlineIsToken || !left.includes('\n')) {
19
+ left = left.trim();
20
+ }
21
+ if (!options.newlineIsToken || !right.includes('\n')) {
22
+ right = right.trim();
23
+ }
24
+ }
25
+ else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
26
+ if (left.endsWith('\n')) {
27
+ left = left.slice(0, -1);
28
+ }
29
+ if (right.endsWith('\n')) {
30
+ right = right.slice(0, -1);
31
+ }
32
+ }
33
+ return super.equals(left, right, options);
34
+ }
35
+ }
36
+ export const lineDiff = new LineDiff();
37
+ export function diffLines(oldStr, newStr, options) {
38
+ return lineDiff.diff(oldStr, newStr, options);
39
+ }
40
+ export function diffTrimmedLines(oldStr, newStr, options) {
41
+ options = generateOptions(options, { ignoreWhitespace: true });
42
+ return lineDiff.diff(oldStr, newStr, options);
43
+ }
44
+ // Exported standalone so it can be used from jsonDiff too.
45
+ export function tokenize(value, options) {
46
+ if (options.stripTrailingCr) {
47
+ // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior
48
+ value = value.replace(/\r\n/g, '\n');
49
+ }
50
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
51
+ // Ignore the final empty token that occurs if the string ends with a new line
52
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
53
+ linesAndNewlines.pop();
54
+ }
55
+ // Merge the content and line separators into single tokens
56
+ for (let i = 0; i < linesAndNewlines.length; i++) {
57
+ const line = linesAndNewlines[i];
58
+ if (i % 2 && !options.newlineIsToken) {
59
+ retLines[retLines.length - 1] += line;
60
+ }
61
+ else {
62
+ retLines.push(line);
63
+ }
64
+ }
65
+ return retLines;
66
+ }
@@ -0,0 +1,229 @@
1
+ // Vendored unchanged from jsdiff 8.0.4; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
2
+ import { diffLines } from '../diff/line.js';
3
+ export const INCLUDE_HEADERS = {
4
+ includeIndex: true,
5
+ includeUnderline: true,
6
+ includeFileHeaders: true
7
+ };
8
+ export const FILE_HEADERS_ONLY = {
9
+ includeIndex: false,
10
+ includeUnderline: false,
11
+ includeFileHeaders: true
12
+ };
13
+ export const OMIT_HEADERS = {
14
+ includeIndex: false,
15
+ includeUnderline: false,
16
+ includeFileHeaders: false
17
+ };
18
+ export function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
19
+ let optionsObj;
20
+ if (!options) {
21
+ optionsObj = {};
22
+ }
23
+ else if (typeof options === 'function') {
24
+ optionsObj = { callback: options };
25
+ }
26
+ else {
27
+ optionsObj = options;
28
+ }
29
+ if (typeof optionsObj.context === 'undefined') {
30
+ optionsObj.context = 4;
31
+ }
32
+ // We copy this into its own variable to placate TypeScript, which thinks
33
+ // optionsObj.context might be undefined in the callbacks below.
34
+ const context = optionsObj.context;
35
+ // @ts-expect-error (runtime check for something that is correctly a static type error)
36
+ if (optionsObj.newlineIsToken) {
37
+ throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');
38
+ }
39
+ if (!optionsObj.callback) {
40
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
41
+ }
42
+ else {
43
+ const { callback } = optionsObj;
44
+ diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
45
+ const patch = diffLinesResultToPatch(diff);
46
+ // TypeScript is unhappy without the cast because it does not understand that `patch` may
47
+ // be undefined here only if `callback` is StructuredPatchCallbackAbortable:
48
+ callback(patch);
49
+ } }));
50
+ }
51
+ function diffLinesResultToPatch(diff) {
52
+ // STEP 1: Build up the patch with no "" lines and with the arrays
53
+ // of lines containing trailing newline characters. We'll tidy up later...
54
+ if (!diff) {
55
+ return;
56
+ }
57
+ diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
58
+ function contextLines(lines) {
59
+ return lines.map(function (entry) { return ' ' + entry; });
60
+ }
61
+ const hunks = [];
62
+ let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
63
+ for (let i = 0; i < diff.length; i++) {
64
+ const current = diff[i], lines = current.lines || splitLines(current.value);
65
+ current.lines = lines;
66
+ if (current.added || current.removed) {
67
+ // If we have previous context, start with that
68
+ if (!oldRangeStart) {
69
+ const prev = diff[i - 1];
70
+ oldRangeStart = oldLine;
71
+ newRangeStart = newLine;
72
+ if (prev) {
73
+ curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
74
+ oldRangeStart -= curRange.length;
75
+ newRangeStart -= curRange.length;
76
+ }
77
+ }
78
+ // Output our changes
79
+ for (const line of lines) {
80
+ curRange.push((current.added ? '+' : '-') + line);
81
+ }
82
+ // Track the updated file position
83
+ if (current.added) {
84
+ newLine += lines.length;
85
+ }
86
+ else {
87
+ oldLine += lines.length;
88
+ }
89
+ }
90
+ else {
91
+ // Identical context lines. Track line changes
92
+ if (oldRangeStart) {
93
+ // Close out any changes that have been output (or join overlapping)
94
+ if (lines.length <= context * 2 && i < diff.length - 2) {
95
+ // Overlapping
96
+ for (const line of contextLines(lines)) {
97
+ curRange.push(line);
98
+ }
99
+ }
100
+ else {
101
+ // end the range and output
102
+ const contextSize = Math.min(lines.length, context);
103
+ for (const line of contextLines(lines.slice(0, contextSize))) {
104
+ curRange.push(line);
105
+ }
106
+ const hunk = {
107
+ oldStart: oldRangeStart,
108
+ oldLines: (oldLine - oldRangeStart + contextSize),
109
+ newStart: newRangeStart,
110
+ newLines: (newLine - newRangeStart + contextSize),
111
+ lines: curRange
112
+ };
113
+ hunks.push(hunk);
114
+ oldRangeStart = 0;
115
+ newRangeStart = 0;
116
+ curRange = [];
117
+ }
118
+ }
119
+ oldLine += lines.length;
120
+ newLine += lines.length;
121
+ }
122
+ }
123
+ // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add
124
+ // "".
125
+ for (const hunk of hunks) {
126
+ for (let i = 0; i < hunk.lines.length; i++) {
127
+ if (hunk.lines[i].endsWith('\n')) {
128
+ hunk.lines[i] = hunk.lines[i].slice(0, -1);
129
+ }
130
+ else {
131
+ hunk.lines.splice(i + 1, 0, '\');
132
+ i++; // Skip the line we just added, then continue iterating
133
+ }
134
+ }
135
+ }
136
+ return {
137
+ oldFileName: oldFileName, newFileName: newFileName,
138
+ oldHeader: oldHeader, newHeader: newHeader,
139
+ hunks: hunks
140
+ };
141
+ }
142
+ }
143
+ /**
144
+ * creates a unified diff patch.
145
+ * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`)
146
+ */
147
+ export function formatPatch(patch, headerOptions) {
148
+ if (!headerOptions) {
149
+ headerOptions = INCLUDE_HEADERS;
150
+ }
151
+ if (Array.isArray(patch)) {
152
+ if (patch.length > 1 && !headerOptions.includeFileHeaders) {
153
+ throw new Error('Cannot omit file headers on a multi-file patch. '
154
+ + '(The result would be unparseable; how would a tool trying to apply '
155
+ + 'the patch know which changes are to which file?)');
156
+ }
157
+ return patch.map(p => formatPatch(p, headerOptions)).join('\n');
158
+ }
159
+ const ret = [];
160
+ if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) {
161
+ ret.push('Index: ' + patch.oldFileName);
162
+ }
163
+ if (headerOptions.includeUnderline) {
164
+ ret.push('===================================================================');
165
+ }
166
+ if (headerOptions.includeFileHeaders) {
167
+ ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader));
168
+ ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader));
169
+ }
170
+ for (let i = 0; i < patch.hunks.length; i++) {
171
+ const hunk = patch.hunks[i];
172
+ // Unified Diff Format quirk: If the chunk size is 0,
173
+ // the first number is one lower than one would expect.
174
+ // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
175
+ if (hunk.oldLines === 0) {
176
+ hunk.oldStart -= 1;
177
+ }
178
+ if (hunk.newLines === 0) {
179
+ hunk.newStart -= 1;
180
+ }
181
+ ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines
182
+ + ' +' + hunk.newStart + ',' + hunk.newLines
183
+ + ' @@');
184
+ for (const line of hunk.lines) {
185
+ ret.push(line);
186
+ }
187
+ }
188
+ return ret.join('\n') + '\n';
189
+ }
190
+ export function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
191
+ if (typeof options === 'function') {
192
+ options = { callback: options };
193
+ }
194
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) {
195
+ const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
196
+ if (!patchObj) {
197
+ return;
198
+ }
199
+ return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions);
200
+ }
201
+ else {
202
+ const { callback } = options;
203
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => {
204
+ if (!patchObj) {
205
+ callback(undefined);
206
+ }
207
+ else {
208
+ callback(formatPatch(patchObj, options.headerOptions));
209
+ }
210
+ } }));
211
+ }
212
+ }
213
+ export function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
214
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
215
+ }
216
+ /**
217
+ * Split `text` into an array of lines, including the trailing newline character (where present)
218
+ */
219
+ function splitLines(text) {
220
+ const hasTrailingNl = text.endsWith('\n');
221
+ const result = text.split('\n').map(line => line + '\n');
222
+ if (hasTrailingNl) {
223
+ result.pop();
224
+ }
225
+ else {
226
+ result.push(result.pop().slice(0, -1));
227
+ }
228
+ return result;
229
+ }
@@ -0,0 +1,15 @@
1
+ // Vendored unchanged from jsdiff 8.0.4; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
2
+ export function generateOptions(options, defaults) {
3
+ if (typeof options === 'function') {
4
+ defaults.callback = options;
5
+ }
6
+ else if (options) {
7
+ for (const name in options) {
8
+ /* istanbul ignore else */
9
+ if (Object.prototype.hasOwnProperty.call(options, name)) {
10
+ defaults[name] = options[name];
11
+ }
12
+ }
13
+ }
14
+ return defaults;
15
+ }
@@ -0,0 +1,219 @@
1
+ // Incremental remote workspace search. A job is owned by one session binding;
2
+ // cancelling it never closes the SSH pool used by other sessions or terminals.
3
+ import { randomUUID } from 'node:crypto'
4
+ import { joinRemotePath } from './paths.js'
5
+ import { requestSessionHint } from './binding.js'
6
+ import { matchGlob } from './search.js'
7
+
8
+ function interrupted(signal) { return Object.assign(new Error(signal.reason === 'timeout' ? 'Search time budget reached' : 'Search cancelled'), { name: 'AbortError' }) }
9
+ // A cancelled caller must stop waiting immediately, but an SSH request already
10
+ // sent still owns capacity until its actual promise settles. Otherwise rapid
11
+ // typing can leave unlimited abandoned reads on the shared SFTP channel.
12
+ class SearchOperations {
13
+ constructor(limit = 6) { this.limit = limit; this.active = 0; this.waiting = [] }
14
+ run(operation, signal) {
15
+ if (signal.aborted) return Promise.reject(interrupted(signal))
16
+ return new Promise((resolve, reject) => {
17
+ const entry = { operation, signal, resolve, reject, started: false }
18
+ entry.abort = () => {
19
+ if (!entry.started) {
20
+ const index = this.waiting.indexOf(entry)
21
+ if (index >= 0) this.waiting.splice(index, 1)
22
+ signal.removeEventListener('abort', entry.abort)
23
+ }
24
+ reject(interrupted(signal))
25
+ }
26
+ signal.addEventListener('abort', entry.abort, { once: true })
27
+ this.waiting.push(entry)
28
+ this.pump()
29
+ })
30
+ }
31
+ pump() {
32
+ while (this.active < this.limit && this.waiting.length) {
33
+ const entry = this.waiting.shift()
34
+ if (entry.signal.aborted) { entry.abort(); continue }
35
+ entry.started = true
36
+ this.active++
37
+ Promise.resolve().then(() => {
38
+ if (entry.signal.aborted) throw interrupted(entry.signal)
39
+ return entry.operation()
40
+ }).then(entry.resolve, entry.reject).finally(() => {
41
+ entry.signal.removeEventListener('abort', entry.abort)
42
+ this.active--
43
+ this.pump()
44
+ })
45
+ }
46
+ }
47
+ }
48
+
49
+ function matchingSnippet(line, normalizedIndex, queryLength, normalizedLength) {
50
+ let startMatch = normalizedIndex, endMatch = normalizedIndex + queryLength
51
+ if (normalizedLength !== line.length) {
52
+ // Lowercasing can expand a character (e.g. Turkish dotted capital I). Map
53
+ // folded offsets back before centering the original, case-preserving text.
54
+ let folded = 0, raw = 0, foundStart = false
55
+ for (const character of line) {
56
+ const next = folded + character.toLowerCase().length
57
+ if (!foundStart && next > normalizedIndex) { startMatch = raw; foundStart = true }
58
+ raw += character.length
59
+ if (next >= normalizedIndex + queryLength) { endMatch = raw; break }
60
+ folded = next
61
+ }
62
+ }
63
+ let from = Math.max(0, startMatch - 100)
64
+ let to = Math.min(line.length, Math.max(from + 500, endMatch))
65
+ if (from > 0 && /[\uDC00-\uDFFF]/.test(line[from])) from--
66
+ if (to < line.length && /[\uDC00-\uDFFF]/.test(line[to])) to++
67
+ return (from > 0 ? '…' : '') + line.slice(from, to) + (to < line.length ? '…' : '')
68
+ }
69
+ const terminal = status => ['completed','partial','cancelled','failed'].includes(status)
70
+
71
+ export class WorkspaceSearches {
72
+ constructor({ maxEntries = 50000, maxResults = 300, timeoutMs = 30000, maxReadBytes = 256 * 1024, maxDepth = 30, decodeBuf = b => b.toString('utf8'), encoding = 'utf-8', now = Date.now } = {}) {
73
+ Object.assign(this, { maxEntries, maxResults, timeoutMs, maxReadBytes, maxDepth, decodeBuf, encoding, now })
74
+ this.jobs = new Map()
75
+ this.operations = new WeakMap()
76
+ }
77
+ owner(binding, hint) { return JSON.stringify([hint.sessionId || hint.local, binding.host, binding.port, binding.username, binding.ws]) }
78
+ snapshot(job) {
79
+ return { id: job.id, query: job.query, mode: job.mode, status: job.status, phase: job.phase,
80
+ results: job.results.slice(), scannedFiles: job.scannedFiles, scannedDirs: job.scannedDirs, scannedEntries: job.scannedEntries,
81
+ skipped: job.skipped, errors: job.errors, currentPath: job.currentPath, elapsedMs: (job.finishedAt ?? this.now()) - job.startedAt,
82
+ truncated: job.truncated, reason: job.reason || '', error: job.error || '' }
83
+ }
84
+ get(owner, id) { const job = this.jobs.get(id); return job?.owner === owner ? this.snapshot(job) : null }
85
+ cancel(owner, id) {
86
+ const job = this.jobs.get(id)
87
+ if (!job || job.owner !== owner) return null
88
+ if (!terminal(job.status)) { job.controller.abort('cancelled'); job.status = 'cancelled'; job.finishedAt = this.now() }
89
+ return this.snapshot(job)
90
+ }
91
+ start(owner, binding, { query, mode = 'names', includeIgnored = false, caseSensitive = false, isIgnored = () => false } = {}) {
92
+ query = typeof query === 'string' ? query.trim() : ''
93
+ if (!query || query.length > 256 || !['names','files','directories','content'].includes(mode)) throw Object.assign(new Error('query (1–256 characters) and a valid search mode are required'), { httpStatus: 400 })
94
+ if (!binding.bound || !binding.ws) throw Object.assign(new Error('Search requires a session bound to a remote workspace'), { httpStatus: 403 })
95
+ for (const job of this.jobs.values()) {
96
+ if (!terminal(job.status) && job.owner === owner) this.cancel(owner, job.id)
97
+ if (terminal(job.status) && this.now() - job.finishedAt > 5 * 60000) this.jobs.delete(job.id)
98
+ }
99
+ if ([...this.jobs.values()].filter(j => !terminal(j.status)).length >= 4) throw Object.assign(new Error('Too many active searches; stop a search and retry'), { httpStatus: 429 })
100
+ while (this.jobs.size >= 40) {
101
+ const old = [...this.jobs.values()].find(j => terminal(j.status))
102
+ if (!old) break
103
+ this.jobs.delete(old.id)
104
+ }
105
+ const job = { id: randomUUID(), owner, query, mode, status: 'running', phase: 'connecting', results: [], scannedFiles: 0, scannedDirs: 0, scannedEntries: 0,
106
+ skipped: 0, errors: 0, currentPath: '', truncated: false, startedAt: this.now(), finishedAt: null, controller: new AbortController() }
107
+ this.jobs.set(job.id, job)
108
+ job.promise = this.run(job, binding, { includeIgnored, caseSensitive, isIgnored })
109
+ return this.snapshot(job)
110
+ }
111
+ async run(job, binding, { includeIgnored, caseSensitive, isIgnored }) {
112
+ const signal = job.controller.signal
113
+ let operations = this.operations.get(binding.pool)
114
+ if (!operations) { operations = new SearchOperations(); this.operations.set(binding.pool, operations) }
115
+ const timer = setTimeout(() => job.controller.abort('timeout'), this.timeoutMs)
116
+ timer.unref?.()
117
+ const stop = () => signal.aborted || job.truncated
118
+ const normalize = value => caseSensitive ? value : value.toLowerCase()
119
+ const query = normalize(job.query)
120
+ const nameMatches = (name, relative) => /[*?]/.test(query)
121
+ ? matchGlob(normalize(job.query.includes('/') ? relative : name), query)
122
+ : normalize(relative).includes(query)
123
+ const add = result => {
124
+ if (stop()) return
125
+ if (job.results.length >= this.maxResults) { job.truncated = true; job.reason = 'results'; return }
126
+ job.results.push(result)
127
+ }
128
+ try {
129
+ const sftp = await operations.run(() => binding.pool.sftp(), signal)
130
+ const queue = [{ path: binding.ws, relative: '', depth: 0 }]
131
+ job.phase = 'scanning'
132
+ const visit = async directory => {
133
+ if (stop()) return
134
+ job.currentPath = directory.relative || '.'
135
+ let entries
136
+ try { entries = await operations.run(() => sftp.readdir(directory.path), signal) }
137
+ catch (error) {
138
+ if (signal.aborted) throw error
139
+ if (!directory.relative) throw error
140
+ job.errors++; return
141
+ }
142
+ if (stop()) return
143
+ job.scannedDirs++
144
+ const files = []
145
+ for (const entry of entries || []) {
146
+ if (stop()) break
147
+ const name = String(entry.filename || '')
148
+ if (!name || name === '.' || name === '..' || /[\/\\\0]/.test(name) || /^[a-z]:/i.test(name)) continue
149
+ if (++job.scannedEntries > this.maxEntries) { job.truncated = true; job.reason = 'entries'; break }
150
+ const attrs = entry.attrs || {}, link = !!attrs.isSymbolicLink?.(), dir = !link && !!attrs.isDirectory?.()
151
+ const relative = directory.relative ? directory.relative + '/' + name : name
152
+ if (!includeIgnored && isIgnored(relative, dir)) { job.skipped++; continue }
153
+ const path = joinRemotePath(directory.path, name)
154
+ if (!dir) job.scannedFiles++
155
+ if (job.mode !== 'content' && (job.mode === 'names' || job.mode === 'directories' && dir || job.mode === 'files' && !dir) && nameMatches(name, relative)) add({ path, relative, name, type: dir ? 'directory' : link ? 'symlink' : 'file' })
156
+ if (dir) {
157
+ if (directory.depth < this.maxDepth) queue.push({ path, relative, depth: directory.depth + 1 })
158
+ else { job.skipped++; job.truncated = true; job.reason = 'depth' }
159
+ } else if (job.mode === 'content') {
160
+ if (link || attrs.size > this.maxReadBytes) job.skipped++
161
+ else files.push({ path, relative, name, attrs })
162
+ }
163
+ }
164
+ // Bounded pipelining keeps high-RTT SFTP usable without unbounded reads.
165
+ for (let offset = 0; offset < files.length && !stop(); offset += 3) {
166
+ await Promise.all(files.slice(offset, offset + 3).map(async file => {
167
+ if (stop()) return
168
+ try {
169
+ let stat = file.attrs
170
+ if (!Number.isFinite(stat.size)) stat = await operations.run(() => sftp.stat(file.path), signal)
171
+ if (stat.size > this.maxReadBytes) { job.skipped++; return }
172
+ const bytes = await operations.run(() => typeof sftp.readPartial === 'function' ? sftp.readPartial(file.path, 0, this.maxReadBytes + 1) : sftp.readFile(file.path), signal)
173
+ if (stop()) return
174
+ if (bytes.length > this.maxReadBytes || bytes.subarray(0, 8192).includes(0)) { job.skipped++; return }
175
+ const lines = this.decodeBuf(bytes, this.encoding).replace(/\r\n/g, '\n').split('\n')
176
+ for (let i = 0; i < lines.length && !stop(); i++) {
177
+ const normalized = normalize(lines[i]), match = normalized.indexOf(query)
178
+ if (match >= 0) add({ path: file.path, relative: file.relative, name: file.name, type: 'file', line: i + 1,
179
+ text: matchingSnippet(lines[i], match, query.length, normalized.length) })
180
+ }
181
+ } catch (error) { if (signal.aborted) throw error; job.errors++ }
182
+ }))
183
+ }
184
+ }
185
+ while (queue.length && !stop()) await Promise.all(queue.splice(0, 2).map(visit))
186
+ if (signal.aborted) throw interrupted(signal)
187
+ if (!terminal(job.status)) job.status = job.truncated || job.errors ? 'partial' : 'completed'
188
+ } catch (error) {
189
+ if (signal.aborted) {
190
+ job.status = signal.reason === 'timeout' ? 'partial' : 'cancelled'
191
+ if (signal.reason === 'timeout') { job.truncated = true; job.reason = 'timeout' }
192
+ } else { job.status = 'failed'; job.error = error.message || String(error) }
193
+ } finally { clearTimeout(timer); job.finishedAt ??= this.now(); job.currentPath = '' }
194
+ }
195
+ dispose() { for (const job of this.jobs.values()) if (!terminal(job.status)) job.controller.abort('disposed'); this.jobs.clear() }
196
+ }
197
+
198
+ export function createSearchRoutes({ searches, sendJson, readBody, resolveRequestBinding, isIgnoredFor = () => () => false }) {
199
+ return [{ kind: 'exact', path: '/dsh-remote/search', async handler(req, res) {
200
+ if (!['GET','POST'].includes(req.method)) return sendJson(res, 405, { ok: false, error: 'method not allowed' })
201
+ try {
202
+ const q = new URL(req.url, 'http://localhost').searchParams
203
+ const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : {}
204
+ const hint = requestSessionHint(req, body)
205
+ if (!hint.sessionId && !hint.local) return sendJson(res, 400, { ok: false, error: 'sessionId or local remote workspace context is required' })
206
+ const binding = await resolveRequestBinding(req, body)
207
+ if (!binding.bound) return sendJson(res, 403, { ok: false, error: 'Search requires a remote workspace' })
208
+ const owner = searches.owner(binding, hint), id = String(body.id || q.get('id') || '')
209
+ if (req.method === 'GET' || body.action === 'cancel') {
210
+ if (!id) return sendJson(res, 400, { ok: false, error: 'search id is required' })
211
+ const search = body.action === 'cancel' ? searches.cancel(owner, id) : searches.get(owner, id)
212
+ return sendJson(res, search ? 200 : 404, search ? { ok: true, search } : { ok: false, error: 'Search not found in this workspace' })
213
+ }
214
+ if (body.action && body.action !== 'start') return sendJson(res, 400, { ok: false, error: 'action must be start or cancel' })
215
+ const search = searches.start(owner, binding, { query: body.query, mode: body.mode, caseSensitive: body.caseSensitive === true, includeIgnored: body.includeIgnored === true, isIgnored: isIgnoredFor(binding.ws) })
216
+ return sendJson(res, 200, { ok: true, search })
217
+ } catch (error) { return sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error) }) }
218
+ } }]
219
+ }