Open History to see the last commit
1import * as NodeModule from "node:module";
2
3import type {
4 DirItem,
5 DirSearchResult,
6 FileItem,
7 FileFinder as FileFinderType,
8 GrepCursor,
9 MixedItem,
10 MixedSearchResult,
11 Result,
12 SearchResult,
13} from "@ff-labs/fff-node";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as LayerMap from "effect/LayerMap";
18import * as Schema from "effect/Schema";
19
20import type {
21 ProjectEntry,
22 ProjectEntryKind,
23 ProjectListEntriesResult,
24 ProjectSearchContentsInput,
25 ProjectSearchContentsResult,
26 ProjectSearchEntriesResult,
27} from "@t3tools/contracts";
28import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
29
30// fff-node's native library stays external; single-executables require disk packages instead of importing them.
31const requireForFff = NodeModule.createRequire(import.meta.url);
32const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
33
34const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
35const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
36const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
37const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
38const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
39const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
40const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
41
42export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
43 "WorkspaceSearchIndexCreateFailed",
44 {
45 cwd: Schema.String,
46 reason: Schema.String,
47 cause: Schema.optional(Schema.Defect()),
48 },
49) {
50 override get message(): string {
51 return `Failed to create the workspace search index for '${this.cwd}'.`;
52 }
53}
54
55export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
56 "WorkspaceSearchIndexScanTimedOut",
57 {
58 cwd: Schema.String,
59 timeout: Schema.String,
60 },
61) {
62 override get message(): string {
63 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
64 }
65}
66
67export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
68 "WorkspaceSearchIndexSearchFailed",
69 {
70 cwd: Schema.String,
71 queryLength: Schema.Number,
72 pageSize: Schema.Number,
73 reason: Schema.String,
74 cause: Schema.optional(Schema.Defect()),
75 },
76) {
77 override get message(): string {
78 return `Workspace search failed for '${this.cwd}'.`;
79 }
80}
81
82export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
83 "WorkspaceSearchIndexRefreshFailed",
84 {
85 cwd: Schema.String,
86 reason: Schema.String,
87 cause: Schema.optional(Schema.Defect()),
88 },
89) {
90 override get message(): string {
91 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
92 }
93}
94
95export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
96 "WorkspaceSearchIndexDestroyFailed",
97 {
98 cwd: Schema.String,
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
104 }
105}
106
107export class WorkspaceSearchIndex extends Context.Service<
108 WorkspaceSearchIndex,
109 {
110 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
111 readonly search: (
112 query: string,
113 limit: number,
114 kind?: ProjectEntryKind,
115 imageOnly?: boolean,
116 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
117 readonly searchContents: (
118 input: Omit<ProjectSearchContentsInput, "cwd">,
119 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
120 readonly refresh: () => Effect.Effect<void, WorkspaceSearchIndexRefreshFailed>;
121 }
122>()("t3/workspace/WorkspaceSearchIndex") {}
123
124function toPosixPath(input: string): string {
125 return input.replaceAll("\\", "/");
126}
127
128function trimDirectorySeparator(input: string): string {
129 return input.endsWith("/") ? input.slice(0, -1) : input;
130}
131
132function parentPathOf(input: string): string | undefined {
133 const separatorIndex = input.lastIndexOf("/");
134 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
135}
136
137function toProjectEntry(item: MixedItem): ProjectEntry | null {
138 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));
139 if (!normalizedPath) {
140 return null;
141 }
142
143 return {
144 path: normalizedPath,
145 kind: item.type,
146 };
147}
148
149function toFileEntry(item: FileItem): ProjectEntry | null {
150 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
151 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
152}
153
154function toDirectoryEntry(item: DirItem): ProjectEntry | null {
155 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
156 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
157}
158
159function mapFileSearchResult(
160 result: SearchResult,
161 limit: number,
162 imageOnly = false,
163): ProjectSearchEntriesResult {
164 const entries = result.items.flatMap((item) => {
165 const entry = toFileEntry(item);
166 return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : [];
167 });
168 return {
169 entries: entries.slice(0, limit),
170 truncated: entries.length > limit || result.totalMatched > result.items.length,
171 };
172}
173
174function mapDirectorySearchResult(
175 result: DirSearchResult,
176 limit: number,
177): ProjectSearchEntriesResult {
178 const entries = result.items.flatMap((item) => {
179 const entry = toDirectoryEntry(item);
180 return entry ? [entry] : [];
181 });
182 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
183 return {
184 entries: entries.slice(0, limit),
185 truncated: result.totalMatched - rootDirectoryCount > limit,
186 };
187}
188
189function mapMixedSearchResult(
190 result: MixedSearchResult,
191 limit: number,
192): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
193 const entries: ProjectEntry[] = [];
194 for (const item of result.items) {
195 const entry = toProjectEntry(item);
196 if (entry) {
197 entries.push(entry);
198 }
199 if (entries.length >= limit) {
200 break;
201 }
202 }
203
204 const rootDirectoryCount = result.items.some(
205 (item) => item.type === "directory" && item.item.relativePath.length === 0,
206 )
207 ? 1
208 : 0;
209 return {
210 entries,
211 truncated: result.totalMatched - rootDirectoryCount > limit,
212 };
213}
214
215const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
216
217function codePointAt(line: string, index: number): string | undefined {
218 const codePoint = line.codePointAt(index);
219 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
220}
221
222function codePointBefore(line: string, index: number): string | undefined {
223 if (index <= 0) return undefined;
224 const previousCodeUnit = line.charCodeAt(index - 1);
225 const previousIndex =
226 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
227 return codePointAt(line, previousIndex);
228}
229
230function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
231 readonly searchQuery: string;
232 readonly regexMode: boolean;
233} {
234 if (input.caseSensitive) {
235 return { searchQuery: input.query, regexMode: input.useRegex };
236 }
237 return input.useRegex
238 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
239 : { searchQuery: input.query.toLowerCase(), regexMode: false };
240}
241
242function mapContentMatchRanges(
243 line: string,
244 byteRanges: ReadonlyArray<readonly [number, number]>,
245): Array<{ readonly start: number; readonly end: number }> {
246 const lineBytes = Buffer.from(line);
247 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
248 return byteRanges.map(([startByte, endByte]) => ({
249 start: toStringIndex(startByte),
250 end: toStringIndex(endByte),
251 }));
252}
253
254// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges.
255function isWholeWordRange(
256 line: string,
257 range: { readonly start: number; readonly end: number },
258): boolean {
259 if (range.end <= range.start) return false;
260 const isWord = (character: string | undefined) =>
261 character !== undefined && WORD_CHARACTER.test(character);
262 const leftIsBoundary =
263 range.start === 0 ||
264 !isWord(codePointBefore(line, range.start)) ||
265 !isWord(codePointAt(line, range.start));
266 const rightIsBoundary =
267 range.end >= line.length ||
268 !isWord(codePointAt(line, range.end)) ||
269 !isWord(codePointBefore(line, range.end));
270 return leftIsBoundary && rightIsBoundary;
271}
272
273function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
274 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
275 for (const entry of entries) {
276 let parentPath = parentPathOf(entry.path);
277 while (parentPath) {
278 if (!entryByPath.has(parentPath)) {
279 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
280 }
281 parentPath = parentPathOf(parentPath);
282 }
283 }
284 return [...entryByPath.values()];
285}
286
287const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
288 cwd: string,
289 variant: WorkspaceSearchIndexVariant,
290) {
291 const result = yield* Effect.try({
292 try: () =>
293 FileFinder.create({
294 basePath: cwd,
295 disableMmapCache: true,
296 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
297 disableContentIndexing: variant !== "content",
298 aiMode: false,
299 }),
300 catch: (cause) =>
301 new WorkspaceSearchIndexCreateFailed({
302 cwd,
303 reason: "FileFinder.create threw unexpectedly.",
304 cause,
305 }),
306 });
307 if (result.ok) return result.value;
308 return yield* new WorkspaceSearchIndexCreateFailed({
309 cwd,
310 reason: result.error,
311 });
312});
313
314const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
315 cwd: string,
316 finder: FileFinderType,
317 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
318): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
319 const result = yield* Effect.tryPromise({
320 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
321 catch: (cause) =>
322 onFailure({
323 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
324 cause,
325 }),
326 });
327 if (!result.ok) {
328 return yield* Effect.fail(onFailure({ reason: result.error }));
329 }
330 if (!result.value) {
331 return yield* new WorkspaceSearchIndexScanTimedOut({
332 cwd,
333 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
334 });
335 }
336});
337
338export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
339 cwd: string,
340 variant: WorkspaceSearchIndexVariant = "paths",
341) {
342 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
343 Effect.try({
344 try: () => finder.destroy(),
345 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
346 }).pipe(Effect.orDie),
347 );
348 let initialScanTimedOut = false;
349 yield* waitForIndexReady(
350 cwd,
351 finder,
352 ({ reason, cause }) =>
353 new WorkspaceSearchIndexCreateFailed({
354 cwd,
355 reason,
356 cause,
357 }),
358 ).pipe(
359 Effect.catchTags({
360 WorkspaceSearchIndexScanTimedOut: (error) =>
361 variant === "paths"
362 ? Effect.sync(() => {
363 initialScanTimedOut = true;
364 })
365 : Effect.fail(error),
366 }),
367 );
368
369 const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning();
370
371 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
372 query: string,
373 pageSize: number,
374 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
375 execute: () => Result<A>,
376 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
377 const result = yield* Effect.try({
378 try: execute,
379 catch: (cause) =>
380 new WorkspaceSearchIndexSearchFailed({
381 cwd,
382 queryLength: query.length,
383 pageSize,
384 reason: `FileFinder.${operation} threw unexpectedly.`,
385 cause,
386 }),
387 });
388 if (!result.ok) {
389 return yield* new WorkspaceSearchIndexSearchFailed({
390 cwd,
391 queryLength: query.length,
392 pageSize,
393 reason: result.error,
394 });
395 }
396 return result.value;
397 });
398
399 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
400 "WorkspaceSearchIndex.refresh",
401 )(function* () {
402 const result = yield* Effect.try({
403 try: () => finder.scanFiles(),
404 catch: (cause) =>
405 new WorkspaceSearchIndexRefreshFailed({
406 cwd,
407 reason: "FileFinder.scanFiles threw unexpectedly.",
408 cause,
409 }),
410 });
411 if (!result.ok) {
412 return yield* new WorkspaceSearchIndexRefreshFailed({
413 cwd,
414 reason: result.error,
415 });
416 }
417 // A rescan that outlasts the wait keeps running, and the finder answers
418 // from its previous index until it finishes, so the index stays usable.
419 yield* waitForIndexReady(
420 cwd,
421 finder,
422 ({ reason, cause }) =>
423 new WorkspaceSearchIndexRefreshFailed({
424 cwd,
425 reason,
426 cause,
427 }),
428 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
429 });
430
431 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
432 function* () {
433 const incompleteBeforeQuery = hasIncompleteInitialScan();
434 const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
435 finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
436 );
437 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
438 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
439 left.path.localeCompare(right.path),
440 );
441 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
442 return {
443 entries,
444 truncated:
445 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
446 };
447 },
448 );
449
450 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
451 "WorkspaceSearchIndex.search",
452 )(function* (rawQuery, limit, kind, imageOnly) {
453 // fff parses any word containing "[" as a glob and has no escape for it; fuzzy
454 // matching is subsequence-based, so dropping "[" still matches "[id]" folders.
455 const query = rawQuery.replaceAll("[", "");
456 const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
457 const incompleteBeforeQuery = hasIncompleteInitialScan();
458 if (kind === "file" || imageOnly) {
459 const result = yield* runSearch(query, pageSize, "fileSearch", () =>
460 finder.fileSearch(query, { pageSize }),
461 );
462 const mapped = mapFileSearchResult(result, limit, imageOnly);
463 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
464 }
465 if (kind === "directory") {
466 const result = yield* runSearch(query, pageSize, "directorySearch", () =>
467 finder.directorySearch(query, { pageSize }),
468 );
469 const mapped = mapDirectorySearchResult(result, limit);
470 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
471 }
472 const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
473 finder.mixedSearch(query, { pageSize }),
474 );
475 const mapped = mapMixedSearchResult(result, limit);
476 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
477 });
478
479 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
480 "WorkspaceSearchIndex.searchContents",
481 )(function* (input) {
482 let { searchQuery, regexMode } = buildContentSearchQuery(input);
483 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
484 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
485 const rawPageSize = input.wholeWord
486 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
487 : input.limit;
488 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
489 let nextCursor: GrepCursor | null = null;
490 let regexFallbackError: string | undefined;
491 let retryLiterally = false;
492
493 do {
494 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
495 const result = yield* runSearch(input.query, input.limit, "grep", () =>
496 finder.grep(searchQuery, {
497 mode: regexMode ? "regex" : "plain",
498 smartCase: !input.caseSensitive && !regexMode,
499 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
500 pageSize: rawPageSize,
501 cursor: nextCursor,
502 timeBudgetMs: remainingTimeBudgetMs,
503 }),
504 );
505 // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix.
506 retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined;
507 if (retryLiterally) {
508 regexFallbackError = result.regexFallbackError;
509 ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false }));
510 continue;
511 }
512
513 for (const match of result.items) {
514 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
515 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
516 );
517 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
518 if (input.wholeWord && matchRanges.length === 0) continue;
519 matches.push({
520 path: toPosixPath(match.relativePath),
521 lineNumber: match.lineNumber,
522 lineContent: match.lineContent,
523 matchRanges,
524 });
525 }
526 nextCursor = result.nextCursor;
527 regexFallbackError ??= result.regexFallbackError;
528 } while (
529 retryLiterally ||
530 (matches.length < input.limit && nextCursor !== null && performance.now() < deadline)
531 );
532
533 return {
534 matches: matches.slice(0, input.limit),
535 truncated: matches.length > input.limit || nextCursor !== null,
536 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
537 };
538 });
539
540 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
541});
542
543export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
544export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
545
546export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
547 `${variant}\n${cwd}`;
548
549function parseWorkspaceSearchIndexKey(key: string): {
550 readonly cwd: string;
551 readonly variant: WorkspaceSearchIndexVariant;
552} {
553 const separatorIndex = key.indexOf("\n");
554 return {
555 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
556 cwd: key.slice(separatorIndex + 1),
557 };
558}
559
560/** @public */
561export const layer = (key: string) => {
562 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
563 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
564};
565
566export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
567 "t3/workspace/WorkspaceSearchIndexMap",
568 {
569 lookup: layer,
570 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
571 },
572) {}