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

DesktopPreReadyFileSystem.ts

60 lines1.9 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/**
36 * @public Service construction is part of the canonical Effect module API.
37 */
38export const make = FileSystem.makeNoop({
39 exists: (path) =>
40 syncFs("exists", path, () => {
41 NodeFS.accessSync(path);
42 return true;
43 }).pipe(
44 Effect.catchIf(
45 (error) => error.reason._tag === "NotFound",
46 () => Effect.succeed(false),
47 ),
48 ),
49 readFileString: (path) => syncFs("readFileString", path, () => NodeFS.readFileSync(path, "utf8")),
50 makeDirectory: (path, options) =>
51 syncFs("makeDirectory", path, () => {
52 NodeFS.mkdirSync(path, { recursive: options?.recursive ?? false });
53 }),
54 writeFileString: (path, data, options) =>
55 syncFs("writeFileString", path, () =>
56 NodeFS.writeFileSync(path, data, { flag: options?.flag ?? "w" }),
57 ),
58});
59​
60export const layer = Layer.succeed(FileSystem.FileSystem, make);