Open History to see the last commit
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 KnownWorkspaces from "./KnownWorkspaces.ts";
24import * as WorkspaceEntries from "./WorkspaceEntries.ts";
25import * as WorkspacePaths from "./WorkspacePaths.ts";
26import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
27
28const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
29
30// Windows also reaches `.git` through trailing dots or spaces, a `:` stream
31// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does.
32const isGitMetadataName = (segment: string) => {
33 const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
34 return name === ".GIT" || name === "GIT~1";
35};
36
37export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
38 "WorkspaceFileSystemOperationError",
39 {
40 workspaceRoot: Schema.String,
41 relativePath: Schema.String,
42 resolvedPath: Schema.String,
43 operationPath: Schema.String,
44 operation: Schema.Literals([
45 "realpath-workspace-root",
46 "realpath-target",
47 "open",
48 "stat",
49 "read",
50 "close",
51 "make-directory",
52 "write-file",
53 ]),
54 cause: Schema.Defect(),
55 },
56) {
57 override get message(): string {
58 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
59 }
60}
61
62export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
63 "WorkspaceFilePathEscapeError",
64 {
65 workspaceRoot: Schema.String,
66 relativePath: Schema.String,
67 resolvedWorkspaceRoot: Schema.String,
68 resolvedPath: Schema.String,
69 },
70) {
71 override get message(): string {
72 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
73 }
74}
75
76export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
77 "WorkspacePathNotFileError",
78 {
79 workspaceRoot: Schema.String,
80 relativePath: Schema.String,
81 resolvedPath: Schema.String,
82 },
83) {
84 override get message(): string {
85 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
86 }
87}
88
89export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
90 "WorkspaceBinaryFileError",
91 {
92 workspaceRoot: Schema.String,
93 relativePath: Schema.String,
94 resolvedPath: Schema.String,
95 },
96) {
97 override get message(): string {
98 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
99 }
100}
101
102export const WorkspaceFileSystemError = Schema.Union([
103 WorkspaceFileSystemOperationError,
104 WorkspaceFilePathEscapeError,
105 WorkspacePathNotFileError,
106 WorkspaceBinaryFileError,
107]);
108export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
109
110export class WorkspaceFileSystem extends Context.Service<
111 WorkspaceFileSystem,
112 {
113 readonly getMetadata: (
114 input: FilesystemGetMetadataInput,
115 ) => Effect.Effect<FilesystemGetMetadataResult>;
116
117 readonly readFile: (
118 input: ProjectReadFileInput,
119 ) => Effect.Effect<
120 ProjectReadFileResult,
121 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
122 >;
123 /** Writes inside a known workspace only. */
124 readonly writeFile: (
125 input: ProjectWriteFileInput,
126 ) => Effect.Effect<
127 ProjectWriteFileResult,
128 | WorkspaceFileSystemError
129 | WorkspacePaths.WorkspacePathOutsideRootError
130 | KnownWorkspaces.UnknownWorkspaceError
131 >;
132 }
133>()("t3/workspace/WorkspaceFileSystem") {}
134
135/** @public Service construction is part of the canonical Effect module API. */
136export const make = Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140 const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
141 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
142
143 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
144 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
145 if (!path.isAbsolute(expandedPath)) return null;
146 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
147 if (stat._tag === "None") return null;
148 if (stat.value.type === "Directory") return { kind: "directory" } as const;
149 if (stat.value.type !== "File") return { kind: "other" } as const;
150 let mimeType: string | undefined;
151 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
152 mimeType = yield* Effect.tryPromise({
153 try: async () => {
154 const handle = await NodeFSP.open(
155 expandedPath,
156 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
157 );
158 try {
159 if (!(await handle.stat()).isFile()) return undefined;
160 const buffer = Buffer.alloc(512);
161 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
162 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
163 } finally {
164 await handle.close();
165 }
166 },
167 catch: () => undefined,
168 }).pipe(Effect.catch(() => Effect.succeed(undefined)));
169 }
170 return {
171 kind: "file",
172 byteLength: Number(stat.value.size),
173 ...(mimeType === undefined ? {} : { mimeType }),
174 } satisfies FilesystemEntryMetadata;
175 });
176
177 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
178 "WorkspaceFileSystem.getMetadata",
179 )(function* (input) {
180 const paths = [...new Set(input.paths)];
181 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
182 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
183 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
184 });
185
186 /** Both paths must already be real paths. */
187 const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
188 const relative = path.relative(realWorkspaceRoot, realPath);
189 return !(
190 relative.startsWith(`..${path.sep}`) ||
191 relative === ".." ||
192 path.isAbsolute(relative)
193 );
194 };
195
196 /**
197 * Git runs config and hooks from its own folders, so a write never lands in one:
198 * a `.git` entry, or a repository folder under another name such as `.bare`.
199 * Folders are checked upward to a linked worktree's top, which holds a `.git`
200 * file, since worktrees can sit inside a bare repository. `absolutePath` must
201 * be normalized.
202 */
203 const isInGitFolder = async (absolutePath: string) => {
204 if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
205 for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
206 const [head, commondir, objects, refs, dotGit] = await Promise.all(
207 ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
208 NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
209 // Any other failure leaves the folder unknown, so the write is refused.
210 if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
211 throw error;
212 }),
213 ),
214 );
215 // What git reads as a repository: HEAD, plus objects and refs here or in
216 // the folder a `commondir` file names, as in a linked worktree's git folder.
217 if (head && (commondir || (objects && refs))) return true;
218 if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
219 }
220 };
221
222 /**
223 * Workspace-relative paths must stay inside the root, symlinks included. An
224 * absolute or `~/` path reads a host file in place, such as a report an agent
225 * wrote to a temp directory; it gets no root check.
226 */
227 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
228 input: ProjectReadFileInput,
229 ) {
230 const requestedPath = input.relativePath.trim();
231 const hostPath = requestedPath.startsWith("~/")
232 ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
233 : requestedPath;
234 if (path.isAbsolute(hostPath)) {
235 const realTargetPath = yield* Effect.tryPromise({
236 try: () => NodeFSP.realpath(hostPath),
237 catch: (cause) =>
238 new WorkspaceFileSystemOperationError({
239 workspaceRoot: input.cwd,
240 relativePath: input.relativePath,
241 resolvedPath: hostPath,
242 operationPath: hostPath,
243 operation: "realpath-target",
244 cause,
245 }),
246 }).pipe(
247 Effect.catchIf(
248 (error) =>
249 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
250 () => Effect.succeed(null),
251 ),
252 );
253 return { relativePath: requestedPath, realTargetPath };
254 }
255
256 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
257 workspaceRoot: input.cwd,
258 relativePath: input.relativePath,
259 });
260
261 const realWorkspaceRoot = yield* Effect.tryPromise({
262 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
263 catch: (cause) =>
264 new WorkspaceFileSystemOperationError({
265 workspaceRoot: input.cwd,
266 relativePath: input.relativePath,
267 resolvedPath: target.absolutePath,
268 operationPath: input.cwd,
269 operation: "realpath-workspace-root",
270 cause,
271 }),
272 });
273 const resolved = yield* Effect.tryPromise({
274 try: async () => {
275 let candidate = target.absolutePath;
276 for (;;) {
277 try {
278 return {
279 realTargetPath: path.join(
280 await NodeFSP.realpath(candidate),
281 path.relative(candidate, target.absolutePath),
282 ),
283 exists: candidate === target.absolutePath,
284 };
285 } catch (error) {
286 if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
287 throw error;
288 }
289 // Like writes, missing reads must check the nearest existing ancestor.
290 // An existing entry that cannot resolve is a dangling link, not absence.
291 const exists = await NodeFSP.lstat(candidate).then(
292 () => true,
293 (cause: NodeJS.ErrnoException) => {
294 if (cause.code !== "ENOENT") throw cause;
295 return false;
296 },
297 );
298 if (exists || path.dirname(candidate) === candidate) throw error;
299 candidate = path.dirname(candidate);
300 }
301 }
302 },
303 catch: (cause) =>
304 new WorkspaceFileSystemOperationError({
305 workspaceRoot: input.cwd,
306 relativePath: input.relativePath,
307 resolvedPath: target.absolutePath,
308 operationPath: target.absolutePath,
309 operation: "realpath-target",
310 cause,
311 }),
312 });
313 if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
314 return yield* new WorkspaceFilePathEscapeError({
315 workspaceRoot: input.cwd,
316 relativePath: input.relativePath,
317 resolvedWorkspaceRoot: realWorkspaceRoot,
318 resolvedPath: resolved.realTargetPath,
319 });
320 }
321 return {
322 relativePath: target.relativePath,
323 realTargetPath: resolved.exists ? resolved.realTargetPath : null,
324 };
325 });
326
327 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
328 "WorkspaceFileSystem.readFile",
329 )(function* (input) {
330 const target = yield* resolveReadTarget(input);
331 const absentResult = {
332 relativePath: target.relativePath,
333 contents: "",
334 byteLength: 0,
335 truncated: false,
336 exists: false,
337 };
338 const realTargetPath = target.realTargetPath;
339 if (realTargetPath === null) return absentResult;
340
341 return yield* Effect.acquireUseRelease(
342 Effect.tryPromise({
343 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
344 // it. Regular files ignore the flag. Windows lacks it.
345 try: () =>
346 NodeFSP.open(
347 realTargetPath,
348 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
349 ),
350 catch: (cause) =>
351 new WorkspaceFileSystemOperationError({
352 workspaceRoot: input.cwd,
353 relativePath: input.relativePath,
354 resolvedPath: realTargetPath,
355 operationPath: realTargetPath,
356 operation: "open",
357 cause,
358 }),
359 }).pipe(
360 Effect.catchIf(
361 (error) =>
362 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
363 () => Effect.succeed(null),
364 ),
365 ),
366 (handle) =>
367 Effect.gen(function* () {
368 if (handle === null) return absentResult;
369 const stat = yield* Effect.tryPromise({
370 try: () => handle.stat(),
371 catch: (cause) =>
372 new WorkspaceFileSystemOperationError({
373 workspaceRoot: input.cwd,
374 relativePath: input.relativePath,
375 resolvedPath: realTargetPath,
376 operationPath: realTargetPath,
377 operation: "stat",
378 cause,
379 }),
380 });
381 if (!stat.isFile()) {
382 return yield* new WorkspacePathNotFileError({
383 workspaceRoot: input.cwd,
384 relativePath: input.relativePath,
385 resolvedPath: realTargetPath,
386 });
387 }
388
389 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
390 const buffer = Buffer.alloc(bytesToRead);
391 const { bytesRead } = yield* Effect.tryPromise({
392 try: () => handle.read(buffer, 0, bytesToRead, 0),
393 catch: (cause) =>
394 new WorkspaceFileSystemOperationError({
395 workspaceRoot: input.cwd,
396 relativePath: input.relativePath,
397 resolvedPath: realTargetPath,
398 operationPath: realTargetPath,
399 operation: "read",
400 cause,
401 }),
402 });
403 const fileBytes = buffer.subarray(0, bytesRead);
404 if (fileBytes.includes(0)) {
405 return yield* new WorkspaceBinaryFileError({
406 workspaceRoot: input.cwd,
407 relativePath: input.relativePath,
408 resolvedPath: realTargetPath,
409 });
410 }
411
412 return {
413 relativePath: target.relativePath,
414 contents: new TextDecoder("utf-8").decode(fileBytes),
415 byteLength: stat.size,
416 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
417 };
418 }),
419 (handle) =>
420 handle === null
421 ? Effect.void
422 : Effect.tryPromise({
423 try: () => handle.close(),
424 catch: (cause) =>
425 new WorkspaceFileSystemOperationError({
426 workspaceRoot: input.cwd,
427 relativePath: input.relativePath,
428 resolvedPath: realTargetPath,
429 operationPath: realTargetPath,
430 operation: "close",
431 cause,
432 }),
433 }),
434 );
435 });
436
437 /**
438 * Resolves the file a write targets. The deepest existing ancestor resolves to
439 * its real path before the root check, so neither the file nor the directories
440 * created for it can follow a symlink out of the root. A dangling symlink is
441 * rejected rather than written through.
442 */
443 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
444 input: ProjectWriteFileInput,
445 ) {
446 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
447 workspaceRoot: input.cwd,
448 relativePath: input.relativePath,
449 });
450 const realWorkspaceRoot = yield* Effect.tryPromise({
451 // Resolve `..` in cwd the way the relative path was resolved, before following links.
452 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
453 catch: (cause) =>
454 new WorkspaceFileSystemOperationError({
455 workspaceRoot: input.cwd,
456 relativePath: input.relativePath,
457 resolvedPath: target.absolutePath,
458 operationPath: input.cwd,
459 operation: "realpath-workspace-root",
460 cause,
461 }),
462 });
463
464 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
465 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
466 const realTargetPath = yield* Effect.tryPromise({
467 try: async () => {
468 for (let depth = segments.length; depth > 0; depth--) {
469 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
470 try {
471 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
472 } catch (error) {
473 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
474 const exists = await NodeFSP.lstat(candidate).then(
475 () => true,
476 () => false,
477 );
478 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
479 }
480 }
481 return path.join(realWorkspaceRoot, ...segments);
482 },
483 catch: (cause) =>
484 new WorkspaceFileSystemOperationError({
485 workspaceRoot: input.cwd,
486 relativePath: input.relativePath,
487 resolvedPath: target.absolutePath,
488 operationPath: target.absolutePath,
489 operation: "realpath-target",
490 cause,
491 }),
492 });
493 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
494 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
495 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
496 Effect.tryPromise({
497 try: () => isInGitFolder(checkedPath),
498 catch: (cause) =>
499 new WorkspaceFileSystemOperationError({
500 workspaceRoot: input.cwd,
501 relativePath: input.relativePath,
502 resolvedPath: realTargetPath,
503 operationPath: checkedPath,
504 operation: "stat",
505 cause,
506 }),
507 }),
508 );
509 if (
510 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
511 (yield* inGitFolder(realTargetPath)) ||
512 (yield* inGitFolder(namedTargetPath))
513 ) {
514 return yield* new WorkspaceFilePathEscapeError({
515 workspaceRoot: input.cwd,
516 relativePath: input.relativePath,
517 resolvedWorkspaceRoot: realWorkspaceRoot,
518 resolvedPath: realTargetPath,
519 });
520 }
521 return { relativePath: target.relativePath, realTargetPath };
522 });
523
524 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
525 "WorkspaceFileSystem.writeFile",
526 )(function* (input) {
527 yield* knownWorkspaces.assertContains(input.cwd);
528 const target = yield* resolveWriteTarget(input);
529 const realTargetPath = target.realTargetPath;
530
531 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
532 Effect.mapError(
533 (cause) =>
534 new WorkspaceFileSystemOperationError({
535 workspaceRoot: input.cwd,
536 relativePath: input.relativePath,
537 resolvedPath: realTargetPath,
538 operationPath: path.dirname(realTargetPath),
539 operation: "make-directory",
540 cause,
541 }),
542 ),
543 );
544 yield* Effect.tryPromise({
545 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
546 try: () =>
547 NodeFSP.writeFile(realTargetPath, input.contents, {
548 flag:
549 NodeFS.constants.O_WRONLY |
550 NodeFS.constants.O_CREAT |
551 NodeFS.constants.O_TRUNC |
552 (NodeFS.constants.O_NOFOLLOW ?? 0),
553 }),
554 catch: (cause) =>
555 new WorkspaceFileSystemOperationError({
556 workspaceRoot: input.cwd,
557 relativePath: input.relativePath,
558 resolvedPath: realTargetPath,
559 operationPath: realTargetPath,
560 operation: "write-file",
561 cause,
562 }),
563 });
564 yield* workspaceEntries.refresh(input.cwd);
565 return { relativePath: target.relativePath };
566 });
567
568 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
569});
570
571export const layer = Layer.effect(WorkspaceFileSystem, make);