The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | /** |
| 2 | * Shared Node-compatible implementation of Effect's `FileSystem` service. |
| 3 | * |
| 4 | * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a |
| 5 | * `FileSystem` layer for Effect programs running on Node-compatible runtimes. |
| 6 | * Platform packages use it to provide file and directory I/O, permissions, |
| 7 | * links, metadata, temporary files and directories, and file watching through |
| 8 | * the shared `FileSystem` service. |
| 9 | * |
| 10 | * @stability unstable |
| 11 | * @since 4.0.0 |
| 12 | */ |
| 13 | import * as BI from "effect/BigInt" |
| 14 | import * as ByteSize from "effect/ByteSize" |
| 15 | import * as Cause from "effect/Cause" |
| 16 | import * as Effect from "effect/Effect" |
| 17 | import { effectify } from "effect/Effect" |
| 18 | import * as FileSystem from "effect/FileSystem" |
| 19 | import { pipe } from "effect/Function" |
| 20 | import * as Layer from "effect/Layer" |
| 21 | import * as Option from "effect/Option" |
| 22 | import * as Error from "effect/PlatformError" |
| 23 | import * as Queue from "effect/Queue" |
| 24 | import * as Stream from "effect/Stream" |
| 25 | import * as Crypto from "node:crypto" |
| 26 | import * as NFS from "node:fs" |
| 27 | import * as OS from "node:os" |
| 28 | import * as Path from "node:path" |
| 29 | import { handleErrnoException } from "./internal/utils.ts" |
| 30 | |
| 31 | const handleBadArgument = (method: string) => (err: unknown) => |
| 32 | Error.badArgument({ |
| 33 | module: "FileSystem", |
| 34 | method, |
| 35 | description: (err as Error).message ?? String(err) |
| 36 | }) |
| 37 | |
| 38 | const bigintToNumber = (value: bigint, field: string): number => { |
| 39 | const number = Number(value) |
| 40 | if (!Number.isSafeInteger(number)) { |
| 41 | throw new RangeError(`${field} exceeds the safe integer range: ${value}`) |
| 42 | } |
| 43 | return number |
| 44 | } |
| 45 | |
| 46 | const bigintToNumberOption = (value: bigint | undefined): Option.Option<number> => |
| 47 | Option.flatMap(Option.fromNullishOr(value), BI.toNumber) |
| 48 | |
| 49 | // Node fills bigint stats from a BigInt64Array, so unsigned 64-bit values such |
| 50 | // as dev_t and ino_t at or above 2^63 are reported as negative. |
| 51 | const toUint64 = (value: bigint): bigint => BigInt.asUintN(64, value) |
| 52 | |
| 53 | const toUint64Option = (value: bigint | undefined): Option.Option<bigint> => |
| 54 | Option.map(Option.fromNullishOr(value), toUint64) |
| 55 | |
| 56 | // fs.write ignores bigint positions. |
| 57 | const positionToNumber = (position: bigint, method: string) => |
| 58 | Effect.try({ |
| 59 | try: () => bigintToNumber(position, "position"), |
| 60 | catch: handleBadArgument(method) |
| 61 | }) |
| 62 | |
| 63 | // == access |
| 64 | |
| 65 | const access = ((): FileSystem.FileSystem["access"] => { |
| 66 | const nodeAccess = effectify( |
| 67 | NFS.access, |
| 68 | handleErrnoException("FileSystem", "access"), |
| 69 | handleBadArgument("access") |
| 70 | ) |
| 71 | return (path, options) => { |
| 72 | let mode = NFS.constants.F_OK |
| 73 | if (options?.readable) { |
| 74 | mode |= NFS.constants.R_OK |
| 75 | } |
| 76 | if (options?.writable) { |
| 77 | mode |= NFS.constants.W_OK |
| 78 | } |
| 79 | return nodeAccess(path, mode) |
| 80 | } |
| 81 | })() |
| 82 | |
| 83 | // == copy |
| 84 | |
| 85 | const copy = ((): FileSystem.FileSystem["copy"] => { |
| 86 | const nodeCp = effectify( |
| 87 | NFS.cp, |
| 88 | handleErrnoException("FileSystem", "copy"), |
| 89 | handleBadArgument("copy") |
| 90 | ) |
| 91 | return (fromPath, toPath, options) => |
| 92 | nodeCp(fromPath, toPath, { |
| 93 | force: options?.overwrite ?? false, |
| 94 | preserveTimestamps: options?.preserveTimestamps ?? false, |
| 95 | recursive: true |
| 96 | }) |
| 97 | })() |
| 98 | |
| 99 | // == copyFile |
| 100 | |
| 101 | const copyFile = (() => { |
| 102 | const nodeCopyFile = effectify( |
| 103 | NFS.copyFile, |
| 104 | handleErrnoException("FileSystem", "copyFile"), |
| 105 | handleBadArgument("copyFile") |
| 106 | ) |
| 107 | return (fromPath: string, toPath: string) => nodeCopyFile(fromPath, toPath) |
| 108 | })() |
| 109 | |
| 110 | // == chmod |
| 111 | |
| 112 | const chmod = (() => { |
| 113 | const nodeChmod = effectify( |
| 114 | NFS.chmod, |
| 115 | handleErrnoException("FileSystem", "chmod"), |
| 116 | handleBadArgument("chmod") |
| 117 | ) |
| 118 | return (path: string, mode: number) => nodeChmod(path, mode) |
| 119 | })() |
| 120 | |
| 121 | // == chown |
| 122 | |
| 123 | const chown = (() => { |
| 124 | const nodeChown = effectify( |
| 125 | NFS.chown, |
| 126 | handleErrnoException("FileSystem", "chown"), |
| 127 | handleBadArgument("chown") |
| 128 | ) |
| 129 | return (path: string, uid: number, gid: number) => nodeChown(path, uid, gid) |
| 130 | })() |
| 131 | |
| 132 | // == link |
| 133 | |
| 134 | const link = (() => { |
| 135 | const nodeLink = effectify( |
| 136 | NFS.link, |
| 137 | handleErrnoException("FileSystem", "link"), |
| 138 | handleBadArgument("link") |
| 139 | ) |
| 140 | return (existingPath: string, newPath: string) => nodeLink(existingPath, newPath) |
| 141 | })() |
| 142 | |
| 143 | // == makeDirectory |
| 144 | |
| 145 | const makeDirectory = ((): FileSystem.FileSystem["makeDirectory"] => { |
| 146 | const nodeMkdir = effectify( |
| 147 | NFS.mkdir, |
| 148 | handleErrnoException("FileSystem", "makeDirectory"), |
| 149 | handleBadArgument("makeDirectory") |
| 150 | ) |
| 151 | return (path, options) => |
| 152 | nodeMkdir(path, { |
| 153 | recursive: options?.recursive ?? false, |
| 154 | mode: options?.mode |
| 155 | }) |
| 156 | })() |
| 157 | |
| 158 | // == makeTempDirectory |
| 159 | |
| 160 | const makeTempDirectoryFactory = (method: string): FileSystem.FileSystem["makeTempDirectory"] => { |
| 161 | const nodeMkdtemp = effectify( |
| 162 | NFS.mkdtemp, |
| 163 | handleErrnoException("FileSystem", method), |
| 164 | handleBadArgument(method) |
| 165 | ) |
| 166 | return (options) => |
| 167 | Effect.suspend(() => { |
| 168 | const prefix = options?.prefix ?? "" |
| 169 | const directory = typeof options?.directory === "string" |
| 170 | ? Path.join(options.directory, ".") |
| 171 | : OS.tmpdir() |
| 172 | |
| 173 | return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + "/") |
| 174 | }) |
| 175 | } |
| 176 | const makeTempDirectory = makeTempDirectoryFactory("makeTempDirectory") |
| 177 | |
| 178 | // == remove |
| 179 | |
| 180 | const removeFactory = (method: string): FileSystem.FileSystem["remove"] => { |
| 181 | const nodeRm = effectify( |
| 182 | NFS.rm, |
| 183 | handleErrnoException("FileSystem", method), |
| 184 | handleBadArgument(method) |
| 185 | ) |
| 186 | return (path, options) => |
| 187 | nodeRm( |
| 188 | path, |
| 189 | { recursive: options?.recursive ?? false, force: options?.force ?? false } |
| 190 | ) |
| 191 | } |
| 192 | const remove = removeFactory("remove") |
| 193 | |
| 194 | // == makeTempDirectoryScoped |
| 195 | |
| 196 | const makeTempDirectoryScoped = ((): FileSystem.FileSystem["makeTempDirectoryScoped"] => { |
| 197 | const makeDirectory = makeTempDirectoryFactory("makeTempDirectoryScoped") |
| 198 | const removeDirectory = removeFactory("makeTempDirectoryScoped") |
| 199 | return (options) => |
| 200 | Effect.acquireRelease( |
| 201 | makeDirectory(options), |
| 202 | (directory) => Effect.orDie(removeDirectory(directory, { recursive: true, force: true })) |
| 203 | ) |
| 204 | })() |
| 205 | |
| 206 | // == open |
| 207 | |
| 208 | const openFlagBits = (flag: FileSystem.OpenFlag): number => { |
| 209 | const { O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY } = NFS.constants |
| 210 | switch (flag) { |
| 211 | case "r": |
| 212 | return O_RDONLY |
| 213 | case "r+": |
| 214 | return O_RDWR |
| 215 | case "w": |
| 216 | return O_TRUNC | O_CREAT | O_WRONLY |
| 217 | case "wx": |
| 218 | return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL |
| 219 | case "w+": |
| 220 | return O_TRUNC | O_CREAT | O_RDWR |
| 221 | case "wx+": |
| 222 | return O_TRUNC | O_CREAT | O_RDWR | O_EXCL |
| 223 | case "a": |
| 224 | return O_APPEND | O_CREAT | O_WRONLY |
| 225 | case "ax": |
| 226 | return O_APPEND | O_CREAT | O_WRONLY | O_EXCL |
| 227 | case "a+": |
| 228 | return O_APPEND | O_CREAT | O_RDWR |
| 229 | case "ax+": |
| 230 | return O_APPEND | O_CREAT | O_RDWR | O_EXCL |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // Reject unsupported platforms: libuv silently ignores unknown flags on Windows. |
| 235 | const noFollowFlags = (method: string, flag: FileSystem.OpenFlag) => |
| 236 | Effect.suspend(() => { |
| 237 | const { O_NOFOLLOW } = NFS.constants |
| 238 | if (process.platform === "win32" || typeof O_NOFOLLOW !== "number" || O_NOFOLLOW === 0) { |
| 239 | return Effect.fail(Error.badArgument({ |
| 240 | module: "FileSystem", |
| 241 | method, |
| 242 | description: "noFollow is not supported on this platform" |
| 243 | })) |
| 244 | } |
| 245 | return Effect.succeed(openFlagBits(flag) | O_NOFOLLOW) |
| 246 | }) |
| 247 | |
| 248 | const openFactory = (method: string): FileSystem.FileSystem["open"] => { |
| 249 | const nodeOpen = effectify( |
| 250 | NFS.open, |
| 251 | handleErrnoException("FileSystem", method), |
| 252 | handleBadArgument(method) |
| 253 | ) |
| 254 | const nodeClose = effectify( |
| 255 | NFS.close, |
| 256 | handleErrnoException("FileSystem", method), |
| 257 | handleBadArgument(method) |
| 258 | ) |
| 259 | |
| 260 | return (path, options) => |
| 261 | pipe( |
| 262 | Effect.acquireRelease( |
| 263 | options?.noFollow === true |
| 264 | ? Effect.flatMap(noFollowFlags(method, options.flag ?? "r"), (flags) => nodeOpen(path, flags, options.mode)) |
| 265 | : nodeOpen(path, options?.flag ?? "r", options?.mode), |
| 266 | (fd) => Effect.orDie(nodeClose(fd)) |
| 267 | ), |
| 268 | Effect.map((fd) => makeFile(fd, options?.flag?.startsWith("a") ?? false)) |
| 269 | ) |
| 270 | } |
| 271 | const open = openFactory("open") |
| 272 | |
| 273 | const negativePosition = (method: string) => |
| 274 | Error.badArgument({ |
| 275 | module: "FileSystem", |
| 276 | method, |
| 277 | description: "Cannot read before the start of the file" |
| 278 | }) |
| 279 | |
| 280 | const makeFile = (() => { |
| 281 | const nodeReadFactory = (method: string) => |
| 282 | effectify( |
| 283 | NFS.read, |
| 284 | handleErrnoException("FileSystem", method), |
| 285 | handleBadArgument(method) |
| 286 | ) |
| 287 | const nodeRead = nodeReadFactory("read") |
| 288 | const nodeReadAlloc = nodeReadFactory("readAlloc") |
| 289 | const nodeStat = effectify( |
| 290 | NFS.fstat, |
| 291 | handleErrnoException("FileSystem", "stat"), |
| 292 | handleBadArgument("stat") |
| 293 | ) |
| 294 | const nodeTruncate = effectify( |
| 295 | NFS.ftruncate, |
| 296 | handleErrnoException("FileSystem", "truncate"), |
| 297 | handleBadArgument("truncate") |
| 298 | ) |
| 299 | |
| 300 | const nodeSync = effectify( |
| 301 | NFS.fsync, |
| 302 | handleErrnoException("FileSystem", "sync"), |
| 303 | handleBadArgument("sync") |
| 304 | ) |
| 305 | |
| 306 | const nodeWriteFactory = (method: string) => |
| 307 | effectify( |
| 308 | NFS.write, |
| 309 | handleErrnoException("FileSystem", method), |
| 310 | handleBadArgument(method) |
| 311 | ) |
| 312 | const nodeWrite = nodeWriteFactory("write") |
| 313 | const nodeWriteAll = nodeWriteFactory("writeAll") |
| 314 | |
| 315 | class FileImpl implements FileSystem.File { |
| 316 | readonly [FileSystem.FileTypeId]: typeof FileSystem.FileTypeId |
| 317 | readonly fd: number |
| 318 | private readonly append: boolean |
| 319 | |
| 320 | private position: bigint = BigInt(0) |
| 321 | |
| 322 | constructor( |
| 323 | fd: number, |
| 324 | append: boolean |
| 325 | ) { |
| 326 | this[FileSystem.FileTypeId] = FileSystem.FileTypeId |
| 327 | this.fd = fd |
| 328 | this.append = append |
| 329 | } |
| 330 | |
| 331 | get stat() { |
| 332 | return Effect.flatMap(nodeStat(this.fd, { bigint: true }), makeFileInfo) |
| 333 | } |
| 334 | |
| 335 | get sync() { |
| 336 | return nodeSync(this.fd) |
| 337 | } |
| 338 | |
| 339 | seek(offset: bigint, from: FileSystem.SeekMode) { |
| 340 | return Effect.suspend(() => { |
| 341 | const position = from === "start" ? offset : this.position + offset |
| 342 | if (position < BigInt(0)) { |
| 343 | return Effect.fail(Error.badArgument({ |
| 344 | module: "FileSystem", |
| 345 | method: "seek", |
| 346 | description: "Cannot seek before the start of the file" |
| 347 | })) |
| 348 | } |
| 349 | this.position = position |
| 350 | return Effect.succeed(position) |
| 351 | }) |
| 352 | } |
| 353 | |
| 354 | read(buffer: Uint8Array, options?: FileSystem.File.ReadOptions) { |
| 355 | return Effect.suspend(() => { |
| 356 | const explicit = options?.position |
| 357 | if (explicit !== undefined) { |
| 358 | return explicit < BigInt(0) |
| 359 | ? Effect.fail(negativePosition("read")) |
| 360 | : nodeRead(this.fd, { buffer, position: explicit }) |
| 361 | } |
| 362 | const position = this.position |
| 363 | return Effect.map( |
| 364 | nodeRead(this.fd, { buffer, position }), |
| 365 | (bytesRead) => { |
| 366 | this.position = position + BigInt(bytesRead) |
| 367 | return bytesRead |
| 368 | } |
| 369 | ) |
| 370 | }) |
| 371 | } |
| 372 | |
| 373 | readAlloc(size: number, options?: FileSystem.File.ReadOptions) { |
| 374 | return Effect.suspend(() => { |
| 375 | try { |
| 376 | if (!Number.isInteger(size) || size < 0) { |
| 377 | throw new RangeError("size must be a non-negative integer") |
| 378 | } |
| 379 | const explicit = options?.position |
| 380 | if (explicit !== undefined && explicit < BigInt(0)) { |
| 381 | return Effect.fail(negativePosition("readAlloc")) |
| 382 | } |
| 383 | const buffer = Buffer.allocUnsafeSlow(size) |
| 384 | const position = explicit ?? this.position |
| 385 | return Effect.map( |
| 386 | nodeReadAlloc(this.fd, { buffer, position }), |
| 387 | (bytesRead): Option.Option<Buffer> => { |
| 388 | if (bytesRead === 0) { |
| 389 | return Option.none() |
| 390 | } |
| 391 | |
| 392 | if (explicit === undefined) { |
| 393 | this.position = position + BigInt(bytesRead) |
| 394 | } |
| 395 | if (bytesRead === size) { |
| 396 | return Option.some(buffer) |
| 397 | } |
| 398 | |
| 399 | const dst = Buffer.allocUnsafeSlow(bytesRead) |
| 400 | buffer.copy(dst, 0, 0, bytesRead) |
| 401 | return Option.some(dst) |
| 402 | } |
| 403 | ) |
| 404 | } catch (cause) { |
| 405 | return Effect.fail(handleBadArgument("readAlloc")(cause)) |
| 406 | } |
| 407 | }) |
| 408 | } |
| 409 | |
| 410 | truncate(length?: number) { |
| 411 | return Effect.map(nodeTruncate(this.fd, length || undefined), () => { |
| 412 | if (!this.append) { |
| 413 | const len = BigInt(length ?? 0) |
| 414 | if (this.position > len) { |
| 415 | this.position = len |
| 416 | } |
| 417 | } |
| 418 | }) |
| 419 | } |
| 420 | |
| 421 | write(buffer: Uint8Array) { |
| 422 | return Effect.suspend(() => { |
| 423 | const position = this.position |
| 424 | return Effect.flatMap( |
| 425 | this.append ? Effect.succeed(undefined) : positionToNumber(position, "write"), |
| 426 | (nodePosition) => |
| 427 | Effect.map( |
| 428 | nodeWrite(this.fd, buffer, undefined, undefined, nodePosition), |
| 429 | (bytesWritten) => { |
| 430 | if (!this.append) { |
| 431 | this.position = position + BigInt(bytesWritten) |
| 432 | } |
| 433 | return bytesWritten |
| 434 | } |
| 435 | ) |
| 436 | ) |
| 437 | }) |
| 438 | } |
| 439 | |
| 440 | private writeAllChunk(buffer: Uint8Array): Effect.Effect<void, Error.PlatformError> { |
| 441 | return Effect.suspend(() => { |
| 442 | const position = this.position |
| 443 | return Effect.flatMap( |
| 444 | this.append ? Effect.succeed(undefined) : positionToNumber(position, "writeAll"), |
| 445 | (nodePosition) => |
| 446 | Effect.flatMap( |
| 447 | nodeWriteAll(this.fd, buffer, undefined, undefined, nodePosition), |
| 448 | (bytesWritten) => { |
| 449 | if (bytesWritten === 0) { |
| 450 | return Effect.fail( |
| 451 | Error.systemError({ |
| 452 | module: "FileSystem", |
| 453 | method: "writeAll", |
| 454 | _tag: "WriteZero", |
| 455 | pathOrDescriptor: this.fd, |
| 456 | description: "write returned 0 bytes written" |
| 457 | }) |
| 458 | ) |
| 459 | } |
| 460 | |
| 461 | if (!this.append) { |
| 462 | this.position = position + BigInt(bytesWritten) |
| 463 | } |
| 464 | |
| 465 | return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void |
| 466 | } |
| 467 | ) |
| 468 | ) |
| 469 | }) |
| 470 | } |
| 471 | |
| 472 | writeAll(buffer: Uint8Array) { |
| 473 | return buffer.length === 0 ? Effect.void : this.writeAllChunk(buffer) |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | return (fd: number, append: boolean): FileSystem.File => new FileImpl(fd, append) |
| 478 | })() |
| 479 | |
| 480 | // == makeTempFile |
| 481 | |
| 482 | const makeTempFileFactory = (method: string): FileSystem.FileSystem["makeTempFile"] => { |
| 483 | const makeDirectory = makeTempDirectoryFactory(method) |
| 484 | return Effect.fnUntraced(function*(options) { |
| 485 | const directory = yield* makeDirectory(options) |
| 486 | const random = Crypto.randomBytes(6).toString("hex") |
| 487 | const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random) |
| 488 | yield* writeFile(name, new Uint8Array(0)) |
| 489 | return name |
| 490 | }) |
| 491 | } |
| 492 | const makeTempFile = makeTempFileFactory("makeTempFile") |
| 493 | |
| 494 | // == makeTempFileScoped |
| 495 | |
| 496 | const makeTempFileScoped = ((): FileSystem.FileSystem["makeTempFileScoped"] => { |
| 497 | const makeFile = makeTempFileFactory("makeTempFileScoped") |
| 498 | const removeDirectory = removeFactory("makeTempFileScoped") |
| 499 | return (options) => |
| 500 | Effect.acquireRelease( |
| 501 | makeFile(options), |
| 502 | (file) => Effect.orDie(removeDirectory(Path.dirname(file), { recursive: true, force: true })) |
| 503 | ) |
| 504 | })() |
| 505 | |
| 506 | // == readDirectory |
| 507 | |
| 508 | const readDirectory: FileSystem.FileSystem["readDirectory"] = (path, options) => |
| 509 | Effect.tryPromise({ |
| 510 | try: () => NFS.promises.readdir(path, options), |
| 511 | catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err as any, [path]) |
| 512 | }) |
| 513 | |
| 514 | const readDirectoryEntries = (path: string) => |
| 515 | Effect.tryPromise({ |
| 516 | try: () => NFS.promises.readdir(path, { withFileTypes: true }), |
| 517 | catch: (err) => handleErrnoException("FileSystem", "readDirectoryEntries")(err as any, [path]) |
| 518 | }).pipe( |
| 519 | Effect.map((entries) => |
| 520 | entries.map((entry): FileSystem.DirectoryEntry => ({ name: entry.name, type: fileType(entry) })) |
| 521 | ) |
| 522 | ) |
| 523 | |
| 524 | // == readFile |
| 525 | |
| 526 | const readFile = (path: string) => |
| 527 | Effect.callback<Uint8Array, Error.PlatformError>((resume, signal) => { |
| 528 | try { |
| 529 | NFS.readFile(path, { signal }, (err, data) => { |
| 530 | if (err) { |
| 531 | resume(Effect.fail(handleErrnoException("FileSystem", "readFile")(err, [path]))) |
| 532 | } else { |
| 533 | resume(Effect.succeed(data)) |
| 534 | } |
| 535 | }) |
| 536 | } catch (err) { |
| 537 | resume(Effect.fail(handleBadArgument("readFile")(err))) |
| 538 | } |
| 539 | }) |
| 540 | |
| 541 | // == readLink |
| 542 | |
| 543 | const readLink = (() => { |
| 544 | const nodeReadLink = effectify( |
| 545 | NFS.readlink, |
| 546 | handleErrnoException("FileSystem", "readLink"), |
| 547 | handleBadArgument("readLink") |
| 548 | ) |
| 549 | return (path: string) => nodeReadLink(path) |
| 550 | })() |
| 551 | |
| 552 | // == realPath |
| 553 | |
| 554 | const realPath = (() => { |
| 555 | const nodeRealPath = effectify( |
| 556 | process.platform === "win32" ? NFS.realpath.native : NFS.realpath, |
| 557 | handleErrnoException("FileSystem", "realPath"), |
| 558 | handleBadArgument("realPath") |
| 559 | ) |
| 560 | return (path: string) => nodeRealPath(path) |
| 561 | })() |
| 562 | |
| 563 | // == rename |
| 564 | |
| 565 | const rename = (() => { |
| 566 | const nodeRename = effectify( |
| 567 | NFS.rename, |
| 568 | handleErrnoException("FileSystem", "rename"), |
| 569 | handleBadArgument("rename") |
| 570 | ) |
| 571 | return (oldPath: string, newPath: string) => nodeRename(oldPath, newPath) |
| 572 | })() |
| 573 | |
| 574 | // == stat |
| 575 | |
| 576 | const fileType = (stat: NFS.BigIntStats | NFS.Dirent): FileSystem.File.Type => |
| 577 | stat.isFile() ? |
| 578 | "File" : |
| 579 | stat.isDirectory() ? |
| 580 | "Directory" : |
| 581 | stat.isSymbolicLink() ? |
| 582 | "SymbolicLink" : |
| 583 | stat.isBlockDevice() ? |
| 584 | "BlockDevice" : |
| 585 | stat.isCharacterDevice() ? |
| 586 | "CharacterDevice" : |
| 587 | stat.isFIFO() ? |
| 588 | "FIFO" : |
| 589 | stat.isSocket() ? |
| 590 | "Socket" : |
| 591 | "Unknown" |
| 592 | |
| 593 | const makeFileInfo = ( |
| 594 | stat: NFS.BigIntStats, |
| 595 | method = "stat" |
| 596 | ): Effect.Effect<FileSystem.File.Info, Error.PlatformError> => |
| 597 | Effect.try({ |
| 598 | try: (): FileSystem.File.Info => ({ |
| 599 | type: fileType(stat), |
| 600 | mtime: Option.fromNullishOr(stat.mtime), |
| 601 | atime: Option.fromNullishOr(stat.atime), |
| 602 | birthtime: Option.fromNullishOr(stat.birthtime), |
| 603 | dev: toUint64(stat.dev), |
| 604 | rdev: toUint64Option(stat.rdev), |
| 605 | ino: toUint64Option(stat.ino), |
| 606 | mode: bigintToNumber(stat.mode, "mode"), |
| 607 | nlink: toUint64Option(stat.nlink), |
| 608 | uid: bigintToNumberOption(stat.uid), |
| 609 | gid: bigintToNumberOption(stat.gid), |
| 610 | size: ByteSize.bytes(stat.size), |
| 611 | blksize: stat.blksize !== undefined ? Option.some(ByteSize.bytes(stat.blksize)) : Option.none(), |
| 612 | blocks: Option.fromNullishOr(stat.blocks) |
| 613 | }), |
| 614 | catch: handleBadArgument(method) |
| 615 | }) |
| 616 | const statFactory = (method: string, nodeStatFn: typeof NFS.stat) => { |
| 617 | const nodeStat = effectify( |
| 618 | nodeStatFn, |
| 619 | handleErrnoException("FileSystem", method), |
| 620 | handleBadArgument(method) |
| 621 | ) |
| 622 | return (path: string) => Effect.flatMap(nodeStat(path, { bigint: true }), (stat) => makeFileInfo(stat, method)) |
| 623 | } |
| 624 | const stat = statFactory("stat", NFS.stat) |
| 625 | const lstat = statFactory("lstat", NFS.lstat) |
| 626 | |
| 627 | // == symlink |
| 628 | |
| 629 | const symlink = (() => { |
| 630 | const nodeSymlink = effectify( |
| 631 | NFS.symlink, |
| 632 | handleErrnoException("FileSystem", "symlink"), |
| 633 | handleBadArgument("symlink") |
| 634 | ) |
| 635 | return (target: string, path: string) => nodeSymlink(target, path) |
| 636 | })() |
| 637 | |
| 638 | // == truncate |
| 639 | |
| 640 | const truncate = (() => { |
| 641 | const nodeTruncate = effectify( |
| 642 | NFS.truncate, |
| 643 | handleErrnoException("FileSystem", "truncate"), |
| 644 | handleBadArgument("truncate") |
| 645 | ) |
| 646 | return (path: string, length?: number) => nodeTruncate(path, length) |
| 647 | })() |
| 648 | |
| 649 | // == utimes |
| 650 | |
| 651 | const utimes = (() => { |
| 652 | const nodeUtimes = effectify( |
| 653 | NFS.utimes, |
| 654 | handleErrnoException("FileSystem", "utime"), |
| 655 | handleBadArgument("utime") |
| 656 | ) |
| 657 | return (path: string, atime: number | Date, mtime: number | Date) => nodeUtimes(path, atime, mtime) |
| 658 | })() |
| 659 | |
| 660 | // == watch |
| 661 | |
| 662 | const watchNode = (path: string, info: FileSystem.File.Info, options?: FileSystem.WatchOptions) => |
| 663 | Stream.callback<FileSystem.WatchEvent, Error.PlatformError>((queue) => |
| 664 | Effect.acquireRelease( |
| 665 | Effect.sync(() => { |
| 666 | const directory = info.type === "Directory" ? path : Path.dirname(path) |
| 667 | const watcher = NFS.watch(path, { |
| 668 | recursive: options?.recursive ?? false |
| 669 | }, (event, path) => { |
| 670 | if (!path) return |
| 671 | switch (event) { |
| 672 | case "rename": { |
| 673 | Effect.runFork(Effect.matchEffect(stat(Path.resolve(directory, path)), { |
| 674 | onSuccess: (_) => Queue.offer(queue, { _tag: "Create", path }), |
| 675 | onFailure: (_) => Queue.offer(queue, { _tag: "Remove", path }) |
| 676 | })) |
| 677 | return |
| 678 | } |
| 679 | case "change": { |
| 680 | Queue.offerUnsafe(queue, { _tag: "Update", path }) |
| 681 | return |
| 682 | } |
| 683 | } |
| 684 | }) |
| 685 | watcher.on("error", (error) => { |
| 686 | Queue.failCauseUnsafe( |
| 687 | queue, |
| 688 | Cause.fail( |
| 689 | Error.systemError({ |
| 690 | module: "FileSystem", |
| 691 | _tag: "Unknown", |
| 692 | method: "watch", |
| 693 | pathOrDescriptor: path, |
| 694 | cause: error |
| 695 | }) |
| 696 | ) |
| 697 | ) |
| 698 | }) |
| 699 | watcher.on("close", () => { |
| 700 | Queue.endUnsafe(queue) |
| 701 | }) |
| 702 | return watcher |
| 703 | }), |
| 704 | (watcher) => Effect.sync(() => watcher.close()) |
| 705 | ).pipe(Effect.tap(() => Effect.sync(() => options?.onReady?.()))) |
| 706 | ) |
| 707 | |
| 708 | const watch = ( |
| 709 | backend: Option.Option<FileSystem.WatchBackend["Service"]>, |
| 710 | path: string, |
| 711 | options?: FileSystem.WatchOptions |
| 712 | ) => |
| 713 | Effect.all([stat(path), Effect.serviceOption(FileSystem.WatchBackend)]).pipe( |
| 714 | Effect.map(([stat, callerBackend]) => |
| 715 | Option.orElse(callerBackend, () => backend).pipe( |
| 716 | Option.flatMap((_) => _.register(path, stat, options)), |
| 717 | Option.getOrElse(() => watchNode(path, stat, options)) |
| 718 | ) |
| 719 | ), |
| 720 | Stream.unwrap |
| 721 | ) |
| 722 | |
| 723 | // == writeFile |
| 724 | |
| 725 | const writeFile: FileSystem.FileSystem["writeFile"] = (path, data, options) => |
| 726 | Effect.callback<void, Error.PlatformError>((resume, signal) => { |
| 727 | try { |
| 728 | NFS.writeFile(path, data, { |
| 729 | signal, |
| 730 | flag: options?.flag, |
| 731 | mode: options?.mode |
| 732 | }, (err) => { |
| 733 | if (err) { |
| 734 | resume(Effect.fail(handleErrnoException("FileSystem", "writeFile")(err, [path]))) |
| 735 | } else { |
| 736 | resume(Effect.void) |
| 737 | } |
| 738 | }) |
| 739 | } catch (err) { |
| 740 | resume(Effect.fail(handleBadArgument("writeFile")(err))) |
| 741 | } |
| 742 | }) |
| 743 | |
| 744 | const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend), (backend) => |
| 745 | FileSystem.make({ |
| 746 | access, |
| 747 | chmod, |
| 748 | chown, |
| 749 | copy, |
| 750 | copyFile, |
| 751 | link, |
| 752 | lstat, |
| 753 | makeDirectory, |
| 754 | makeTempDirectory, |
| 755 | makeTempDirectoryScoped, |
| 756 | makeTempFile, |
| 757 | makeTempFileScoped, |
| 758 | open, |
| 759 | readDirectory, |
| 760 | readDirectoryEntries, |
| 761 | readFile, |
| 762 | readLink, |
| 763 | realPath, |
| 764 | remove, |
| 765 | rename, |
| 766 | stat, |
| 767 | symlink, |
| 768 | truncate, |
| 769 | utimes, |
| 770 | watch(path, options) { |
| 771 | return watch(backend, path, options) |
| 772 | }, |
| 773 | writeFile |
| 774 | })) |
| 775 | |
| 776 | /** |
| 777 | * Provides the `FileSystem` service backed by Node filesystem APIs, including |
| 778 | * file operations, directory operations, links, metadata, and file watching. |
| 779 | * |
| 780 | * @stability unstable |
| 781 | * @category layers |
| 782 | * @since 4.0.0 |
| 783 | */ |
| 784 | export const layer: Layer.Layer<FileSystem.FileSystem> = Layer.effect(FileSystem.FileSystem)(makeFileSystem) |