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

WorkspaceFileSystem.ts

303 lines9.9 KB

1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * WorkspaceFileSystem - Effect service contract for workspace file mutations.
4 *
5 * Owns workspace-root-relative file read/write operations and their associated
6 * safety checks and cache invalidation hooks.
7 *
8 * @module WorkspaceFileSystem
9 */
10import * as NodeFSP from "node:fs/promises";
11​
12import type {
13 ProjectReadFileInput,
14 ProjectReadFileResult,
15 ProjectWriteFileInput,
16 ProjectWriteFileResult,
17} from "@v12/contracts";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Path from "effect/Path";
23import * as Schema from "effect/Schema";
24​
25import * as WorkspaceEntries from "./WorkspaceEntries.ts";
26import * as WorkspacePaths from "./WorkspacePaths.ts";
27​
28const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
29​
30export class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(
31 "WorkspaceFileSystemOperationError",
32 {
33 workspaceRoot: Schema.String,
34 relativePath: Schema.String,
35 resolvedPath: Schema.String,
36 operationPath: Schema.String,
37 operation: Schema.Literals([
38 "realpath-workspace-root",
39 "realpath-target",
40 "open",
41 "stat",
42 "read",
43 "close",
44 "make-directory",
45 "write-file",
46 ]),
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
52 }
54​
55export class WorkspaceFilePathEscapeError extends Schema.TaggedErrorClass<WorkspaceFilePathEscapeError>()(
56 "WorkspaceFilePathEscapeError",
57 {
58 workspaceRoot: Schema.String,
59 relativePath: Schema.String,
60 resolvedWorkspaceRoot: Schema.String,
61 resolvedPath: Schema.String,
62 },
63) {
64 override get message(): string {
65 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
66 }
68​
69export class WorkspacePathNotFileError extends Schema.TaggedErrorClass<WorkspacePathNotFileError>()(
70 "WorkspacePathNotFileError",
71 {
72 workspaceRoot: Schema.String,
73 relativePath: Schema.String,
74 resolvedPath: Schema.String,
75 },
76) {
77 override get message(): string {
78 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
79 }
81​
82export class WorkspaceBinaryFileError extends Schema.TaggedErrorClass<WorkspaceBinaryFileError>()(
83 "WorkspaceBinaryFileError",
84 {
85 workspaceRoot: Schema.String,
86 relativePath: Schema.String,
87 resolvedPath: Schema.String,
88 },
89) {
90 override get message(): string {
91 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
92 }
94​
95export const WorkspaceFileSystemError = Schema.Union([
96 WorkspaceFileSystemOperationError,
97 WorkspaceFilePathEscapeError,
98 WorkspacePathNotFileError,
99 WorkspaceBinaryFileError,
100]);
101export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
102​
103/** Service tag for workspace file operations. */
104export class WorkspaceFileSystem extends Context.Service<
105 WorkspaceFileSystem,
106 {
107 /** Read a UTF-8 text file relative to the workspace root. */
108 readonly readFile: (
109 input: ProjectReadFileInput,
110 ) => Effect.Effect<
111 ProjectReadFileResult,
112 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
113 >;
114 /**
115 * Write a file relative to the workspace root.
116 *
117 * Creates parent directories as needed and rejects paths that escape the
118 * workspace root.
119 */
120 readonly writeFile: (
121 input: ProjectWriteFileInput,
122 ) => Effect.Effect<
123 ProjectWriteFileResult,
124 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
125 >;
126 }
127>()("v12/workspace/WorkspaceFileSystem") {}
128​
129export const make = Effect.gen(function* () {
130 const fileSystem = yield* FileSystem.FileSystem;
131 const path = yield* Path.Path;
132 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
133 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
134​
135 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
136 "WorkspaceFileSystem.readFile",
137 )(function* (input) {
138 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
139 workspaceRoot: input.cwd,
140 relativePath: input.relativePath,
141 });
142​
143 const realWorkspaceRoot = yield* Effect.tryPromise({
144 try: () => NodeFSP.realpath(input.cwd),
145 catch: (cause) =>
146 new WorkspaceFileSystemOperationError({
147 workspaceRoot: input.cwd,
148 relativePath: input.relativePath,
149 resolvedPath: target.absolutePath,
150 operationPath: input.cwd,
151 operation: "realpath-workspace-root",
152 cause,
153 }),
154 });
155 const realTargetPath = yield* Effect.tryPromise({
156 try: () => NodeFSP.realpath(target.absolutePath),
157 catch: (cause) =>
158 new WorkspaceFileSystemOperationError({
159 workspaceRoot: input.cwd,
160 relativePath: input.relativePath,
161 resolvedPath: target.absolutePath,
162 operationPath: target.absolutePath,
163 operation: "realpath-target",
164 cause,
165 }),
166 });
167 const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
168 if (
169 relativeRealPath.startsWith(`..${path.sep}`) ||
170 relativeRealPath === ".." ||
171 path.isAbsolute(relativeRealPath)
172 ) {
173 return yield* new WorkspaceFilePathEscapeError({
174 workspaceRoot: input.cwd,
175 relativePath: input.relativePath,
176 resolvedWorkspaceRoot: realWorkspaceRoot,
177 resolvedPath: realTargetPath,
178 });
179 }
180​
181 return yield* Effect.acquireUseRelease(
182 Effect.tryPromise({
183 try: () => NodeFSP.open(realTargetPath, "r"),
184 catch: (cause) =>
185 new WorkspaceFileSystemOperationError({
186 workspaceRoot: input.cwd,
187 relativePath: input.relativePath,
188 resolvedPath: realTargetPath,
189 operationPath: realTargetPath,
190 operation: "open",
191 cause,
192 }),
193 }),
194 (handle) =>
195 Effect.gen(function* () {
196 const stat = yield* Effect.tryPromise({
197 try: () => handle.stat(),
198 catch: (cause) =>
199 new WorkspaceFileSystemOperationError({
200 workspaceRoot: input.cwd,
201 relativePath: input.relativePath,
202 resolvedPath: realTargetPath,
203 operationPath: realTargetPath,
204 operation: "stat",
205 cause,
206 }),
207 });
208 if (!stat.isFile()) {
209 return yield* new WorkspacePathNotFileError({
210 workspaceRoot: input.cwd,
211 relativePath: input.relativePath,
212 resolvedPath: realTargetPath,
213 });
214 }
215​
216 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
217 const buffer = Buffer.alloc(bytesToRead);
218 const { bytesRead } = yield* Effect.tryPromise({
219 try: () => handle.read(buffer, 0, bytesToRead, 0),
220 catch: (cause) =>
221 new WorkspaceFileSystemOperationError({
222 workspaceRoot: input.cwd,
223 relativePath: input.relativePath,
224 resolvedPath: realTargetPath,
225 operationPath: realTargetPath,
226 operation: "read",
227 cause,
228 }),
229 });
230 const fileBytes = buffer.subarray(0, bytesRead);
231 if (fileBytes.includes(0)) {
232 return yield* new WorkspaceBinaryFileError({
233 workspaceRoot: input.cwd,
234 relativePath: input.relativePath,
235 resolvedPath: realTargetPath,
236 });
237 }
238​
239 return {
240 relativePath: target.relativePath,
241 contents: new TextDecoder("utf-8").decode(fileBytes),
242 byteLength: stat.size,
243 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
244 };
245 }),
246 (handle) =>
247 Effect.tryPromise({
248 try: () => handle.close(),
249 catch: (cause) =>
250 new WorkspaceFileSystemOperationError({
251 workspaceRoot: input.cwd,
252 relativePath: input.relativePath,
253 resolvedPath: realTargetPath,
254 operationPath: realTargetPath,
255 operation: "close",
256 cause,
257 }),
258 }),
259 );
260 });
261​
262 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
263 "WorkspaceFileSystem.writeFile",
264 )(function* (input) {
265 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
266 workspaceRoot: input.cwd,
267 relativePath: input.relativePath,
268 });
269​
270 yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
271 Effect.mapError(
272 (cause) =>
273 new WorkspaceFileSystemOperationError({
274 workspaceRoot: input.cwd,
275 relativePath: input.relativePath,
276 resolvedPath: target.absolutePath,
277 operationPath: path.dirname(target.absolutePath),
278 operation: "make-directory",
279 cause,
280 }),
281 ),
282 );
283 yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
284 Effect.mapError(
285 (cause) =>
286 new WorkspaceFileSystemOperationError({
287 workspaceRoot: input.cwd,
288 relativePath: input.relativePath,
289 resolvedPath: target.absolutePath,
290 operationPath: target.absolutePath,
291 operation: "write-file",
292 cause,
293 }),
294 ),
295 );
296 yield* workspaceEntries.refresh(input.cwd);
297 return { relativePath: target.relativePath };
298 });
299​
300 return WorkspaceFileSystem.of({ readFile, writeFile });
301});
302​
303export const layer = Layer.effect(WorkspaceFileSystem, make);