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