Open History to see the last commit
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 * @since 4.0.0
11 */
12import * as Cause from "effect/Cause"
13import * as Effect from "effect/Effect"
14import { effectify } from "effect/Effect"
15import * as FileSystem from "effect/FileSystem"
16import { pipe } from "effect/Function"
17import * as Layer from "effect/Layer"
18import * as Option from "effect/Option"
19import * as Error from "effect/PlatformError"
20import * as Queue from "effect/Queue"
21import * as Stream from "effect/Stream"
22import * as Crypto from "node:crypto"
23import * as NFS from "node:fs"
24import * as OS from "node:os"
25import * as Path from "node:path"
26import { handleErrnoException } from "./internal/utils.ts"
27
28const handleBadArgument = (method: string) => (err: unknown) =>
29 Error.badArgument({
30 module: "FileSystem",
31 method,
32 description: (err as Error).message ?? String(err)
33 })
34
35// == access
36
37const access = ((): FileSystem.FileSystem["access"] => {
38 const nodeAccess = effectify(
39 NFS.access,
40 handleErrnoException("FileSystem", "access"),
41 handleBadArgument("access")
42 )
43 return (path, options) => {
44 let mode = NFS.constants.F_OK
45 if (options?.readable) {
46 mode |= NFS.constants.R_OK
47 }
48 if (options?.writable) {
49 mode |= NFS.constants.W_OK
50 }
51 return nodeAccess(path, mode)
52 }
53})()
54
55// == copy
56
57const copy = ((): FileSystem.FileSystem["copy"] => {
58 const nodeCp = effectify(
59 NFS.cp,
60 handleErrnoException("FileSystem", "copy"),
61 handleBadArgument("copy")
62 )
63 return (fromPath, toPath, options) =>
64 nodeCp(fromPath, toPath, {
65 force: options?.overwrite ?? false,
66 preserveTimestamps: options?.preserveTimestamps ?? false,
67 recursive: true
68 })
69})()
70
71// == copyFile
72
73const copyFile = (() => {
74 const nodeCopyFile = effectify(
75 NFS.copyFile,
76 handleErrnoException("FileSystem", "copyFile"),
77 handleBadArgument("copyFile")
78 )
79 return (fromPath: string, toPath: string) => nodeCopyFile(fromPath, toPath)
80})()
81
82// == chmod
83
84const chmod = (() => {
85 const nodeChmod = effectify(
86 NFS.chmod,
87 handleErrnoException("FileSystem", "chmod"),
88 handleBadArgument("chmod")
89 )
90 return (path: string, mode: number) => nodeChmod(path, mode)
91})()
92
93// == chown
94
95const chown = (() => {
96 const nodeChown = effectify(
97 NFS.chown,
98 handleErrnoException("FileSystem", "chown"),
99 handleBadArgument("chown")
100 )
101 return (path: string, uid: number, gid: number) => nodeChown(path, uid, gid)
102})()
103
104// == glob
105
106const glob = ((): FileSystem.FileSystem["glob"] => {
107 const nodeGlob = effectify(
108 NFS.glob,
109 handleErrnoException("FileSystem", "glob"),
110 handleBadArgument("glob")
111 )
112 return (pattern: string, options) =>
113 nodeGlob(pattern, {
114 cwd: options?.root,
115 exclude: options?.exclude
116 })
117})()
118
119// == link
120
121const link = (() => {
122 const nodeLink = effectify(
123 NFS.link,
124 handleErrnoException("FileSystem", "link"),
125 handleBadArgument("link")
126 )
127 return (existingPath: string, newPath: string) => nodeLink(existingPath, newPath)
128})()
129
130// == makeDirectory
131
132const makeDirectory = ((): FileSystem.FileSystem["makeDirectory"] => {
133 const nodeMkdir = effectify(
134 NFS.mkdir,
135 handleErrnoException("FileSystem", "makeDirectory"),
136 handleBadArgument("makeDirectory")
137 )
138 return (path, options) =>
139 nodeMkdir(path, {
140 recursive: options?.recursive ?? false,
141 mode: options?.mode
142 })
143})()
144
145// == makeTempDirectory
146
147const makeTempDirectoryFactory = (method: string): FileSystem.FileSystem["makeTempDirectory"] => {
148 const nodeMkdtemp = effectify(
149 NFS.mkdtemp,
150 handleErrnoException("FileSystem", method),
151 handleBadArgument(method)
152 )
153 return (options) =>
154 Effect.suspend(() => {
155 const prefix = options?.prefix ?? ""
156 const directory = typeof options?.directory === "string"
157 ? Path.join(options.directory, ".")
158 : OS.tmpdir()
159
160 return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + "/")
161 })
162}
163const makeTempDirectory = makeTempDirectoryFactory("makeTempDirectory")
164
165// == remove
166
167const removeFactory = (method: string): FileSystem.FileSystem["remove"] => {
168 const nodeRm = effectify(
169 NFS.rm,
170 handleErrnoException("FileSystem", method),
171 handleBadArgument(method)
172 )
173 return (path, options) =>
174 nodeRm(
175 path,
176 { recursive: options?.recursive ?? false, force: options?.force ?? false }
177 )
178}
179const remove = removeFactory("remove")
180
181// == makeTempDirectoryScoped
182
183const makeTempDirectoryScoped = ((): FileSystem.FileSystem["makeTempDirectoryScoped"] => {
184 const makeDirectory = makeTempDirectoryFactory("makeTempDirectoryScoped")
185 const removeDirectory = removeFactory("makeTempDirectoryScoped")
186 return (options) =>
187 Effect.acquireRelease(
188 makeDirectory(options),
189 (directory) => Effect.orDie(removeDirectory(directory, { recursive: true }))
190 )
191})()
192
193// == open
194
195const openFactory = (method: string): FileSystem.FileSystem["open"] => {
196 const nodeOpen = effectify(
197 NFS.open,
198 handleErrnoException("FileSystem", method),
199 handleBadArgument(method)
200 )
201 const nodeClose = effectify(
202 NFS.close,
203 handleErrnoException("FileSystem", method),
204 handleBadArgument(method)
205 )
206
207 return (path, options) =>
208 pipe(
209 Effect.acquireRelease(
210 nodeOpen(path, options?.flag ?? "r", options?.mode),
211 (fd) => Effect.orDie(nodeClose(fd))
212 ),
213 Effect.map((fd) => makeFile(FileSystem.FileDescriptor(fd), options?.flag?.startsWith("a") ?? false))
214 )
215}
216const open = openFactory("open")
217
218const makeFile = (() => {
219 const nodeReadFactory = (method: string) =>
220 effectify(
221 NFS.read,
222 handleErrnoException("FileSystem", method),
223 handleBadArgument(method)
224 )
225 const nodeRead = nodeReadFactory("read")
226 const nodeReadAlloc = nodeReadFactory("readAlloc")
227 const nodeStat = effectify(
228 NFS.fstat,
229 handleErrnoException("FileSystem", "stat"),
230 handleBadArgument("stat")
231 )
232 const nodeTruncate = effectify(
233 NFS.ftruncate,
234 handleErrnoException("FileSystem", "truncate"),
235 handleBadArgument("truncate")
236 )
237
238 const nodeSync = effectify(
239 NFS.fsync,
240 handleErrnoException("FileSystem", "sync"),
241 handleBadArgument("sync")
242 )
243
244 const nodeWriteFactory = (method: string) =>
245 effectify(
246 NFS.write,
247 handleErrnoException("FileSystem", method),
248 handleBadArgument(method)
249 )
250 const nodeWrite = nodeWriteFactory("write")
251 const nodeWriteAll = nodeWriteFactory("writeAll")
252
253 class FileImpl implements FileSystem.File {
254 readonly [FileSystem.FileTypeId]: typeof FileSystem.FileTypeId
255 readonly fd: FileSystem.File.Descriptor
256 private readonly append: boolean
257
258 private position: bigint = BigInt(0)
259
260 constructor(
261 fd: FileSystem.File.Descriptor,
262 append: boolean
263 ) {
264 this[FileSystem.FileTypeId] = FileSystem.FileTypeId
265 this.fd = fd
266 this.append = append
267 }
268
269 get stat() {
270 return Effect.map(nodeStat(this.fd), makeFileInfo)
271 }
272
273 get sync() {
274 return nodeSync(this.fd)
275 }
276
277 seek(offset: FileSystem.SizeInput, from: FileSystem.SeekMode) {
278 const offsetSize = FileSystem.Size(offset)
279 return Effect.sync(() => {
280 if (from === "start") {
281 this.position = offsetSize
282 } else if (from === "current") {
283 this.position = this.position + offsetSize
284 }
285
286 return this.position
287 })
288 }
289
290 read(buffer: Uint8Array) {
291 return Effect.suspend(() => {
292 const position = this.position
293 return Effect.map(
294 nodeRead(this.fd, { buffer, position }),
295 (bytesRead) => {
296 const sizeRead = FileSystem.Size(bytesRead)
297 this.position = position + sizeRead
298 return sizeRead
299 }
300 )
301 })
302 }
303
304 readAlloc(size: FileSystem.SizeInput) {
305 const sizeNumber = Number(size)
306 return Effect.suspend(() => {
307 const buffer = Buffer.allocUnsafeSlow(sizeNumber)
308 const position = this.position
309 return Effect.map(
310 nodeReadAlloc(this.fd, { buffer, position }),
311 (bytesRead): Option.Option<Buffer> => {
312 if (bytesRead === 0) {
313 return Option.none()
314 }
315
316 this.position = position + BigInt(bytesRead)
317 if (bytesRead === sizeNumber) {
318 return Option.some(buffer)
319 }
320
321 const dst = Buffer.allocUnsafeSlow(bytesRead)
322 buffer.copy(dst, 0, 0, bytesRead)
323 return Option.some(dst)
324 }
325 )
326 })
327 }
328
329 truncate(length?: FileSystem.SizeInput) {
330 return Effect.map(nodeTruncate(this.fd, length ? Number(length) : undefined), () => {
331 if (!this.append) {
332 const len = BigInt(length ?? 0)
333 if (this.position > len) {
334 this.position = len
335 }
336 }
337 })
338 }
339
340 write(buffer: Uint8Array) {
341 return Effect.suspend(() => {
342 const position = this.position
343 return Effect.map(
344 nodeWrite(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)),
345 (bytesWritten) => {
346 const sizeWritten = FileSystem.Size(bytesWritten)
347 if (!this.append) {
348 this.position = position + sizeWritten
349 }
350 return sizeWritten
351 }
352 )
353 })
354 }
355
356 private writeAllChunk(buffer: Uint8Array): Effect.Effect<void, Error.PlatformError> {
357 return Effect.suspend(() => {
358 const position = this.position
359 return Effect.flatMap(
360 nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)),
361 (bytesWritten) => {
362 if (bytesWritten === 0) {
363 return Effect.fail(
364 Error.systemError({
365 module: "FileSystem",
366 method: "writeAll",
367 _tag: "WriteZero",
368 pathOrDescriptor: this.fd,
369 description: "write returned 0 bytes written"
370 })
371 )
372 }
373
374 if (!this.append) {
375 this.position = position + BigInt(bytesWritten)
376 }
377
378 return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void
379 }
380 )
381 })
382 }
383
384 writeAll(buffer: Uint8Array) {
385 return this.writeAllChunk(buffer)
386 }
387 }
388
389 return (fd: FileSystem.File.Descriptor, append: boolean): FileSystem.File => new FileImpl(fd, append)
390})()
391
392// == makeTempFile
393
394const makeTempFileFactory = (method: string): FileSystem.FileSystem["makeTempFile"] => {
395 const makeDirectory = makeTempDirectoryFactory(method)
396 return Effect.fnUntraced(function*(options) {
397 const directory = yield* makeDirectory(options)
398 const random = Crypto.randomBytes(6).toString("hex")
399 const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random)
400 yield* writeFile(name, new Uint8Array(0))
401 return name
402 })
403}
404const makeTempFile = makeTempFileFactory("makeTempFile")
405
406// == makeTempFileScoped
407
408const makeTempFileScoped = ((): FileSystem.FileSystem["makeTempFileScoped"] => {
409 const makeFile = makeTempFileFactory("makeTempFileScoped")
410 const removeDirectory = removeFactory("makeTempFileScoped")
411 return (options) =>
412 Effect.acquireRelease(
413 makeFile(options),
414 (file) => Effect.orDie(removeDirectory(Path.dirname(file), { recursive: true }))
415 )
416})()
417
418// == readDirectory
419
420const readDirectory: FileSystem.FileSystem["readDirectory"] = (path, options) =>
421 Effect.tryPromise({
422 try: () => NFS.promises.readdir(path, options),
423 catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err as any, [path])
424 })
425
426// == readFile
427
428const readFile = (path: string) =>
429 Effect.callback<Uint8Array, Error.PlatformError>((resume, signal) => {
430 try {
431 NFS.readFile(path, { signal }, (err, data) => {
432 if (err) {
433 resume(Effect.fail(handleErrnoException("FileSystem", "readFile")(err, [path])))
434 } else {
435 resume(Effect.succeed(data))
436 }
437 })
438 } catch (err) {
439 resume(Effect.fail(handleBadArgument("readFile")(err)))
440 }
441 })
442
443// == readLink
444
445const readLink = (() => {
446 const nodeReadLink = effectify(
447 NFS.readlink,
448 handleErrnoException("FileSystem", "readLink"),
449 handleBadArgument("readLink")
450 )
451 return (path: string) => nodeReadLink(path)
452})()
453
454// == realPath
455
456const realPath = (() => {
457 const nodeRealPath = effectify(
458 NFS.realpath,
459 handleErrnoException("FileSystem", "realPath"),
460 handleBadArgument("realPath")
461 )
462 return (path: string) => nodeRealPath(path)
463})()
464
465// == rename
466
467const rename = (() => {
468 const nodeRename = effectify(
469 NFS.rename,
470 handleErrnoException("FileSystem", "rename"),
471 handleBadArgument("rename")
472 )
473 return (oldPath: string, newPath: string) => nodeRename(oldPath, newPath)
474})()
475
476// == stat
477
478const makeFileInfo = (stat: NFS.Stats): FileSystem.File.Info => ({
479 type: stat.isFile() ?
480 "File" :
481 stat.isDirectory() ?
482 "Directory" :
483 stat.isSymbolicLink() ?
484 "SymbolicLink" :
485 stat.isBlockDevice() ?
486 "BlockDevice" :
487 stat.isCharacterDevice() ?
488 "CharacterDevice" :
489 stat.isFIFO() ?
490 "FIFO" :
491 stat.isSocket() ?
492 "Socket" :
493 "Unknown",
494 mtime: Option.fromNullishOr(stat.mtime),
495 atime: Option.fromNullishOr(stat.atime),
496 birthtime: Option.fromNullishOr(stat.birthtime),
497 dev: stat.dev,
498 rdev: Option.fromNullishOr(stat.rdev),
499 ino: Option.fromNullishOr(stat.ino),
500 mode: stat.mode,
501 nlink: Option.fromNullishOr(stat.nlink),
502 uid: Option.fromNullishOr(stat.uid),
503 gid: Option.fromNullishOr(stat.gid),
504 size: FileSystem.Size(stat.size),
505 blksize: stat.blksize !== undefined ? Option.some(FileSystem.Size(stat.blksize)) : Option.none(),
506 blocks: Option.fromNullishOr(stat.blocks)
507})
508const stat = (() => {
509 const nodeStat = effectify(
510 NFS.stat,
511 handleErrnoException("FileSystem", "stat"),
512 handleBadArgument("stat")
513 )
514 return (path: string) => Effect.map(nodeStat(path), makeFileInfo)
515})()
516
517// == symlink
518
519const symlink = (() => {
520 const nodeSymlink = effectify(
521 NFS.symlink,
522 handleErrnoException("FileSystem", "symlink"),
523 handleBadArgument("symlink")
524 )
525 return (target: string, path: string) => nodeSymlink(target, path)
526})()
527
528// == truncate
529
530const truncate = (() => {
531 const nodeTruncate = effectify(
532 NFS.truncate,
533 handleErrnoException("FileSystem", "truncate"),
534 handleBadArgument("truncate")
535 )
536 return (path: string, length?: FileSystem.SizeInput) =>
537 nodeTruncate(path, length !== undefined ? Number(length) : undefined)
538})()
539
540// == utimes
541
542const utimes = (() => {
543 const nodeUtimes = effectify(
544 NFS.utimes,
545 handleErrnoException("FileSystem", "utime"),
546 handleBadArgument("utime")
547 )
548 return (path: string, atime: number | Date, mtime: number | Date) => nodeUtimes(path, atime, mtime)
549})()
550
551// == watch
552
553const watchNode = (path: string) =>
554 Stream.callback<FileSystem.WatchEvent, Error.PlatformError>((queue) =>
555 Effect.acquireRelease(
556 Effect.sync(() => {
557 const watcher = NFS.watch(path, {
558 recursive: true
559 }, (event, path) => {
560 if (!path) return
561 switch (event) {
562 case "rename": {
563 Effect.runFork(Effect.matchEffect(stat(path), {
564 onSuccess: (_) => Queue.offer(queue, { _tag: "Create", path }),
565 onFailure: (_) => Queue.offer(queue, { _tag: "Remove", path })
566 }))
567 return
568 }
569 case "change": {
570 Queue.offerUnsafe(queue, { _tag: "Update", path })
571 return
572 }
573 }
574 })
575 watcher.on("error", (error) => {
576 Queue.failCauseUnsafe(
577 queue,
578 Cause.fail(
579 Error.systemError({
580 module: "FileSystem",
581 _tag: "Unknown",
582 method: "watch",
583 pathOrDescriptor: path,
584 cause: error
585 })
586 )
587 )
588 })
589 watcher.on("close", () => {
590 Queue.endUnsafe(queue)
591 })
592 return watcher
593 }),
594 (watcher) => Effect.sync(() => watcher.close())
595 )
596 )
597
598const watch = (backend: Option.Option<FileSystem.WatchBackend["Service"]>, path: string) =>
599 stat(path).pipe(
600 Effect.map((stat) =>
601 backend.pipe(
602 Option.flatMap((_) => _.register(path, stat)),
603 Option.getOrElse(() => watchNode(path))
604 )
605 ),
606 Stream.unwrap
607 )
608
609// == writeFile
610
611const writeFile: FileSystem.FileSystem["writeFile"] = (path, data, options) =>
612 Effect.callback<void, Error.PlatformError>((resume, signal) => {
613 try {
614 NFS.writeFile(path, data, {
615 signal,
616 flag: options?.flag,
617 mode: options?.mode
618 }, (err) => {
619 if (err) {
620 resume(Effect.fail(handleErrnoException("FileSystem", "writeFile")(err, [path])))
621 } else {
622 resume(Effect.void)
623 }
624 })
625 } catch (err) {
626 resume(Effect.fail(handleBadArgument("writeFile")(err)))
627 }
628 })
629
630const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend), (backend) =>
631 FileSystem.make({
632 access,
633 chmod,
634 chown,
635 copy,
636 copyFile,
637 glob,
638 link,
639 makeDirectory,
640 makeTempDirectory,
641 makeTempDirectoryScoped,
642 makeTempFile,
643 makeTempFileScoped,
644 open,
645 readDirectory,
646 readFile,
647 readLink,
648 realPath,
649 remove,
650 rename,
651 stat,
652 symlink,
653 truncate,
654 utimes,
655 watch(path) {
656 return watch(backend, path)
657 },
658 writeFile
659 }))
660
661/**
662 * Provides the `FileSystem` service backed by Node filesystem APIs, including
663 * file operations, directory operations, links, metadata, and file watching.
664 *
665 * @category layers
666 * @since 4.0.0
667 */
668export const layer: Layer.Layer<FileSystem.FileSystem> = Layer.effect(FileSystem.FileSystem)(makeFileSystem)