Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as RcMap from "effect/RcMap";
9import * as Schema from "effect/Schema";
10
11import type {
12 FilesystemBrowseInput,
13 FilesystemBrowseResult,
14 ProjectEntry,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectListIgnoredFilesInput,
18 ProjectListIgnoredFilesResult,
19 ProjectSearchContentsInput,
20 ProjectSearchContentsResult,
21 ProjectSearchEntriesInput,
22 ProjectSearchEntriesResult,
23} from "@t3tools/contracts";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
26import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
27
28import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as WorkspacePaths from "./WorkspacePaths.ts";
31import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
32
33export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
34 "WorkspaceEntriesWindowsPathUnsupportedError",
35 {
36 cwd: Schema.optional(Schema.String),
37 partialPath: Schema.String,
38 platform: Schema.String,
39 },
40) {
41 override get message(): string {
42 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
43 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
44 }
45}
46
47export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
48 "WorkspaceEntriesCurrentProjectRequiredError",
49 {
50 partialPath: Schema.String,
51 },
52) {
53 override get message(): string {
54 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
55 }
56}
57
58export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
59 "WorkspaceEntriesReadDirectoryError",
60 {
61 cwd: Schema.optional(Schema.String),
62 partialPath: Schema.String,
63 parentPath: Schema.String,
64 cause: Schema.Defect(),
65 },
66) {
67 override get message(): string {
68 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
69 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
70 }
71}
72
73export const WorkspaceEntriesBrowseError = Schema.Union([
74 WorkspaceEntriesWindowsPathUnsupportedError,
75 WorkspaceEntriesCurrentProjectRequiredError,
76 WorkspaceEntriesReadDirectoryError,
77]);
78export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
79
80export const WorkspaceEntriesError = Schema.Union([
81 WorkspaceEntriesReadDirectoryError,
82 WorkspacePaths.WorkspaceRootNotExistsError,
83 WorkspacePaths.WorkspaceRootCreateFailedError,
84 WorkspacePaths.WorkspaceRootStatFailedError,
85 WorkspacePaths.WorkspaceRootNotDirectoryError,
86 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
87 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
88 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
89]);
90export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
91
92export class WorkspaceEntries extends Context.Service<
93 WorkspaceEntries,
94 {
95 readonly browse: (
96 input: FilesystemBrowseInput,
97 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
98 readonly list: (
99 input: ProjectListEntriesInput,
100 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
101 readonly search: (
102 input: ProjectSearchEntriesInput,
103 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
104 readonly listIgnoredFiles: (
105 input: ProjectListIgnoredFilesInput,
106 ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
107 readonly searchContents: (
108 input: ProjectSearchContentsInput,
109 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
110 readonly refresh: (cwd: string) => Effect.Effect<void>;
111 }
112>()("t3/workspace/WorkspaceEntries") {}
113
114/** Ignored files offered for copying; more than this is a build folder, not config. */
115const IGNORED_FILES_LIMIT = 200;
116
117/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
118const IGNORE_CHECK_CHUNK_SIZE = 1000;
119
120const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
121 input: FilesystemBrowseInput,
122 path: Path.Path,
123): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
124 const platform = yield* HostProcess.Platform;
125 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
126 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
127 cwd: input.cwd,
128 partialPath: input.partialPath,
129 platform,
130 });
131 }
132
133 if (!isExplicitRelativePath(input.partialPath)) {
134 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
135 }
136
137 if (!input.cwd) {
138 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
139 partialPath: input.partialPath,
140 });
141 }
142 return path.resolve(
143 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
144 input.partialPath,
145 );
146});
147
148/** @public Service construction is part of the canonical Effect module API. */
149export const make = Effect.gen(function* () {
150 const path = yield* Path.Path;
151 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
152 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
153 const vcsProcess = yield* VcsProcess.VcsProcess;
154
155 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
156 cwd: string,
157 ): Effect.fn.Return<string, WorkspaceEntriesError> {
158 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
159 });
160
161 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
162 function* (cwd) {
163 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
164 Effect.orElseSucceed(() => cwd),
165 );
166 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
167 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
168 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
169 continue;
170 }
171 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
172 function* (
173 cause:
174 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
175 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
176 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
177 ) {
178 yield* Effect.logWarning("Failed to refresh workspace search index", {
179 cwd,
180 variant,
181 cause,
182 });
183 yield* workspaceSearchIndexes.invalidate(indexKey);
184 },
185 );
186 yield* Effect.gen(function* () {
187 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
188 yield* searchIndex.refresh();
189 }).pipe(
190 Effect.provide(workspaceSearchIndexes.get(indexKey)),
191 Effect.catchTags({
192 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
193 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
194 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
195 }),
196 );
197 }
198 },
199 );
200
201 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
202 function* (input) {
203 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
204 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
205 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
206 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
207
208 const dirents = yield* Effect.tryPromise({
209 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
210 catch: (cause) =>
211 new WorkspaceEntriesReadDirectoryError({
212 cwd: input.cwd,
213 partialPath: input.partialPath,
214 parentPath,
215 cause,
216 }),
217 }).pipe(
218 Effect.catchIf(
219 (error) => {
220 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
221 return code === "EACCES" || code === "EPERM";
222 },
223 () => Effect.succeed([]),
224 ),
225 );
226
227 const showHidden = endsWithSeparator || prefix.startsWith(".");
228 const lowerPrefix = prefix.toLowerCase();
229 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
230 for (const dirent of dirents) {
231 if (
232 dirent.isDirectory() &&
233 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
234 (showHidden || !dirent.name.startsWith("."))
235 ) {
236 entries.push({
237 name: dirent.name,
238 fullPath: path.join(parentPath, dirent.name),
239 });
240 }
241 }
242
243 return {
244 parentPath,
245 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
246 };
247 },
248 );
249
250 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
251 function* (input) {
252 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
253 const normalizedQuery = normalizeSearchQuery(input.query, {
254 trimLeadingPattern: /^[@./]+/,
255 });
256 return yield* Effect.gen(function* () {
257 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
258 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
259 }).pipe(
260 Effect.provide(
261 workspaceSearchIndexes.get(
262 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
263 ),
264 ),
265 );
266 },
267 );
268
269 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
270 "WorkspaceEntries.searchContents",
271 )(function* (input) {
272 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
273 return yield* Effect.gen(function* () {
274 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
275 return yield* searchIndex.searchContents(input);
276 }).pipe(
277 Effect.provide(
278 workspaceSearchIndexes.get(
279 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
280 ),
281 ),
282 );
283 });
284
285 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
286 function* (input) {
287 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
288 if (input.directoryPath !== undefined) {
289 const directoryPath = input.directoryPath;
290 const toError = (cause: unknown) =>
291 new WorkspaceEntriesReadDirectoryError({
292 cwd: normalizedCwd,
293 partialPath: directoryPath,
294 parentPath: path.resolve(normalizedCwd, directoryPath),
295 cause,
296 });
297 const target =
298 directoryPath === ""
299 ? { absolutePath: normalizedCwd, relativePath: "" }
300 : yield* workspacePaths
301 .resolveRelativePathWithinRoot({
302 workspaceRoot: normalizedCwd,
303 relativePath: directoryPath,
304 })
305 .pipe(Effect.mapError(toError));
306 const { entries, throughSymlink } = yield* Effect.tryPromise({
307 try: async () => {
308 const root = await NodeFSP.realpath(normalizedCwd);
309 const directory = await NodeFSP.realpath(target.absolutePath);
310 const relative = path.relative(root, directory);
311 if (
312 relative === ".." ||
313 relative.startsWith(`..${path.sep}`) ||
314 path.isAbsolute(relative) ||
315 relative.split(path.sep).includes(".git") ||
316 target.relativePath.split("/").includes(".git")
317 ) {
318 throw new Error("Directory must be inside the workspace and outside .git.");
319 }
320 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
321 return {
322 entries: children.flatMap((child): ProjectEntry[] => {
323 if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
324 return [
325 {
326 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
327 kind: child.isDirectory() ? "directory" : "file",
328 },
329 ];
330 }),
331 // Git refuses to classify paths beyond a symbolic link.
332 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
333 };
334 },
335 catch: toError,
336 });
337 // Use stdin so large directories cannot exceed the command-line argument limit.
338 // Ignore classification is optional in non-git workspaces or when git is unavailable.
339 const checkIgnore = (paths: ReadonlyArray<string>) =>
340 vcsProcess
341 .run({
342 operation: "WorkspaceEntries.list",
343 command: "git",
344 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
345 cwd: normalizedCwd,
346 stdin: `${paths.join("\0")}\0`,
347 allowNonZeroExit: true,
348 timeoutMs: 10_000,
349 maxOutputBytes: 16 * 1024 * 1024,
350 })
351 .pipe(Effect.orElseSucceed(() => undefined));
352 // Git consults the index for every path it classifies, which costs hundreds of
353 // milliseconds for a `node_modules`-sized folder. Asking about the folder itself answers
354 // for every child: `check-ignore` exits 0 only when the folder is ignored and nothing
355 // under it is tracked, and an ignored folder hides all of its children. Git reads paths as
356 // pathspecs, so a folder whose path has magic (`:foo`) or glob (`[id]`) characters, or
357 // one reached through a symlink, can get a different answer per child and still asks git
358 // about each.
359 if (
360 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
361 target.relativePath !== "" &&
362 !throughSymlink &&
363 !/^:|[*?[\\]/.test(target.relativePath) &&
364 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
365 ) {
366 return {
367 entries: entries.map((entry) => ({ ...entry, ignored: true })),
368 truncated: false,
369 };
370 }
371 const ignored = new Set<string>();
372 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
373 const result = yield* checkIgnore(
374 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
375 );
376 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
377 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
378 }
379 return {
380 entries: entries.map((entry) =>
381 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
382 ),
383 truncated: false,
384 };
385 }
386 return yield* Effect.gen(function* () {
387 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
388 return yield* searchIndex.list();
389 }).pipe(
390 Effect.provide(
391 workspaceSearchIndexes.get(
392 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
393 ),
394 ),
395 );
396 },
397 );
398
399 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
400 "WorkspaceEntries.listIgnoredFiles",
401 )(function* (input) {
402 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
403 // `--directory` reports a folder holding nothing but ignored files as one
404 // `name/` entry, which is how `node_modules` and build output drop out.
405 const result = yield* vcsProcess
406 .run({
407 operation: "WorkspaceEntries.listIgnoredFiles",
408 command: "git",
409 args: [
410 "-c",
411 "core.fsmonitor=false",
412 "ls-files",
413 "--others",
414 "--ignored",
415 "--exclude-standard",
416 "--directory",
417 "--no-empty-directory",
418 "-z",
419 ],
420 cwd: normalizedCwd,
421 allowNonZeroExit: true,
422 timeoutMs: 10_000,
423 maxOutputBytes: 4 * 1024 * 1024,
424 })
425 .pipe(Effect.orElseSucceed(() => undefined));
426 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
427 const paths = result.stdout
428 .split("\0")
429 .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
430 .toSorted();
431 const files = yield* Effect.promise(() =>
432 Promise.all(
433 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
434 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
435 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
436 () => null,
437 );
438 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
439 }),
440 ),
441 );
442 return {
443 files: files.filter((file) => file !== null),
444 truncated: paths.length > IGNORED_FILES_LIMIT,
445 };
446 });
447
448 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
449});
450
451export const layer = Layer.effect(WorkspaceEntries, make).pipe(
452 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
453 Layer.provide(VcsProcess.layer),
454);