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

WorkspacePaths.ts

227 lines7.1 KB

1/**
2 * WorkspacePaths - Effect service contract for workspace path handling.
3 *
4 * Owns normalization and validation of workspace roots plus safe resolution of
5 * workspace-root-relative paths.
6 *
7 * @module WorkspacePaths
8 */
9​
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16​
17import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
18​
19export class WorkspaceRootNotExistsError extends Schema.TaggedError<WorkspaceRootNotExistsError>()(
20 "WorkspaceRootNotExistsError",
21 {
22 workspaceRoot: Schema.String,
23 normalizedWorkspaceRoot: Schema.String,
24 },
25) {
26 override get message(): string {
27 return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;
28 }
30​
31export class WorkspaceRootCreateFailedError extends Schema.TaggedError<WorkspaceRootCreateFailedError>()(
32 "WorkspaceRootCreateFailedError",
33 {
34 workspaceRoot: Schema.String,
35 normalizedWorkspaceRoot: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;
41 }
43​
44export class WorkspaceRootStatFailedError extends Schema.TaggedError<WorkspaceRootStatFailedError>()(
45 "WorkspaceRootStatFailedError",
46 {
47 workspaceRoot: Schema.String,
48 normalizedWorkspaceRoot: Schema.String,
49 phase: Schema.Literals(["validate-existing", "verify-created"]),
50 cause: Schema.Defect(),
51 },
52) {
53 override get message(): string {
54 return `Failed to stat workspace root '${this.normalizedWorkspaceRoot}' during '${this.phase}'.`;
55 }
57​
58export class WorkspaceRootNotDirectoryError extends Schema.TaggedError<WorkspaceRootNotDirectoryError>()(
59 "WorkspaceRootNotDirectoryError",
60 {
61 workspaceRoot: Schema.String,
62 normalizedWorkspaceRoot: Schema.String,
63 },
64) {
65 override get message(): string {
66 return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;
67 }
69​
70export class WorkspacePathOutsideRootError extends Schema.TaggedError<WorkspacePathOutsideRootError>()(
71 "WorkspacePathOutsideRootError",
72 {
73 workspaceRoot: Schema.String,
74 relativePath: Schema.String,
75 },
76) {
77 override get message(): string {
78 return `Workspace file path must be relative to the project root: ${this.relativePath}`;
79 }
81​
82export const WorkspacePathsError = Schema.Union([
83 WorkspaceRootNotExistsError,
84 WorkspaceRootCreateFailedError,
85 WorkspaceRootStatFailedError,
86 WorkspaceRootNotDirectoryError,
87 WorkspacePathOutsideRootError,
88]);
89export type WorkspacePathsError = typeof WorkspacePathsError.Type;
90​
91/** Service tag for workspace path normalization and resolution. */
92export class WorkspacePaths extends Context.Service<
93 WorkspacePaths,
94 {
95 /** Normalize a user-provided workspace root and verify it exists as a directory. */
96 readonly normalizeWorkspaceRoot: (
97 workspaceRoot: string,
98 options?: { readonly createIfMissing?: boolean },
99 ) => Effect.Effect<
100 string,
101 | WorkspaceRootNotExistsError
102 | WorkspaceRootCreateFailedError
103 | WorkspaceRootStatFailedError
104 | WorkspaceRootNotDirectoryError
105 >;
106 /**
107 * Resolve a relative path within a validated workspace root.
108 *
109 * Rejects absolute paths and traversal attempts outside the workspace root.
110 */
111 readonly resolveRelativePathWithinRoot: (input: {
112 workspaceRoot: string;
113 relativePath: string;
114 }) => Effect.Effect<
115 { absolutePath: string; relativePath: string },
116 WorkspacePathOutsideRootError
117 >;
118 }
119>()("t3/workspace/WorkspacePaths") {}
120​
121function toPosixRelativePath(input: string): string {
122 return input.replaceAll("\\", "/");
124​
125export const make = Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128​
129 const statWorkspaceRoot = Effect.fn("WorkspacePaths.statWorkspaceRoot")(function* (
130 workspaceRoot: string,
131 normalizedWorkspaceRoot: string,
132 phase: WorkspaceRootStatFailedError["phase"],
133 ) {
134 return yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(
135 Effect.matchEffect({
136 onFailure: (cause) =>
137 cause.reason._tag === "NotFound"
138 ? Effect.succeed(null)
139 : Effect.fail(
140 new WorkspaceRootStatFailedError({
141 workspaceRoot,
142 normalizedWorkspaceRoot,
143 phase,
144 cause,
145 }),
146 ),
147 onSuccess: Effect.succeed,
148 }),
149 );
150 });
151​
152 const normalizeWorkspaceRoot: WorkspacePaths["Service"]["normalizeWorkspaceRoot"] = Effect.fn(
153 "WorkspacePaths.normalizeWorkspaceRoot",
154 )(function* (workspaceRoot, options) {
155 const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim()));
156 let workspaceStat = yield* statWorkspaceRoot(
157 workspaceRoot,
158 normalizedWorkspaceRoot,
159 "validate-existing",
160 );
161 if (!workspaceStat && options?.createIfMissing) {
162 yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
163 Effect.mapError(
164 (cause) =>
165 new WorkspaceRootCreateFailedError({
166 workspaceRoot,
167 normalizedWorkspaceRoot,
168 cause,
169 }),
170 ),
171 );
172 workspaceStat = yield* statWorkspaceRoot(
173 workspaceRoot,
174 normalizedWorkspaceRoot,
175 "verify-created",
176 );
177 }
178 if (!workspaceStat) {
179 return yield* new WorkspaceRootNotExistsError({
180 workspaceRoot,
181 normalizedWorkspaceRoot,
182 });
183 }
184 if (workspaceStat.type !== "Directory") {
185 return yield* new WorkspaceRootNotDirectoryError({
186 workspaceRoot,
187 normalizedWorkspaceRoot,
188 });
189 }
190 return normalizedWorkspaceRoot;
191 });
192​
193 const resolveRelativePathWithinRoot: WorkspacePaths["Service"]["resolveRelativePathWithinRoot"] =
194 Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) {
195 const normalizedInputPath = input.relativePath.trim();
196 if (path.isAbsolute(normalizedInputPath)) {
197 return yield* new WorkspacePathOutsideRootError({
198 workspaceRoot: input.workspaceRoot,
199 relativePath: input.relativePath,
200 });
201 }
202​
203 const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);
204 const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));
205 if (
206 relativeToRoot.length === 0 ||
207 relativeToRoot === "." ||
208 relativeToRoot.startsWith("../") ||
209 relativeToRoot === ".." ||
210 path.isAbsolute(relativeToRoot)
211 ) {
212 return yield* new WorkspacePathOutsideRootError({
213 workspaceRoot: input.workspaceRoot,
214 relativePath: input.relativePath,
215 });
216 }
217​
218 return {
219 absolutePath,
220 relativePath: relativeToRoot,
221 };
222 });
223​
224 return WorkspacePaths.of({ normalizeWorkspaceRoot, resolveRelativePathWithinRoot });
225});
226​
227export const layer = Layer.effect(WorkspacePaths, make);