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