| 36 | |
| 37 | /** @internal */ |
| 38 | export const make = ( |
| 39 | impl: Omit<FileSystem, "exists" | "readFileString" | "stream" | "sink" | "writeFileString"> |
| 40 | ): FileSystem => { |
| 41 | return tag.of({ |
| 42 | ...impl, |
| 43 | exists: (path) => |
| 44 | pipe( |
| 45 | impl.access(path), |
| 46 | Effect.as(true), |
| 47 | Effect.catchTag("SystemError", (e) => e.reason === "NotFound" ? Effect.succeed(false) : Effect.fail(e)) |
| 48 | ), |
| 49 | readFileString: (path, encoding) => |
| 50 | Effect.tryMap(impl.readFile(path), { |
| 51 | try: (_) => new TextDecoder(encoding).decode(_), |
| 52 | catch: (cause) => |
| 53 | new Error.BadArgument({ |
| 54 | module: "FileSystem", |
| 55 | method: "readFileString", |
| 56 | description: "invalid encoding", |
| 57 | cause |
| 58 | }) |
| 59 | }), |
| 60 | stream: (path, options) => |
| 61 | pipe( |
| 62 | impl.open(path, { flag: "r" }), |
| 63 | options?.offset ? |
| 64 | Effect.tap((file) => file.seek(options.offset!, "start")) : |
| 65 | identity, |
| 66 | Effect.map((file) => stream(file, options)), |
| 67 | Stream.unwrapScoped |
| 68 | ), |
| 69 | sink: (path, options) => |
| 70 | pipe( |
| 71 | impl.open(path, { flag: "w", ...options }), |
| 72 | Effect.map((file) => Sink.forEach((_: Uint8Array) => file.writeAll(_))), |
| 73 | Sink.unwrapScoped |
| 74 | ), |
| 75 | writeFileString: (path, data, options) => |
| 76 | Effect.flatMap( |
| 77 | Effect.try({ |
| 78 | try: () => new TextEncoder().encode(data), |
| 79 | catch: (cause) => |
| 80 | new Error.BadArgument({ |
| 81 | module: "FileSystem", |
| 82 | method: "writeFileString", |
| 83 | description: "could not encode string", |
| 84 | cause |
| 85 | }) |
| 86 | }), |
| 87 | (_) => impl.writeFile(path, _, options) |
| 88 | ) |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | const notFound = (method: string, path: string) => |
| 93 | new Error.SystemError({ |