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 path reads a host file in place, such as a report an agent wrote to a
225 * 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 if (path.isAbsolute(requestedPath)) {
232 const realTargetPath = yield* Effect.tryPromise({
233 try: () => NodeFSP.realpath(requestedPath),
234 catch: (cause) =>
235 new WorkspaceFileSystemOperationError({
236 workspaceRoot: input.cwd,
237 relativePath: input.relativePath,
238 resolvedPath: requestedPath,
239 operationPath: requestedPath,
240 operation: "realpath-target",
241 cause,
242 }),
243 }).pipe(
244 Effect.catchIf(
245 (error) =>
246 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
247 () => Effect.succeed(null),
248 ),
249 );
250 return { relativePath: requestedPath, realTargetPath };
251 }
252
253 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
254 workspaceRoot: input.cwd,
255 relativePath: input.relativePath,
256 });
257
258 const realWorkspaceRoot = yield* Effect.tryPromise({
259 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
260 catch: (cause) =>
261 new WorkspaceFileSystemOperationError({
262 workspaceRoot: input.cwd,
263 relativePath: input.relativePath,
264 resolvedPath: target.absolutePath,
265 operationPath: input.cwd,
266 operation: "realpath-workspace-root",
267 cause,
268 }),
269 });
270 const resolved = yield* Effect.tryPromise({
271 try: async () => {
272 let candidate = target.absolutePath;
273 for (;;) {
274 try {
275 return {
276 realTargetPath: path.join(
277 await NodeFSP.realpath(candidate),
278 path.relative(candidate, target.absolutePath),
279 ),
280 exists: candidate === target.absolutePath,
281 };
282 } catch (error) {
283 if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
284 throw error;
285 }
286 // Like writes, missing reads must check the nearest existing ancestor.
287 // An existing entry that cannot resolve is a dangling link, not absence.
288 const exists = await NodeFSP.lstat(candidate).then(
289 () => true,
290 (cause: NodeJS.ErrnoException) => {
291 if (cause.code !== "ENOENT") throw cause;
292 return false;
293 },
294 );
295 if (exists || path.dirname(candidate) === candidate) throw error;
296 candidate = path.dirname(candidate);
297 }
298 }
299 },
300 catch: (cause) =>
301 new WorkspaceFileSystemOperationError({
302 workspaceRoot: input.cwd,
303 relativePath: input.relativePath,
304 resolvedPath: target.absolutePath,
305 operationPath: target.absolutePath,
306 operation: "realpath-target",
307 cause,
308 }),
309 });
310 if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
311 return yield* new WorkspaceFilePathEscapeError({
312 workspaceRoot: input.cwd,
313 relativePath: input.relativePath,
314 resolvedWorkspaceRoot: realWorkspaceRoot,
315 resolvedPath: resolved.realTargetPath,
316 });
317 }
318 return {
319 relativePath: target.relativePath,
320 realTargetPath: resolved.exists ? resolved.realTargetPath : null,
321 };
322 });
323
324 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
325 "WorkspaceFileSystem.readFile",
326 )(function* (input) {
327 const target = yield* resolveReadTarget(input);
328 const absentResult = {
329 relativePath: target.relativePath,
330 contents: "",
331 byteLength: 0,
332 truncated: false,
333 exists: false,
334 };
335 const realTargetPath = target.realTargetPath;
336 if (realTargetPath === null) return absentResult;
337
338 return yield* Effect.acquireUseRelease(
339 Effect.tryPromise({
340 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
341 // it. Regular files ignore the flag. Windows lacks it.
342 try: () =>
343 NodeFSP.open(
344 realTargetPath,
345 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
346 ),
347 catch: (cause) =>
348 new WorkspaceFileSystemOperationError({
349 workspaceRoot: input.cwd,
350 relativePath: input.relativePath,
351 resolvedPath: realTargetPath,
352 operationPath: realTargetPath,
353 operation: "open",
354 cause,
355 }),
356 }).pipe(
357 Effect.catchIf(
358 (error) =>
359 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
360 () => Effect.succeed(null),
361 ),
362 ),
363 (handle) =>
364 Effect.gen(function* () {
365 if (handle === null) return absentResult;
366 const stat = yield* Effect.tryPromise({
367 try: () => handle.stat(),
368 catch: (cause) =>
369 new WorkspaceFileSystemOperationError({
370 workspaceRoot: input.cwd,
371 relativePath: input.relativePath,
372 resolvedPath: realTargetPath,
373 operationPath: realTargetPath,
374 operation: "stat",
375 cause,
376 }),
377 });
378 if (!stat.isFile()) {
379 return yield* new WorkspacePathNotFileError({
380 workspaceRoot: input.cwd,
381 relativePath: input.relativePath,
382 resolvedPath: realTargetPath,
383 });
384 }
385
386 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
387 const buffer = Buffer.alloc(bytesToRead);
388 const { bytesRead } = yield* Effect.tryPromise({
389 try: () => handle.read(buffer, 0, bytesToRead, 0),
390 catch: (cause) =>
391 new WorkspaceFileSystemOperationError({
392 workspaceRoot: input.cwd,
393 relativePath: input.relativePath,
394 resolvedPath: realTargetPath,
395 operationPath: realTargetPath,
396 operation: "read",
397 cause,
398 }),
399 });
400 const fileBytes = buffer.subarray(0, bytesRead);
401 if (fileBytes.includes(0)) {
402 return yield* new WorkspaceBinaryFileError({
403 workspaceRoot: input.cwd,
404 relativePath: input.relativePath,
405 resolvedPath: realTargetPath,
406 });
407 }
408
409 return {
410 relativePath: target.relativePath,
411 contents: new TextDecoder("utf-8").decode(fileBytes),
412 byteLength: stat.size,
413 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
414 };
415 }),
416 (handle) =>
417 handle === null
418 ? Effect.void
419 : Effect.tryPromise({
420 try: () => handle.close(),
421 catch: (cause) =>
422 new WorkspaceFileSystemOperationError({
423 workspaceRoot: input.cwd,
424 relativePath: input.relativePath,
425 resolvedPath: realTargetPath,
426 operationPath: realTargetPath,
427 operation: "close",
428 cause,
429 }),
430 }),
431 );
432 });
433
434 /**
435 * Resolves the file a write targets. The deepest existing ancestor resolves to
436 * its real path before the root check, so neither the file nor the directories
437 * created for it can follow a symlink out of the root. A dangling symlink is
438 * rejected rather than written through.
439 */
440 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
441 input: ProjectWriteFileInput,
442 ) {
443 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
444 workspaceRoot: input.cwd,
445 relativePath: input.relativePath,
446 });
447 const realWorkspaceRoot = yield* Effect.tryPromise({
448 // Resolve `..` in cwd the way the relative path was resolved, before following links.
449 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
450 catch: (cause) =>
451 new WorkspaceFileSystemOperationError({
452 workspaceRoot: input.cwd,
453 relativePath: input.relativePath,
454 resolvedPath: target.absolutePath,
455 operationPath: input.cwd,
456 operation: "realpath-workspace-root",
457 cause,
458 }),
459 });
460
461 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
462 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
463 const realTargetPath = yield* Effect.tryPromise({
464 try: async () => {
465 for (let depth = segments.length; depth > 0; depth--) {
466 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
467 try {
468 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
469 } catch (error) {
470 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
471 const exists = await NodeFSP.lstat(candidate).then(
472 () => true,
473 () => false,
474 );
475 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
476 }
477 }
478 return path.join(realWorkspaceRoot, ...segments);
479 },
480 catch: (cause) =>
481 new WorkspaceFileSystemOperationError({
482 workspaceRoot: input.cwd,
483 relativePath: input.relativePath,
484 resolvedPath: target.absolutePath,
485 operationPath: target.absolutePath,
486 operation: "realpath-target",
487 cause,
488 }),
489 });
490 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
491 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
492 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
493 Effect.tryPromise({
494 try: () => isInGitFolder(checkedPath),
495 catch: (cause) =>
496 new WorkspaceFileSystemOperationError({
497 workspaceRoot: input.cwd,
498 relativePath: input.relativePath,
499 resolvedPath: realTargetPath,
500 operationPath: checkedPath,
501 operation: "stat",
502 cause,
503 }),
504 }),
505 );
506 if (
507 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
508 (yield* inGitFolder(realTargetPath)) ||
509 (yield* inGitFolder(namedTargetPath))
510 ) {
511 return yield* new WorkspaceFilePathEscapeError({
512 workspaceRoot: input.cwd,
513 relativePath: input.relativePath,
514 resolvedWorkspaceRoot: realWorkspaceRoot,
515 resolvedPath: realTargetPath,
516 });
517 }
518 return { relativePath: target.relativePath, realTargetPath };
519 });
520
521 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
522 "WorkspaceFileSystem.writeFile",
523 )(function* (input) {
524 yield* knownWorkspaces.assertContains(input.cwd);
525 const target = yield* resolveWriteTarget(input);
526 const realTargetPath = target.realTargetPath;
527
528 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
529 Effect.mapError(
530 (cause) =>
531 new WorkspaceFileSystemOperationError({
532 workspaceRoot: input.cwd,
533 relativePath: input.relativePath,
534 resolvedPath: realTargetPath,
535 operationPath: path.dirname(realTargetPath),
536 operation: "make-directory",
537 cause,
538 }),
539 ),
540 );
541 yield* Effect.tryPromise({
542 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
543 try: () =>
544 NodeFSP.writeFile(realTargetPath, input.contents, {
545 flag:
546 NodeFS.constants.O_WRONLY |
547 NodeFS.constants.O_CREAT |
548 NodeFS.constants.O_TRUNC |
549 (NodeFS.constants.O_NOFOLLOW ?? 0),
550 }),
551 catch: (cause) =>
552 new WorkspaceFileSystemOperationError({
553 workspaceRoot: input.cwd,
554 relativePath: input.relativePath,
555 resolvedPath: realTargetPath,
556 operationPath: realTargetPath,
557 operation: "write-file",
558 cause,
559 }),
560 });
561 yield* workspaceEntries.refresh(input.cwd);
562 return { relativePath: target.relativePath };
563 });
564
565 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
566});
567
568export const layer = Layer.effect(WorkspaceFileSystem, make);