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 ProjectListEntriesInput,
15 ProjectListEntriesResult,
16 ProjectSearchContentsInput,
17 ProjectSearchContentsResult,
18 ProjectSearchEntriesInput,
19 ProjectSearchEntriesResult,
20} from "@t3tools/contracts";
21import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
22import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
23import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
24
25import { expandHomePathWith } from "../pathExpansion.ts";
26import * as WorkspacePaths from "./WorkspacePaths.ts";
27import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
28
29export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
30 "WorkspaceEntriesWindowsPathUnsupportedError",
31 {
32 cwd: Schema.optional(Schema.String),
33 partialPath: Schema.String,
34 platform: Schema.String,
35 },
36) {
37 override get message(): string {
38 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
39 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
40 }
41}
42
43export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
44 "WorkspaceEntriesCurrentProjectRequiredError",
45 {
46 partialPath: Schema.String,
47 },
48) {
49 override get message(): string {
50 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
51 }
52}
53
54export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
55 "WorkspaceEntriesReadDirectoryError",
56 {
57 cwd: Schema.optional(Schema.String),
58 partialPath: Schema.String,
59 parentPath: Schema.String,
60 cause: Schema.Defect(),
61 },
62) {
63 override get message(): string {
64 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
65 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
66 }
67}
68
69export const WorkspaceEntriesBrowseError = Schema.Union([
70 WorkspaceEntriesWindowsPathUnsupportedError,
71 WorkspaceEntriesCurrentProjectRequiredError,
72 WorkspaceEntriesReadDirectoryError,
73]);
74export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
75
76export const WorkspaceEntriesError = Schema.Union([
77 WorkspacePaths.WorkspaceRootNotExistsError,
78 WorkspacePaths.WorkspaceRootCreateFailedError,
79 WorkspacePaths.WorkspaceRootStatFailedError,
80 WorkspacePaths.WorkspaceRootNotDirectoryError,
81 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
82 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
83 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
84]);
85export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
86
87export class WorkspaceEntries extends Context.Service<
88 WorkspaceEntries,
89 {
90 readonly browse: (
91 input: FilesystemBrowseInput,
92 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
93 readonly list: (
94 input: ProjectListEntriesInput,
95 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
96 readonly search: (
97 input: ProjectSearchEntriesInput,
98 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
99 readonly searchContents: (
100 input: ProjectSearchContentsInput,
101 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
102 readonly refresh: (cwd: string) => Effect.Effect<void>;
103 }
104>()("t3/workspace/WorkspaceEntries") {}
105
106const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
107 input: FilesystemBrowseInput,
108 path: Path.Path,
109): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
110 const platform = yield* HostProcessPlatform;
111 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
112 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
113 cwd: input.cwd,
114 partialPath: input.partialPath,
115 platform,
116 });
117 }
118
119 if (!isExplicitRelativePath(input.partialPath)) {
120 return path.resolve(expandHomePathWith(input.partialPath, path));
121 }
122
123 if (!input.cwd) {
124 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
125 partialPath: input.partialPath,
126 });
127 }
128 return path.resolve(expandHomePathWith(input.cwd, path), input.partialPath);
129});
130
131/** @public Service construction is part of the canonical Effect module API. */
132export const make = Effect.gen(function* () {
133 const path = yield* Path.Path;
134 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
135 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
136
137 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
138 cwd: string,
139 ): Effect.fn.Return<string, WorkspaceEntriesError> {
140 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
141 });
142
143 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
144 function* (cwd) {
145 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
146 Effect.orElseSucceed(() => cwd),
147 );
148 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
149 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
150 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
151 continue;
152 }
153 const recoverRefreshFailure = (
154 cause:
155 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
156 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
157 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
158 ) =>
159 Effect.gen(function* () {
160 yield* Effect.logWarning("Failed to refresh workspace search index", {
161 cwd,
162 variant,
163 cause,
164 });
165 yield* workspaceSearchIndexes.invalidate(indexKey);
166 });
167 yield* Effect.gen(function* () {
168 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
169 yield* searchIndex.refresh();
170 }).pipe(
171 Effect.provide(workspaceSearchIndexes.get(indexKey)),
172 Effect.catchTags({
173 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
174 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
175 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
176 }),
177 );
178 }
179 },
180 );
181
182 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
183 function* (input) {
184 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
185 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
186 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
187 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
188
189 const dirents = yield* Effect.tryPromise({
190 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
191 catch: (cause) =>
192 new WorkspaceEntriesReadDirectoryError({
193 cwd: input.cwd,
194 partialPath: input.partialPath,
195 parentPath,
196 cause,
197 }),
198 }).pipe(
199 Effect.catchIf(
200 (error) => {
201 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
202 return code === "EACCES" || code === "EPERM";
203 },
204 () => Effect.succeed([]),
205 ),
206 );
207
208 const showHidden = endsWithSeparator || prefix.startsWith(".");
209 const lowerPrefix = prefix.toLowerCase();
210 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
211 for (const dirent of dirents) {
212 if (
213 dirent.isDirectory() &&
214 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
215 (showHidden || !dirent.name.startsWith("."))
216 ) {
217 entries.push({
218 name: dirent.name,
219 fullPath: path.join(parentPath, dirent.name),
220 });
221 }
222 }
223
224 return {
225 parentPath,
226 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
227 };
228 },
229 );
230
231 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
232 function* (input) {
233 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
234 const normalizedQuery = normalizeSearchQuery(input.query, {
235 trimLeadingPattern: /^[@./]+/,
236 });
237 return yield* Effect.gen(function* () {
238 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
239 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
240 }).pipe(
241 Effect.provide(
242 workspaceSearchIndexes.get(
243 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
244 ),
245 ),
246 );
247 },
248 );
249
250 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
251 "WorkspaceEntries.searchContents",
252 )(function* (input) {
253 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
254 return yield* Effect.gen(function* () {
255 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
256 return yield* searchIndex.searchContents(input);
257 }).pipe(
258 Effect.provide(
259 workspaceSearchIndexes.get(
260 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
261 ),
262 ),
263 );
264 });
265
266 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
267 function* (input) {
268 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
269 return yield* Effect.gen(function* () {
270 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
271 return yield* searchIndex.list();
272 }).pipe(
273 Effect.provide(
274 workspaceSearchIndexes.get(
275 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
276 ),
277 ),
278 );
279 },
280 );
281
282 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
283});
284
285export const layer = Layer.effect(WorkspaceEntries, make).pipe(
286 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
287);