Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child
2import * as NodeFSP from "node:fs/promises";
3import * as NodeModule from "node:module";
4
5import type {
6 DirItem,
7 FileItem,
8 FileFinder as FileFinderType,
9 GrepCursor,
10 MixedItem,
11 Result,
12 WatchEvent,
13 WatchUnsubscribe,
14} from "@ff-labs/fff-node";
15import * as Clock from "effect/Clock";
16import * as Context from "effect/Context";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as LayerMap from "effect/LayerMap";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25
26import type {
27 ProjectEntry,
28 ProjectEntryKind,
29 ProjectListEntriesResult,
30 ProjectSearchContentsInput,
31 ProjectSearchContentsResult,
32 ProjectSearchEntriesResult,
33} from "@t3tools/contracts";
34import * as HostProcess from "@t3tools/shared/HostProcess";
35import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
36import { scoreSubsequenceMatch } from "@t3tools/shared/searchRanking";
37
38import * as VcsProcess from "../vcs/VcsProcess.ts";
39import { type IgnoreDecision, type IgnoreFile, parseIgnoreFile } from "./IgnorePatterns.ts";
40
41// fff-node's native library stays external; single-executables require disk packages instead of importing them.
42const requireForFff = NodeModule.createRequire(import.meta.url);
43const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
44
45// A glob intersects existing extension constraints; fff ORs bare `*.ext` constraints together.
46const IMAGE_SEARCH_CONSTRAINT = `**/*.{${PROJECT_FAVICON_EXTENSIONS.map((extension) =>
47 extension.slice(1).replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`),
48).join(",")}}`;
49
50// fff 0.11 disables filename fallback above this match count per base/overflow segment.
51const FFF_FILENAME_FALLBACK_MAX_MATCHES = 15_000;
52
53const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
54const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
55const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
56const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
57export const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
58const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
59const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
60const GIT_GREP_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
61// fff's lineContent cap; matches past it are reported without ranges.
62const CONTENT_LINE_MAX_LENGTH = 512;
63const SYMLINK_SCAN_CONCURRENCY = 16;
64// A scan no watcher can invalidate is reused this long, so typing does not rescan every folder.
65const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000;
66// A rescan that outlasts this leaves the read on the previous scan.
67const SYMLINK_RESCAN_WAIT = "5 millis";
68// Each page is a synchronous native call; small pages let searches run between them.
69const SYMLINK_DIRECTORY_PAGE_SIZE = 1_000;
70
71export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
72 "WorkspaceSearchIndexCreateFailed",
73 {
74 cwd: Schema.String,
75 reason: Schema.String,
76 cause: Schema.optional(Schema.Defect()),
77 },
78) {
79 override get message(): string {
80 return `Failed to create the workspace search index for '${this.cwd}'.`;
81 }
82}
83
84export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
85 "WorkspaceSearchIndexScanTimedOut",
86 {
87 cwd: Schema.String,
88 timeout: Schema.String,
89 },
90) {
91 override get message(): string {
92 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
93 }
94}
95
96export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
97 "WorkspaceSearchIndexSearchFailed",
98 {
99 cwd: Schema.String,
100 queryLength: Schema.Number,
101 pageSize: Schema.Number,
102 reason: Schema.String,
103 cause: Schema.optional(Schema.Defect()),
104 },
105) {
106 override get message(): string {
107 return `Workspace search failed for '${this.cwd}'.`;
108 }
109}
110
111export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
112 "WorkspaceSearchIndexRefreshFailed",
113 {
114 cwd: Schema.String,
115 reason: Schema.String,
116 cause: Schema.optional(Schema.Defect()),
117 },
118) {
119 override get message(): string {
120 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
121 }
122}
123
124export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
125 "WorkspaceSearchIndexDestroyFailed",
126 {
127 cwd: Schema.String,
128 cause: Schema.Defect(),
129 },
130) {
131 override get message(): string {
132 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
133 }
134}
135
136export class WorkspaceSearchIndex extends Context.Service<
137 WorkspaceSearchIndex,
138 {
139 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
140 readonly search: (
141 query: string,
142 limit: number,
143 kind?: ProjectEntryKind,
144 imageOnly?: boolean,
145 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
146 readonly searchContents: (
147 input: Omit<ProjectSearchContentsInput, "cwd">,
148 ) => Effect.Effect<
149 ProjectSearchContentsResult,
150 WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndexSearchFailed
151 >;
152 readonly refresh: () => Effect.Effect<void, WorkspaceSearchIndexRefreshFailed>;
153 }
154>()("t3/workspace/WorkspaceSearchIndex") {}
155
156// Only the host separator becomes `/`: on POSIX `\` is a file name character.
157function toPosixPath(input: string, hostIsWindows: boolean): string {
158 return hostIsWindows ? input.replaceAll("\\", "/") : input;
159}
160
161function trimDirectorySeparator(input: string): string {
162 return input.endsWith("/") ? input.slice(0, -1) : input;
163}
164
165function parentPathOf(input: string): string | undefined {
166 const separatorIndex = input.lastIndexOf("/");
167 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
168}
169
170function toProjectEntry(item: MixedItem, hostIsWindows: boolean): ProjectEntry | null {
171 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath, hostIsWindows));
172 if (!normalizedPath) {
173 return null;
174 }
175
176 return {
177 path: normalizedPath,
178 kind: item.type,
179 };
180}
181
182function toFileEntry(item: FileItem, hostIsWindows: boolean): ProjectEntry | null {
183 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
184 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
185}
186
187function toDirectoryEntry(item: DirItem, hostIsWindows: boolean): ProjectEntry | null {
188 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
189 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
190}
191
192function isLoneFuzzyPath(query: string): boolean {
193 const trimmed = query.trim();
194 return (
195 !/\s/u.test(trimmed) &&
196 (trimmed.startsWith("/") || (trimmed.endsWith("/") && !/^[*!\\]/u.test(trimmed)))
197 );
198}
199
200type SearchPage<I> = { readonly items: ReadonlyArray<I>; readonly totalMatched: number };
201
202function mapFileSearchResult(
203 result: SearchPage<FileItem>,
204 limit: number,
205 hostIsWindows: boolean,
206 imageOnly = false,
207): ProjectSearchEntriesResult {
208 const entries = result.items.flatMap((item) => {
209 const entry = toFileEntry(item, hostIsWindows);
210 return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : [];
211 });
212 return {
213 entries: entries.slice(0, limit),
214 truncated: entries.length > limit || result.totalMatched > result.items.length,
215 };
216}
217
218function mapDirectorySearchResult(
219 result: SearchPage<DirItem>,
220 limit: number,
221 hostIsWindows: boolean,
222): ProjectSearchEntriesResult {
223 const entries = result.items.flatMap((item) => {
224 const entry = toDirectoryEntry(item, hostIsWindows);
225 return entry ? [entry] : [];
226 });
227 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
228 return {
229 entries: entries.slice(0, limit),
230 truncated: result.totalMatched - rootDirectoryCount > limit,
231 };
232}
233
234function mapMixedSearchResult(
235 result: SearchPage<MixedItem>,
236 limit: number,
237 hostIsWindows: boolean,
238): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
239 const entries: ProjectEntry[] = [];
240 for (const item of result.items) {
241 const entry = toProjectEntry(item, hostIsWindows);
242 if (entry) {
243 entries.push(entry);
244 }
245 if (entries.length >= limit) {
246 break;
247 }
248 }
249
250 const rootDirectoryCount = result.items.some(
251 (item) => item.type === "directory" && item.item.relativePath.length === 0,
252 )
253 ? 1
254 : 0;
255 return {
256 entries,
257 truncated: result.totalMatched - rootDirectoryCount > limit,
258 };
259}
260
261const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
262
263function codePointAt(line: string, index: number): string | undefined {
264 const codePoint = line.codePointAt(index);
265 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
266}
267
268function codePointBefore(line: string, index: number): string | undefined {
269 if (index <= 0) return undefined;
270 const previousCodeUnit = line.charCodeAt(index - 1);
271 const previousIndex =
272 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
273 return codePointAt(line, previousIndex);
274}
275
276function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
277 readonly searchQuery: string;
278 readonly regexMode: boolean;
279} {
280 if (input.caseSensitive) {
281 return { searchQuery: input.query, regexMode: input.useRegex };
282 }
283 return input.useRegex
284 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
285 : { searchQuery: input.query.toLowerCase(), regexMode: false };
286}
287
288const ASCII_WORD = /^\w+$/;
289
290// A whole-word search for an ASCII word asks fff for the word itself, so substring hits are dropped
291// natively instead of filling pages with lines the JS check then discards. `-u` keeps `\b` and `i`
292// to ASCII: plain search does not fold `ſ` or `K`, and any non-ASCII neighbour stays a candidate.
293function buildWholeWordPattern(query: string, caseSensitive: boolean): string {
294 return `(?${caseSensitive ? "" : "i"}-u)\\b${query}\\b`;
295}
296
297// fff's ranges for that pattern are not used: the JS word check decides, on every hit in the line.
298function findWordRanges(
299 line: string,
300 word: string,
301 caseSensitive: boolean,
302): Array<{ readonly start: number; readonly end: number }> {
303 // No `u` flag: with it, `i` would fold `ſ` and `K` onto ASCII letters.
304 return Array.from(line.matchAll(new RegExp(word, caseSensitive ? "g" : "gi")), (match) => ({
305 start: match.index,
306 end: match.index + match[0].length,
307 }));
308}
309
310function mapContentMatchRanges(
311 line: string,
312 byteRanges: ReadonlyArray<readonly [number, number]>,
313): Array<{ readonly start: number; readonly end: number }> {
314 const lineBytes = Buffer.from(line);
315 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
316 return byteRanges.map(([startByte, endByte]) => ({
317 start: toStringIndex(startByte),
318 end: toStringIndex(endByte),
319 }));
320}
321
322function escapeRegExp(input: string): string {
323 return input.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
324}
325
326// Git before 2.55 reports wrong `--column` values for every match after a line's first, so
327// later matches are found by their text, searching on from the end of the previous one.
328function locateRegexMatches(
329 line: string,
330 matches: { readonly column: number; readonly texts: ReadonlyArray<string> } | undefined,
331): Array<readonly [number, number]> {
332 if (!matches) return [];
333 const lineBytes = Buffer.from(line);
334 const ranges: Array<readonly [number, number]> = [];
335 let start = matches.column - 1;
336 for (const text of matches.texts) {
337 const textBytes = Buffer.from(text);
338 if (ranges.length > 0) start = lineBytes.indexOf(textBytes, ranges.at(-1)![1]);
339 if (start < 0) break;
340 ranges.push([start, start + textBytes.length]);
341 }
342 return ranges;
343}
344
345// `git grep -z` records: NUL-separated fields, one record per line; a truncated last line is dropped.
346function parseGitGrepRecords(
347 stdout: string,
348 fieldCount: number,
349 truncated: boolean,
350): Array<Array<string>> {
351 const lines = stdout.split("\n");
352 if (truncated || lines.at(-1) === "") lines.pop();
353 const records: Array<Array<string>> = [];
354 for (const line of lines) {
355 const fields = line.split("\0");
356 if (fields.length < fieldCount) continue;
357 // Only the last field (the line or match text) can contain NUL bytes.
358 records.push([...fields.slice(0, fieldCount - 1), fields.slice(fieldCount - 1).join("\0")]);
359 }
360 return records;
361}
362
363// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges.
364function isWholeWordRange(
365 line: string,
366 range: { readonly start: number; readonly end: number },
367): boolean {
368 if (range.end <= range.start) return false;
369 const isWord = (character: string | undefined) =>
370 character !== undefined && WORD_CHARACTER.test(character);
371 const leftIsBoundary =
372 range.start === 0 ||
373 !isWord(codePointBefore(line, range.start)) ||
374 !isWord(codePointAt(line, range.start));
375 const rightIsBoundary =
376 range.end >= line.length ||
377 !isWord(codePointAt(line, range.end)) ||
378 !isWord(codePointBefore(line, range.end));
379 return leftIsBoundary && rightIsBoundary;
380}
381
382function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
383 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
384 for (const entry of entries) {
385 let parentPath = parentPathOf(entry.path);
386 while (parentPath) {
387 if (!entryByPath.has(parentPath)) {
388 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
389 }
390 parentPath = parentPathOf(parentPath);
391 }
392 }
393 return [...entryByPath.values()];
394}
395
396interface ScannedDirectory {
397 readonly directory: string;
398 readonly links: ReadonlyArray<ProjectEntry>;
399 /** Every symlink in the folder, including ones dropped for leaving the workspace. */
400 readonly linkPaths: ReadonlyArray<string>;
401 /** A nested repository (or the workspace's own), whose ignore rules own what is below it. */
402 readonly isRepository: boolean;
403 readonly ignoreFile: string | undefined;
404}
405
406const joinEntryPath = (directory: string, name: string) =>
407 directory ? `${directory}/${name}` : name;
408
409/**
410 * fff skips symlinks, and `followSymlinks` drops file links, dedupes folder links, and walks out
411 * of the workspace. So links are read from the folders fff already indexed (ignore rules applied),
412 * without descending into them, and kept only when they resolve inside the workspace.
413 */
414const scanDirectory = Effect.fn("WorkspaceSearchIndex.scanDirectory")(function* (
415 fileSystem: FileSystem.FileSystem,
416 path: Path.Path,
417 cwd: string,
418 root: string,
419 directory: string,
420) {
421 // Effect's readDirectory returns bare names; one lstat per child would cost far more.
422 const children = yield* Effect.promise(() =>
423 NodeFSP.readdir(path.join(cwd, directory), { withFileTypes: true }).catch(() => []),
424 );
425 const links: ProjectEntry[] = [];
426 const linkPaths: string[] = [];
427 let isRepository = false;
428 let ignoreFile: string | undefined;
429 for (const child of children) {
430 if (child.name === ".git") isRepository = true;
431 if (child.name === ".ignore" && child.isFile()) {
432 ignoreFile = yield* fileSystem
433 .readFileString(path.join(cwd, directory, child.name))
434 .pipe(Effect.orElseSucceed(() => undefined));
435 }
436 if (!child.isSymbolicLink()) continue;
437 const entryPath = joinEntryPath(directory, child.name);
438 linkPaths.push(entryPath);
439 const absolutePath = path.join(cwd, entryPath);
440 const target = yield* Effect.all([
441 fileSystem.realPath(absolutePath),
442 fileSystem.stat(absolutePath),
443 ]).pipe(Effect.orElseSucceed(() => undefined));
444 if (!target) continue;
445 const relative = path.relative(root, target[0]);
446 if (
447 relative === ".." ||
448 relative.startsWith(`..${path.sep}`) ||
449 path.isAbsolute(relative) ||
450 relative.split(path.sep).includes(".git") ||
451 (target[1].type !== "Directory" && target[1].type !== "File")
452 ) {
453 continue;
454 }
455 links.push({ path: entryPath, kind: target[1].type === "Directory" ? "directory" : "file" });
456 }
457 return { directory, links, linkPaths, isRepository, ignoreFile } satisfies ScannedDirectory;
458});
459
460/** Whether `entryPath` is `directory` itself or below it. */
461const isWithin = (entryPath: string, directory: string) =>
462 directory === "" || entryPath.startsWith(`${directory}/`);
463
464/**
465 * fff reads `.ignore` files alongside git's rules, and like ripgrep the nearest one that matches
466 * decides, ahead of any `.gitignore`. `ignoreFiles` is ordered deepest folder first.
467 */
468function decideByIgnoreFiles(
469 entry: ProjectEntry,
470 ignoreFiles: ReadonlyArray<{ readonly directory: string; readonly file: IgnoreFile }>,
471): IgnoreDecision | undefined {
472 for (const { directory, file } of ignoreFiles) {
473 if (!isWithin(entry.path, directory) || entry.path === directory) continue;
474 const relative = directory ? entry.path.slice(directory.length + 1) : entry.path;
475 // Like git and ripgrep, a link is never a folder to a folder-only rule, whatever it targets.
476 const decision = file.decide(relative, false);
477 if (decision) return decision;
478 }
479 return undefined;
480}
481
482/** Places each symlink before the first index result that matches the query less closely. */
483function mergeSymlinkMatches(
484 indexed: ProjectSearchEntriesResult,
485 linkPaths: ReadonlySet<string>,
486 symlinks: ReadonlyArray<ProjectEntry>,
487 query: string,
488 limit: number,
489): ProjectSearchEntriesResult {
490 if (linkPaths.size === 0) return indexed;
491 // fff's watcher indexes links created after its scan, under a kind of its own choosing, so a
492 // path it already returned takes the link's kind (or drops out of a kind-filtered search).
493 const symlinkByPath = new Map(symlinks.map((entry) => [entry.path, entry]));
494 const score = (entry: ProjectEntry) =>
495 scoreSubsequenceMatch(entry.path.toLowerCase(), query) ?? Number.POSITIVE_INFINITY;
496 const indexedPaths = new Set(indexed.entries.map((entry) => entry.path));
497 const pending = symlinks
498 .flatMap((entry) => {
499 const entryScore = score(entry);
500 return Number.isFinite(entryScore) && !indexedPaths.has(entry.path)
501 ? [{ entry, score: entryScore }]
502 : [];
503 })
504 .toSorted((left, right) => left.score - right.score);
505 const entries: ProjectEntry[] = [];
506 let nextPending = 0;
507 for (const indexedEntry of indexed.entries) {
508 const entry = linkPaths.has(indexedEntry.path)
509 ? symlinkByPath.get(indexedEntry.path)
510 : indexedEntry;
511 if (!entry) continue;
512 const entryScore = score(entry);
513 while (nextPending < pending.length && pending[nextPending]!.score < entryScore) {
514 entries.push(pending[nextPending++]!.entry);
515 }
516 entries.push(entry);
517 }
518 for (; nextPending < pending.length; nextPending += 1) entries.push(pending[nextPending]!.entry);
519 return {
520 entries: entries.slice(0, limit),
521 truncated: indexed.truncated || entries.length > limit,
522 };
523}
524
525// fff applies .gitignore files only; Git also ignores paths from .git/info/exclude and the global excludes file.
526const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths")(function* (
527 vcsProcess: VcsProcess.VcsProcess["Service"],
528 cwd: string,
529 hostIsWindows: boolean,
530) {
531 const result = yield* vcsProcess
532 .run({
533 operation: "WorkspaceSearchIndex.listGitIgnoredPaths",
534 command: "git",
535 args: [
536 "-c",
537 "core.fsmonitor=false",
538 "ls-files",
539 "--others",
540 "--ignored",
541 "--exclude-standard",
542 "--directory",
543 "-z",
544 ],
545 cwd,
546 allowNonZeroExit: true,
547 timeoutMs: 10_000,
548 maxOutputBytes: 16 * 1024 * 1024,
549 })
550 .pipe(Effect.orElseSucceed(() => undefined));
551 if (!result || result.exitCode !== 0 || result.stdoutTruncated) return [];
552 // Folders keep their trailing `/`.
553 return result.stdout
554 .split("\0")
555 .filter((entry) => entry.length > 0)
556 .map((entry) => toPosixPath(entry, hostIsWindows));
557});
558
559function mixedItemPath(item: MixedItem): string {
560 return item.item.relativePath;
561}
562
563function isIgnoredPath(
564 ignoredPaths: ReadonlySet<string>,
565 relativePath: string,
566 hostIsWindows: boolean,
567): boolean {
568 if (ignoredPaths.size === 0) return false;
569 let candidate: string | undefined = trimDirectorySeparator(
570 toPosixPath(relativePath, hostIsWindows),
571 );
572 while (candidate) {
573 if (ignoredPaths.has(candidate)) return true;
574 candidate = parentPathOf(candidate);
575 }
576 return false;
577}
578
579const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
580 cwd: string,
581 variant: WorkspaceSearchIndexVariant,
582) {
583 const result = yield* Effect.try({
584 try: () =>
585 FileFinder.create({
586 basePath: cwd,
587 disableMmapCache: true,
588 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
589 disableContentIndexing: variant !== "content",
590 aiMode: false,
591 }),
592 catch: (cause) =>
593 new WorkspaceSearchIndexCreateFailed({
594 cwd,
595 reason: "FileFinder.create threw unexpectedly.",
596 cause,
597 }),
598 });
599 if (result.ok) return result.value;
600 return yield* new WorkspaceSearchIndexCreateFailed({
601 cwd,
602 reason: result.error,
603 });
604});
605
606const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
607 cwd: string,
608 finder: FileFinderType,
609 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
610): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
611 const result = yield* Effect.tryPromise({
612 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
613 catch: (cause) =>
614 onFailure({
615 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
616 cause,
617 }),
618 });
619 if (!result.ok) {
620 return yield* Effect.fail(onFailure({ reason: result.error }));
621 }
622 if (!result.value) {
623 return yield* new WorkspaceSearchIndexScanTimedOut({
624 cwd,
625 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
626 });
627 }
628});
629
630export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
631 cwd: string,
632 variant: WorkspaceSearchIndexVariant = "paths",
633) {
634 const hostIsWindows = yield* HostProcess.isWindows;
635 const fileSystem = yield* FileSystem.FileSystem;
636 const path = yield* Path.Path;
637 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
638 Effect.try({
639 try: () => finder.destroy(),
640 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
641 }).pipe(Effect.orDie),
642 );
643 let initialScanTimedOut = false;
644 // The content index reads every file, which takes minutes where antivirus scans each open,
645 // so content searches do not wait for it; git grep answers until it is ready.
646 let contentIndexPending = variant === "content";
647 const vcsProcess = yield* VcsProcess.VcsProcess;
648
649 /** The nearest `.ignore` with a pattern matching `relativePath` itself decides. */
650 const makeIgnoreFileDecider = () => {
651 const ignoreFiles = new Map<string, IgnoreFile | undefined>();
652 const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* (
653 directory: string,
654 ) {
655 if (ignoreFiles.has(directory)) return ignoreFiles.get(directory);
656 const contents = yield* fileSystem
657 .readFileString(path.join(cwd, directory, ".ignore"))
658 .pipe(Effect.option);
659 const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined;
660 ignoreFiles.set(directory, file);
661 return file;
662 });
663 return Effect.fn("WorkspaceSearchIndex.decideByIgnoreFile")(function* (
664 relativePath: string,
665 isFolder: boolean,
666 ) {
667 const segments = relativePath.split("/");
668 for (let ancestor = segments.length - 1; ancestor >= 0; ancestor -= 1) {
669 const directory = segments.slice(0, ancestor).join("/");
670 const file = yield* readIgnoreFile(directory);
671 const relative = directory ? relativePath.slice(directory.length + 1) : relativePath;
672 const decision = file?.decide(relative, isFolder);
673 if (decision) return decision;
674 }
675 return undefined;
676 });
677 };
678
679 // Like ripgrep and fff, a `.ignore` that re-includes a path overrules Git's ignore rules for it.
680 const loadIgnoredPaths = Effect.fn("WorkspaceSearchIndex.loadIgnoredPaths")(function* () {
681 const decide = makeIgnoreFileDecider();
682 const ignored = new Set<string>();
683 for (const entry of yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows)) {
684 const relativePath = trimDirectorySeparator(entry);
685 if ((yield* decide(relativePath, entry.endsWith("/"))) !== "included") {
686 ignored.add(relativePath);
687 }
688 }
689 return ignored;
690 });
691 let ignoredPaths = yield* loadIgnoredPaths();
692 if (variant === "paths") {
693 yield* waitForIndexReady(
694 cwd,
695 finder,
696 ({ reason, cause }) =>
697 new WorkspaceSearchIndexCreateFailed({
698 cwd,
699 reason,
700 cause,
701 }),
702 ).pipe(
703 Effect.catchTags({
704 WorkspaceSearchIndexScanTimedOut: () =>
705 Effect.sync(() => {
706 initialScanTimedOut = true;
707 }),
708 }),
709 );
710 }
711
712 // fff's isScanning takes the picker lock too, so progress is read off the JS thread.
713 const isScanning = Effect.promise(async () => {
714 try {
715 const progress = await finder.getScanProgressAsync();
716 return !progress.ok || progress.value.isScanning;
717 } catch {
718 return true;
719 }
720 });
721 const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false));
722
723 const isContentIndexReady = Effect.fn("WorkspaceSearchIndex.isContentIndexReady")(function* () {
724 if (!contentIndexPending) return true;
725 const progress = yield* Effect.promise(() =>
726 finder.getScanProgressAsync().catch(() => undefined),
727 );
728 if (progress?.ok && !progress.value.isScanning && progress.value.isWarmupComplete) {
729 contentIndexPending = false;
730 }
731 return !contentIndexPending;
732 });
733
734 const runGitGrep = Effect.fn("WorkspaceSearchIndex.runGitGrep")(function* (
735 pattern: string,
736 options: {
737 readonly regexMode: boolean;
738 readonly ignoreCase: boolean;
739 readonly maxMatchesPerFile: number;
740 readonly onlyMatching: boolean;
741 },
742 ) {
743 return yield* vcsProcess
744 .run({
745 operation: "WorkspaceSearchIndex.gitGrep",
746 command: "git",
747 args: [
748 "-c",
749 "core.quotePath=false",
750 "-c",
751 "core.fsmonitor=false",
752 "-c",
753 "grep.column=false",
754 "-c",
755 "grep.fullName=false",
756 "-c",
757 "submodule.recurse=false",
758 "grep",
759 "--untracked",
760 "--no-color",
761 "-I",
762 "-n",
763 "-z",
764 "-m",
765 String(options.maxMatchesPerFile),
766 ...(options.onlyMatching ? ["-o", "--column"] : []),
767 ...(options.ignoreCase ? ["-i"] : []),
768 options.regexMode ? "-P" : "-F",
769 "-e",
770 pattern,
771 ],
772 cwd,
773 allowNonZeroExit: true,
774 // Defender scanning fff's warmup reads slows git too; a late answer beats a failure.
775 timeoutMs: 30_000,
776 maxOutputBytes: GIT_GREP_MAX_OUTPUT_BYTES,
777 outputMode: "truncate",
778 appendTruncationMarker: false,
779 })
780 .pipe(Effect.option);
781 });
782
783 // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest
784 // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles.
785 const makeIgnoreFileFilter = () => {
786 const decide = makeIgnoreFileDecider();
787 return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* (
788 relativePath: string,
789 ) {
790 const segments = relativePath.split("/");
791 for (let depth = 1; depth <= segments.length; depth += 1) {
792 const candidate = segments.slice(0, depth).join("/");
793 if ((yield* decide(candidate, depth < segments.length)) === "ignored") return true;
794 }
795 return false;
796 });
797 };
798
799 // fff's grep before its content index is ready opens every file itself, as slowly as the build.
800 // None when git cannot search this folder (not a repository, git missing, no PCRE for a regex).
801 const searchContentsWithGit = Effect.fn("WorkspaceSearchIndex.searchContentsWithGit")(function* (
802 input: Omit<ProjectSearchContentsInput, "cwd">,
803 ): Effect.fn.Return<Option.Option<ProjectSearchContentsResult>> {
804 const options = {
805 ignoreCase: !input.caseSensitive,
806 maxMatchesPerFile: CONTENT_SEARCH_MAX_MATCHES_PER_FILE,
807 onlyMatching: false,
808 };
809 let regexMode = input.useRegex;
810 let regexFallbackError: string | undefined;
811 let result = yield* runGitGrep(input.query, { ...options, regexMode });
812 if (regexMode && Option.isSome(result) && result.value.exitCode === 128) {
813 if (/USE_LIBPCRE|Perl-compatible/i.test(result.value.stderr)) return Option.none();
814 // fff searches an invalid pattern as a literal and reports why.
815 regexFallbackError = result.value.stderr.trim().split("\n")[0] || "Invalid regex";
816 regexMode = false;
817 result = yield* runGitGrep(input.query, { ...options, regexMode });
818 }
819 if (Option.isNone(result) || result.value.exitCode > 1) return Option.none();
820
821 // Per line: the first match's byte column and every match's text, in order.
822 const regexMatches = new Map<string, { readonly column: number; readonly texts: string[] }>();
823 let rangesTruncated = false;
824 if (regexMode) {
825 // Ranges come from git too: running the user's pattern in JS could backtrack without bound.
826 const ranges = yield* runGitGrep(input.query, { ...options, regexMode, onlyMatching: true });
827 // Without ranges, whole-word filtering would drop every hit and report no matches.
828 if (Option.isNone(ranges) || ranges.value.exitCode > 1) return Option.none();
829 rangesTruncated = ranges.value.stdoutTruncated;
830 if (ranges.value.exitCode === 0) {
831 for (const record of parseGitGrepRecords(
832 ranges.value.stdout,
833 4,
834 ranges.value.stdoutTruncated,
835 )) {
836 const [relativePath, lineNumber, column, text] = record as [
837 string,
838 string,
839 string,
840 string,
841 ];
842 const key = `${relativePath}\0${lineNumber}`;
843 const lineMatches = regexMatches.get(key);
844 if (lineMatches) lineMatches.texts.push(text);
845 else regexMatches.set(key, { column: Number(column), texts: [text] });
846 }
847 }
848 }
849 const literal = regexMode
850 ? undefined
851 : new RegExp(escapeRegExp(input.query), input.caseSensitive ? "gu" : "giu");
852
853 const isExcludedByIgnoreFiles = makeIgnoreFileFilter();
854 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
855 let rangesCutOff = false;
856 for (const record of parseGitGrepRecords(
857 result.value.stdout,
858 3,
859 result.value.stdoutTruncated,
860 )) {
861 const [relativePath, lineNumber, rawLine] = record as [string, string, string];
862 if (yield* isExcludedByIgnoreFiles(relativePath)) continue;
863 const key = `${relativePath}\0${lineNumber}`;
864 // Lines past the cut-off of a truncated ranges run have no ranges; stop there instead.
865 if (rangesTruncated && !regexMatches.has(key)) {
866 rangesCutOff = true;
867 break;
868 }
869 const lineContent = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).slice(
870 0,
871 CONTENT_LINE_MAX_LENGTH,
872 );
873 const matchRanges = (
874 literal
875 ? Array.from(lineContent.matchAll(literal), (match) => ({
876 start: match.index,
877 end: match.index + match[0].length,
878 }))
879 : mapContentMatchRanges(
880 lineContent,
881 locateRegexMatches(lineContent, regexMatches.get(key)),
882 )
883 ).filter(
884 (range) =>
885 range.end <= lineContent.length &&
886 (!input.wholeWord || isWholeWordRange(lineContent, range)),
887 );
888 if (input.wholeWord && matchRanges.length === 0) continue;
889 matches.push({
890 path: relativePath,
891 lineNumber: Number(lineNumber),
892 lineContent,
893 matchRanges,
894 });
895 if (matches.length > input.limit) break;
896 }
897 return Option.some({
898 matches: matches.slice(0, input.limit),
899 truncated: matches.length > input.limit || result.value.stdoutTruncated || rangesCutOff,
900 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
901 });
902 });
903
904 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
905 query: string,
906 pageSize: number,
907 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
908 execute: () => Promise<Result<A>>,
909 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
910 // fff's searches wait on its picker lock, which its watcher can hold for minutes.
911 const result = yield* Effect.tryPromise({
912 try: execute,
913 catch: (cause) =>
914 new WorkspaceSearchIndexSearchFailed({
915 cwd,
916 queryLength: query.length,
917 pageSize,
918 reason: `FileFinder.${operation} rejected unexpectedly.`,
919 cause,
920 }),
921 });
922 if (!result.ok) {
923 return yield* new WorkspaceSearchIndexSearchFailed({
924 cwd,
925 queryLength: query.length,
926 pageSize,
927 reason: result.error,
928 });
929 }
930 return result.value;
931 });
932
933 const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
934
935 const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")(
936 function* () {
937 const directories: string[] = [];
938 // fff's pageIndex is an offset into the results, not a page number.
939 for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) {
940 const result = yield* Effect.promise(async () => {
941 try {
942 return await finder.directorySearchAsync("", {
943 pageIndex,
944 pageSize: SYMLINK_DIRECTORY_PAGE_SIZE,
945 });
946 } catch {
947 return undefined;
948 }
949 });
950 if (!result?.ok) return directories;
951 for (const item of result.value.items) {
952 const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
953 if (directory) directories.push(directory);
954 }
955 if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories;
956 }
957 },
958 );
959
960 /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */
961 const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* (
962 repository: string,
963 entries: ReadonlyArray<ProjectEntry>,
964 ) {
965 const relativePaths = entries.map(
966 (entry) => `./${repository ? entry.path.slice(repository.length + 1) : entry.path}`,
967 );
968 const repositoryCwd = path.join(cwd, repository);
969 const result = yield* vcsProcess
970 .run({
971 operation: "WorkspaceSearchIndex.listGitIgnored",
972 command: "git",
973 // fff applies ignore rules to tracked paths too, so the index is not consulted.
974 // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs.
975 args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"],
976 cwd: repositoryCwd,
977 stdin: `${relativePaths.join("\0")}\0`,
978 allowNonZeroExit: true,
979 timeoutMs: 10_000,
980 maxOutputBytes: 16 * 1024 * 1024,
981 })
982 .pipe(Effect.orElseSucceed(() => undefined));
983 // Exit 1 means nothing matched.
984 if (result?.exitCode === 1) return [];
985 if (result?.exitCode !== 0 || result.stdoutTruncated) {
986 // Outside git no rules apply (git exits before reading stdin, so the cause is lost).
987 // Any other failure hides the repository's links rather than leaking ones it ignores.
988 const insideRepository = yield* vcsProcess
989 .run({
990 operation: "WorkspaceSearchIndex.listGitIgnored",
991 command: "git",
992 args: ["rev-parse", "--git-dir"],
993 cwd: repositoryCwd,
994 timeoutMs: 10_000,
995 })
996 .pipe(
997 Effect.as(true),
998 Effect.orElseSucceed(() => false),
999 );
1000 return insideRepository ? entries.map((entry) => entry.path) : [];
1001 }
1002 return result.stdout
1003 .split("\0")
1004 .filter(Boolean)
1005 .map((ignoredPath) => {
1006 const relativePath = ignoredPath.replace(/^\.\//, "");
1007 return repository ? `${repository}/${relativePath}` : relativePath;
1008 });
1009 });
1010
1011 const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () {
1012 const indexComplete = !(yield* isScanning);
1013 const directories = yield* listIndexedDirectories();
1014 const scanned = yield* Effect.forEach(
1015 ["", ...directories],
1016 (directory) => scanDirectory(fileSystem, path, cwd, root, directory),
1017 { concurrency: SYMLINK_SCAN_CONCURRENCY },
1018 );
1019 const candidates = scanned.flatMap((directory) => directory.links);
1020 const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths));
1021 if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete };
1022
1023 const ignoreFiles = scanned
1024 .flatMap(({ directory, ignoreFile }) =>
1025 ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }],
1026 )
1027 .toSorted((left, right) => right.directory.length - left.directory.length);
1028 const decisions = new Map(
1029 candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]),
1030 );
1031 const repositories = [
1032 "",
1033 ...scanned.flatMap(({ directory, isRepository }) =>
1034 isRepository && directory ? [directory] : [],
1035 ),
1036 ].toSorted((left, right) => right.length - left.length);
1037 const entriesByRepository = Map.groupBy(
1038 candidates.filter((entry) => decisions.get(entry.path) === undefined),
1039 (entry) =>
1040 repositories.find(
1041 (repository) => isWithin(entry.path, repository) && entry.path !== repository,
1042 ) ?? "",
1043 );
1044 const ignored = new Set(
1045 (yield* Effect.forEach(
1046 entriesByRepository,
1047 ([repository, entries]) => listGitIgnored(repository, entries),
1048 { concurrency: 4 },
1049 )).flat(),
1050 );
1051 return {
1052 entries: candidates.filter((entry) =>
1053 decisions.get(entry.path) === undefined
1054 ? !ignored.has(entry.path)
1055 : decisions.get(entry.path) === "included",
1056 ),
1057 linkPaths,
1058 indexComplete,
1059 };
1060 });
1061
1062 // One scan runs at a time and outlives the reads that started it. Only the first read waits for
1063 // it in full: after that a change or expiry marks the result stale, and reads wait briefly for
1064 // the rescan before answering from the last finished one, so file churn cannot stall search.
1065 type SymlinkScan = Effect.Success<ReturnType<typeof scanSymlinkEntries>>;
1066 let lastSymlinkScan: SymlinkScan | undefined;
1067 let lastSymlinkScanExpiresAt: number | undefined;
1068 let pendingSymlinkScan: Deferred.Deferred<SymlinkScan> | undefined;
1069 let symlinkScanStale = false;
1070 let knownLinkPaths: ReadonlySet<string> = new Set();
1071 const invalidateSymlinkScan = () => {
1072 symlinkScanStale = true;
1073 };
1074 const isKnownLink = (absolutePath: string) =>
1075 [cwd, root].some((base) =>
1076 knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)),
1077 );
1078 const onWatchBatch = (events: ReadonlyArray<WatchEvent>) => {
1079 // fff reports a link replaced in place as `modified`, so edits to known links count too.
1080 const editsOnly = events.every(
1081 (event) =>
1082 event.kind === "modified" &&
1083 !/(^|[\\/])\.(git)?ignore$/.test(event.path) &&
1084 !isKnownLink(event.path),
1085 );
1086 if (!editsOnly) invalidateSymlinkScan();
1087 };
1088 // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so
1089 // each read retries until one is in place. Subscribing waits on fff's picker lock, which its
1090 // watcher holds while it indexes a new folder, so it runs off the JS thread.
1091 let unwatch: WatchUnsubscribe | undefined;
1092 yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.()));
1093 const ensureWatching = Effect.fn("WorkspaceSearchIndex.ensureWatching")(function* () {
1094 if (unwatch) return true;
1095 const result = yield* Effect.promise(() =>
1096 finder.watchAsync(onWatchBatch).catch(() => undefined),
1097 );
1098 if (result?.ok) unwatch = result.value;
1099 return unwatch !== undefined;
1100 });
1101 const indexScope = yield* Effect.scope;
1102 const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () {
1103 symlinkScanStale = false;
1104 const done = yield* Deferred.make<SymlinkScan>();
1105 pendingSymlinkScan = done;
1106 yield* Effect.gen(function* () {
1107 // Subscribing before the scan starts means no change during it goes unseen.
1108 const watched = yield* ensureWatching();
1109 const result = yield* scanSymlinkEntries();
1110 lastSymlinkScan = result;
1111 knownLinkPaths = result.linkPaths;
1112 // Without a watcher, or before fff has seen every folder, the result is kept only briefly.
1113 lastSymlinkScanExpiresAt =
1114 watched && result.indexComplete
1115 ? undefined
1116 : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS;
1117 return result;
1118 }).pipe(
1119 Effect.onExit((exit) =>
1120 Effect.sync(() => {
1121 pendingSymlinkScan = undefined;
1122 }).pipe(Effect.andThen(Deferred.done(done, exit))),
1123 ),
1124 Effect.forkIn(indexScope),
1125 );
1126 return done;
1127 });
1128 const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () {
1129 if (
1130 lastSymlinkScanExpiresAt !== undefined &&
1131 (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt
1132 ) {
1133 symlinkScanStale = true;
1134 }
1135 const pending =
1136 pendingSymlinkScan ??
1137 (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined);
1138 let result = lastSymlinkScan;
1139 if (pending && result === undefined) {
1140 result = yield* Deferred.await(pending);
1141 } else if (pending) {
1142 const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT));
1143 if (Option.isSome(fresh)) result = fresh.value;
1144 }
1145 if (result === undefined)
1146 return yield* Effect.die("The symlink scan finished without a result.");
1147 return {
1148 // Git's ignore rules hide a link the same way searchVisible hides the files it indexes.
1149 entries: result.entries.filter(
1150 (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows),
1151 ),
1152 linkPaths: result.linkPaths,
1153 };
1154 });
1155
1156 // Grows the first page until hidden entries can no longer crowd visible ones out of it.
1157 const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* <I, Metadata>(
1158 query: string,
1159 pageSize: number,
1160 operation: "directorySearch" | "fileSearch" | "mixedSearch",
1161 execute: (pageSize: number) => Promise<Result<SearchPage<I> & Metadata>>,
1162 pathOf: (item: I) => string,
1163 ): Effect.fn.Return<SearchPage<I> & Metadata, WorkspaceSearchIndexSearchFailed> {
1164 let size = pageSize;
1165 while (true) {
1166 const fetchSize = size;
1167 const result = yield* runSearch(query, fetchSize, operation, () => execute(fetchSize));
1168 if (ignoredPaths.size === 0) return result;
1169 const items = result.items.filter(
1170 (item) => !isIgnoredPath(ignoredPaths, pathOf(item), hostIsWindows),
1171 );
1172 if (
1173 items.length >= pageSize ||
1174 result.items.length >= result.totalMatched ||
1175 fetchSize >= WORKSPACE_INDEX_PAGE_SIZE
1176 ) {
1177 return {
1178 ...result,
1179 items,
1180 totalMatched: result.totalMatched - (result.items.length - items.length),
1181 };
1182 }
1183 size = Math.min(WORKSPACE_INDEX_PAGE_SIZE, fetchSize * 4);
1184 }
1185 });
1186
1187 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
1188 "WorkspaceSearchIndex.refresh",
1189 )(function* () {
1190 // scanFiles waits on fff's picker lock, which its watcher can hold for seconds.
1191 const result = yield* Effect.tryPromise({
1192 try: () => finder.scanFilesAsync(),
1193 catch: (cause) =>
1194 new WorkspaceSearchIndexRefreshFailed({
1195 cwd,
1196 reason: "FileFinder.scanFilesAsync rejected unexpectedly.",
1197 cause,
1198 }),
1199 });
1200 if (!result.ok) {
1201 return yield* new WorkspaceSearchIndexRefreshFailed({
1202 cwd,
1203 reason: result.error,
1204 });
1205 }
1206 // A rescan that outlasts the wait keeps running, and the finder answers
1207 // from its previous index until it finishes, so the index stays usable.
1208 yield* waitForIndexReady(
1209 cwd,
1210 finder,
1211 ({ reason, cause }) =>
1212 new WorkspaceSearchIndexRefreshFailed({
1213 cwd,
1214 reason,
1215 cause,
1216 }),
1217 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
1218 ignoredPaths = yield* loadIgnoredPaths();
1219 invalidateSymlinkScan();
1220 });
1221
1222 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
1223 function* () {
1224 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1225 const result = yield* searchVisible(
1226 "",
1227 WORKSPACE_INDEX_PAGE_SIZE,
1228 "mixedSearch",
1229 (pageSize) => finder.mixedSearchAsync("", { pageSize }),
1230 mixedItemPath,
1231 );
1232 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows);
1233 const symlinks = yield* listSymlinkEntries();
1234 // fff's watcher can index a link the scan rejected; only accepted links are listed.
1235 const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path));
1236 const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted(
1237 (left, right) => left.path.localeCompare(right.path),
1238 );
1239 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
1240 return {
1241 entries,
1242 truncated:
1243 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
1244 };
1245 },
1246 );
1247
1248 const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* (
1249 query: string,
1250 limit: number,
1251 kind: ProjectEntryKind | undefined,
1252 imageOnly: boolean | undefined,
1253 ) {
1254 const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries();
1255 const symlinks = allSymlinks.filter((entry) =>
1256 imageOnly
1257 ? entry.kind === "file" && isProjectFaviconPath(entry.path)
1258 : kind === undefined || entry.kind === kind,
1259 );
1260 // Index results that are filtered-out links get dropped in the merge, so fetch past them.
1261 const indexLimit = limit + linkPaths.size - symlinks.length;
1262 const pageSize = Math.max(1, indexLimit + 1);
1263 const merge = (indexed: ProjectSearchEntriesResult) =>
1264 mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit);
1265 if (kind === "file" || imageOnly) {
1266 const searchFiles = (fileQuery: string, size: number) =>
1267 searchVisible(
1268 query,
1269 size,
1270 "fileSearch",
1271 (fetchSize) => finder.fileSearchAsync(fileQuery, { pageSize: fetchSize }),
1272 (item: FileItem) => item.relativePath,
1273 );
1274 // Adding a constraint changes fff's lone-path parse; offset pages can skip tied matches.
1275 if (imageOnly && isLoneFuzzyPath(query)) {
1276 const result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1277 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, true));
1278 }
1279 let result = yield* searchFiles(
1280 imageOnly ? `${query} ${IMAGE_SEARCH_CONSTRAINT}` : query,
1281 pageSize,
1282 );
1283 if (
1284 imageOnly &&
1285 query.trim() &&
1286 result.totalFiles > FFF_FILENAME_FALLBACK_MAX_MATCHES &&
1287 result.totalMatched > 0
1288 ) {
1289 const unfiltered = yield* runSearch(query, 1, "fileSearch", () =>
1290 finder.fileSearchAsync(query, { pageSize: 1 }),
1291 );
1292 if (unfiltered.totalMatched > FFF_FILENAME_FALLBACK_MAX_MATCHES) {
1293 result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1294 }
1295 }
1296 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly));
1297 }
1298 if (kind === "directory") {
1299 const result = yield* searchVisible(
1300 query,
1301 pageSize,
1302 "directorySearch",
1303 (size) => finder.directorySearchAsync(query, { pageSize: size }),
1304 (item) => item.relativePath,
1305 );
1306 return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows));
1307 }
1308 const result = yield* searchVisible(
1309 query,
1310 pageSize,
1311 "mixedSearch",
1312 (size) => finder.mixedSearchAsync(query, { pageSize: size }),
1313 mixedItemPath,
1314 );
1315 return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows));
1316 });
1317
1318 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
1319 "WorkspaceSearchIndex.search",
1320 )(function* (rawQuery, limit, kind, imageOnly) {
1321 // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy
1322 // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths.
1323 // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working.
1324 const query = rawQuery.replaceAll("[", "");
1325 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1326 let mapped = yield* searchNames(query, limit, kind, imageOnly);
1327 if (mapped.entries.length === 0 && query.includes("{")) {
1328 mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly);
1329 }
1330 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
1331 });
1332
1333 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
1334 "WorkspaceSearchIndex.searchContents",
1335 )(function* (input) {
1336 if (!(yield* isContentIndexReady())) {
1337 const gitResult = yield* searchContentsWithGit(input);
1338 if (Option.isSome(gitResult)) return gitResult.value;
1339 yield* waitForIndexReady(
1340 cwd,
1341 finder,
1342 ({ reason, cause }) =>
1343 new WorkspaceSearchIndexSearchFailed({
1344 cwd,
1345 queryLength: input.query.length,
1346 pageSize: input.limit,
1347 reason,
1348 cause,
1349 }),
1350 );
1351 contentIndexPending = false;
1352 }
1353 // fff reads glob and path syntax out of a query even in regex mode, so only a bare word qualifies.
1354 const wholeWordPrefilter = input.wholeWord && !input.useRegex && ASCII_WORD.test(input.query);
1355 let { searchQuery, regexMode } = wholeWordPrefilter
1356 ? { searchQuery: buildWholeWordPattern(input.query, input.caseSensitive), regexMode: true }
1357 : buildContentSearchQuery(input);
1358 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
1359 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
1360 const rawPageSize = input.wholeWord
1361 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
1362 : input.limit;
1363 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
1364 let nextCursor: GrepCursor | null = null;
1365 let regexFallbackError: string | undefined;
1366 let retryLiterally = false;
1367
1368 do {
1369 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
1370 const result = yield* runSearch(input.query, input.limit, "grep", () =>
1371 finder.grepAsync(searchQuery, {
1372 mode: regexMode ? "regex" : "plain",
1373 smartCase: !input.caseSensitive && !regexMode,
1374 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
1375 pageSize: rawPageSize,
1376 cursor: nextCursor,
1377 timeBudgetMs: remainingTimeBudgetMs,
1378 }),
1379 );
1380 // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix.
1381 retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined;
1382 if (retryLiterally) {
1383 regexFallbackError = result.regexFallbackError;
1384 ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false }));
1385 continue;
1386 }
1387
1388 for (const match of result.items) {
1389 if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue;
1390 const matchRanges = (
1391 wholeWordPrefilter
1392 ? findWordRanges(match.lineContent, input.query, input.caseSensitive)
1393 : mapContentMatchRanges(match.lineContent, match.matchRanges)
1394 ).filter((range) => !input.wholeWord || isWholeWordRange(match.lineContent, range));
1395 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
1396 if (input.wholeWord && matchRanges.length === 0) continue;
1397 matches.push({
1398 path: toPosixPath(match.relativePath, hostIsWindows),
1399 lineNumber: match.lineNumber,
1400 lineContent: match.lineContent,
1401 matchRanges,
1402 });
1403 }
1404 nextCursor = result.nextCursor;
1405 regexFallbackError ??= result.regexFallbackError;
1406 } while (
1407 retryLiterally ||
1408 (matches.length < input.limit && nextCursor !== null && performance.now() < deadline)
1409 );
1410
1411 return {
1412 matches: matches.slice(0, input.limit),
1413 truncated: matches.length > input.limit || nextCursor !== null,
1414 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
1415 };
1416 });
1417
1418 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
1419});
1420
1421export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
1422export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
1423
1424export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
1425 `${variant}\n${cwd}`;
1426
1427function parseWorkspaceSearchIndexKey(key: string): {
1428 readonly cwd: string;
1429 readonly variant: WorkspaceSearchIndexVariant;
1430} {
1431 const separatorIndex = key.indexOf("\n");
1432 return {
1433 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
1434 cwd: key.slice(separatorIndex + 1),
1435 };
1436}
1437
1438/** @public */
1439export const layer = (key: string) => {
1440 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
1441 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
1442};
1443
1444export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
1445 "t3/workspace/WorkspaceSearchIndexMap",
1446 {
1447 lookup: layer,
1448 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
1449 },
1450) {}