Open History to see the last commit
1import {
2 FileFinder,
3 type FileItem,
4 type GrepCursor,
5 type GrepOptions,
6 type GrepResult,
7 type WatchEvent,
8} from "@ff-labs/fff-node";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { afterEach, expect, it } from "@effect/vitest";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import { ChildProcessSpawner } from "effect/process";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as TestClock from "effect/testing/TestClock";
21import { vi } from "vite-plus/test";
22
23import * as VcsProcess from "../vcs/VcsProcess.ts";
24import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
25
26const testLayer = VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer));
27
28afterEach(() => {
29 vi.restoreAllMocks();
30});
31
32function fileItem(relativePath: string): FileItem {
33 return {
34 relativePath,
35 fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
36 size: 1,
37 modified: 0,
38 accessFrecencyScore: 0,
39 modificationFrecencyScore: 0,
40 totalFrecencyScore: 0,
41 gitStatus: "clean",
42 };
43}
44
45it.live("image searches match the image subset of a file search without fetching every file", () =>
46 Effect.gen(function* () {
47 const fileSystem = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const vcsProcess = yield* VcsProcess.VcsProcess;
50 const writeFiles = Effect.fn(function* (root: string, relativePaths: ReadonlyArray<string>) {
51 for (const relativePath of relativePaths) {
52 yield* fileSystem.makeDirectory(path.dirname(path.join(root, relativePath)), {
53 recursive: true,
54 });
55 yield* fileSystem.writeFileString(path.join(root, relativePath), "");
56 yield* fileSystem.utimes(path.join(root, relativePath), 0, 0);
57 }
58 });
59
60 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-search-" });
61 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
62 yield* fileSystem.writeFileString(path.join(cwd, ".git/info/exclude"), "hidden/\n");
63 yield* writeFiles(cwd, [
64 ...Array.from({ length: 220 }, (_, index) => `assets/source-${index}.ts`),
65 ...PROJECT_FAVICON_EXTENSIONS.flatMap((extension) => [
66 `assets/logo${extension}`,
67 `other/logo${extension.toUpperCase()}`,
68 ]),
69 "assets/logo.ts",
70 "assets/logotype.png",
71 "assetss/logotype.png",
72 "assets/images/logo.PNG",
73 "assets/foo{bar}.png",
74 "assets/[id].png",
75 "hidden/logo.png",
76 ]);
77
78 const fileSearch = vi.spyOn(FileFinder.prototype, "fileSearchAsync");
79 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
80 yield* searchIndex.search("", 200, undefined, true);
81 const nativeResult = yield* Effect.promise(
82 (): ReturnType<FileFinder["fileSearchAsync"]> => fileSearch.mock.results[0]?.value,
83 );
84 if (!nativeResult.ok) return yield* Effect.die(nativeResult.error);
85 expect(nativeResult.value.items.length).toBeLessThanOrEqual(201);
86
87 // The image glob must not change fff's parse of fuzzy paths, globs, negations or locations.
88 for (const query of [
89 "",
90 "logo",
91 "lgo",
92 "*.png",
93 "!*.png",
94 "assets/**",
95 "!assets/",
96 "assets*/",
97 "/assets",
98 "assets/",
99 "logo:12",
100 "/assets/logotype.png",
101 "assets/images/",
102 "logo *.svg !other",
103 "foo{bar}.png",
104 "[id].png",
105 "*.{png,svg}",
106 "hidden/",
107 ]) {
108 const ordinary = yield* searchIndex.search(query, 1000, "file");
109 const expected = ordinary.entries.filter((entry) => isProjectFaviconPath(entry.path));
110 for (const limit of [1, 200]) {
111 const images = yield* searchIndex.search(query, limit, "directory", true);
112 expect(images, `query=${query} limit=${limit}`).toEqual({
113 entries: expected.slice(0, limit),
114 truncated: expected.length > limit,
115 });
116 }
117 }
118
119 // Past 15,000 matches fff drops its filename fallback, which the image glob would otherwise
120 // reorder: "x/logo/logo.png" must keep its place relative to "a/xxlogo.png".
121 const largeCwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-rank-" });
122 yield* writeFiles(largeCwd, [
123 ...Array.from({ length: 14_998 }, (_, index) => `b/logo-${index}.png`),
124 "x/logo/source.ts",
125 "a/xxlogo.png",
126 "x/logo/logo.png",
127 ]);
128 const largeIndex = yield* WorkspaceSearchIndex.make(largeCwd);
129 const pairPaths = ["a/xxlogo.png", "x/logo/logo.png"];
130 const ordinary = yield* largeIndex.search("logo", 20_000, "file");
131 const images = yield* largeIndex.search("logo", 20_000, "file", true);
132 expect(images.entries).toHaveLength(15_000);
133 expect(images.entries.filter((entry) => pairPaths.includes(entry.path))).toEqual(
134 ordinary.entries.filter((entry) => pairPaths.includes(entry.path)),
135 );
136 }).pipe(Effect.scoped, Effect.provide(testLayer)),
137);
138
139it.effect("fetches past a first page of Git-ignored results", () =>
140 Effect.scoped(
141 Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-ignored-" });
145 const vcsProcess = yield* VcsProcess.VcsProcess;
146 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
147 yield* fs.writeFileString(path.join(cwd, ".git", "info", "exclude"), "hidden/\n");
148 yield* fs.makeDirectory(path.join(cwd, "hidden"));
149 yield* fs.writeFileString(path.join(cwd, "hidden", "a.ts"), "");
150
151 const items = [
152 fileItem("hidden/a.ts"),
153 fileItem("hidden/b.ts"),
154 fileItem("hidden/c.ts"),
155 fileItem("src/a.ts"),
156 ];
157 const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({
158 ok: true as const,
159 value: {
160 items: items.slice(0, options?.pageSize),
161 scores: [],
162 totalMatched: items.length,
163 totalFiles: items.length,
164 },
165 }));
166 const finder = {
167 destroy: vi.fn(),
168 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
169 getScanProgressAsync: async () => ({
170 ok: true as const,
171 value: { isScanning: false },
172 }),
173 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
174 fileSearchAsync: fileSearch,
175 } as unknown as FileFinder;
176 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
177
178 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
179 const result = yield* searchIndex.search("a", 1, "file", false);
180
181 expect(result).toEqual({ entries: [{ kind: "file", path: "src/a.ts" }], truncated: false });
182 }),
183 ).pipe(Effect.provide(testLayer)),
184);
185
186// A backslash is a file name character on Linux and macOS, so only Windows may treat it as a separator.
187it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
188 "keeps a backslash in a POSIX folder name as part of the search result path",
189 () =>
190 Effect.scoped(
191 Effect.gen(function* () {
192 const items = [fileItem("dir\\one/report.txt")];
193 const finder = {
194 destroy: vi.fn(),
195 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
196 getScanProgressAsync: async () => ({
197 ok: true as const,
198 value: { isScanning: false },
199 }),
200 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
201 fileSearchAsync: vi.fn(async () => ({
202 ok: true as const,
203 value: { items, scores: [], totalMatched: 1, totalFiles: 1 },
204 })),
205 } as unknown as FileFinder;
206 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
207
208 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
209 const result = yield* searchIndex.search("report", 50, "file");
210
211 expect(result.entries).toEqual([{ kind: "file", path: "dir\\one/report.txt" }]);
212 }),
213 ).pipe(Effect.provide(testLayer)),
214);
215
216it.effect("continues whole-word searches after a filtered grep page", () =>
217 Effect.scoped(
218 Effect.gen(function* () {
219 const nextCursor = {
220 __brand: "GrepCursor",
221 _offset: 1,
222 } as GrepCursor;
223 const grepResult = (
224 lineContent: string,
225 matchRanges: Array<[number, number]>,
226 cursor: GrepCursor | null,
227 ): GrepResult => ({
228 items: [
229 {
230 relativePath: "src/words.ts",
231 fileName: "words.ts",
232 gitStatus: "unmodified",
233 size: lineContent.length,
234 modified: 0,
235 isBinary: false,
236 totalFrecencyScore: 0,
237 accessFrecencyScore: 0,
238 modificationFrecencyScore: 0,
239 lineNumber: 1,
240 col: 0,
241 byteOffset: 0,
242 lineContent,
243 matchRanges,
244 },
245 ],
246 totalMatched: 1,
247 totalFilesSearched: 1,
248 totalFiles: 1,
249 filteredFileCount: 1,
250 nextCursor: cursor,
251 });
252 const grep = vi.fn(async (_query: string, options?: GrepOptions) =>
253 options?.cursor
254 ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
255 : {
256 ok: true as const,
257 value: grepResult("needleSuffix", [[0, 6]], nextCursor),
258 },
259 );
260 const finder = {
261 destroy: vi.fn(),
262 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
263 getScanProgressAsync: async () => ({
264 ok: true as const,
265 value: { isScanning: false },
266 }),
267 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
268 grepAsync: grep,
269 } as unknown as FileFinder;
270 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
271
272 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
273 const result = yield* searchIndex.searchContents({
274 query: "needle",
275 limit: 1,
276 caseSensitive: true,
277 wholeWord: true,
278 useRegex: false,
279 });
280
281 expect(result).toEqual({
282 matches: [
283 {
284 path: "src/words.ts",
285 lineNumber: 1,
286 lineContent: "needle",
287 matchRanges: [{ start: 0, end: 6 }],
288 },
289 ],
290 truncated: false,
291 });
292 expect(grep).toHaveBeenCalledTimes(2);
293 expect(grep.mock.calls[0]?.[0]).toBe(String.raw`(?-u)\bneedle\b`);
294 expect(grep.mock.calls[0]?.[1]?.mode).toBe("regex");
295 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
296 }),
297 ).pipe(Effect.provide(testLayer)),
298);
299
300it.live("answers content searches with git grep while a slow content index builds", () =>
301 Effect.gen(function* () {
302 const fileSystem = yield* FileSystem.FileSystem;
303 const path = yield* Path.Path;
304 const vcsProcess = yield* VcsProcess.VcsProcess;
305 const repoRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" });
306 yield* vcsProcess.run({
307 operation: "test.gitInit",
308 command: "git",
309 args: ["init"],
310 cwd: repoRoot,
311 });
312 // User git config must not change git grep's records or make it refuse --untracked.
313 for (const setting of ["grep.column", "grep.fullName", "submodule.recurse"]) {
314 yield* vcsProcess.run({
315 operation: "test.gitConfig",
316 command: "git",
317 args: ["config", setting, "true"],
318 cwd: repoRoot,
319 });
320 }
321 const cwd = path.join(repoRoot, "project");
322 yield* fileSystem.makeDirectory(cwd);
323 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n");
324 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
325 yield* fileSystem.writeFileString(
326 path.join(cwd, "src/a.ts"),
327 "const Needle = 1;\r\nneedles(a.b);\nnone\n",
328 );
329 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "needle\n");
330 // fff leaves out what `.ignore` excludes, so git results must leave it out too.
331 yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "out/\n");
332 yield* fileSystem.makeDirectory(path.join(cwd, "out/deep"), { recursive: true });
333 yield* fileSystem.writeFileString(path.join(cwd, "out/deep/g.txt"), "needle\n");
334
335 let isWarmupComplete = false;
336 const grep = vi.fn(async () => ({
337 ok: true as const,
338 value: {
339 items: [],
340 totalMatched: 0,
341 totalFilesSearched: 0,
342 totalFiles: 0,
343 filteredFileCount: 0,
344 nextCursor: null,
345 } satisfies GrepResult,
346 }));
347 const finder = {
348 destroy: vi.fn(),
349 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
350 getScanProgressAsync: async () => ({
351 ok: true as const,
352 value: { isScanning: false, isWarmupComplete },
353 }),
354 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
355 grepAsync: grep,
356 } as unknown as FileFinder;
357 const noPcreFinder = {
358 ...finder,
359 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
360 } as unknown as FileFinder;
361 vi.spyOn(FileFinder, "create")
362 .mockReturnValueOnce({ ok: true, value: finder })
363 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
364 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
365 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
366 .mockReturnValueOnce({ ok: true, value: noPcreFinder });
367
368 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
369 const search = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
370 searchIndex.searchContents({
371 query: "needle",
372 limit: 10,
373 caseSensitive: false,
374 wholeWord: false,
375 useRegex: false,
376 ...input,
377 });
378
379 expect(yield* search({})).toEqual({
380 matches: [
381 {
382 path: "src/a.ts",
383 lineNumber: 1,
384 lineContent: "const Needle = 1;",
385 matchRanges: [{ start: 6, end: 12 }],
386 },
387 {
388 path: "src/a.ts",
389 lineNumber: 2,
390 lineContent: "needles(a.b);",
391 matchRanges: [{ start: 0, end: 6 }],
392 },
393 ],
394 truncated: false,
395 });
396 expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]);
397 expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([
398 [{ start: 8, end: 11 }],
399 ]);
400 expect(
401 (yield* search({ query: "ne+dles?", useRegex: true })).matches.map(
402 (match) => match.matchRanges,
403 ),
404 ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]);
405 // Git's match text can end on the `\r` of a CRLF line.
406 expect(
407 (yield* search({ query: "needle|1;.*", useRegex: true })).matches.map(
408 (match) => match.matchRanges,
409 ),
410 ).toEqual([
411 [
412 { start: 6, end: 12 },
413 { start: 15, end: 17 },
414 ],
415 [{ start: 0, end: 6 }],
416 ]);
417 expect(
418 (yield* search({ query: "\\r", useRegex: true })).matches.map((match) => match.matchRanges),
419 ).toEqual([[]]);
420 expect(
421 (yield* search({ query: "[a-z]e", useRegex: true })).matches.map(
422 (match) => match.matchRanges,
423 ),
424 ).toEqual([
425 [{ start: 4, end: 6 }],
426 [
427 { start: 6, end: 8 },
428 { start: 10, end: 12 },
429 ],
430 [
431 { start: 0, end: 2 },
432 { start: 4, end: 6 },
433 ],
434 [{ start: 2, end: 4 }],
435 ]);
436 const invalid = yield* search({ query: "a.b(", useRegex: true });
437 expect(invalid.matches).toEqual([]);
438 expect(invalid.regexFallbackError).toBeDefined();
439 expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true });
440 expect(grep).not.toHaveBeenCalled();
441
442 // When git cannot give regex results or their ranges, fff answers once ready instead.
443 const failingGitIndex = (
444 failingArgument: string,
445 stderr: string,
446 output: { readonly exitCode: number; readonly stdout: string } = {
447 exitCode: 128,
448 stdout: "",
449 },
450 ) =>
451 WorkspaceSearchIndex.make(cwd, "content").pipe(
452 Effect.provideService(
453 VcsProcess.VcsProcess,
454 VcsProcess.VcsProcess.of({
455 run: (input) =>
456 input.args.includes(failingArgument)
457 ? Effect.succeed({
458 exitCode: ChildProcessSpawner.ExitCode(output.exitCode),
459 stdout: output.stdout,
460 stderr,
461 stdoutTruncated: output.exitCode === 0,
462 stderrTruncated: false,
463 })
464 : vcsProcess.run(input),
465 }),
466 ),
467 );
468 const regexInput = {
469 query: "ne+dles?",
470 limit: 10,
471 caseSensitive: false,
472 wholeWord: true,
473 useRegex: true,
474 };
475 const noPcreIndex = yield* failingGitIndex(
476 "-P",
477 "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n",
478 );
479 expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined();
480 expect(grep).toHaveBeenCalledTimes(1);
481 const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n");
482 yield* noRangesIndex.searchContents(regexInput);
483 expect(grep).toHaveBeenCalledTimes(2);
484 // Ranges output cut off after line 1: line 2 is left out and the result says so.
485 const cutRangesIndex = yield* failingGitIndex("-o", "", {
486 exitCode: 0,
487 stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002",
488 });
489 expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({
490 matches: [
491 {
492 path: "src/a.ts",
493 lineNumber: 1,
494 lineContent: "const Needle = 1;",
495 matchRanges: [{ start: 6, end: 12 }],
496 },
497 ],
498 truncated: true,
499 });
500 // A column that does not point at its text (a file edited between the two runs, or invalid
501 // UTF-8 before the match) still lands on that text, never on other text.
502 const staleRangesIndex = yield* failingGitIndex("-o", "", {
503 exitCode: 0,
504 stdout: "src/a.ts\u00001\u00001\u0000Needle\n",
505 });
506 expect(
507 (yield* staleRangesIndex.searchContents(regexInput)).matches.map(
508 (match) => match.matchRanges,
509 ),
510 ).toEqual([[{ start: 6, end: 12 }]]);
511 yield* fileSystem.writeFile(
512 path.join(cwd, "src/latin1.ts"),
513 new Uint8Array([...Buffer.from("caf"), 0xe9, ...Buffer.from(" needle needle\n")]),
514 );
515 expect(
516 (yield* search({ query: "needle", wholeWord: true, useRegex: true })).matches.map((match) => [
517 match.path,
518 match.matchRanges,
519 ]),
520 ).toEqual([
521 ["src/a.ts", [{ start: 6, end: 12 }]],
522 [
523 "src/latin1.ts",
524 [
525 { start: 5, end: 11 },
526 { start: 12, end: 18 },
527 ],
528 ],
529 ]);
530 yield* fileSystem.remove(path.join(cwd, "src/latin1.ts"));
531 // Outside a UTF-8 locale, git's `.` matches one byte of `中`.
532 yield* fileSystem.writeFileString(path.join(cwd, "src/cjk.ts"), "x中 y\n");
533 vi.stubEnv("LC_ALL", "C");
534 const partialCharacter = yield* search({ query: "x.", wholeWord: true, useRegex: true }).pipe(
535 Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
536 );
537 expect(partialCharacter.matches.map((match) => [match.path, match.matchRanges])).toEqual([
538 ["src/cjk.ts", [{ start: 0, end: 2 }]],
539 ]);
540 yield* fileSystem.remove(path.join(cwd, "src/cjk.ts"));
541
542 // Lines longer than the 512-character cap are matched whole, then show only ranges that fit.
543 yield* fileSystem.writeFileString(
544 path.join(cwd, "src/long.ts"),
545 [
546 `${" ".repeat(600)}token`,
547 `${" ".repeat(507)}tokenized`,
548 `é token ${"d".repeat(600)} token`,
549 `é tokenized${" ".repeat(600)}token`,
550 // The cap falls inside the emoji, so the shown line drops it whole.
551 `token ${"a".repeat(505)}😀`,
552 ].join("\n"),
553 );
554 const longLines = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
555 search({ query: "token", ...input }).pipe(
556 Effect.map((result) =>
557 result.matches.map((match) => [
558 match.lineNumber,
559 match.lineContent.length,
560 match.matchRanges,
561 ]),
562 ),
563 );
564 const wholeWordLines = [
565 [1, 512, []],
566 [3, 512, [{ start: 2, end: 7 }]],
567 [4, 512, []],
568 [5, 511, [{ start: 0, end: 5 }]],
569 ];
570 expect(yield* longLines({ wholeWord: true })).toEqual(wholeWordLines);
571 expect(yield* longLines({ query: "tok+en", wholeWord: true, useRegex: true })).toEqual(
572 wholeWordLines,
573 );
574 expect(yield* longLines({ query: "tok+en\\w*", useRegex: true })).toEqual([
575 [1, 512, []],
576 [2, 512, []],
577 [3, 512, [{ start: 2, end: 7 }]],
578 [4, 512, [{ start: 2, end: 11 }]],
579 [5, 511, [{ start: 0, end: 5 }]],
580 ]);
581
582 // Windows cannot name a file with a newline.
583 if (HostProcess.Platform.defaultValue() !== "win32") {
584 const newlinePath = "src/one\ntwo.txt";
585 yield* fileSystem.writeFileString(path.join(cwd, newlinePath), "unique_lf_needle\n");
586 for (const input of [
587 { query: "unique_lf_needle" },
588 { query: "unique_lf_n.+", useRegex: true },
589 ]) {
590 expect((yield* search({ ...input, caseSensitive: true })).matches).toEqual([
591 {
592 path: newlinePath,
593 lineNumber: 1,
594 lineContent: "unique_lf_needle",
595 matchRanges: [{ start: 0, end: 16 }],
596 },
597 ]);
598 }
599 yield* fileSystem.remove(path.join(cwd, newlinePath));
600 }
601
602 isWarmupComplete = true;
603 yield* search({});
604 expect(grep).toHaveBeenCalledTimes(3);
605 expect(finder.destroy).not.toHaveBeenCalled();
606 }).pipe(Effect.scoped, Effect.provide(testLayer)),
607);
608
609// Git stops at 100 lines per file, so lines that only contain the word must not use them up.
610it.live.each(["needle", "wörld"])(
611 "finds the whole word %s past many longer words in one file while the content index builds",
612 (word) =>
613 Effect.gen(function* () {
614 const fileSystem = yield* FileSystem.FileSystem;
615 const path = yield* Path.Path;
616 const vcsProcess = yield* VcsProcess.VcsProcess;
617 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-word-" });
618 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
619 yield* fileSystem.writeFileString(
620 path.join(cwd, "a.ts"),
621 `${Array.from({ length: 150 }, (_, index) => `const ${word}Suffix${index} = 1;`).join("\n")}\n${word}();\n`,
622 );
623 const grep = vi.fn();
624 vi.spyOn(FileFinder, "create").mockReturnValueOnce({
625 ok: true,
626 value: {
627 destroy: vi.fn(),
628 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
629 getScanProgressAsync: async () => ({
630 ok: true as const,
631 value: { isScanning: true, isWarmupComplete: false },
632 }),
633 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
634 grepAsync: grep,
635 } as unknown as FileFinder,
636 });
637
638 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
639 const result = yield* searchIndex.searchContents({
640 query: word,
641 limit: 10,
642 caseSensitive: false,
643 wholeWord: true,
644 useRegex: false,
645 });
646
647 expect(result.matches).toEqual([
648 {
649 path: "a.ts",
650 lineNumber: 151,
651 lineContent: `${word}();`,
652 matchRanges: [{ start: 0, end: word.length }],
653 },
654 ]);
655 expect(grep).not.toHaveBeenCalled();
656 }).pipe(Effect.scoped, Effect.provide(testLayer)),
657);
658
659// Git grep's standard excludes skip every Git-ignored file, so a folder a `.ignore` re-includes needs its own pass.
660it.live("content search while indexing finds files a .ignore re-includes", () =>
661 Effect.gen(function* () {
662 const fileSystem = yield* FileSystem.FileSystem;
663 const path = yield* Path.Path;
664 const vcsProcess = yield* VcsProcess.VcsProcess;
665 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-reinclude-" });
666 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
667 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "notes/\nbuild/\n");
668 yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "!notes/\nnotes/*.txt\n");
669 yield* fileSystem.makeDirectory(path.join(cwd, "notes"));
670 yield* fileSystem.writeFileString(path.join(cwd, "notes", "standup.md"), "needle\n");
671 yield* fileSystem.writeFileString(path.join(cwd, "notes", "skip.txt"), "needle\n");
672 yield* fileSystem.makeDirectory(path.join(cwd, "build"));
673 yield* fileSystem.writeFileString(path.join(cwd, "build", "out.js"), "needle\n");
674 yield* fileSystem.writeFileString(path.join(cwd, "top.ts"), "needle\n");
675 const grep = vi.fn();
676 vi.spyOn(FileFinder, "create").mockReturnValueOnce({
677 ok: true,
678 value: {
679 destroy: vi.fn(),
680 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
681 getScanProgressAsync: async () => ({
682 ok: true as const,
683 value: { isScanning: true, isWarmupComplete: false },
684 }),
685 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
686 grepAsync: grep,
687 } as unknown as FileFinder,
688 });
689
690 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
691 const result = yield* searchIndex.searchContents({
692 query: "needle",
693 limit: 10,
694 caseSensitive: false,
695 wholeWord: false,
696 useRegex: false,
697 });
698
699 expect(result.matches.map((match) => match.path).toSorted()).toEqual([
700 "notes/standup.md",
701 "top.ts",
702 ]);
703 expect(grep).not.toHaveBeenCalled();
704 }).pipe(Effect.scoped, Effect.provide(testLayer)),
705);
706
707function fakeSymlinkFinder(
708 directories: ReadonlyArray<string>,
709 options: {
710 readonly indexed?: ReadonlyArray<{
711 readonly path: string;
712 readonly kind: "file" | "directory";
713 }>;
714 readonly watchFailures?: number;
715 } = {},
716) {
717 const watchers: Array<(events: ReadonlyArray<WatchEvent>) => void> = [];
718 let watchFailures = options.watchFailures ?? 0;
719 // fff's pageIndex is an offset into the results, not a page number.
720 const directorySearch = vi.fn(
721 async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => {
722 const offset = searchOptions?.pageIndex ?? 0;
723 const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100));
724 return {
725 ok: true as const,
726 value: {
727 items: items.map((relativePath) => ({ relativePath })),
728 totalMatched: directories.length,
729 },
730 };
731 },
732 );
733 const indexedItems = (options.indexed ?? []).map((entry) => ({
734 type: entry.kind,
735 item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) },
736 }));
737 const finder = {
738 destroy: vi.fn(),
739 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
740 // fff's isScanning waits on the picker lock on the JS thread.
741 isScanning: () => {
742 throw new Error("isScanning must not run on the JS thread");
743 },
744 getScanProgressAsync: async () => ({
745 ok: true as const,
746 value: { isScanning: false },
747 }),
748 // fff's watch waits on the picker lock on the JS thread.
749 watch: () => {
750 throw new Error("watch must not run on the JS thread");
751 },
752 watchAsync: async (callback: (events: ReadonlyArray<WatchEvent>) => void) => {
753 if (watchFailures > 0) {
754 watchFailures -= 1;
755 return { ok: false as const, error: "File system watcher is not ready" };
756 }
757 watchers.push(callback);
758 return { ok: true as const, value: () => undefined };
759 },
760 directorySearchAsync: directorySearch,
761 fileSearchAsync: async () => {
762 const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : []));
763 return { ok: true as const, value: { items, scores: [], totalMatched: items.length } };
764 },
765 mixedSearchAsync: async () => ({
766 ok: true as const,
767 value: { items: indexedItems, totalMatched: indexedItems.length },
768 }),
769 } as unknown as FileFinder;
770 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
771 return {
772 directorySearch,
773 notifyWatchers: (events: ReadonlyArray<WatchEvent>) =>
774 watchers.forEach((watcher) => watcher(events)),
775 };
776}
777
778const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) =>
779 searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path)));
780
781it.effect("reads symlinks again after the watcher reports a change", () =>
782 Effect.scoped(
783 Effect.gen(function* () {
784 if ((yield* HostProcess.Platform) === "win32") return;
785 const fileSystem = yield* FileSystem.FileSystem;
786 const path = yield* Path.Path;
787 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
788 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
789 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
790 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
791 const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]);
792
793 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
794 const concurrent = yield* Effect.all(
795 Array.from({ length: 8 }, () => listedPaths(searchIndex)),
796 { concurrency: "unbounded" },
797 );
798 yield* fileSystem.remove(path.join(cwd, "old-link.ts"));
799 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
800 const beforeNotice = yield* listedPaths(searchIndex);
801 // Editing a file cannot move a link, so it does not cost a rescan.
802 notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]);
803 const afterEdit = yield* listedPaths(searchIndex);
804 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
805 const afterNotice = yield* listedPaths(searchIndex);
806 // fff reports a link replaced in place as modified.
807 yield* fileSystem.remove(path.join(cwd, "new-link.ts"));
808 yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts"));
809 notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]);
810 const afterReplace = yield* listedPaths(searchIndex);
811
812 expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"]));
813 expect(beforeNotice).toEqual(["old-link.ts"]);
814 expect(afterEdit).toEqual(["old-link.ts"]);
815 expect(afterNotice).toEqual(["new-link.ts"]);
816 expect(afterReplace).toEqual([]);
817 expect(directorySearch).toHaveBeenCalledTimes(3);
818 }),
819 ).pipe(Effect.provide(testLayer)),
820);
821
822it.effect("answers from the last symlink scan while a slow rescan runs", () =>
823 Effect.scoped(
824 Effect.gen(function* () {
825 if ((yield* HostProcess.Platform) === "win32") return;
826 const fileSystem = yield* FileSystem.FileSystem;
827 const path = yield* Path.Path;
828 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" });
829 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
830 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
831 const { notifyWatchers } = fakeSymlinkFinder([]);
832 // Holding git's ignore check open keeps the rescan from finishing.
833 const gate = yield* Deferred.make<void>();
834 let holdIgnoreChecks = false;
835 const vcsProcess = yield* VcsProcess.VcsProcess;
836 const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(
837 Effect.provideService(VcsProcess.VcsProcess, {
838 ...vcsProcess,
839 run: (input) =>
840 holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored"
841 ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input)))
842 : vcsProcess.run(input),
843 }),
844 );
845 expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]);
846
847 holdIgnoreChecks = true;
848 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
849 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
850 const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex));
851 yield* TestClock.adjust("1 second");
852 expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]);
853
854 yield* Deferred.succeed(gate, undefined);
855 expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]);
856 }),
857 ).pipe(Effect.provide(testLayer)),
858);
859
860it.effect("keeps symlinks once the watcher subscribes after starting late", () =>
861 Effect.scoped(
862 Effect.gen(function* () {
863 if ((yield* HostProcess.Platform) === "win32") return;
864 const fileSystem = yield* FileSystem.FileSystem;
865 const path = yield* Path.Path;
866 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
867 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
868 yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts"));
869 const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 });
870
871 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
872 const scansAfterRound: number[] = [];
873 for (let round = 0; round < 5; round += 1) {
874 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
875 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
876 scansAfterRound.push(directorySearch.mock.calls.length);
877 yield* TestClock.adjust("1 minute");
878 }
879
880 // An unwatched scan serves reads only briefly; the third has a watcher and is kept.
881 expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]);
882 }),
883 ).pipe(Effect.provide(testLayer)),
884);
885
886it.effect(
887 "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones",
888 () =>
889 Effect.scoped(
890 Effect.gen(function* () {
891 if ((yield* HostProcess.Platform) === "win32") return;
892 const fileSystem = yield* FileSystem.FileSystem;
893 const path = yield* Path.Path;
894 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" });
895 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
896 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
897 yield* fileSystem.symlink("src", path.join(cwd, "src-link"));
898 // A link the scan rejects stays out even when the watcher indexed it.
899 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
900 fakeSymlinkFinder([], {
901 indexed: [
902 { path: "outside-link", kind: "file" },
903 { path: "src-link", kind: "file" },
904 { path: "link-file.ts", kind: "file" },
905 ],
906 });
907
908 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
909 const searched = yield* searchIndex.search("link", 10);
910 const files = yield* searchIndex.search("link", 1, "file");
911 const listed = yield* searchIndex.list();
912
913 expect(searched.entries).toEqual([
914 { path: "src-link", kind: "directory" },
915 { path: "link-file.ts", kind: "file" },
916 ]);
917 // The dropped link does not take the only slot.
918 expect(files).toEqual({
919 entries: [{ path: "link-file.ts", kind: "file" }],
920 truncated: false,
921 });
922 expect(listed.entries).toEqual([
923 { path: "link-file.ts", kind: "file" },
924 { path: "src-link", kind: "directory" },
925 ]);
926 }),
927 ).pipe(Effect.provide(testLayer)),
928);
929
930it.effect("finds symlinks in folders past the first page of the index", () =>
931 Effect.scoped(
932 Effect.gen(function* () {
933 if ((yield* HostProcess.Platform) === "win32") return;
934 const fileSystem = yield* FileSystem.FileSystem;
935 const path = yield* Path.Path;
936 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" });
937 yield* fileSystem.makeDirectory(path.join(cwd, "late"));
938 yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), "");
939 yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts"));
940 // Folders fff lists but that are gone by the time they are read are skipped.
941 const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`);
942 const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]);
943
944 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
945
946 expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]);
947 expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([
948 0, 1_000,
949 ]);
950 }),
951 ).pipe(Effect.provide(testLayer)),
952);
953
954it.effect("keeps symlinks Git does not ignore when a link's name looks like a git pathspec", () =>
955 Effect.scoped(
956 Effect.gen(function* () {
957 if ((yield* HostProcess.Platform) === "win32") return;
958 const fileSystem = yield* FileSystem.FileSystem;
959 const path = yield* Path.Path;
960 const vcsProcess = yield* VcsProcess.VcsProcess;
961 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pathspec-" });
962 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
963 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored-link\n");
964 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
965 yield* fileSystem.symlink("a.ts", path.join(cwd, "docs-link"));
966 yield* fileSystem.symlink("a.ts", path.join(cwd, ":(link)"));
967 yield* fileSystem.symlink("a.ts", path.join(cwd, "ignored-link"));
968 // Stage so `ls-files --others` skips it and `listGitIgnored` must hide it.
969 yield* vcsProcess.run({
970 operation: "test.gitAdd",
971 command: "git",
972 args: ["add", "-f", "ignored-link"],
973 cwd,
974 });
975 fakeSymlinkFinder([]);
976
977 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
978
979 expect(yield* listedPaths(searchIndex)).toEqual([":(link)", "docs-link"]);
980 }),
981 ).pipe(Effect.provide(testLayer)),
982);
983
984// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
985it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
986 "refuses to index a workspace rooted at the home directory",
987 () =>
988 Effect.scoped(
989 Effect.gen(function* () {
990 const fs = yield* FileSystem.FileSystem;
991 const path = yield* Path.Path;
992 const home = yield* fs.realPath(
993 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
994 );
995 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
996 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
997 yield* Effect.acquireRelease(
998 Effect.sync(() => vi.stubEnv("HOME", home)),
999 () => Effect.sync(() => vi.unstubAllEnvs()),
1000 );
1001
1002 const result = yield* WorkspaceSearchIndex.make(home).pipe(
1003 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
1004 Effect.map(({ entries }) => entries),
1005 Effect.catchTags({
1006 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
1007 }),
1008 );
1009
1010 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
1011 }),
1012 ).pipe(Effect.provide(testLayer)),
1013);
1014
1015// ripgrep and fff let a matching `.ignore` decide ahead of `.gitignore`, so Git's list must not hide it.
1016it.live("finds Git-ignored files that a root .ignore re-includes", () =>
1017 Effect.gen(function* () {
1018 const fileSystem = yield* FileSystem.FileSystem;
1019 const path = yield* Path.Path;
1020 const vcsProcess = yield* VcsProcess.VcsProcess;
1021 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-reinclude-" });
1022 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
1023 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "notes/\n");
1024 yield* fileSystem.writeFileString(
1025 path.join(cwd, ".ignore"),
1026 "!notes/\nnotes/**/*\n!notes/**/\n!notes/**/*.md\n",
1027 );
1028 yield* fileSystem.makeDirectory(path.join(cwd, "notes", "daily"), { recursive: true });
1029 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.md"), "");
1030 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.txt"), "");
1031
1032 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
1033 const result = yield* searchIndex.search("standup", 50, "file");
1034
1035 expect(result.entries).toEqual([{ kind: "file", path: "notes/daily/standup.md" }]);
1036 }).pipe(Effect.scoped, Effect.provide(testLayer)),
1037);
1038
1039// Real fff: the native whole-word pattern must return what the plain search and the JS word check did.
1040it.live.each([
1041 { query: "needle", caseSensitive: true, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
1042 { query: "NEEDLE", caseSensitive: false, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
1043 // fff reads `*.ts` as a file constraint, which a regex built around the whole query would lose.
1044 { query: "*.ts needle", caseSensitive: true, expected: ["words.ts:2:0-6,8-14"] },
1045 // Plain search folds ASCII case only: `ſ` is not an `s`, and the Kelvin sign is not a `k`.
1046 { query: "s", caseSensitive: false, expected: ["fold.txt:2:0-1"] },
1047 { query: "k", caseSensitive: false, expected: ["fold.txt:4:0-1"] },
1048 // fff stops at 100 lines per file, so the 150 lines of a longer word must not use them up.
1049 {
1050 query: "wörld",
1051 caseSensitive: true,
1052 expected: ["unicode.txt:151:0-5", "unicode.txt:152:7-12", "unicode.txt:156:1-6"],
1053 },
1054 // Only the ASCII letters fold, as in plain search: `WÖRLD` is not found.
1055 {
1056 query: "WÖRLD",
1057 caseSensitive: false,
1058 expected: ["unicode.txt:151:0-5", "unicode.txt:152:0-5,7-12", "unicode.txt:156:1-6"],
1059 },
1060 // `²` is a word character here but not for a Rust `\b`, and a byte that is not UTF-8 ends a word.
1061 { query: "²", caseSensitive: true, expected: ["unicode.txt:155:0-1"] },
1062])("matches whole words in a real workspace for $query", ({ query, caseSensitive, expected }) =>
1063 Effect.gen(function* () {
1064 const fileSystem = yield* FileSystem.FileSystem;
1065 const path = yield* Path.Path;
1066 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-whole-word-" });
1067 yield* fileSystem.writeFileString(
1068 path.join(cwd, "words.ts"),
1069 "needleSuffix\nneedle, needle.\n\u00e9needle\n",
1070 );
1071 yield* fileSystem.writeFileString(path.join(cwd, "notes.md"), "needle *.ts\n");
1072 yield* fileSystem.writeFileString(path.join(cwd, "fold.txt"), "\u017f\ns\n\u212a\nk\n");
1073 yield* fileSystem.writeFile(
1074 path.join(cwd, "unicode.txt"),
1075 Buffer.concat([
1076 Buffer.from(`${"wörldé\n".repeat(150)}wörld\nWöRLD “wörld”\nWÖRLD\nwörld²\n²`),
1077 Buffer.of(0xff, 0x0a, 0xff),
1078 Buffer.from("wörld"),
1079 Buffer.of(0xe2, 0x82, 0x0a),
1080 ]),
1081 );
1082
1083 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
1084 const result = yield* searchIndex.searchContents({
1085 query,
1086 limit: 500,
1087 caseSensitive,
1088 wholeWord: true,
1089 useRegex: false,
1090 });
1091
1092 expect(
1093 result.matches
1094 .map(
1095 (match) =>
1096 `${match.path}:${match.lineNumber}:${match.matchRanges.map((range) => `${range.start}-${range.end}`).join(",")}`,
1097 )
1098 .toSorted(),
1099 ).toEqual(expected);
1100 }).pipe(Effect.scoped, Effect.provide(testLayer)),
1101);