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
120/** Children classified at once when listing a folder; each symlink costs a realpath and a stat. */
121const SYMLINK_RESOLVE_BATCH_SIZE = 64;
122
123const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
124 input: FilesystemBrowseInput,
125 path: Path.Path,
126): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
127 const platform = yield* HostProcess.Platform;
128 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
129 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
130 cwd: input.cwd,
131 partialPath: input.partialPath,
132 platform,
133 });
134 }
135
136 if (!isExplicitRelativePath(input.partialPath)) {
137 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
138 }
139
140 if (!input.cwd) {
141 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
142 partialPath: input.partialPath,
143 });
144 }
145 return path.resolve(
146 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
147 input.partialPath,
148 );
149});
150
151/** @public */
152export const make = Effect.gen(function* () {
153 const path = yield* Path.Path;
154 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
155 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
156 const vcsProcess = yield* VcsProcess.VcsProcess;
157
158 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
159 cwd: string,
160 ): Effect.fn.Return<string, WorkspaceEntriesError> {
161 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
162 });
163
164 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
165 function* (cwd) {
166 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
167 Effect.orElseSucceed(() => cwd),
168 );
169 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
170 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
171 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
172 continue;
173 }
174 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
175 function* (
176 cause:
177 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
178 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
179 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
180 ) {
181 yield* Effect.logWarning("Failed to refresh workspace search index", {
182 cwd,
183 variant,
184 cause,
185 });
186 yield* workspaceSearchIndexes.invalidate(indexKey);
187 },
188 );
189 yield* Effect.gen(function* () {
190 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
191 yield* searchIndex.refresh();
192 }).pipe(
193 Effect.provide(workspaceSearchIndexes.get(indexKey)),
194 Effect.catchTags({
195 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
196 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
197 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
198 }),
199 );
200 }
201 },
202 );
203
204 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
205 function* (input) {
206 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
207 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
208 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
209 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
210
211 const dirents = yield* Effect.tryPromise({
212 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
213 catch: (cause) =>
214 new WorkspaceEntriesReadDirectoryError({
215 cwd: input.cwd,
216 partialPath: input.partialPath,
217 parentPath,
218 cause,
219 }),
220 }).pipe(
221 Effect.catchIf(
222 (error) => {
223 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
224 return code === "EACCES" || code === "EPERM";
225 },
226 () => Effect.succeed([]),
227 ),
228 );
229
230 const showHidden = endsWithSeparator || prefix.startsWith(".");
231 const lowerPrefix = prefix.toLowerCase();
232 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
233 for (const dirent of dirents) {
234 if (
235 dirent.isDirectory() &&
236 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
237 (showHidden || !dirent.name.startsWith("."))
238 ) {
239 entries.push({
240 name: dirent.name,
241 fullPath: path.join(parentPath, dirent.name),
242 });
243 }
244 }
245
246 return {
247 parentPath,
248 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
249 };
250 },
251 );
252
253 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
254 function* (input) {
255 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
256 const normalizedQuery = normalizeSearchQuery(input.query, {
257 trimLeadingPattern: /^[@./]+/,
258 });
259 return yield* Effect.gen(function* () {
260 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
261 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
262 }).pipe(
263 Effect.provide(
264 workspaceSearchIndexes.get(
265 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
266 ),
267 ),
268 );
269 },
270 );
271
272 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
273 "WorkspaceEntries.searchContents",
274 )(function* (input) {
275 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
276 return yield* Effect.gen(function* () {
277 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
278 return yield* searchIndex.searchContents(input);
279 }).pipe(
280 Effect.provide(
281 workspaceSearchIndexes.get(
282 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
283 ),
284 ),
285 );
286 });
287
288 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
289 function* (input) {
290 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
291 if (input.directoryPath !== undefined) {
292 const directoryPath = input.directoryPath;
293 const toError = (cause: unknown) =>
294 new WorkspaceEntriesReadDirectoryError({
295 cwd: normalizedCwd,
296 partialPath: directoryPath,
297 parentPath: path.resolve(normalizedCwd, directoryPath),
298 cause,
299 });
300 const target =
301 directoryPath === ""
302 ? { absolutePath: normalizedCwd, relativePath: "" }
303 : yield* workspacePaths
304 .resolveRelativePathWithinRoot({
305 workspaceRoot: normalizedCwd,
306 relativePath: directoryPath,
307 })
308 .pipe(Effect.mapError(toError));
309 const { entries, throughSymlink } = yield* Effect.tryPromise({
310 try: async () => {
311 const root = await NodeFSP.realpath(normalizedCwd);
312 const directory = await NodeFSP.realpath(target.absolutePath);
313 const relative = path.relative(root, directory);
314 if (
315 relative === ".." ||
316 relative.startsWith(`..${path.sep}`) ||
317 path.isAbsolute(relative) ||
318 relative.split(path.sep).includes(".git") ||
319 target.relativePath.split("/").includes(".git")
320 ) {
321 throw new Error("Directory must be inside the workspace and outside .git.");
322 }
323 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
324 const isSameOrInside = (parent: string, child: string) => {
325 const relativeChild = path.relative(parent, child);
326 return (
327 relativeChild !== ".." &&
328 !relativeChild.startsWith(`..${path.sep}`) &&
329 !path.isAbsolute(relativeChild)
330 );
331 };
332 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
333 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
334 const loadVisitedFolders = () =>
335 (visitedFolders ??= (async () => {
336 const folders = [root];
337 let current = normalizedCwd;
338 for (const segment of target.relativePath.split("/").filter(Boolean)) {
339 current = path.join(current, segment);
340 folders.push(await NodeFSP.realpath(current));
341 }
342 return folders;
343 })());
344 const resolveSymlinkKind = async (
345 name: string,
346 ): Promise<ProjectEntry["kind"] | undefined> => {
347 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
348 () => undefined,
349 );
350 if (
351 resolved === undefined ||
352 !isSameOrInside(root, resolved) ||
353 path.relative(root, resolved).split(path.sep).includes(".git")
354 ) {
355 return undefined;
356 }
357 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
358 if (stat?.isFile()) return "file";
359 if (!stat?.isDirectory()) return undefined;
360 const folders = await loadVisitedFolders();
361 return folders.some((folder) => isSameOrInside(resolved, folder))
362 ? undefined
363 : "directory";
364 };
365 // Bound filesystem work for directories such as pnpm node_modules.
366 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
367 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
368 kinds.push(
369 ...(await Promise.all(
370 children
371 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
372 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
373 if (child.name === ".git") return undefined;
374 if (child.isDirectory()) return "directory";
375 if (child.isFile()) return "file";
376 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
377 }),
378 )),
379 );
380 }
381 return {
382 entries: children.flatMap((child, index): ProjectEntry[] => {
383 const kind = kinds[index];
384 if (kind === undefined) return [];
385 return [
386 {
387 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
388 kind,
389 },
390 ];
391 }),
392 // Git refuses to classify paths beyond a symbolic link.
393 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
394 };
395 },
396 catch: toError,
397 });
398 // stdin avoids argument limits; ignore classification is optional without git/repositories.
399 const checkIgnore = (paths: ReadonlyArray<string>) =>
400 vcsProcess
401 .run({
402 operation: "WorkspaceEntries.list",
403 command: "git",
404 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
405 cwd: normalizedCwd,
406 stdin: `${paths.join("\0")}\0`,
407 allowNonZeroExit: true,
408 timeoutMs: 10_000,
409 maxOutputBytes: 16 * 1024 * 1024,
410 })
411 .pipe(Effect.orElseSucceed(() => undefined));
412 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
413 // Symlinks and pathspec magic still need per-child checks.
414 if (
415 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
416 target.relativePath !== "" &&
417 !throughSymlink &&
418 !/^:|[*?[\\]/.test(target.relativePath) &&
419 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
420 ) {
421 return {
422 entries: entries.map((entry) => ({ ...entry, ignored: true })),
423 truncated: false,
424 };
425 }
426 const ignored = new Set<string>();
427 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
428 const result = yield* checkIgnore(
429 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
430 );
431 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
432 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
433 }
434 return {
435 entries: entries.map((entry) =>
436 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
437 ),
438 truncated: false,
439 };
440 }
441 return yield* Effect.gen(function* () {
442 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
443 return yield* searchIndex.list();
444 }).pipe(
445 Effect.provide(
446 workspaceSearchIndexes.get(
447 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
448 ),
449 ),
450 );
451 },
452 );
453
454 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
455 "WorkspaceEntries.listIgnoredFiles",
456 )(function* (input) {
457 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
458 // `--directory` reports a folder holding nothing but ignored files as one
459 // `name/` entry, which is how `node_modules` and build output drop out.
460 const result = yield* vcsProcess
461 .run({
462 operation: "WorkspaceEntries.listIgnoredFiles",
463 command: "git",
464 args: [
465 "-c",
466 "core.fsmonitor=false",
467 "ls-files",
468 "--others",
469 "--ignored",
470 "--exclude-standard",
471 "--directory",
472 "--no-empty-directory",
473 "-z",
474 ],
475 cwd: normalizedCwd,
476 allowNonZeroExit: true,
477 timeoutMs: 10_000,
478 maxOutputBytes: 4 * 1024 * 1024,
479 })
480 .pipe(Effect.orElseSucceed(() => undefined));
481 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
482 const paths = result.stdout
483 .split("\0")
484 .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
485 .toSorted();
486 const files = yield* Effect.promise(() =>
487 Promise.all(
488 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
489 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
490 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
491 () => null,
492 );
493 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
494 }),
495 ),
496 );
497 return {
498 files: files.filter((file) => file !== null),
499 truncated: paths.length > IGNORED_FILES_LIMIT,
500 };
501 });
502
503 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
504});
505
506export const layer = Layer.effect(WorkspaceEntries, make).pipe(
507 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
508 Layer.provide(VcsProcess.layer),
509);