@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +49 -3
- package/dist/config-manager.js +329 -87
- package/dist/config-recovery.d.ts +28 -0
- package/dist/config-recovery.js +81 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +9 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +26 -16
- package/dist/handlers/search-answers.d.ts +58 -0
- package/dist/handlers/search-answers.js +172 -0
- package/dist/handlers/search-handlers.js +4 -92
- package/dist/index.js +14 -7
- package/dist/npm-scripts/remote.js +2 -3
- package/dist/remote-device/broadcast-analytics.d.ts +28 -0
- package/dist/remote-device/broadcast-analytics.js +41 -0
- package/dist/remote-device/desktop-commander-integration.js +19 -25
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +137 -30
- package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
- package/dist/remote-device/mqtt-enrollment.js +162 -0
- package/dist/remote-device/mqtt-transport.d.ts +44 -0
- package/dist/remote-device/mqtt-transport.js +197 -0
- package/dist/remote-device/remote-channel.d.ts +12 -0
- package/dist/remote-device/remote-channel.js +55 -8
- package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
- package/dist/remote-device/transport-analytics.d.ts +29 -0
- package/dist/remote-device/transport-analytics.js +44 -0
- package/dist/remote-device/transport-telemetry.d.ts +32 -0
- package/dist/remote-device/transport-telemetry.js +48 -0
- package/dist/search-manager.d.ts +239 -27
- package/dist/search-manager.js +746 -312
- package/dist/server.js +44 -11
- package/dist/terminal-manager.d.ts +138 -21
- package/dist/terminal-manager.js +300 -215
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +21 -70
- package/dist/tools/edit.js +12 -4
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +171 -68
- package/dist/tools/pdf/extract-images.d.ts +2 -0
- package/dist/tools/pdf/extract-images.js +4 -1
- package/dist/tools/pdf/index.d.ts +5 -3
- package/dist/tools/pdf/index.js +4 -3
- package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
- package/dist/tools/pdf/lib/pdf2md.js +12 -5
- package/dist/tools/pdf/manipulations.d.ts +12 -1
- package/dist/tools/pdf/manipulations.js +17 -4
- package/dist/tools/pdf/markdown.d.ts +96 -0
- package/dist/tools/pdf/markdown.js +485 -20
- package/dist/tools/pdf/utils.d.ts +2 -2
- package/dist/tools/pdf/utils.js +4 -4
- package/dist/tools/process.js +8 -5
- package/dist/tools/schemas.d.ts +1 -1
- package/dist/tools/schemas.js +15 -6
- package/dist/tools/search.d.ts +32 -0
- package/dist/tools/search.js +202 -0
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +6 -6
- package/dist/ui/config-editor/src/app.js +2 -15
- package/dist/utils/ab-test.js +27 -9
- package/dist/utils/atomic-write.d.ts +14 -0
- package/dist/utils/atomic-write.js +80 -0
- package/dist/utils/capture.d.ts +17 -1
- package/dist/utils/capture.js +177 -68
- package/dist/utils/exit-process.d.ts +24 -0
- package/dist/utils/exit-process.js +31 -0
- package/dist/utils/feature-flags.js +2 -1
- package/dist/utils/files/base.d.ts +3 -1
- package/dist/utils/files/docx.d.ts +3 -0
- package/dist/utils/files/docx.js +24 -9
- package/dist/utils/files/excel.d.ts +10 -0
- package/dist/utils/files/excel.js +93 -33
- package/dist/utils/files/factory.d.ts +22 -1
- package/dist/utils/files/factory.js +59 -4
- package/dist/utils/files/image.d.ts +12 -4
- package/dist/utils/files/image.js +19 -8
- package/dist/utils/files/index.d.ts +5 -3
- package/dist/utils/files/index.js +4 -3
- package/dist/utils/files/pdf.js +18 -36
- package/dist/utils/files/text.d.ts +21 -5
- package/dist/utils/files/text.js +90 -86
- package/dist/utils/internal-facts.d.ts +3 -0
- package/dist/utils/internal-facts.js +23 -0
- package/dist/utils/lazy-package.d.ts +23 -0
- package/dist/utils/lazy-package.js +42 -0
- package/dist/utils/open-browser.js +2 -1
- package/dist/utils/process-detection.d.ts +24 -5
- package/dist/utils/process-detection.js +199 -89
- package/dist/utils/process-tree.d.ts +14 -0
- package/dist/utils/process-tree.js +223 -0
- package/dist/utils/rename.d.ts +9 -0
- package/dist/utils/rename.js +74 -0
- package/dist/utils/ripgrep-resolver.js +9 -14
- package/dist/utils/shell.d.ts +42 -0
- package/dist/utils/shell.js +187 -0
- package/dist/utils/system-info.js +9 -7
- package/dist/utils/trackTools.js +2 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
- package/package.json +8 -2
- package/vendor/telemetry-contract/README.md +56 -0
- package/vendor/telemetry-contract/package.json +32 -0
- package/vendor/telemetry-contract/transport.d.ts +38 -0
- package/vendor/telemetry-contract/transport.js +164 -0
- package/vendor/telemetry-contract/transport.test.js +39 -0
package/dist/search-manager.js
CHANGED
|
@@ -1,11 +1,129 @@
|
|
|
1
1
|
import { spawn } from 'child_process';
|
|
2
|
+
import { constants } from 'buffer';
|
|
3
|
+
import { once } from 'events';
|
|
2
4
|
import path from 'path';
|
|
3
5
|
import fs from 'fs/promises';
|
|
4
6
|
import { validatePath } from './tools/filesystem.js';
|
|
5
7
|
import { capture } from './utils/capture.js';
|
|
8
|
+
import { logger } from './utils/logger.js';
|
|
6
9
|
import { getRipgrepPath } from './utils/ripgrep-resolver.js';
|
|
7
10
|
import { isExcelFile } from './utils/files/index.js';
|
|
8
|
-
import
|
|
11
|
+
import { exceljsPackage } from './utils/files/excel.js';
|
|
12
|
+
import { pizzipPackage } from './utils/files/docx.js';
|
|
13
|
+
/**
|
|
14
|
+
* Default time limit of a file search for an exact filename ("package.json"):
|
|
15
|
+
* a quick lookup of one known file, which gives up rather than walk a huge tree.
|
|
16
|
+
* A content search for the same text looks for every reference to that file,
|
|
17
|
+
* so it has no default limit.
|
|
18
|
+
*/
|
|
19
|
+
const EXACT_FILENAME_SEARCH_TIMEOUT_MS = 1500;
|
|
20
|
+
/** The longest a timer waits (2^31 - 1 ms, ~24.8 days): setTimeout fires a longer delay after 1 ms */
|
|
21
|
+
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
22
|
+
/** The extensions of the files the Excel and DOCX searches are for (see targetsOfficeFiles) */
|
|
23
|
+
const EXCEL_EXTENSIONS = ['.xlsx', '.xls', '.xlsm', '.xlsb'];
|
|
24
|
+
const DOCX_EXTENSIONS = ['.docx'];
|
|
25
|
+
/**
|
|
26
|
+
* The OS errors ripgrep reports for a path it may not read ("rg: <path>: ...
|
|
27
|
+
* (os error N)"): on Windows ERROR_ACCESS_DENIED (5); elsewhere EACCES (13) and
|
|
28
|
+
* EPERM (1: on macOS, a folder its privacy settings protect). On Windows, 1 is
|
|
29
|
+
* an error of another kind.
|
|
30
|
+
*/
|
|
31
|
+
const PERMISSION_OS_ERRORS = process.platform === 'win32' ? [5] : [1, 13];
|
|
32
|
+
/** Whether an error of the Excel/DOCX search is about permissions */
|
|
33
|
+
const isPermissionError = (error) => ['EACCES', 'EPERM'].includes(error?.code ?? '');
|
|
34
|
+
const errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
35
|
+
/** The alternatives of a filePattern ("*.js|*.ts") */
|
|
36
|
+
const filePatternAlternatives = (filePattern) => (filePattern ?? '').split('|').map(p => p.trim()).filter(Boolean);
|
|
37
|
+
/** Answers show this many characters of a result's text, then '...' if there is more */
|
|
38
|
+
export const SHOWN_TEXT_CHARS = 100;
|
|
39
|
+
/**
|
|
40
|
+
* What a session keeps of a line's text: what answers show, and one character
|
|
41
|
+
* more so they still know to add '...'. ripgrep sends each line whole (--json
|
|
42
|
+
* ignores --max-columns), and a line can be megabytes long. Copied, because a
|
|
43
|
+
* V8 substring keeps the whole string it was cut from alive. No text (ripgrep
|
|
44
|
+
* sends text that is not valid UTF-8 as "bytes") stays no text, as it always was.
|
|
45
|
+
*/
|
|
46
|
+
const keptText = (text) => text === undefined ? undefined : Buffer.from(text.slice(0, SHOWN_TEXT_CHARS + 1), 'utf16le').toString('utf16le');
|
|
47
|
+
/**
|
|
48
|
+
* A glob as ripgrep matches its -g globs (gitignore style), for the files
|
|
49
|
+
* ripgrep doesn't select itself: a file search's files, and the Excel and DOCX
|
|
50
|
+
* files. Without a '/' it is matched against the file's name, with one against
|
|
51
|
+
* its path below the search path ('/'-separated). '*' and '?' stop at '/', "**"
|
|
52
|
+
* as a whole path segment spans folders, "[...]" is a character class ("[!...]"
|
|
53
|
+
* negated) and "{a,b}" a choice.
|
|
54
|
+
*/
|
|
55
|
+
function ripgrepGlobMatcher(glob, ignoreCase) {
|
|
56
|
+
const byPath = glob.includes('/'); // "/x.ts" too: x.ts in the search path itself
|
|
57
|
+
let regex;
|
|
58
|
+
try {
|
|
59
|
+
regex = new RegExp(`^${globRegexSource(glob.replace(/^\//, ''))}$`, ignoreCase ? 'i' : '');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// A glob ripgrep rejects too ("[z-a]"): every glob a search uses reaches
|
|
63
|
+
// ripgrep (see buildRipgrepArgs), and the search answers with its error
|
|
64
|
+
return () => false;
|
|
65
|
+
}
|
|
66
|
+
return relativePath => regex.test(byPath ? relativePath : relativePath.slice(relativePath.lastIndexOf('/') + 1));
|
|
67
|
+
}
|
|
68
|
+
/** The regular expression source of a glob (see ripgrepGlobMatcher) */
|
|
69
|
+
function globRegexSource(glob) {
|
|
70
|
+
let source = '';
|
|
71
|
+
for (let i = 0; i < glob.length; i++) {
|
|
72
|
+
const c = glob[i];
|
|
73
|
+
const classEnd = c === '[' ? characterClassEnd(glob, i) : -1;
|
|
74
|
+
const choiceEnd = c === '{' ? glob.indexOf('}', i) : -1;
|
|
75
|
+
if (c === '*' && glob[i + 1] === '*' && (i === 0 || glob[i - 1] === '/') && (i + 2 === glob.length || glob[i + 2] === '/')) {
|
|
76
|
+
// "**" as a whole path segment: any number of folders ("**/": none too)
|
|
77
|
+
source += i + 2 === glob.length ? '.*' : '(?:.*/)?';
|
|
78
|
+
i += i + 2 === glob.length ? 1 : 2;
|
|
79
|
+
}
|
|
80
|
+
else if (c === '*') {
|
|
81
|
+
source += '[^/]*';
|
|
82
|
+
}
|
|
83
|
+
else if (c === '?') {
|
|
84
|
+
source += '[^/]';
|
|
85
|
+
}
|
|
86
|
+
else if (classEnd > 0) {
|
|
87
|
+
let body = glob.slice(i + 1, classEnd);
|
|
88
|
+
const negated = body.startsWith('!') || body.startsWith('^');
|
|
89
|
+
if (negated)
|
|
90
|
+
body = body.slice(1);
|
|
91
|
+
source += `[${negated ? '^/' : ''}${body.replace(/[\\\]^]/g, '\\$&')}]`;
|
|
92
|
+
i = classEnd;
|
|
93
|
+
}
|
|
94
|
+
else if (choiceEnd > 0) {
|
|
95
|
+
source += `(?:${glob.slice(i + 1, choiceEnd).split(',').map(globRegexSource).join('|')})`;
|
|
96
|
+
i = choiceEnd;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
source += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return source;
|
|
103
|
+
}
|
|
104
|
+
/** A file's path below the search path, '/'-separated (just its name when it is the search path) */
|
|
105
|
+
const pathBelow = (root, file) => path.relative(root, file).split(path.sep).join('/') || path.basename(file);
|
|
106
|
+
/** A glob that matches `text` itself: each glob character in a class of its own ("[*]", "[[]") */
|
|
107
|
+
const literalGlob = (text) => text.replace(/[*?[\]{}]/g, '[$&]');
|
|
108
|
+
/** The ']' that closes the character class opening at `start` (one right after "[" or "[!" is part of it), or -1 */
|
|
109
|
+
function characterClassEnd(glob, start) {
|
|
110
|
+
let i = start + 1;
|
|
111
|
+
if (glob[i] === '!' || glob[i] === '^')
|
|
112
|
+
i++;
|
|
113
|
+
if (glob[i] === ']')
|
|
114
|
+
i++;
|
|
115
|
+
return glob.indexOf(']', i);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The longest line of ripgrep output the server assembles, in characters: a
|
|
119
|
+
* match or context line in its JSON. Half of V8's longest string (2^29 - 24
|
|
120
|
+
* characters in Node 24), past which the append throws and the server exits:
|
|
121
|
+
* only a longer line is skipped, and answers name its file. Any shorter line is
|
|
122
|
+
* processed whole.
|
|
123
|
+
*/
|
|
124
|
+
export const MAX_OUTPUT_LINE_CHARS = Math.floor(constants.MAX_STRING_LENGTH / 2);
|
|
125
|
+
/** The most of ripgrep's error output (stderr) a session keeps, in characters */
|
|
126
|
+
const MAX_KEPT_ERROR_CHARS = 64 * 1024;
|
|
9
127
|
/**
|
|
10
128
|
* Search Session Manager - handles ripgrep processes like terminal sessions
|
|
11
129
|
* Supports both file search and content search with progressive results
|
|
@@ -13,6 +131,7 @@ import PizZip from 'pizzip';
|
|
|
13
131
|
constructor() {
|
|
14
132
|
this.sessions = new Map();
|
|
15
133
|
this.sessionCounter = 0;
|
|
134
|
+
this.cleanupTimer = null;
|
|
16
135
|
}
|
|
17
136
|
/**
|
|
18
137
|
* Start a new search session (like start_process)
|
|
@@ -32,54 +151,53 @@ import PizZip from 'pizzip';
|
|
|
32
151
|
catch (err) {
|
|
33
152
|
throw new Error(`Failed to locate ripgrep binary: ${err instanceof Error ? err.message : String(err)}`);
|
|
34
153
|
}
|
|
35
|
-
// Start ripgrep process
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
154
|
+
// Start ripgrep process. It matches a glob with a '/' ("src/*.ts") against
|
|
155
|
+
// the path below its working directory: that must be the root path. A root
|
|
156
|
+
// that can't be stat'ed (missing...) can't be searched: start_search answers
|
|
157
|
+
// with why, as for any search that can't start.
|
|
158
|
+
const rootIsDirectory = (await fs.stat(validPath)).isDirectory();
|
|
159
|
+
const rgProcess = spawn(rgPath, args, {
|
|
160
|
+
windowsHide: true, // Prevent visible console windows on Windows
|
|
161
|
+
cwd: rootIsDirectory ? validPath : undefined
|
|
162
|
+
});
|
|
163
|
+
await this.whenStarted(rgProcess);
|
|
40
164
|
// Create session
|
|
165
|
+
let markCompleted;
|
|
166
|
+
const completed = new Promise(resolve => { markCompleted = resolve; });
|
|
41
167
|
const session = {
|
|
42
168
|
id: sessionId,
|
|
43
169
|
process: rgProcess,
|
|
44
170
|
results: [],
|
|
45
171
|
isComplete: false,
|
|
46
|
-
isError: false,
|
|
47
172
|
startTime: Date.now(),
|
|
48
173
|
lastReadTime: Date.now(),
|
|
49
174
|
options,
|
|
50
175
|
buffer: '',
|
|
176
|
+
skippedLines: new Map(),
|
|
51
177
|
totalMatches: 0,
|
|
52
|
-
totalContextLines: 0
|
|
178
|
+
totalContextLines: 0,
|
|
179
|
+
filePatternIncludes: this.filePatternIncludes(options, validPath),
|
|
180
|
+
pendingSources: new Set(['ripgrep']),
|
|
181
|
+
unsearched: new Map(),
|
|
182
|
+
completed,
|
|
183
|
+
markCompleted
|
|
53
184
|
};
|
|
54
185
|
this.sessions.set(sessionId, session);
|
|
55
186
|
// Set up process event handlers
|
|
56
187
|
this.setupProcessHandlers(session);
|
|
57
188
|
// Start cleanup interval now that we have a session
|
|
58
|
-
startCleanupIfNeeded();
|
|
59
|
-
// Set up
|
|
60
|
-
// For exact filename searches, use a shorter default timeout
|
|
61
|
-
const timeoutMs = options.timeout ??
|
|
62
|
-
|
|
189
|
+
this.startCleanupIfNeeded();
|
|
190
|
+
// Set up the time limit, if any: it stops every source still running.
|
|
191
|
+
// For exact filename file searches, use a shorter default timeout
|
|
192
|
+
const timeoutMs = options.timeout ??
|
|
193
|
+
(this.isExactFilenameSearch(options) ? EXACT_FILENAME_SEARCH_TIMEOUT_MS : undefined);
|
|
63
194
|
if (timeoutMs) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
}, timeoutMs);
|
|
195
|
+
session.timeLimitMs = timeoutMs;
|
|
196
|
+
session.timeoutTimer = setTimeout(() => {
|
|
197
|
+
session.stopReason ?? (session.stopReason = 'timed_out');
|
|
198
|
+
this.stopSources(session);
|
|
199
|
+
}, Math.min(timeoutMs, LONGEST_TIMER_MS));
|
|
69
200
|
}
|
|
70
|
-
// Clear timer on process completion
|
|
71
|
-
session.process.once('close', () => {
|
|
72
|
-
if (killTimer) {
|
|
73
|
-
clearTimeout(killTimer);
|
|
74
|
-
killTimer = null;
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
session.process.once('error', () => {
|
|
78
|
-
if (killTimer) {
|
|
79
|
-
clearTimeout(killTimer);
|
|
80
|
-
killTimer = null;
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
201
|
capture('search_session_started', {
|
|
84
202
|
sessionId,
|
|
85
203
|
searchType: options.searchType,
|
|
@@ -92,37 +210,19 @@ import PizZip from 'pizzip';
|
|
|
92
210
|
// - filePattern explicitly targets Excel files (*.xlsx, *.xls, etc.)
|
|
93
211
|
// - or rootPath is an Excel file itself
|
|
94
212
|
const shouldSearchExcel = options.searchType === 'content' &&
|
|
95
|
-
this.
|
|
213
|
+
this.targetsOfficeFiles(EXCEL_EXTENSIONS, options.filePattern, validPath);
|
|
96
214
|
if (shouldSearchExcel) {
|
|
97
|
-
this.searchExcelFiles(validPath, options.pattern, options.ignoreCase !== false,
|
|
98
|
-
options.
|
|
99
|
-
).then(excelResults => {
|
|
100
|
-
// Add Excel results to session (merged after initial response)
|
|
101
|
-
for (const result of excelResults) {
|
|
102
|
-
session.results.push(result);
|
|
103
|
-
session.totalMatches++;
|
|
104
|
-
}
|
|
105
|
-
}).catch((err) => {
|
|
106
|
-
// Log Excel search errors but don't fail the whole search
|
|
107
|
-
capture('excel_search_error', { error: err instanceof Error ? err.message : String(err) });
|
|
108
|
-
});
|
|
215
|
+
this.startOfficeSource(session, 'excel', sink => this.searchExcelFiles(validPath, options.pattern, options.ignoreCase !== false, sink, options.filePattern, // Pass filePattern to filter Excel files too
|
|
216
|
+
options.includeHidden === true));
|
|
109
217
|
}
|
|
110
218
|
// For content searches, also search DOCX files
|
|
111
219
|
const shouldSearchDocx = options.searchType === 'content' &&
|
|
112
|
-
this.
|
|
220
|
+
this.targetsOfficeFiles(DOCX_EXTENSIONS, options.filePattern, validPath);
|
|
113
221
|
if (shouldSearchDocx) {
|
|
114
|
-
this.searchDocxFiles(validPath, options.pattern, options.ignoreCase !== false,
|
|
115
|
-
).then(docxResults => {
|
|
116
|
-
for (const result of docxResults) {
|
|
117
|
-
session.results.push(result);
|
|
118
|
-
session.totalMatches++;
|
|
119
|
-
}
|
|
120
|
-
}).catch((err) => {
|
|
121
|
-
capture('docx_search_error', { error: err instanceof Error ? err.message : String(err) });
|
|
122
|
-
});
|
|
222
|
+
this.startOfficeSource(session, 'docx', sink => this.searchDocxFiles(validPath, options.pattern, options.ignoreCase !== false, sink, options.filePattern, options.includeHidden === true));
|
|
123
223
|
}
|
|
124
224
|
// Wait for first chunk of data or early completion instead of fixed delay
|
|
125
|
-
//
|
|
225
|
+
// Office searches run in background and add their matches to the session as they find them
|
|
126
226
|
const firstChunk = new Promise(resolve => {
|
|
127
227
|
const onData = () => {
|
|
128
228
|
session.process.stdout?.off('data', onData);
|
|
@@ -133,14 +233,7 @@ import PizZip from 'pizzip';
|
|
|
133
233
|
});
|
|
134
234
|
// Only wait for ripgrep first chunk - Excel results merge asynchronously
|
|
135
235
|
await firstChunk;
|
|
136
|
-
return {
|
|
137
|
-
sessionId,
|
|
138
|
-
isComplete: session.isComplete,
|
|
139
|
-
isError: session.isError,
|
|
140
|
-
results: [...session.results],
|
|
141
|
-
totalResults: session.totalMatches,
|
|
142
|
-
runtime: Date.now() - session.startTime
|
|
143
|
-
};
|
|
236
|
+
return { ...this.stateOf(session), results: [...session.results] };
|
|
144
237
|
}
|
|
145
238
|
/**
|
|
146
239
|
* Read search results with offset-based pagination (like read_file)
|
|
@@ -153,40 +246,72 @@ import PizZip from 'pizzip';
|
|
|
153
246
|
}
|
|
154
247
|
// Get all results (excluding internal markers)
|
|
155
248
|
const allResults = session.results.filter(r => r.file !== '__LAST_READ_MARKER__');
|
|
249
|
+
// Every read keeps the session from cleanup, a read of the last results too
|
|
250
|
+
session.lastReadTime = Date.now();
|
|
156
251
|
// Handle negative offsets (tail behavior) - like file reading
|
|
157
252
|
if (offset < 0) {
|
|
158
253
|
const tailCount = Math.abs(offset);
|
|
159
254
|
const tailResults = allResults.slice(-tailCount);
|
|
160
255
|
return {
|
|
256
|
+
...this.stateOf(session),
|
|
161
257
|
results: tailResults,
|
|
162
258
|
returnedCount: tailResults.length,
|
|
163
|
-
|
|
164
|
-
totalMatches: session.totalMatches, // Actual matches only
|
|
165
|
-
isComplete: session.isComplete,
|
|
166
|
-
isError: session.isError && !!session.error?.trim(), // Only error if we have actual errors
|
|
167
|
-
error: session.error?.trim() || undefined,
|
|
168
|
-
hasMoreResults: false, // Tail always returns what's available
|
|
169
|
-
runtime: Date.now() - session.startTime,
|
|
170
|
-
wasIncomplete: session.wasIncomplete
|
|
259
|
+
hasMoreResults: false // Tail always returns what's available
|
|
171
260
|
};
|
|
172
261
|
}
|
|
173
262
|
// Handle positive offsets (range behavior) - like file reading
|
|
174
263
|
const slicedResults = allResults.slice(offset, offset + length);
|
|
175
264
|
const hasMoreResults = offset + length < allResults.length || !session.isComplete;
|
|
176
|
-
session.lastReadTime = Date.now();
|
|
177
265
|
return {
|
|
266
|
+
...this.stateOf(session),
|
|
178
267
|
results: slicedResults,
|
|
179
268
|
returnedCount: slicedResults.length,
|
|
180
|
-
|
|
181
|
-
|
|
269
|
+
hasMoreResults
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/** What answers say about a session (see handlers/search-answers.ts) */
|
|
273
|
+
stateOf(session) {
|
|
274
|
+
return {
|
|
275
|
+
sessionId: session.id,
|
|
182
276
|
isComplete: session.isComplete,
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
277
|
+
outcome: session.outcome,
|
|
278
|
+
failure: session.failure,
|
|
279
|
+
unsearched: [...session.unsearched.values()],
|
|
280
|
+
timeLimitMs: session.timeLimitMs,
|
|
281
|
+
maxResults: session.options.maxResults,
|
|
282
|
+
totalMatches: session.totalMatches,
|
|
283
|
+
totalResults: session.totalMatches + session.totalContextLines,
|
|
284
|
+
runtime: (session.endTime ?? Date.now()) - session.startTime,
|
|
285
|
+
skippedLines: this.skippedLinesOf(session)
|
|
188
286
|
};
|
|
189
287
|
}
|
|
288
|
+
skippedLinesOf(session) {
|
|
289
|
+
return [...session.skippedLines].map(([file, count]) => ({ file, count }));
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Keeps ripgrep's error output for the answer (shown when a search fails
|
|
293
|
+
* without results), each piece once and up to MAX_KEPT_ERROR_CHARS: a search
|
|
294
|
+
* over folders it can't read can print an error per entry, and the session
|
|
295
|
+
* keeps this until it is cleaned up. What comes first is kept.
|
|
296
|
+
*/
|
|
297
|
+
keepErrorOutput(session, text) {
|
|
298
|
+
const kept = session.error ?? '';
|
|
299
|
+
if (kept.length >= MAX_KEPT_ERROR_CHARS)
|
|
300
|
+
return;
|
|
301
|
+
session.error = kept + text.slice(0, MAX_KEPT_ERROR_CHARS - kept.length);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Resolves with all of a session's results once it is complete: every source
|
|
305
|
+
* has finished, or the search was stopped.
|
|
306
|
+
*/
|
|
307
|
+
async waitForCompletion(sessionId) {
|
|
308
|
+
const session = this.sessions.get(sessionId);
|
|
309
|
+
if (!session) {
|
|
310
|
+
throw new Error(`Search session ${sessionId} not found`);
|
|
311
|
+
}
|
|
312
|
+
await session.completed;
|
|
313
|
+
return [...session.results];
|
|
314
|
+
}
|
|
190
315
|
/**
|
|
191
316
|
* Terminate a search session (like force_terminate)
|
|
192
317
|
*/
|
|
@@ -195,13 +320,38 @@ import PizZip from 'pizzip';
|
|
|
195
320
|
if (!session) {
|
|
196
321
|
return false;
|
|
197
322
|
}
|
|
198
|
-
if (!session.
|
|
199
|
-
session.
|
|
200
|
-
|
|
323
|
+
if (!session.isComplete)
|
|
324
|
+
session.stopReason ?? (session.stopReason = 'stopped');
|
|
325
|
+
this.stopSources(session);
|
|
201
326
|
// Don't delete session immediately - let user read final results
|
|
202
327
|
// It will be cleaned up by cleanup process
|
|
203
328
|
return true;
|
|
204
329
|
}
|
|
330
|
+
/**
|
|
331
|
+
* Stop every running search and drop all sessions and the cleanup timer.
|
|
332
|
+
* For owners that tear the search manager down (shutdown, tests); a later
|
|
333
|
+
* startSearch() starts afresh.
|
|
334
|
+
*/
|
|
335
|
+
dispose() {
|
|
336
|
+
for (const session of this.sessions.values()) {
|
|
337
|
+
this.stopSources(session);
|
|
338
|
+
}
|
|
339
|
+
this.sessions.clear();
|
|
340
|
+
if (this.cleanupTimer) {
|
|
341
|
+
clearInterval(this.cleanupTimer);
|
|
342
|
+
this.cleanupTimer = null;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Start the periodic cleanup of old sessions. It is housekeeping only, so it
|
|
347
|
+
* is unref'd: it must never keep the process alive on its own.
|
|
348
|
+
*/
|
|
349
|
+
startCleanupIfNeeded() {
|
|
350
|
+
if (this.cleanupTimer)
|
|
351
|
+
return;
|
|
352
|
+
this.cleanupTimer = setInterval(() => this.cleanupSessions(), 5 * 60 * 1000);
|
|
353
|
+
this.cleanupTimer.unref();
|
|
354
|
+
}
|
|
205
355
|
/**
|
|
206
356
|
* Get list of active search sessions (like list_sessions)
|
|
207
357
|
*/
|
|
@@ -211,11 +361,46 @@ import PizZip from 'pizzip';
|
|
|
211
361
|
searchType: session.options.searchType,
|
|
212
362
|
pattern: session.options.pattern,
|
|
213
363
|
isComplete: session.isComplete,
|
|
214
|
-
isError: session.
|
|
215
|
-
runtime: Date.now() - session.startTime,
|
|
364
|
+
isError: session.outcome === 'failed',
|
|
365
|
+
runtime: (session.endTime ?? Date.now()) - session.startTime,
|
|
216
366
|
totalResults: session.totalMatches + session.totalContextLines
|
|
217
367
|
}));
|
|
218
368
|
}
|
|
369
|
+
/**
|
|
370
|
+
* Run an Excel or DOCX search as one of the session's sources: its matches are
|
|
371
|
+
* collected as it finds them, until it has searched every file or the session
|
|
372
|
+
* stops it (stop_search, timeout, maxResults).
|
|
373
|
+
*/
|
|
374
|
+
startOfficeSource(session, source, search) {
|
|
375
|
+
session.pendingSources.add(source);
|
|
376
|
+
const sink = {
|
|
377
|
+
onMatch: result => {
|
|
378
|
+
if (session.pendingSources.has(source))
|
|
379
|
+
this.collectMatch(session, result);
|
|
380
|
+
},
|
|
381
|
+
isStopped: () => !session.pendingSources.has(source),
|
|
382
|
+
couldNotRead: (what, filePath, error) => {
|
|
383
|
+
if (!session.pendingSources.has(source))
|
|
384
|
+
return;
|
|
385
|
+
const code = error?.code;
|
|
386
|
+
if (isPermissionError(error))
|
|
387
|
+
this.noteUnsearched(session, 'permissions', filePath);
|
|
388
|
+
else
|
|
389
|
+
this.noteUnsearched(session, `${source}_${what}`, what === 'folder' ? `${filePath}: ${code ?? errorText(error)}` : filePath);
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
search(sink)
|
|
393
|
+
.catch((err) => {
|
|
394
|
+
// Log Office search errors but don't fail the whole search: its answer
|
|
395
|
+
// says that part couldn't be searched
|
|
396
|
+
const message = errorText(err);
|
|
397
|
+
logger.error(`The ${source} part of search ${session.id} failed; its matches are missing: ${message}`);
|
|
398
|
+
capture(`${source}_search_error`, { error: message });
|
|
399
|
+
if (session.pendingSources.has(source))
|
|
400
|
+
this.noteUnsearched(session, `${source}_search`, message);
|
|
401
|
+
})
|
|
402
|
+
.finally(() => this.finishSource(session, source));
|
|
403
|
+
}
|
|
219
404
|
/**
|
|
220
405
|
* Search Excel files for content matches
|
|
221
406
|
* Called during content search to include Excel files alongside text files
|
|
@@ -225,51 +410,35 @@ import PizZip from 'pizzip';
|
|
|
225
410
|
* and inject into SearchManager, similar to how file handlers are structured in src/utils/files/
|
|
226
411
|
* This would allow adding other file type searches (PDF, etc.) without bloating search-manager.ts
|
|
227
412
|
*/
|
|
228
|
-
async searchExcelFiles(rootPath, pattern, ignoreCase,
|
|
229
|
-
const results = [];
|
|
413
|
+
async searchExcelFiles(rootPath, pattern, ignoreCase, sink, filePattern, includeHidden = false) {
|
|
230
414
|
// Office file search always uses literal matching to prevent ReDoS.
|
|
231
415
|
// Regex patterns are treated as literal strings — this is intentional.
|
|
232
416
|
const searchTerm = ignoreCase ? pattern.toLowerCase() : pattern;
|
|
233
417
|
// Find Excel files recursively
|
|
234
|
-
let excelFiles = await this.findExcelFiles(rootPath);
|
|
418
|
+
let excelFiles = await this.findExcelFiles(rootPath, sink, includeHidden);
|
|
235
419
|
// Filter by filePattern if provided
|
|
236
420
|
if (filePattern) {
|
|
237
|
-
|
|
238
|
-
excelFiles = excelFiles.filter(filePath => {
|
|
239
|
-
const fileName = path.basename(filePath);
|
|
240
|
-
return patterns.some(pat => {
|
|
241
|
-
// Support glob-like patterns
|
|
242
|
-
if (pat.includes('*')) {
|
|
243
|
-
// Escape all regex metacharacters first (preserving * for glob expansion),
|
|
244
|
-
// then convert the remaining * wildcards to .* for glob matching.
|
|
245
|
-
// Without this, patterns like report(2024).xlsx or [draft].xlsx would be
|
|
246
|
-
// misinterpreted as regex groups/character-classes.
|
|
247
|
-
const regexPat = pat
|
|
248
|
-
.replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape metacharacters except *
|
|
249
|
-
.replace(/\*/g, '.*'); // glob * → regex .*
|
|
250
|
-
return new RegExp(`^${regexPat}$`, 'i').test(fileName);
|
|
251
|
-
}
|
|
252
|
-
// Exact match (case-insensitive)
|
|
253
|
-
return fileName.toLowerCase() === pat.toLowerCase();
|
|
254
|
-
});
|
|
255
|
-
});
|
|
421
|
+
excelFiles = this.filterOfficeFiles(excelFiles, filePattern, rootPath);
|
|
256
422
|
}
|
|
257
|
-
|
|
258
|
-
|
|
423
|
+
if (excelFiles.length === 0)
|
|
424
|
+
return;
|
|
425
|
+
// ExcelJS, to search all sheets: loaded here if the server hasn't yet
|
|
426
|
+
// (a search runs in the background, so it isn't refused while it loads)
|
|
427
|
+
const ExcelJS = exceljsPackage.load();
|
|
259
428
|
for (const filePath of excelFiles) {
|
|
260
|
-
if (
|
|
429
|
+
if (sink.isStopped())
|
|
261
430
|
break;
|
|
262
431
|
try {
|
|
263
|
-
const workbook = new ExcelJS.
|
|
432
|
+
const workbook = new ExcelJS.Workbook();
|
|
264
433
|
await workbook.xlsx.readFile(filePath);
|
|
265
434
|
// Search ALL sheets in the workbook (row-wise for speed and cross-column matching)
|
|
266
435
|
for (const worksheet of workbook.worksheets) {
|
|
267
|
-
if (
|
|
436
|
+
if (sink.isStopped())
|
|
268
437
|
break;
|
|
269
438
|
const sheetName = worksheet.name;
|
|
270
439
|
// Iterate through rows (faster than cell-by-cell)
|
|
271
440
|
worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
|
|
272
|
-
if (
|
|
441
|
+
if (sink.isStopped())
|
|
273
442
|
return;
|
|
274
443
|
// Build a concatenated string of all cell values in the row
|
|
275
444
|
const rowValues = [];
|
|
@@ -304,7 +473,7 @@ import PizZip from 'pizzip';
|
|
|
304
473
|
const matchIndex = textToSearch.indexOf(searchTerm);
|
|
305
474
|
if (matchIndex !== -1) {
|
|
306
475
|
const matchContext = this.getMatchContext(rowText, matchIndex, searchTerm.length);
|
|
307
|
-
|
|
476
|
+
sink.onMatch({
|
|
308
477
|
file: `${filePath}:${sheetName}!Row${rowNumber}`,
|
|
309
478
|
line: rowNumber,
|
|
310
479
|
match: matchContext,
|
|
@@ -315,25 +484,36 @@ import PizZip from 'pizzip';
|
|
|
315
484
|
}
|
|
316
485
|
}
|
|
317
486
|
catch (error) {
|
|
318
|
-
// Skip files that can't be read (permission issues, corrupted, etc.)
|
|
487
|
+
// Skip files that can't be read (permission issues, corrupted, etc.); the answer says so
|
|
488
|
+
sink.couldNotRead('file', filePath, error);
|
|
319
489
|
continue;
|
|
320
490
|
}
|
|
321
491
|
}
|
|
322
|
-
return results;
|
|
323
492
|
}
|
|
324
493
|
/**
|
|
325
|
-
*
|
|
494
|
+
* Whether the Excel/DOCX search walks into a folder: never node_modules, and a
|
|
495
|
+
* hidden one (a name starting with '.') only with includeHidden, as ripgrep
|
|
496
|
+
* enters hidden folders only with --hidden.
|
|
497
|
+
*/
|
|
498
|
+
officeWalkEnters(name, includeHidden) {
|
|
499
|
+
return name !== 'node_modules' && (includeHidden || !name.startsWith('.'));
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Find all Excel files in a directory recursively. Stops walking once the
|
|
503
|
+
* search is stopped; a folder it can't list is reported to the sink.
|
|
326
504
|
*/
|
|
327
|
-
async findExcelFiles(rootPath) {
|
|
505
|
+
async findExcelFiles(rootPath, sink, includeHidden = false) {
|
|
328
506
|
const excelFiles = [];
|
|
507
|
+
const enters = (name) => this.officeWalkEnters(name, includeHidden);
|
|
329
508
|
async function walk(dir) {
|
|
509
|
+
if (sink.isStopped())
|
|
510
|
+
return;
|
|
330
511
|
try {
|
|
331
512
|
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
332
513
|
for (const entry of entries) {
|
|
333
514
|
const fullPath = path.join(dir, entry.name);
|
|
334
515
|
if (entry.isDirectory()) {
|
|
335
|
-
|
|
336
|
-
if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
|
|
516
|
+
if (enters(entry.name)) {
|
|
337
517
|
await walk(fullPath);
|
|
338
518
|
}
|
|
339
519
|
}
|
|
@@ -342,8 +522,9 @@ import PizZip from 'pizzip';
|
|
|
342
522
|
}
|
|
343
523
|
}
|
|
344
524
|
}
|
|
345
|
-
catch {
|
|
346
|
-
// Skip directories we can't read
|
|
525
|
+
catch (error) {
|
|
526
|
+
// Skip directories we can't read; the answer says so
|
|
527
|
+
sink.couldNotRead('folder', dir, error);
|
|
347
528
|
}
|
|
348
529
|
}
|
|
349
530
|
// Check if rootPath is a file or directory
|
|
@@ -362,51 +543,72 @@ import PizZip from 'pizzip';
|
|
|
362
543
|
return excelFiles;
|
|
363
544
|
}
|
|
364
545
|
/**
|
|
365
|
-
*
|
|
546
|
+
* The Excel/DOCX files a filePattern selects, as ripgrep's globs select text
|
|
547
|
+
* files (ripgrepGlobMatcher), ignoring case: one of its alternatives matches
|
|
548
|
+
* the file (any file, when all of them are "!" alternatives), and none of its
|
|
549
|
+
* "!" alternatives leaves it out (see officeFileExcluded). A search path that
|
|
550
|
+
* is itself a file is searched whatever the pattern says, as ripgrep searches
|
|
551
|
+
* a file it is given.
|
|
366
552
|
*/
|
|
367
|
-
|
|
368
|
-
const
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
553
|
+
filterOfficeFiles(files, filePattern, rootPath) {
|
|
554
|
+
const patterns = filePatternAlternatives(filePattern);
|
|
555
|
+
const includes = patterns.filter(pat => !pat.startsWith('!')).map(pat => ripgrepGlobMatcher(pat, true));
|
|
556
|
+
const excludes = patterns.filter(pat => pat.startsWith('!')).map(pat => pat.slice(1));
|
|
557
|
+
return files.filter(filePath => {
|
|
558
|
+
if (filePath === rootPath)
|
|
372
559
|
return true;
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
560
|
+
const relativePath = pathBelow(rootPath, filePath);
|
|
561
|
+
return (includes.length === 0 || includes.some(matches => matches(relativePath))) &&
|
|
562
|
+
!excludes.some(pat => this.officeFileExcluded(relativePath, pat));
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Whether a "!" alternative of a filePattern (given without its "!") leaves an
|
|
567
|
+
* Excel/DOCX file out - as it leaves text files out of ripgrep's search: when
|
|
568
|
+
* it matches the file, or a directory between the search path and the file;
|
|
569
|
+
* ending in '/', only directories.
|
|
570
|
+
*/
|
|
571
|
+
officeFileExcluded(relativePath, exclusion) {
|
|
572
|
+
const dirOnly = exclusion.endsWith('/');
|
|
573
|
+
const matches = ripgrepGlobMatcher(exclusion.replace(/\/+$/, ''), true);
|
|
574
|
+
const parts = relativePath.split('/');
|
|
575
|
+
// The directories between the search path and the file, then the file itself
|
|
576
|
+
const candidates = parts.map((_, i) => parts.slice(0, i + 1).join('/')).slice(0, dirOnly ? -1 : undefined);
|
|
577
|
+
return candidates.some(candidate => matches(candidate));
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Whether a content search runs the Excel or DOCX search, the one for files
|
|
581
|
+
* with these extensions. Only when contextually relevant: the rootPath is
|
|
582
|
+
* such a file, or a filePattern alternative targets them ("*.xlsx",
|
|
583
|
+
* "budget.xlsx") - which one that leaves files out ("!*.xlsx") does not.
|
|
584
|
+
* Each alternative is checked on its own, so "report.xlsx|memo.docx" runs both.
|
|
585
|
+
*/
|
|
586
|
+
targetsOfficeFiles(extensions, filePattern, rootPath) {
|
|
587
|
+
const lowerRootPath = rootPath.toLowerCase();
|
|
588
|
+
const targetingPatterns = filePatternAlternatives(filePattern)
|
|
589
|
+
.filter(pattern => !pattern.startsWith('!'))
|
|
590
|
+
.map(pattern => pattern.toLowerCase());
|
|
591
|
+
return extensions.some(ext => lowerRootPath.endsWith(ext) ||
|
|
592
|
+
targetingPatterns.some(pattern => pattern.includes(`*${ext}`) || pattern.endsWith(ext)));
|
|
382
593
|
}
|
|
383
594
|
/**
|
|
384
595
|
* Search DOCX files for content matches
|
|
385
596
|
* Extracts <w:t> text from document.xml and searches it
|
|
386
597
|
*/
|
|
387
|
-
async searchDocxFiles(rootPath, pattern, ignoreCase,
|
|
388
|
-
const results = [];
|
|
598
|
+
async searchDocxFiles(rootPath, pattern, ignoreCase, sink, filePattern, includeHidden = false) {
|
|
389
599
|
// Office file search always uses literal matching to prevent ReDoS.
|
|
390
600
|
// Regex patterns are treated as literal strings — this is intentional.
|
|
391
601
|
const searchTerm = ignoreCase ? pattern.toLowerCase() : pattern;
|
|
392
|
-
let docxFiles = await this.findDocxFiles(rootPath);
|
|
602
|
+
let docxFiles = await this.findDocxFiles(rootPath, sink, includeHidden);
|
|
393
603
|
if (filePattern) {
|
|
394
|
-
|
|
395
|
-
docxFiles = docxFiles.filter(filePath => {
|
|
396
|
-
const fileName = path.basename(filePath);
|
|
397
|
-
return patterns.some(pat => {
|
|
398
|
-
if (pat.includes('*')) {
|
|
399
|
-
const regexPat = pat
|
|
400
|
-
.replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape metacharacters except *
|
|
401
|
-
.replace(/\*/g, '.*'); // glob * → regex .*
|
|
402
|
-
return new RegExp(`^${regexPat}$`, 'i').test(fileName);
|
|
403
|
-
}
|
|
404
|
-
return fileName.toLowerCase() === pat.toLowerCase();
|
|
405
|
-
});
|
|
406
|
-
});
|
|
604
|
+
docxFiles = this.filterOfficeFiles(docxFiles, filePattern, rootPath);
|
|
407
605
|
}
|
|
606
|
+
if (docxFiles.length === 0)
|
|
607
|
+
return;
|
|
608
|
+
// PizZip, to open the DOCX files: loaded here if the server hasn't yet
|
|
609
|
+
const PizZip = pizzipPackage.load();
|
|
408
610
|
for (const filePath of docxFiles) {
|
|
409
|
-
if (
|
|
611
|
+
if (sink.isStopped())
|
|
410
612
|
break;
|
|
411
613
|
try {
|
|
412
614
|
const buf = await fs.readFile(filePath);
|
|
@@ -415,7 +617,7 @@ import PizZip from 'pizzip';
|
|
|
415
617
|
const xmlParts = ['word/document.xml', 'word/header1.xml', 'word/header2.xml',
|
|
416
618
|
'word/header3.xml', 'word/footer1.xml', 'word/footer2.xml', 'word/footer3.xml'];
|
|
417
619
|
for (const xmlPath of xmlParts) {
|
|
418
|
-
if (
|
|
620
|
+
if (sink.isStopped())
|
|
419
621
|
break;
|
|
420
622
|
const file = zip.file(xmlPath);
|
|
421
623
|
if (!file)
|
|
@@ -426,7 +628,7 @@ import PizZip from 'pizzip';
|
|
|
426
628
|
let m;
|
|
427
629
|
let lineNum = 0;
|
|
428
630
|
while ((m = wtRe.exec(xml)) !== null) {
|
|
429
|
-
if (
|
|
631
|
+
if (sink.isStopped())
|
|
430
632
|
break;
|
|
431
633
|
const text = m[1];
|
|
432
634
|
if (!text || !text.trim())
|
|
@@ -437,7 +639,7 @@ import PizZip from 'pizzip';
|
|
|
437
639
|
if (matchIndex !== -1) {
|
|
438
640
|
const matchContext = this.getMatchContext(text, matchIndex, searchTerm.length);
|
|
439
641
|
const partName = xmlPath === 'word/document.xml' ? '' : `:${xmlPath.replace('word/', '')}`;
|
|
440
|
-
|
|
642
|
+
sink.onMatch({
|
|
441
643
|
file: `${filePath}${partName}`,
|
|
442
644
|
line: lineNum,
|
|
443
645
|
match: matchContext,
|
|
@@ -447,25 +649,30 @@ import PizZip from 'pizzip';
|
|
|
447
649
|
}
|
|
448
650
|
}
|
|
449
651
|
}
|
|
450
|
-
catch {
|
|
652
|
+
catch (error) {
|
|
653
|
+
// A file that can't be read: the answer says so
|
|
654
|
+
sink.couldNotRead('file', filePath, error);
|
|
451
655
|
continue;
|
|
452
656
|
}
|
|
453
657
|
}
|
|
454
|
-
return results;
|
|
455
658
|
}
|
|
456
659
|
/**
|
|
457
|
-
* Find all DOCX files in a directory recursively
|
|
660
|
+
* Find all DOCX files in a directory recursively. Stops walking once the
|
|
661
|
+
* search is stopped; a folder it can't list is reported to the sink.
|
|
458
662
|
*/
|
|
459
|
-
async findDocxFiles(rootPath) {
|
|
663
|
+
async findDocxFiles(rootPath, sink, includeHidden = false) {
|
|
460
664
|
const docxFiles = [];
|
|
665
|
+
const enters = (name) => this.officeWalkEnters(name, includeHidden);
|
|
461
666
|
const isDocx = (name) => name.toLowerCase().endsWith('.docx');
|
|
462
667
|
async function walk(dir) {
|
|
668
|
+
if (sink.isStopped())
|
|
669
|
+
return;
|
|
463
670
|
try {
|
|
464
671
|
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
465
672
|
for (const entry of entries) {
|
|
466
673
|
const fullPath = path.join(dir, entry.name);
|
|
467
674
|
if (entry.isDirectory()) {
|
|
468
|
-
if (
|
|
675
|
+
if (enters(entry.name)) {
|
|
469
676
|
await walk(fullPath);
|
|
470
677
|
}
|
|
471
678
|
}
|
|
@@ -474,7 +681,9 @@ import PizZip from 'pizzip';
|
|
|
474
681
|
}
|
|
475
682
|
}
|
|
476
683
|
}
|
|
477
|
-
catch {
|
|
684
|
+
catch (error) {
|
|
685
|
+
sink.couldNotRead('folder', dir, error);
|
|
686
|
+
}
|
|
478
687
|
}
|
|
479
688
|
try {
|
|
480
689
|
const stats = await fs.stat(rootPath);
|
|
@@ -521,13 +730,20 @@ import PizZip from 'pizzip';
|
|
|
521
730
|
getActiveSessionCount() {
|
|
522
731
|
return Array.from(this.sessions.values()).filter(session => !session.isComplete).length;
|
|
523
732
|
}
|
|
733
|
+
/**
|
|
734
|
+
* A file search for one exact filename ("package.json"): a lookup of a known
|
|
735
|
+
* file, unlike a content search for that same text
|
|
736
|
+
*/
|
|
737
|
+
isExactFilenameSearch(options) {
|
|
738
|
+
return options.searchType === 'files' && this.isExactFilename(options.pattern, options.literalSearch);
|
|
739
|
+
}
|
|
524
740
|
/**
|
|
525
741
|
* Detect if pattern looks like an exact filename
|
|
526
|
-
* (has file extension and no glob wildcards)
|
|
742
|
+
* (has file extension and no glob wildcards; a literal pattern has none)
|
|
527
743
|
*/
|
|
528
|
-
isExactFilename(pattern) {
|
|
744
|
+
isExactFilename(pattern, literal = false) {
|
|
529
745
|
return /\.[a-zA-Z0-9]+$/.test(pattern) &&
|
|
530
|
-
!this.isGlobPattern(pattern);
|
|
746
|
+
(literal || !this.isGlobPattern(pattern));
|
|
531
747
|
}
|
|
532
748
|
/**
|
|
533
749
|
* Detect if pattern contains glob wildcards
|
|
@@ -541,33 +757,35 @@ import PizZip from 'pizzip';
|
|
|
541
757
|
pattern.includes('}');
|
|
542
758
|
}
|
|
543
759
|
/**
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
* - filePattern explicitly targets Excel files (*.xlsx, *.xls, *.xlsm, *.xlsb)
|
|
547
|
-
* - or the rootPath itself is an Excel file
|
|
760
|
+
* A file search's filePattern alternatives other than "!", which a file it
|
|
761
|
+
* finds must match one of (see filePatternSelects); undefined when there are none
|
|
548
762
|
*/
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
763
|
+
filePatternIncludes(options, root) {
|
|
764
|
+
if (options.searchType !== 'files')
|
|
765
|
+
return undefined;
|
|
766
|
+
const includes = filePatternAlternatives(options.filePattern).filter(pattern => !pattern.startsWith('!'));
|
|
767
|
+
if (includes.length === 0)
|
|
768
|
+
return undefined;
|
|
769
|
+
return { root, matchers: includes.map(glob => ripgrepGlobMatcher(glob, options.ignoreCase !== false)) };
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Whether a file a file search found is one its filePattern selects: ripgrep
|
|
773
|
+
* checked the "!" alternatives (see buildRipgrepArgs), one of the others must
|
|
774
|
+
* match it. ripgrep can't check those itself: with the pattern's glob in the
|
|
775
|
+
* same list, any glob that matches lets a file in.
|
|
776
|
+
*/
|
|
777
|
+
filePatternSelects(session, file) {
|
|
778
|
+
const includes = session.filePatternIncludes;
|
|
779
|
+
if (!includes)
|
|
780
|
+
return true;
|
|
781
|
+
const relativePath = pathBelow(includes.root, file);
|
|
782
|
+
return includes.matchers.some(matches => matches(relativePath));
|
|
568
783
|
}
|
|
569
784
|
buildRipgrepArgs(options) {
|
|
570
|
-
|
|
785
|
+
// These arguments are the whole search: the user's ripgrep config file
|
|
786
|
+
// (RIPGREP_CONFIG_PATH) must not add flags such as --hidden, --glob,
|
|
787
|
+
// --max-count or --null that change what is found or the output parsed here
|
|
788
|
+
const args = ['--no-config'];
|
|
571
789
|
if (options.searchType === 'content') {
|
|
572
790
|
// Content search mode
|
|
573
791
|
args.push('--json', '--line-number');
|
|
@@ -590,45 +808,47 @@ import PizZip from 'pizzip';
|
|
|
590
808
|
if (options.includeHidden) {
|
|
591
809
|
args.push('--hidden');
|
|
592
810
|
}
|
|
811
|
+
// maxResults caps the TOTAL number of matches (see collectMatch()), so no
|
|
812
|
+
// file can contribute more than that: -m stops ripgrep there in each file.
|
|
813
|
+
// Without it a folder search keeps a file's whole output in ripgrep's memory
|
|
814
|
+
// until the file is done, however little of it the search can use. (ripgrep
|
|
815
|
+
// still prints a match that falls in the trailing context of its last one;
|
|
816
|
+
// collectRipgrepLine() takes it like any other. --files ignores -m.)
|
|
593
817
|
if (options.maxResults && options.maxResults > 0) {
|
|
594
818
|
args.push('-m', options.maxResults.toString());
|
|
595
819
|
}
|
|
596
820
|
// File pattern filtering (for file type restrictions like *.js, *.d.ts)
|
|
597
|
-
if (options.filePattern) {
|
|
598
|
-
const
|
|
599
|
-
.
|
|
600
|
-
.map(p => p.trim())
|
|
601
|
-
.filter(Boolean);
|
|
602
|
-
for (const p of patterns) {
|
|
603
|
-
if (options.searchType === 'content') {
|
|
604
|
-
args.push('-g', p);
|
|
605
|
-
}
|
|
606
|
-
else {
|
|
607
|
-
// For file search: use --iglob for case-insensitive or --glob for case-sensitive
|
|
608
|
-
if (options.ignoreCase !== false) {
|
|
609
|
-
args.push('--iglob', p);
|
|
610
|
-
}
|
|
611
|
-
else {
|
|
612
|
-
args.push('--glob', p);
|
|
613
|
-
}
|
|
614
|
-
}
|
|
821
|
+
if (options.filePattern && options.searchType === 'content') {
|
|
822
|
+
for (const p of filePatternAlternatives(options.filePattern)) {
|
|
823
|
+
args.push('-g', p);
|
|
615
824
|
}
|
|
616
825
|
}
|
|
617
826
|
// Handle the main search pattern
|
|
618
827
|
if (options.searchType === 'files') {
|
|
619
828
|
// For file search: determine how to treat the pattern
|
|
829
|
+
// (--iglob for case-insensitive or --glob for case-sensitive)
|
|
620
830
|
const globFlag = options.ignoreCase !== false ? '--iglob' : '--glob';
|
|
621
|
-
|
|
831
|
+
// literalSearch: the pattern is an exact string, glob characters and all
|
|
832
|
+
const name = options.literalSearch ? literalGlob(options.pattern) : options.pattern;
|
|
833
|
+
if (this.isExactFilename(options.pattern, options.literalSearch)) {
|
|
622
834
|
// Exact filename: use appropriate glob flag with the exact pattern
|
|
623
|
-
args.push(globFlag,
|
|
835
|
+
args.push(globFlag, name);
|
|
624
836
|
}
|
|
625
|
-
else if (this.isGlobPattern(options.pattern)) {
|
|
837
|
+
else if (!options.literalSearch && this.isGlobPattern(options.pattern)) {
|
|
626
838
|
// Already a glob pattern: use appropriate glob flag as-is
|
|
627
839
|
args.push(globFlag, options.pattern);
|
|
628
840
|
}
|
|
629
841
|
else {
|
|
630
842
|
// Substring/fuzzy search: wrap with wildcards
|
|
631
|
-
args.push(globFlag, `*${
|
|
843
|
+
args.push(globFlag, `*${name}*`);
|
|
844
|
+
}
|
|
845
|
+
// filePattern narrows the files the pattern finds. Its "!" alternatives
|
|
846
|
+
// come after the pattern's glob, since ripgrep's last matching glob wins;
|
|
847
|
+
// the others are checked on what ripgrep finds (filePatternSelects), and
|
|
848
|
+
// still reach ripgrep as --pre-globs: it parses them (an invalid one is its
|
|
849
|
+
// error, as for any glob) but without --pre never applies them
|
|
850
|
+
for (const p of filePatternAlternatives(options.filePattern)) {
|
|
851
|
+
args.push(...(p.startsWith('!') ? [globFlag, p] : ['--pre-glob', p]));
|
|
632
852
|
}
|
|
633
853
|
// Add the root path for file mode
|
|
634
854
|
args.push(options.rootPath);
|
|
@@ -640,18 +860,37 @@ import PizZip from 'pizzip';
|
|
|
640
860
|
}
|
|
641
861
|
return args;
|
|
642
862
|
}
|
|
863
|
+
/**
|
|
864
|
+
* Resolves once ripgrep has started; else logs why it could not start (not
|
|
865
|
+
* found, not executable...) and rejects with the error start_search always
|
|
866
|
+
* reported. 'spawn' or 'error' comes on the next tick, before any I/O, so
|
|
867
|
+
* the caller still sets up its handlers in time.
|
|
868
|
+
*/
|
|
869
|
+
async whenStarted(child) {
|
|
870
|
+
try {
|
|
871
|
+
await once(child, 'spawn');
|
|
872
|
+
}
|
|
873
|
+
catch (error) {
|
|
874
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
875
|
+
logger.error(`Failed to start ripgrep: ${reason}`);
|
|
876
|
+
throw Object.assign(new Error('Failed to start ripgrep process'), { cause: error });
|
|
877
|
+
}
|
|
878
|
+
}
|
|
643
879
|
setupProcessHandlers(session) {
|
|
644
880
|
const { process } = session;
|
|
881
|
+
// Decoded as streams: a character cut between two chunks stays whole
|
|
882
|
+
// (decoding each chunk on its own made it U+FFFD, in matches and paths)
|
|
883
|
+
process.stdout?.setEncoding('utf8');
|
|
884
|
+
process.stderr?.setEncoding('utf8');
|
|
645
885
|
process.stdout?.on('data', (data) => {
|
|
646
|
-
session.
|
|
647
|
-
this.
|
|
886
|
+
session.printedOutput = true;
|
|
887
|
+
this.processOutput(session, data);
|
|
648
888
|
});
|
|
649
889
|
process.stderr?.on('data', (data) => {
|
|
650
890
|
const errorText = data.toString();
|
|
651
|
-
// Store error text for potential user display
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
// Filter meaningful errors
|
|
891
|
+
// Store error text for potential user display (bounded: see keepErrorOutput)
|
|
892
|
+
this.keepErrorOutput(session, errorText);
|
|
893
|
+
// Filter meaningful errors, for telemetry; they are part of the text kept above
|
|
655
894
|
const filteredErrors = errorText
|
|
656
895
|
.split('\n')
|
|
657
896
|
.filter(line => {
|
|
@@ -664,11 +903,9 @@ import PizZip from 'pizzip';
|
|
|
664
903
|
return false;
|
|
665
904
|
return true;
|
|
666
905
|
});
|
|
667
|
-
// Only add to session.error if there are actual meaningful errors after filtering
|
|
668
906
|
if (filteredErrors.length > 0) {
|
|
669
907
|
const meaningfulErrors = filteredErrors.join('\n').trim();
|
|
670
908
|
if (meaningfulErrors) {
|
|
671
|
-
session.error = (session.error || '') + meaningfulErrors + '\n';
|
|
672
909
|
capture('search_session_error', {
|
|
673
910
|
sessionId: session.id,
|
|
674
911
|
error: meaningfulErrors.substring(0, 200)
|
|
@@ -677,93 +914,297 @@ import PizZip from 'pizzip';
|
|
|
677
914
|
}
|
|
678
915
|
});
|
|
679
916
|
process.on('close', (code) => {
|
|
680
|
-
// Process
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
//
|
|
686
|
-
//
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
// 3. We found no results at all
|
|
694
|
-
if (code !== 0 && code !== 1 && code !== 2) {
|
|
695
|
-
// Codes 0=success, 1=no matches, 2=some files couldn't be searched
|
|
696
|
-
if (session.error?.trim() && session.totalMatches === 0) {
|
|
697
|
-
session.isError = true;
|
|
698
|
-
session.error = session.error || `ripgrep exited with code ${code}`;
|
|
699
|
-
}
|
|
917
|
+
// Process the last line, if the output did not end with a newline
|
|
918
|
+
this.processOutput(session, '', true);
|
|
919
|
+
// Exit codes: 0 found, 1 found nothing, 2 an error. No code: a signal
|
|
920
|
+
// ended it, ours (time limit, stop_search, maxResults) or not.
|
|
921
|
+
// A content search's ripgrep prints a JSON line for each file it searches
|
|
922
|
+
// and a summary at the end: exiting 2 with nothing printed, it could not
|
|
923
|
+
// search at all (an invalid pattern or glob), rather than meeting files it
|
|
924
|
+
// couldn't read. A file search prints only the names it finds, so for it
|
|
925
|
+
// the error must say so: a glob it could not parse. Its error is the answer,
|
|
926
|
+
// whatever the Excel/DOCX searches find.
|
|
927
|
+
const couldNotSearch = session.options.searchType === 'content' || /^rg: error parsing glob /m.test(session.error ?? '');
|
|
928
|
+
if (code === 2 && !session.printedOutput && session.error?.trim() && couldNotSearch) {
|
|
929
|
+
session.failure = { error: session.error.trim() };
|
|
700
930
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
wasIncomplete: session.wasIncomplete || false // NEW: Track incomplete searches
|
|
712
|
-
});
|
|
713
|
-
// Rely on cleanupSessions(maxAge) only; no per-session timer
|
|
931
|
+
else if (code === 2) {
|
|
932
|
+
this.noteRipgrepErrors(session);
|
|
933
|
+
}
|
|
934
|
+
else if (code !== 0 && code !== 1 && !session.stoppedRipgrep) {
|
|
935
|
+
const how = code === null ? `signal ${session.process.signalCode}` : `exit code ${code}`;
|
|
936
|
+
session.ripgrepTrouble ?? (session.ripgrepTrouble = how);
|
|
937
|
+
this.noteUnsearched(session, 'ripgrep_ended', how);
|
|
938
|
+
}
|
|
939
|
+
session.exitCode = code;
|
|
940
|
+
this.finishSource(session, 'ripgrep');
|
|
714
941
|
});
|
|
715
942
|
process.on('error', (error) => {
|
|
716
|
-
session.isComplete = true;
|
|
717
|
-
session.isError = true;
|
|
718
943
|
session.error = `Process error: ${error.message}`;
|
|
719
|
-
|
|
944
|
+
session.ripgrepTrouble ?? (session.ripgrepTrouble = session.error);
|
|
945
|
+
this.noteUnsearched(session, 'ripgrep_ended', session.error);
|
|
946
|
+
this.finishSource(session, 'ripgrep');
|
|
720
947
|
});
|
|
721
948
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
949
|
+
/**
|
|
950
|
+
* ripgrep searched, and ended with exit code 2: some paths couldn't be
|
|
951
|
+
* searched, each named on stderr ("rg: <path>: <why> (os error N)"). Those it
|
|
952
|
+
* may not read are about permissions; any other error is trouble, which fails
|
|
953
|
+
* a search that found nothing (see outcomeOf).
|
|
954
|
+
*/
|
|
955
|
+
noteRipgrepErrors(session) {
|
|
956
|
+
const errors = (session.error ?? '').split('\n').filter(line => line.startsWith('rg: ')).map(line => line.slice(4).trim());
|
|
957
|
+
for (const error of errors) {
|
|
958
|
+
const osError = Number(/\(os error (\d+)\)$/.exec(error)?.[1]);
|
|
959
|
+
if (PERMISSION_OS_ERRORS.includes(osError)) {
|
|
960
|
+
this.noteUnsearched(session, 'permissions', error);
|
|
961
|
+
}
|
|
962
|
+
else {
|
|
963
|
+
session.ripgrepTrouble ?? (session.ripgrepTrouble = error);
|
|
964
|
+
this.noteUnsearched(session, 'ripgrep_error', error);
|
|
965
|
+
}
|
|
727
966
|
}
|
|
728
|
-
|
|
729
|
-
session.
|
|
967
|
+
if (errors.length === 0) {
|
|
968
|
+
session.ripgrepTrouble ?? (session.ripgrepTrouble = 'exit code 2');
|
|
969
|
+
this.noteUnsearched(session, 'ripgrep_ended', 'exit code 2');
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
/** Something the search couldn't search: counted by kind, the first one kept as the example */
|
|
973
|
+
noteUnsearched(session, kind, example) {
|
|
974
|
+
const noted = session.unsearched.get(kind);
|
|
975
|
+
if (noted)
|
|
976
|
+
noted.count++;
|
|
977
|
+
else
|
|
978
|
+
session.unsearched.set(kind, { kind, count: 1, example });
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* The session's one outcome, once every source is done. A failure first:
|
|
982
|
+
* ripgrep couldn't search at all, or had trouble and nothing was found. Then
|
|
983
|
+
* what stopped the search, if anything did; then what couldn't be searched.
|
|
984
|
+
*/
|
|
985
|
+
outcomeOf(session) {
|
|
986
|
+
if (!session.failure && session.ripgrepTrouble && session.totalMatches === 0) {
|
|
987
|
+
const error = session.error?.trim();
|
|
988
|
+
session.failure = error ? { error } : { ripgrepEnded: session.ripgrepTrouble };
|
|
989
|
+
}
|
|
990
|
+
if (session.failure)
|
|
991
|
+
return 'failed';
|
|
992
|
+
if (session.stopReason)
|
|
993
|
+
return session.stopReason;
|
|
994
|
+
return session.unsearched.size > 0 ? 'partial' : 'completed';
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* A source has ended, or was stopped. This is the one place a session
|
|
998
|
+
* completes: when its last source is done, whatever the order they end in.
|
|
999
|
+
*/
|
|
1000
|
+
finishSource(session, source) {
|
|
1001
|
+
session.pendingSources.delete(source);
|
|
1002
|
+
if (session.pendingSources.size > 0 || session.isComplete)
|
|
1003
|
+
return;
|
|
1004
|
+
session.outcome = this.outcomeOf(session);
|
|
1005
|
+
session.isComplete = true;
|
|
1006
|
+
session.endTime = Date.now();
|
|
1007
|
+
clearTimeout(session.timeoutTimer);
|
|
1008
|
+
capture('search_session_completed', {
|
|
1009
|
+
sessionId: session.id,
|
|
1010
|
+
exitCode: session.exitCode,
|
|
1011
|
+
totalResults: session.totalMatches + session.totalContextLines,
|
|
1012
|
+
totalMatches: session.totalMatches,
|
|
1013
|
+
runtime: session.endTime - session.startTime,
|
|
1014
|
+
outcome: session.outcome,
|
|
1015
|
+
wasIncomplete: session.outcome === 'partial' // Some files couldn't be searched
|
|
1016
|
+
});
|
|
1017
|
+
session.markCompleted();
|
|
1018
|
+
// Rely on cleanupSessions(maxAge) only; no per-session timer
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Stop every source still running (stop_search, timeout, dispose); the
|
|
1022
|
+
* session completes once ripgrep has exited.
|
|
1023
|
+
*/
|
|
1024
|
+
stopSources(session) {
|
|
1025
|
+
this.stopOfficeSources(session);
|
|
1026
|
+
this.stopRipgrep(session);
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* The Excel/DOCX searches are done as of now. They can't be interrupted
|
|
1030
|
+
* mid-file: each stops at its next check, and anything it still finds is dropped.
|
|
1031
|
+
*/
|
|
1032
|
+
stopOfficeSources(session) {
|
|
1033
|
+
for (const source of session.pendingSources) {
|
|
1034
|
+
if (source === 'excel' || source === 'docx')
|
|
1035
|
+
this.finishSource(session, source);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
stopRipgrep(session) {
|
|
1039
|
+
if (session.pendingSources.has('ripgrep') && !session.process.killed) {
|
|
1040
|
+
session.stoppedRipgrep = true;
|
|
1041
|
+
session.process.kill('SIGTERM');
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Split ripgrep's output into lines as it arrives. Only the new text is split,
|
|
1046
|
+
* its first piece joined to the line pending from earlier chunks, so a line
|
|
1047
|
+
* costs time linear in its length (splitting the whole pending line again for
|
|
1048
|
+
* every chunk made a long line quadratic). With isFinal, the pending line is
|
|
1049
|
+
* complete as it is.
|
|
1050
|
+
*/
|
|
1051
|
+
processOutput(session, text, isFinal = false) {
|
|
1052
|
+
const pieces = text.split('\n');
|
|
1053
|
+
const lines = [];
|
|
1054
|
+
pieces.forEach((piece, i) => {
|
|
1055
|
+
this.appendToLine(session, piece);
|
|
1056
|
+
if (i < pieces.length - 1 || isFinal) {
|
|
1057
|
+
const line = this.takeLine(session);
|
|
1058
|
+
if (line !== undefined)
|
|
1059
|
+
lines.push(line);
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
this.processLines(session, lines);
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Add text to the line being received, unless that makes it longer than
|
|
1066
|
+
* MAX_OUTPUT_LINE_CHARS: then the line is skipped, noted by its file, and
|
|
1067
|
+
* the rest of it dropped as it arrives.
|
|
1068
|
+
*/
|
|
1069
|
+
appendToLine(session, text) {
|
|
1070
|
+
if (session.skippingLine || !text)
|
|
1071
|
+
return;
|
|
1072
|
+
if (session.buffer.length + text.length <= MAX_OUTPUT_LINE_CHARS) {
|
|
1073
|
+
session.buffer += text;
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
const file = this.fileOfOutputLine((session.buffer + text).slice(0, 4096)) ?? '';
|
|
1077
|
+
session.skippedLines.set(file, (session.skippedLines.get(file) ?? 0) + 1);
|
|
1078
|
+
session.skippingLine = true;
|
|
1079
|
+
session.buffer = '';
|
|
1080
|
+
}
|
|
1081
|
+
/** The line being received, now complete; undefined if it was skipped */
|
|
1082
|
+
takeLine(session) {
|
|
1083
|
+
const line = session.buffer;
|
|
1084
|
+
session.buffer = '';
|
|
1085
|
+
if (session.skippingLine) {
|
|
1086
|
+
session.skippingLine = false;
|
|
1087
|
+
return undefined;
|
|
1088
|
+
}
|
|
1089
|
+
return line;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* The file a line of ripgrep's --json output is about, read from the line's
|
|
1093
|
+
* start: {"type":"match","data":{"path":{"text":"..."},... (a path that is
|
|
1094
|
+
* not valid UTF-8 comes as "bytes" and is not read)
|
|
1095
|
+
*/
|
|
1096
|
+
fileOfOutputLine(start) {
|
|
1097
|
+
const quoted = /^\{"type":"\w+","data":\{"path":\{"text":("(?:[^"\\]|\\.)*")/.exec(start)?.[1];
|
|
1098
|
+
try {
|
|
1099
|
+
return quoted ? JSON.parse(quoted) : undefined;
|
|
1100
|
+
}
|
|
1101
|
+
catch {
|
|
1102
|
+
// A malformed escape in the path: the skipped line is then counted without a file name
|
|
1103
|
+
return undefined;
|
|
730
1104
|
}
|
|
1105
|
+
}
|
|
1106
|
+
processLines(session, lines) {
|
|
731
1107
|
for (const line of lines) {
|
|
732
1108
|
if (!line.trim())
|
|
733
1109
|
continue;
|
|
734
|
-
const
|
|
735
|
-
if (result) {
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
}
|
|
741
|
-
else {
|
|
742
|
-
session.totalMatches++;
|
|
743
|
-
}
|
|
1110
|
+
const parsed = this.parseLine(line, session.options.searchType);
|
|
1111
|
+
if (parsed?.kind === 'match' && parsed.result.type === 'file' && !this.filePatternSelects(session, parsed.result.file)) {
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
if (parsed) {
|
|
1115
|
+
this.collectRipgrepLine(session, parsed);
|
|
744
1116
|
// Early termination for exact filename matches (if enabled)
|
|
745
|
-
if (
|
|
746
|
-
session.options.
|
|
747
|
-
this.
|
|
1117
|
+
if (parsed.kind === 'match' &&
|
|
1118
|
+
session.options.earlyTermination !== false && // Default to true
|
|
1119
|
+
this.isExactFilenameSearch(session.options)) {
|
|
748
1120
|
const pat = path.normalize(session.options.pattern);
|
|
749
|
-
const filePath = path.normalize(result.file);
|
|
1121
|
+
const filePath = path.normalize(parsed.result.file);
|
|
750
1122
|
const ignoreCase = session.options.ignoreCase !== false;
|
|
751
1123
|
const ends = ignoreCase
|
|
752
1124
|
? filePath.toLowerCase().endsWith(pat.toLowerCase())
|
|
753
1125
|
: filePath.endsWith(pat);
|
|
754
1126
|
if (ends) {
|
|
755
1127
|
// Found exact match, terminate search early
|
|
756
|
-
setTimeout(() =>
|
|
757
|
-
if (!session.process.killed) {
|
|
758
|
-
session.process.kill('SIGTERM');
|
|
759
|
-
}
|
|
760
|
-
}, 100); // Small delay to allow any remaining results
|
|
1128
|
+
setTimeout(() => this.stopRipgrep(session), 100); // Small delay to allow any remaining results
|
|
761
1129
|
break;
|
|
762
1130
|
}
|
|
763
1131
|
}
|
|
764
1132
|
}
|
|
765
1133
|
}
|
|
766
1134
|
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Collect one line of ripgrep output. Once maxResults matches are in, only the
|
|
1137
|
+
* last match's trailing context is still collected - a matching line inside it
|
|
1138
|
+
* is kept as context, like grep -m - and ripgrep is stopped when it ends.
|
|
1139
|
+
*/
|
|
1140
|
+
collectRipgrepLine(session, line) {
|
|
1141
|
+
if (line.kind !== 'match' && line.kind !== 'context') {
|
|
1142
|
+
// A file ended (or the next began): no trailing context is pending any more
|
|
1143
|
+
session.trailingContext = undefined;
|
|
1144
|
+
}
|
|
1145
|
+
else if (!this.atMaxResults(session)) {
|
|
1146
|
+
if (line.kind === 'context') {
|
|
1147
|
+
session.results.push(line.result);
|
|
1148
|
+
session.totalContextLines++;
|
|
1149
|
+
}
|
|
1150
|
+
else {
|
|
1151
|
+
// Note where this match's trailing context ends, in case it is the last match
|
|
1152
|
+
const contextLines = session.options.contextLines ?? 0;
|
|
1153
|
+
session.trailingContext = line.result.type === 'content' && line.result.line !== undefined && contextLines > 0
|
|
1154
|
+
? { file: line.result.file, lastLine: line.result.line + contextLines }
|
|
1155
|
+
: undefined;
|
|
1156
|
+
this.collectMatch(session, line.result);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
else {
|
|
1160
|
+
const trailing = session.trailingContext;
|
|
1161
|
+
const lineNumber = line.result.line;
|
|
1162
|
+
if (trailing && line.result.file === trailing.file && lineNumber !== undefined && lineNumber <= trailing.lastLine) {
|
|
1163
|
+
session.results.push({ ...line.result, context: true });
|
|
1164
|
+
session.totalContextLines++;
|
|
1165
|
+
if (lineNumber === trailing.lastLine) {
|
|
1166
|
+
session.trailingContext = undefined;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
else {
|
|
1170
|
+
// Past the last match's trailing context: everything from here on is dropped
|
|
1171
|
+
session.trailingContext = undefined;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
this.stopAtMaxResults(session);
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* The one place a session counts a match - from ripgrep, Excel or DOCX alike -
|
|
1178
|
+
* so maxResults caps the TOTAL number of matches a search returns.
|
|
1179
|
+
*/
|
|
1180
|
+
collectMatch(session, result) {
|
|
1181
|
+
if (this.atMaxResults(session))
|
|
1182
|
+
return;
|
|
1183
|
+
session.results.push(result);
|
|
1184
|
+
session.totalMatches++;
|
|
1185
|
+
if (this.atMaxResults(session)) {
|
|
1186
|
+
session.stopReason ?? (session.stopReason = 'max_results');
|
|
1187
|
+
this.stopAtMaxResults(session);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
/** Whether options.maxResults matches are in: later ones are dropped */
|
|
1191
|
+
atMaxResults(session) {
|
|
1192
|
+
const { maxResults } = session.options;
|
|
1193
|
+
return !!maxResults && maxResults > 0 && session.totalMatches >= maxResults;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Once maxResults matches are in, stop the sources that cannot contribute
|
|
1197
|
+
* anything more: the Excel/DOCX searches at once, ripgrep when the last
|
|
1198
|
+
* match's trailing context is complete.
|
|
1199
|
+
*/
|
|
1200
|
+
stopAtMaxResults(session) {
|
|
1201
|
+
if (!this.atMaxResults(session))
|
|
1202
|
+
return;
|
|
1203
|
+
this.stopOfficeSources(session);
|
|
1204
|
+
if (!session.trailingContext) {
|
|
1205
|
+
this.stopRipgrep(session);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
767
1208
|
parseLine(line, searchType) {
|
|
768
1209
|
if (searchType === 'content') {
|
|
769
1210
|
// Parse JSON output from content search
|
|
@@ -773,26 +1214,32 @@ import PizZip from 'pizzip';
|
|
|
773
1214
|
// Handle multiple submatches per line - return first submatch
|
|
774
1215
|
const submatch = parsed.data?.submatches?.[0];
|
|
775
1216
|
return {
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
1217
|
+
kind: 'match',
|
|
1218
|
+
result: {
|
|
1219
|
+
file: parsed.data.path.text,
|
|
1220
|
+
line: parsed.data.line_number,
|
|
1221
|
+
match: keptText(submatch?.match?.text || parsed.data.lines.text),
|
|
1222
|
+
type: 'content'
|
|
1223
|
+
}
|
|
780
1224
|
};
|
|
781
1225
|
}
|
|
782
1226
|
if (parsed.type === 'context') {
|
|
783
1227
|
return {
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1228
|
+
kind: 'context',
|
|
1229
|
+
result: {
|
|
1230
|
+
context: true,
|
|
1231
|
+
file: parsed.data.path.text,
|
|
1232
|
+
line: parsed.data.line_number,
|
|
1233
|
+
match: keptText(parsed.data.lines.text.trim()),
|
|
1234
|
+
type: 'content'
|
|
1235
|
+
}
|
|
788
1236
|
};
|
|
789
1237
|
}
|
|
790
|
-
//
|
|
791
|
-
if (parsed.type === '
|
|
792
|
-
|
|
793
|
-
return null;
|
|
1238
|
+
// begin/end frame each file's lines; summary closes the output
|
|
1239
|
+
if (parsed.type === 'begin' || parsed.type === 'end') {
|
|
1240
|
+
return { kind: parsed.type, file: parsed.data.path.text };
|
|
794
1241
|
}
|
|
795
|
-
return
|
|
1242
|
+
return { kind: 'summary' };
|
|
796
1243
|
}
|
|
797
1244
|
catch (error) {
|
|
798
1245
|
// Skip invalid JSON lines
|
|
@@ -802,27 +1249,14 @@ import PizZip from 'pizzip';
|
|
|
802
1249
|
else {
|
|
803
1250
|
// File search - each line is a file path
|
|
804
1251
|
return {
|
|
805
|
-
|
|
806
|
-
|
|
1252
|
+
kind: 'match',
|
|
1253
|
+
result: {
|
|
1254
|
+
file: line.trim(),
|
|
1255
|
+
type: 'file'
|
|
1256
|
+
}
|
|
807
1257
|
};
|
|
808
1258
|
}
|
|
809
1259
|
}
|
|
810
1260
|
}
|
|
811
1261
|
// Global search manager instance
|
|
812
1262
|
export const searchManager = new SearchManager();
|
|
813
|
-
// Cleanup management - run on fixed schedule
|
|
814
|
-
let cleanupInterval = null;
|
|
815
|
-
/**
|
|
816
|
-
* Start cleanup interval - now runs on fixed schedule
|
|
817
|
-
*/
|
|
818
|
-
function startCleanupIfNeeded() {
|
|
819
|
-
if (!cleanupInterval) {
|
|
820
|
-
cleanupInterval = setInterval(() => {
|
|
821
|
-
searchManager.cleanupSessions();
|
|
822
|
-
}, 5 * 60 * 1000);
|
|
823
|
-
// Also check immediately after a short delay (let search process finish)
|
|
824
|
-
setTimeout(() => {
|
|
825
|
-
searchManager.cleanupSessions();
|
|
826
|
-
}, 1000);
|
|
827
|
-
}
|
|
828
|
-
}
|