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

DesktopPreReadyFileSystem.ts

65 lines2.0 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Effect's Node FileSystem is async, and pre-ready startup must not yield before the Clerk bridge registers its privileged scheme.
2import * as NodeFS from "node:fs";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as PlatformError from "effect/PlatformError";
7​
8const systemErrorTag = (cause: unknown): PlatformError.SystemErrorTag => {
9 switch ((cause as NodeJS.ErrnoException | undefined)?.code) {
10 case "EEXIST":
11 return "AlreadyExists";
12 case "ENOENT":
13 return "NotFound";
14 case "EACCES":
15 case "EPERM":
16 return "PermissionDenied";
17 default:
18 return "Unknown";
19 }
20};
21​
22const syncFs = <A>(method: string, path: string, run: () => A) =>
23 Effect.try({
24 try: run,
25 catch: (cause) =>
26 PlatformError.systemError({
27 _tag: systemErrorTag(cause),
28 module: "FileSystem",
29 method,
30 pathOrDescriptor: path,
31 cause,
32 }),
33 });
34​
35/** @public */
36export const make = FileSystem.makeNoop({
37 exists: (path) =>
38 syncFs("exists", path, () => {
39 NodeFS.accessSync(path);
40 return true;
41 }).pipe(
42 Effect.catchIf(
43 (error) => error.reason._tag === "NotFound",
44 () => Effect.succeed(false),
45 ),
46 ),
47 readFileString: (path) => syncFs("readFileString", path, () => NodeFS.readFileSync(path, "utf8")),
48 makeDirectory: (path, options) =>
49 syncFs("makeDirectory", path, () => {
50 NodeFS.mkdirSync(path, { recursive: options?.recursive ?? false });
51 }),
52 remove: (path, options) =>
53 syncFs("remove", path, () =>
54 NodeFS.rmSync(path, {
55 recursive: options?.recursive ?? false,
56 force: options?.force ?? false,
57 }),
58 ),
59 writeFileString: (path, data, options) =>
60 syncFs("writeFileString", path, () =>
61 NodeFS.writeFileSync(path, data, { flag: options?.flag ?? "w" }),
62 ),
63});
64​
65export const layer = Layer.succeed(FileSystem.FileSystem, make);