@innovatorved/code-lab 0.1.7 → 0.1.9

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/src/search.ts ADDED
@@ -0,0 +1,389 @@
1
+ /**
2
+ * @innovatorved/code-lab — High-Performance Cross-File Search & Replace Core
3
+ * ============================================================================
4
+ * Pure TypeScript implementation of workspace-wide text search and atomic multi-file
5
+ * replacements. Supports regex, whole-word, case-sensitive matching, glob filtering,
6
+ * line/column coordinate extraction, and match highlight snippets.
7
+ *
8
+ * Strict leaf module: fully typed, zero explicit any, zero empty catches.
9
+ */
10
+
11
+ export interface SearchOptions {
12
+ query?: string;
13
+ caseSensitive?: boolean;
14
+ wholeWord?: boolean;
15
+ regex?: boolean;
16
+ isRegex?: boolean;
17
+ include?: string;
18
+ includeGlob?: string;
19
+ includePattern?: string | string[];
20
+ exclude?: string;
21
+ excludeGlob?: string;
22
+ excludePattern?: string | string[];
23
+ maxMatches?: number;
24
+ maxMatchesPerFile?: number;
25
+ targetFiles?: string[];
26
+ }
27
+
28
+ export interface SearchMatchItem {
29
+ line: number;
30
+ col: number;
31
+ column?: number;
32
+ length: number;
33
+ matchText?: string;
34
+ lineText: string;
35
+ beforeSnippet?: string;
36
+ afterSnippet?: string;
37
+ matchIndex?: number;
38
+ matchEndIndex?: number;
39
+ }
40
+
41
+ export interface SearchMatchGroup {
42
+ file: string;
43
+ matches: SearchMatchItem[];
44
+ }
45
+
46
+ export interface SearchResult extends Array<SearchMatchGroup> {
47
+ matches: SearchMatchGroup[];
48
+ totalMatches: number;
49
+ fileCount: number;
50
+ filesCount: number;
51
+ query: string;
52
+ durationMs?: number;
53
+ error?: string;
54
+ }
55
+
56
+ export interface ReplaceResult {
57
+ updatedFiles: Record<string, string>;
58
+ replacedCount: number;
59
+ filesAffected: string[];
60
+ }
61
+
62
+ /**
63
+ * Escapes regex special characters in a literal string.
64
+ */
65
+ export function escapeRegex(text: string): string {
66
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
67
+ }
68
+
69
+ /**
70
+ * Normalizes a virtual workspace path (POSIX forward-slashes, no leading ./ or /).
71
+ */
72
+ export function normalizeSearchPath(filePath: string): string {
73
+ let p = filePath.replace(/\\/g, '/');
74
+ while (p.startsWith('./')) {
75
+ p = p.slice(2);
76
+ }
77
+ while (p.startsWith('/')) {
78
+ p = p.slice(1);
79
+ }
80
+ return p;
81
+ }
82
+
83
+ /**
84
+ * Matches a file path against a glob or literal substring filter.
85
+ */
86
+ export function matchesGlob(filePath: string, pattern: string): boolean {
87
+ if (!pattern || pattern === '*' || pattern === '**') return true;
88
+ const normPath = normalizeSearchPath(filePath);
89
+ const normPattern = normalizeSearchPath(pattern);
90
+
91
+ if (normPattern === normPath) return true;
92
+
93
+ // Plain substring match if no wildcards present
94
+ if (!normPattern.includes('*') && !normPattern.includes('?')) {
95
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
96
+ }
97
+
98
+ // Convert glob pattern to regular expression
99
+ let regexStr = '^';
100
+ let i = 0;
101
+ while (i < normPattern.length) {
102
+ const c = normPattern[i];
103
+ if (c === '*') {
104
+ if (normPattern[i + 1] === '*') {
105
+ regexStr += '.*';
106
+ i += 2;
107
+ if (normPattern[i] === '/') {
108
+ i++;
109
+ }
110
+ continue;
111
+ } else {
112
+ regexStr += '[^/]*';
113
+ i++;
114
+ continue;
115
+ }
116
+ } else if (c === '?') {
117
+ regexStr += '[^/]';
118
+ i++;
119
+ continue;
120
+ } else if ('./+^$()|[]{}\\'.includes(c)) {
121
+ regexStr += '\\' + c;
122
+ i++;
123
+ continue;
124
+ } else {
125
+ regexStr += c;
126
+ i++;
127
+ }
128
+ }
129
+ regexStr += '$';
130
+
131
+ try {
132
+ const re = new RegExp(regexStr);
133
+ return re.test(normPath);
134
+ } catch (err) {
135
+ void err;
136
+ return normPath.includes(normPattern.replace(/[*?]/g, ''));
137
+ }
138
+ }
139
+
140
+ function checkFilter(path: string, filter?: string | string[]): boolean {
141
+ if (!filter) return true;
142
+ if (Array.isArray(filter)) {
143
+ return filter.some((f) => matchesGlob(path, f));
144
+ }
145
+ return matchesGlob(path, filter);
146
+ }
147
+
148
+ function createSearchResult(
149
+ groups: SearchMatchGroup[],
150
+ totalMatches: number,
151
+ fileCount: number,
152
+ query: string,
153
+ error?: string
154
+ ): SearchResult {
155
+ const arr = [...groups];
156
+ const result = Object.assign(arr, {
157
+ matches: groups,
158
+ totalMatches,
159
+ fileCount,
160
+ filesCount: fileCount,
161
+ query,
162
+ durationMs: 0,
163
+ error
164
+ });
165
+ return result as SearchResult;
166
+ }
167
+
168
+ /**
169
+ * Searches across a map of virtual files for matching text or regex patterns.
170
+ */
171
+ export function searchInFiles(
172
+ files: Record<string, string>,
173
+ queryOrOptions: string | SearchOptions,
174
+ optionsOrUndefined?: SearchOptions
175
+ ): SearchResult {
176
+ let query = '';
177
+ let opts: SearchOptions = {};
178
+
179
+ if (typeof queryOrOptions === 'string') {
180
+ query = queryOrOptions;
181
+ opts = optionsOrUndefined || {};
182
+ } else if (queryOrOptions && typeof queryOrOptions === 'object') {
183
+ opts = queryOrOptions;
184
+ query = opts.query || '';
185
+ }
186
+
187
+ if (!query) {
188
+ return createSearchResult([], 0, 0, query);
189
+ }
190
+
191
+ const isCaseSensitive = Boolean(opts.caseSensitive);
192
+ const isWholeWord = Boolean(opts.wholeWord);
193
+ const isRegex = Boolean(opts.regex || opts.isRegex);
194
+ const maxMatches = opts.maxMatches ?? 10000;
195
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1000;
196
+
197
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
198
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
199
+
200
+ let patternStr = isRegex ? query : escapeRegex(query);
201
+ if (isWholeWord) {
202
+ patternStr = `\\b${patternStr}\\b`;
203
+ }
204
+
205
+ let regex: RegExp = /(?:)/;
206
+ try {
207
+ regex = new RegExp(patternStr, isCaseSensitive ? 'g' : 'gi');
208
+ } catch (err) {
209
+ const _err = err;
210
+ const msg =
211
+ typeof _err === 'object' && _err && 'message' in _err
212
+ ? String((_err as { message: unknown }).message)
213
+ : 'Invalid regular expression';
214
+ return createSearchResult([], 0, 0, query, msg);
215
+ }
216
+
217
+ const matchedGroups: SearchMatchGroup[] = [];
218
+ let totalMatches = 0;
219
+
220
+ for (const [filePath, content] of Object.entries(files)) {
221
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
222
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
223
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
224
+
225
+ const fileMatches: SearchMatchItem[] = [];
226
+ const lines = content.split('\n');
227
+
228
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
229
+ const lineText = lines[lineIndex];
230
+ regex.lastIndex = 0;
231
+ let m: RegExpExecArray | null = null;
232
+
233
+ while ((m = regex.exec(lineText)) !== null) {
234
+ const matchLen = m[0].length;
235
+ const col = m.index + 1;
236
+ fileMatches.push({
237
+ line: lineIndex + 1,
238
+ col,
239
+ column: col,
240
+ length: matchLen,
241
+ matchText: m[0],
242
+ lineText,
243
+ beforeSnippet: lineText.slice(0, m.index),
244
+ afterSnippet: lineText.slice(m.index + matchLen),
245
+ matchIndex: m.index,
246
+ matchEndIndex: m.index + matchLen
247
+ });
248
+ totalMatches++;
249
+
250
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
251
+ break;
252
+ }
253
+
254
+ // Prevent infinite loop on zero-width match
255
+ if (matchLen === 0) {
256
+ regex.lastIndex++;
257
+ if (regex.lastIndex > lineText.length) {
258
+ break;
259
+ }
260
+ }
261
+ }
262
+
263
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
264
+ break;
265
+ }
266
+ }
267
+
268
+ if (fileMatches.length > 0) {
269
+ matchedGroups.push({
270
+ file: filePath,
271
+ matches: fileMatches
272
+ });
273
+ }
274
+
275
+ if (totalMatches >= maxMatches) {
276
+ break;
277
+ }
278
+ }
279
+
280
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
281
+ }
282
+
283
+ /**
284
+ * Replaces occurrences of a query pattern across virtual workspace files.
285
+ */
286
+ export function replaceInFiles(
287
+ files: Record<string, string>,
288
+ arg2: string | SearchOptions,
289
+ arg3: string,
290
+ arg4?: SearchOptions | string[]
291
+ ): ReplaceResult {
292
+ let query = '';
293
+ const replacement = typeof arg3 === 'string' ? arg3 : '';
294
+ let opts: SearchOptions = {};
295
+ let targetFiles: string[] | undefined = undefined;
296
+
297
+ if (typeof arg2 === 'string') {
298
+ query = arg2;
299
+ if (Array.isArray(arg4)) {
300
+ targetFiles = arg4;
301
+ } else if (arg4 && typeof arg4 === 'object') {
302
+ opts = arg4;
303
+ targetFiles = opts.targetFiles;
304
+ }
305
+ } else if (arg2 && typeof arg2 === 'object') {
306
+ opts = arg2;
307
+ query = opts.query || '';
308
+ if (Array.isArray(arg4)) {
309
+ targetFiles = arg4;
310
+ } else {
311
+ targetFiles = opts.targetFiles;
312
+ }
313
+ }
314
+
315
+ if (!query) {
316
+ return {
317
+ updatedFiles: { ...files },
318
+ replacedCount: 0,
319
+ filesAffected: []
320
+ };
321
+ }
322
+
323
+ const isCaseSensitive = Boolean(opts.caseSensitive);
324
+ const isWholeWord = Boolean(opts.wholeWord);
325
+ const isRegex = Boolean(opts.regex || opts.isRegex);
326
+
327
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
328
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
329
+
330
+ let patternStr = isRegex ? query : escapeRegex(query);
331
+ if (isWholeWord) {
332
+ patternStr = `\\b${patternStr}\\b`;
333
+ }
334
+
335
+ let regex: RegExp = /(?:)/;
336
+ try {
337
+ regex = new RegExp(patternStr, isCaseSensitive ? 'g' : 'gi');
338
+ } catch (err) {
339
+ void err;
340
+ return {
341
+ updatedFiles: { ...files },
342
+ replacedCount: 0,
343
+ filesAffected: []
344
+ };
345
+ }
346
+
347
+ const updatedFiles: Record<string, string> = { ...files };
348
+ const filesAffected: string[] = [];
349
+ let replacedCount = 0;
350
+
351
+ for (const [filePath, content] of Object.entries(files)) {
352
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
353
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
354
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
355
+
356
+ // Count matches safely
357
+ regex.lastIndex = 0;
358
+ let countInFile = 0;
359
+ let m: RegExpExecArray | null;
360
+ while ((m = regex.exec(content)) !== null) {
361
+ countInFile++;
362
+ if (m[0].length === 0) {
363
+ regex.lastIndex++;
364
+ if (regex.lastIndex > content.length) {
365
+ break;
366
+ }
367
+ }
368
+ }
369
+
370
+ if (countInFile > 0) {
371
+ regex.lastIndex = 0;
372
+ let newContent: string;
373
+ if (isRegex) {
374
+ newContent = content.replace(regex, replacement);
375
+ } else {
376
+ newContent = content.replace(regex, () => replacement);
377
+ }
378
+ updatedFiles[filePath] = newContent;
379
+ filesAffected.push(filePath);
380
+ replacedCount += countInFile;
381
+ }
382
+ }
383
+
384
+ return {
385
+ updatedFiles,
386
+ replacedCount,
387
+ filesAffected
388
+ };
389
+ }