Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkspaceFileSystem.ts

378 lines13.1 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4​
5import type {
6 FilesystemEntryMetadata,
7 FilesystemGetMetadataInput,
8 FilesystemGetMetadataResult,
9 ProjectReadFileInput,
10 ProjectReadFileResult,
11 ProjectWriteFileInput,
12 ProjectWriteFileResult,
13} from "@t3tools/contracts";
14import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22​
23import * as WorkspaceEntries from "./WorkspaceEntries.ts";
24import * as WorkspacePaths from "./WorkspacePaths.ts";
25import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
26​
27const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
28​
29export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
30 "WorkspaceFileSystemOperationError",
31 {
32 workspaceRoot: Schema.String,
33 relativePath: Schema.String,
34 resolvedPath: Schema.String,
35 operationPath: Schema.String,
36 operation: Schema.Literals([
37 "realpath-workspace-root",
38 "realpath-target",
39 "open",
40 "stat",
41 "read",
42 "close",
43 "make-directory",
44 "write-file",
45 ]),
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
51 }
53​
54export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
55 "WorkspaceFilePathEscapeError",
56 {
57 workspaceRoot: Schema.String,
58 relativePath: Schema.String,
59 resolvedWorkspaceRoot: Schema.String,
60 resolvedPath: Schema.String,
61 },
62) {
63 override get message(): string {
64 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
65 }
67​
68export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
69 "WorkspacePathNotFileError",
70 {
71 workspaceRoot: Schema.String,
72 relativePath: Schema.String,
73 resolvedPath: Schema.String,
74 },
75) {
76 override get message(): string {
77 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
78 }
80​
81export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
82 "WorkspaceBinaryFileError",
83 {
84 workspaceRoot: Schema.String,
85 relativePath: Schema.String,
86 resolvedPath: Schema.String,
87 },
88) {
89 override get message(): string {
90 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
91 }
93​
94export const WorkspaceFileSystemError = Schema.Union([
95 WorkspaceFileSystemOperationError,
96 WorkspaceFilePathEscapeError,
97 WorkspacePathNotFileError,
98 WorkspaceBinaryFileError,
99]);
100export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
101​
102export class WorkspaceFileSystem extends Context.Service<
103 WorkspaceFileSystem,
104 {
105 readonly getMetadata: (
106 input: FilesystemGetMetadataInput,
107 ) => Effect.Effect<FilesystemGetMetadataResult>;
108​
109 readonly readFile: (
110 input: ProjectReadFileInput,
111 ) => Effect.Effect<
112 ProjectReadFileResult,
113 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
114 >;
115 readonly writeFile: (
116 input: ProjectWriteFileInput,
117 ) => Effect.Effect<
118 ProjectWriteFileResult,
119 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
120 >;
121 }
122>()("t3/workspace/WorkspaceFileSystem") {}
123​
124/** @public Service construction is part of the canonical Effect module API. */
125export const make = Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
129 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
130​
131 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
132 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
133 if (!path.isAbsolute(expandedPath)) return null;
134 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
135 if (stat._tag === "None") return null;
136 if (stat.value.type === "Directory") return { kind: "directory" } as const;
137 if (stat.value.type !== "File") return { kind: "other" } as const;
138 let mimeType: string | undefined;
139 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
140 mimeType = yield* Effect.tryPromise({
141 try: async () => {
142 const handle = await NodeFSP.open(
143 expandedPath,
144 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
145 );
146 try {
147 if (!(await handle.stat()).isFile()) return undefined;
148 const buffer = Buffer.alloc(512);
149 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
150 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
151 } finally {
152 await handle.close();
153 }
154 },
155 catch: () => undefined,
156 }).pipe(Effect.catch(() => Effect.succeed(undefined)));
157 }
158 return {
159 kind: "file",
160 byteLength: Number(stat.value.size),
161 ...(mimeType === undefined ? {} : { mimeType }),
162 } satisfies FilesystemEntryMetadata;
163 });
164​
165 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
166 "WorkspaceFileSystem.getMetadata",
167 )(function* (input) {
168 const paths = [...new Set(input.paths)];
169 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
170 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
171 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
172 });
173​
174 /**
175 * Workspace-relative paths must stay inside the root, symlinks included. An
176 * absolute path reads a host file in place, such as a report an agent wrote to a
177 * temp directory; it gets no root check.
178 */
179 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
180 input: ProjectReadFileInput,
181 ) {
182 const requestedPath = input.relativePath.trim();
183 if (path.isAbsolute(requestedPath)) {
184 const realTargetPath = yield* Effect.tryPromise({
185 try: () => NodeFSP.realpath(requestedPath),
186 catch: (cause) =>
187 new WorkspaceFileSystemOperationError({
188 workspaceRoot: input.cwd,
189 relativePath: input.relativePath,
190 resolvedPath: requestedPath,
191 operationPath: requestedPath,
192 operation: "realpath-target",
193 cause,
194 }),
195 });
196 return { relativePath: requestedPath, realTargetPath };
197 }
198​
199 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
200 workspaceRoot: input.cwd,
201 relativePath: input.relativePath,
202 });
203​
204 const realWorkspaceRoot = yield* Effect.tryPromise({
205 try: () => NodeFSP.realpath(input.cwd),
206 catch: (cause) =>
207 new WorkspaceFileSystemOperationError({
208 workspaceRoot: input.cwd,
209 relativePath: input.relativePath,
210 resolvedPath: target.absolutePath,
211 operationPath: input.cwd,
212 operation: "realpath-workspace-root",
213 cause,
214 }),
215 });
216 const realTargetPath = yield* Effect.tryPromise({
217 try: () => NodeFSP.realpath(target.absolutePath),
218 catch: (cause) =>
219 new WorkspaceFileSystemOperationError({
220 workspaceRoot: input.cwd,
221 relativePath: input.relativePath,
222 resolvedPath: target.absolutePath,
223 operationPath: target.absolutePath,
224 operation: "realpath-target",
225 cause,
226 }),
227 });
228 const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
229 if (
230 relativeRealPath.startsWith(`..${path.sep}`) ||
231 relativeRealPath === ".." ||
232 path.isAbsolute(relativeRealPath)
233 ) {
234 return yield* new WorkspaceFilePathEscapeError({
235 workspaceRoot: input.cwd,
236 relativePath: input.relativePath,
237 resolvedWorkspaceRoot: realWorkspaceRoot,
238 resolvedPath: realTargetPath,
239 });
240 }
241 return { relativePath: target.relativePath, realTargetPath };
242 });
243​
244 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
245 "WorkspaceFileSystem.readFile",
246 )(function* (input) {
247 const target = yield* resolveReadTarget(input);
248 const realTargetPath = target.realTargetPath;
249​
250 return yield* Effect.acquireUseRelease(
251 Effect.tryPromise({
252 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
253 // it. Regular files ignore the flag. Windows lacks it.
254 try: () =>
255 NodeFSP.open(
256 realTargetPath,
257 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
258 ),
259 catch: (cause) =>
260 new WorkspaceFileSystemOperationError({
261 workspaceRoot: input.cwd,
262 relativePath: input.relativePath,
263 resolvedPath: realTargetPath,
264 operationPath: realTargetPath,
265 operation: "open",
266 cause,
267 }),
268 }),
269 (handle) =>
270 Effect.gen(function* () {
271 const stat = yield* Effect.tryPromise({
272 try: () => handle.stat(),
273 catch: (cause) =>
274 new WorkspaceFileSystemOperationError({
275 workspaceRoot: input.cwd,
276 relativePath: input.relativePath,
277 resolvedPath: realTargetPath,
278 operationPath: realTargetPath,
279 operation: "stat",
280 cause,
281 }),
282 });
283 if (!stat.isFile()) {
284 return yield* new WorkspacePathNotFileError({
285 workspaceRoot: input.cwd,
286 relativePath: input.relativePath,
287 resolvedPath: realTargetPath,
288 });
289 }
290​
291 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
292 const buffer = Buffer.alloc(bytesToRead);
293 const { bytesRead } = yield* Effect.tryPromise({
294 try: () => handle.read(buffer, 0, bytesToRead, 0),
295 catch: (cause) =>
296 new WorkspaceFileSystemOperationError({
297 workspaceRoot: input.cwd,
298 relativePath: input.relativePath,
299 resolvedPath: realTargetPath,
300 operationPath: realTargetPath,
301 operation: "read",
302 cause,
303 }),
304 });
305 const fileBytes = buffer.subarray(0, bytesRead);
306 if (fileBytes.includes(0)) {
307 return yield* new WorkspaceBinaryFileError({
308 workspaceRoot: input.cwd,
309 relativePath: input.relativePath,
310 resolvedPath: realTargetPath,
311 });
312 }
313​
314 return {
315 relativePath: target.relativePath,
316 contents: new TextDecoder("utf-8").decode(fileBytes),
317 byteLength: stat.size,
318 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
319 };
320 }),
321 (handle) =>
322 Effect.tryPromise({
323 try: () => handle.close(),
324 catch: (cause) =>
325 new WorkspaceFileSystemOperationError({
326 workspaceRoot: input.cwd,
327 relativePath: input.relativePath,
328 resolvedPath: realTargetPath,
329 operationPath: realTargetPath,
330 operation: "close",
331 cause,
332 }),
333 }),
334 );
335 });
336​
337 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
338 "WorkspaceFileSystem.writeFile",
339 )(function* (input) {
340 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
341 workspaceRoot: input.cwd,
342 relativePath: input.relativePath,
343 });
344​
345 yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
346 Effect.mapError(
347 (cause) =>
348 new WorkspaceFileSystemOperationError({
349 workspaceRoot: input.cwd,
350 relativePath: input.relativePath,
351 resolvedPath: target.absolutePath,
352 operationPath: path.dirname(target.absolutePath),
353 operation: "make-directory",
354 cause,
355 }),
356 ),
357 );
358 yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
359 Effect.mapError(
360 (cause) =>
361 new WorkspaceFileSystemOperationError({
362 workspaceRoot: input.cwd,
363 relativePath: input.relativePath,
364 resolvedPath: target.absolutePath,
365 operationPath: target.absolutePath,
366 operation: "write-file",
367 cause,
368 }),
369 ),
370 );
371 yield* workspaceEntries.refresh(input.cwd);
372 return { relativePath: target.relativePath };
373 });
374​
375 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
376});
377​
378export const layer = Layer.effect(WorkspaceFileSystem, make);