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 enableFsRootScanning: true,
300 enableHomeDirScanning: true,
301 }),
302 catch: (cause) =>
303 new WorkspaceSearchIndexCreateFailed({
304 cwd,
305 reason: "FileFinder.create threw unexpectedly.",
306 cause,
307 }),
308 });
309 if (result.ok) return result.value;
310 return yield* new WorkspaceSearchIndexCreateFailed({
311 cwd,
312 reason: result.error,
313 });
314});
315
316const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
317 cwd: string,
318 finder: FileFinderType,
319 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
320): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
321 const result = yield* Effect.tryPromise({
322 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
323 catch: (cause) =>
324 onFailure({
325 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
326 cause,
327 }),
328 });
329 if (!result.ok) {
330 return yield* Effect.fail(onFailure({ reason: result.error }));
331 }
332 if (!result.value) {
333 return yield* new WorkspaceSearchIndexScanTimedOut({
334 cwd,
335 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
336 });
337 }
338});
339
340export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
341 cwd: string,
342 variant: WorkspaceSearchIndexVariant = "paths",
343) {
344 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
345 Effect.try({
346 try: () => finder.destroy(),
347 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
348 }).pipe(Effect.orDie),
349 );
350 let initialScanTimedOut = false;
351 yield* waitForIndexReady(
352 cwd,
353 finder,
354 ({ reason, cause }) =>
355 new WorkspaceSearchIndexCreateFailed({
356 cwd,
357 reason,
358 cause,
359 }),
360 ).pipe(
361 Effect.catchTags({
362 WorkspaceSearchIndexScanTimedOut: (error) =>
363 variant === "paths"
364 ? Effect.sync(() => {
365 initialScanTimedOut = true;
366 })
367 : Effect.fail(error),
368 }),
369 );
370
371 const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning();
372
373 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
374 query: string,
375 pageSize: number,
376 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
377 execute: () => Result<A>,
378 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
379 const result = yield* Effect.try({
380 try: execute,
381 catch: (cause) =>
382 new WorkspaceSearchIndexSearchFailed({
383 cwd,
384 queryLength: query.length,
385 pageSize,
386 reason: `FileFinder.${operation} threw unexpectedly.`,
387 cause,
388 }),
389 });
390 if (!result.ok) {
391 return yield* new WorkspaceSearchIndexSearchFailed({
392 cwd,
393 queryLength: query.length,
394 pageSize,
395 reason: result.error,
396 });
397 }
398 return result.value;
399 });
400
401 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
402 "WorkspaceSearchIndex.refresh",
403 )(function* () {
404 const result = yield* Effect.try({
405 try: () => finder.scanFiles(),
406 catch: (cause) =>
407 new WorkspaceSearchIndexRefreshFailed({
408 cwd,
409 reason: "FileFinder.scanFiles threw unexpectedly.",
410 cause,
411 }),
412 });
413 if (!result.ok) {
414 return yield* new WorkspaceSearchIndexRefreshFailed({
415 cwd,
416 reason: result.error,
417 });
418 }
419 // A rescan that outlasts the wait keeps running, and the finder answers
420 // from its previous index until it finishes, so the index stays usable.
421 yield* waitForIndexReady(
422 cwd,
423 finder,
424 ({ reason, cause }) =>
425 new WorkspaceSearchIndexRefreshFailed({
426 cwd,
427 reason,
428 cause,
429 }),
430 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
431 });
432
433 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
434 function* () {
435 const incompleteBeforeQuery = hasIncompleteInitialScan();
436 const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
437 finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
438 );
439 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
440 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
441 left.path.localeCompare(right.path),
442 );
443 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
444 return {
445 entries,
446 truncated:
447 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
448 };
449 },
450 );
451
452 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
453 "WorkspaceSearchIndex.search",
454 )(function* (query, limit, kind, imageOnly) {
455 const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
456 const incompleteBeforeQuery = hasIncompleteInitialScan();
457 if (kind === "file" || imageOnly) {
458 const result = yield* runSearch(query, pageSize, "fileSearch", () =>
459 finder.fileSearch(query, { pageSize }),
460 );
461 const mapped = mapFileSearchResult(result, limit, imageOnly);
462 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
463 }
464 if (kind === "directory") {
465 const result = yield* runSearch(query, pageSize, "directorySearch", () =>
466 finder.directorySearch(query, { pageSize }),
467 );
468 const mapped = mapDirectorySearchResult(result, limit);
469 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
470 }
471 const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
472 finder.mixedSearch(query, { pageSize }),
473 );
474 const mapped = mapMixedSearchResult(result, limit);
475 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
476 });
477
478 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
479 "WorkspaceSearchIndex.searchContents",
480 )(function* (input) {
481 const { searchQuery, regexMode } = buildContentSearchQuery(input);
482 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
483 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
484 const rawPageSize = input.wholeWord
485 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
486 : input.limit;
487 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
488 let nextCursor: GrepCursor | null = null;
489 let regexFallbackError: string | undefined;
490
491 do {
492 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
493 const result = yield* runSearch(input.query, input.limit, "grep", () =>
494 finder.grep(searchQuery, {
495 mode: regexMode ? "regex" : "plain",
496 smartCase: !input.caseSensitive && !regexMode,
497 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
498 pageSize: rawPageSize,
499 cursor: nextCursor,
500 timeBudgetMs: remainingTimeBudgetMs,
501 }),
502 );
503
504 for (const match of result.items) {
505 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
506 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
507 );
508 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
509 if (input.wholeWord && matchRanges.length === 0) continue;
510 matches.push({
511 path: toPosixPath(match.relativePath),
512 lineNumber: match.lineNumber,
513 lineContent: match.lineContent,
514 matchRanges,
515 });
516 }
517 nextCursor = result.nextCursor;
518 regexFallbackError ??= result.regexFallbackError;
519 } while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);
520
521 return {
522 matches: matches.slice(0, input.limit),
523 truncated: matches.length > input.limit || nextCursor !== null,
524 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
525 };
526 });
527
528 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
529});
530
531export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
532export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
533
534export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
535 `${variant}\n${cwd}`;
536
537function parseWorkspaceSearchIndexKey(key: string): {
538 readonly cwd: string;
539 readonly variant: WorkspaceSearchIndexVariant;
540} {
541 const separatorIndex = key.indexOf("\n");
542 return {
543 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
544 cwd: key.slice(separatorIndex + 1),
545 };
546}
547
548/** @public */
549export const layer = (key: string) => {
550 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
551 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
552};
553
554export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
555 "t3/workspace/WorkspaceSearchIndexMap",
556 {
557 lookup: layer,
558 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
559 },
560) {}