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

WorkspaceFileSystem.ts

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