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

FileSystem.ts

1,437 lines40.6 KB

1/**
2 * Effect service for reading, writing, inspecting, and watching files.
3 *
4 * The `FileSystem` service is the portable boundary between Effect programs and
5 * the host file system. Programs depend on the service from `effect/FileSystem`;
6 * platform packages provide concrete layers at the edge. Operations return
7 * `Effect`, `Stream`, or `Sink` values and report failures as `PlatformError`
8 * instead of throwing.
9 *
10 * **Mental model**
11 *
12 * `FileSystem` is a capability, not a global singleton. Request it with
13 * `yield* FileSystem.FileSystem` inside an effect, compose file work like any
14 * other effect, and provide a platform or test implementation when the program
15 * is run. Scoped operations such as `open`, `makeTempFileScoped`, and
16 * `makeTempDirectoryScoped` bind resource cleanup to `Scope`.
17 *
18 * **Common tasks**
19 *
20 * - Create, copy, rename, remove, chmod, chown, link, and symlink paths.
21 * - Read and write whole files as bytes or strings.
22 * - Stream large files with `stream` and `sink`, using binary size helpers such
23 * as `KiB` and `MiB` for chunk sizes and offsets.
24 * - Inspect metadata with `stat`, check accessibility with `access` or
25 * `exists`, and canonicalize paths with `realPath`.
26 * - Watch files or directories with `watch` when the platform implementation
27 * supports it.
28 *
29 * **Example** (Write and clean up a temporary file)
30 *
31 * ```ts
32 * import { Effect, FileSystem } from "effect"
33 *
34 * const program = Effect.gen(function*() {
35 * const fs = yield* FileSystem.FileSystem
36 *
37 * const directory = yield* fs.makeTempDirectoryScoped()
38 * const path = `${directory}/message.txt`
39 *
40 * yield* fs.writeFileString(path, "hello")
41 * return yield* fs.readFileString(path)
42 * })
43 * ```
44 *
45 * **Gotchas**
46 *
47 * Paths are interpreted by the provided implementation, so relative paths, case
48 * sensitivity, permissions, links, and watch behavior are platform-dependent.
49 * Size options are normalized to branded bigint byte counts; prefer the `Size`,
50 * `KiB`, `MiB`, and related helpers for offsets, chunk sizes, and truncation
51 * lengths. A program that uses this service still needs a concrete layer, such
52 * as `NodeFileSystem.layer`, before it can access the real file system.
53 *
54 * @since 4.0.0
55 */
56import * as Arr from "./Array.ts"
57import * as Brand from "./Brand.ts"
58import * as Cause from "./Cause.ts"
59import * as Context from "./Context.ts"
60import * as Effect from "./Effect.ts"
61import { pipe } from "./Function.ts"
62import * as Layer from "./Layer.ts"
63import * as Option from "./Option.ts"
64import { badArgument, type PlatformError, systemError } from "./PlatformError.ts"
65import { hasProperty } from "./Predicate.ts"
66import type * as Pull from "./Pull.ts"
67import type { Scope } from "./Scope.ts"
68import * as Sink from "./Sink.ts"
69import * as Stream from "./Stream.ts"
70​
71const TypeId = "~effect/platform/FileSystem"
72​
73/**
74 * Core interface for file system operations in Effect.
75 *
76 * **Details**
77 *
78 * The FileSystem interface provides a comprehensive set of file and directory operations
79 * that work cross-platform. All operations return Effect values that can be composed,
80 * transformed, and executed safely with proper error handling.
81 *
82 * **Example** (Accessing file system operations)
83 *
84 * ```ts
85 * import { Console, Effect, FileSystem } from "effect"
86 *
87 * const program = Effect.gen(function*() {
88 * const fs = yield* FileSystem.FileSystem
89 *
90 * // Basic file operations
91 * const exists = yield* fs.exists("./config.json")
92 * if (!exists) {
93 * yield* fs.writeFileString("./config.json", "{\"env\": \"development\"}")
94 * }
95 *
96 * // Directory operations
97 * yield* fs.makeDirectory("./logs", { recursive: true })
98 *
99 * // File information
100 * const stats = yield* fs.stat("./config.json")
101 * yield* Console.log(`File size: ${stats.size} bytes`)
102 *
103 * // Streaming operations
104 * const content = yield* fs.readFileString("./config.json")
105 * yield* Console.log("Config:", content)
106 * })
107 * ```
108 *
109 * @category models
110 * @since 4.0.0
111 */
112export interface FileSystem {
113 readonly [TypeId]: typeof TypeId
114​
115 /**
116 * Checks whether a file can be accessed.
117 * You can optionally specify the level of access to check for.
118 */
119 readonly access: (
120 path: string,
121 options?: {
122 readonly ok?: boolean | undefined
123 readonly readable?: boolean | undefined
124 readonly writable?: boolean | undefined
125 }
126 ) => Effect.Effect<void, PlatformError>
127 /**
128 * Copy a file or directory from `fromPath` to `toPath`.
129 *
130 * **Details**
131 *
132 * Equivalent to `cp -r`.
133 */
134 readonly copy: (
135 fromPath: string,
136 toPath: string,
137 options?: {
138 readonly overwrite?: boolean | undefined
139 readonly preserveTimestamps?: boolean | undefined
140 }
141 ) => Effect.Effect<void, PlatformError>
142 /**
143 * Copy a file from `fromPath` to `toPath`.
144 */
145 readonly copyFile: (
146 fromPath: string,
147 toPath: string
148 ) => Effect.Effect<void, PlatformError>
149 /**
150 * Change the permissions of a file.
151 */
152 readonly chmod: (
153 path: string,
154 mode: number
155 ) => Effect.Effect<void, PlatformError>
156 /**
157 * Change the owner and group of a file.
158 */
159 readonly chown: (
160 path: string,
161 uid: number,
162 gid: number
163 ) => Effect.Effect<void, PlatformError>
164 /**
165 * Checks whether a path exists.
166 */
167 readonly exists: (
168 path: string
169 ) => Effect.Effect<boolean, PlatformError>
170 /**
171 * Create a hard link from `fromPath` to `toPath`.
172 */
173 readonly link: (
174 fromPath: string,
175 toPath: string
176 ) => Effect.Effect<void, PlatformError>
177 /**
178 * Create a directory at `path`. You can optionally specify the mode and
179 * whether to recursively create nested directories.
180 */
181 readonly makeDirectory: (
182 path: string,
183 options?: {
184 readonly recursive?: boolean | undefined
185 readonly mode?: number | undefined
186 }
187 ) => Effect.Effect<void, PlatformError>
188 /**
189 * Create a temporary directory.
190 *
191 * **Details**
192 *
193 * By default the directory will be created inside the system's default
194 * temporary directory, but you can specify a different location by setting
195 * the `directory` option.
196 *
197 * You can also specify a prefix for the directory name by setting the
198 * `prefix` option.
199 */
200 readonly makeTempDirectory: (options?: {
201 readonly directory?: string | undefined
202 readonly prefix?: string | undefined
203 }) => Effect.Effect<string, PlatformError>
204 /**
205 * Create a temporary directory inside a scope.
206 *
207 * **Details**
208 *
209 * Functionally equivalent to `makeTempDirectory`, but the directory will be
210 * automatically deleted when the scope is closed.
211 */
212 readonly makeTempDirectoryScoped: (options?: {
213 readonly directory?: string | undefined
214 readonly prefix?: string | undefined
215 }) => Effect.Effect<string, PlatformError, Scope>
216 /**
217 * Create a temporary file.
218 * The directory creation is functionally equivalent to `makeTempDirectory`.
219 * The file name will be a randomly generated string.
220 */
221 readonly makeTempFile: (options?: {
222 readonly directory?: string | undefined
223 readonly prefix?: string | undefined
224 readonly suffix?: string | undefined
225 }) => Effect.Effect<string, PlatformError>
226 /**
227 * Create a temporary file inside a scope.
228 *
229 * **Details**
230 *
231 * Functionally equivalent to `makeTempFile`, but the file will be
232 * automatically deleted when the scope is closed.
233 */
234 readonly makeTempFileScoped: (options?: {
235 readonly directory?: string | undefined
236 readonly prefix?: string | undefined
237 readonly suffix?: string | undefined
238 }) => Effect.Effect<string, PlatformError, Scope>
239 /**
240 * Open a file at `path` with the specified `options`.
241 *
242 * **Details**
243 *
244 * The file handle will be automatically closed when the scope is closed.
245 */
246 readonly open: (
247 path: string,
248 options?: {
249 readonly flag?: OpenFlag | undefined
250 readonly mode?: number | undefined
251 }
252 ) => Effect.Effect<File, PlatformError, Scope>
253 /**
254 * List the contents of a directory.
255 *
256 * **Details**
257 *
258 * You can recursively list the contents of nested directories by setting the
259 * `recursive` option.
260 */
261 readonly readDirectory: (
262 path: string,
263 options?: {
264 readonly recursive?: boolean | undefined
265 }
266 ) => Effect.Effect<Array<string>, PlatformError>
267 /**
268 * Read the contents of a file.
269 */
270 readonly readFile: (
271 path: string
272 ) => Effect.Effect<Uint8Array, PlatformError>
273 /**
274 * Read the contents of a file.
275 */
276 readonly readFileString: (
277 path: string,
278 encoding?: string
279 ) => Effect.Effect<string, PlatformError>
280 /**
281 * Read the destination of a symbolic link.
282 */
283 readonly readLink: (
284 path: string
285 ) => Effect.Effect<string, PlatformError>
286 /**
287 * Resolve a path to its canonicalized absolute pathname.
288 */
289 readonly realPath: (
290 path: string
291 ) => Effect.Effect<string, PlatformError>
292 /**
293 * Remove a file or directory.
294 */
295 readonly remove: (
296 path: string,
297 options?: {
298 /**
299 * When `true`, you can recursively remove nested directories.
300 */
301 readonly recursive?: boolean | undefined
302 /**
303 * When `true`, exceptions will be ignored if `path` does not exist.
304 */
305 readonly force?: boolean | undefined
306 }
307 ) => Effect.Effect<void, PlatformError>
308 /**
309 * Rename a file or directory.
310 */
311 readonly rename: (
312 oldPath: string,
313 newPath: string
314 ) => Effect.Effect<void, PlatformError>
315 /**
316 * Create a writable `Sink` for the specified `path`.
317 */
318 readonly sink: (
319 path: string,
320 options?: {
321 readonly flag?: OpenFlag | undefined
322 readonly mode?: number | undefined
323 }
324 ) => Sink.Sink<void, Uint8Array, never, PlatformError>
325 /**
326 * Get information about a file at `path`.
327 */
328 readonly stat: (
329 path: string
330 ) => Effect.Effect<File.Info, PlatformError>
331 /**
332 * Create a readable `Stream` for the specified `path`.
333 *
334 * **Details**
335 *
336 * Changing the `bufferSize` option will change the internal buffer size of
337 * the stream. It defaults to `4`.
338 *
339 * The `chunkSize` option will change the size of the chunks emitted by the
340 * stream. It defaults to 64kb.
341 *
342 * Changing `offset` and `bytesToRead` will change the offset and the number
343 * of bytes to read from the file.
344 */
345 readonly stream: (
346 path: string,
347 options?: {
348 readonly bytesToRead?: SizeInput | undefined
349 readonly chunkSize?: SizeInput | undefined
350 readonly offset?: SizeInput | undefined
351 }
352 ) => Stream.Stream<Uint8Array, PlatformError>
353 /**
354 * Create a symbolic link from `fromPath` to `toPath`.
355 */
356 readonly symlink: (
357 fromPath: string,
358 toPath: string
359 ) => Effect.Effect<void, PlatformError>
360 /**
361 * Truncate a file to a specified length. If the `length` is not specified,
362 * the file will be truncated to length `0`.
363 */
364 readonly truncate: (
365 path: string,
366 length?: SizeInput
367 ) => Effect.Effect<void, PlatformError>
368 /**
369 * Change the file system timestamps of the file at `path`.
370 */
371 readonly utimes: (
372 path: string,
373 atime: Date | number,
374 mtime: Date | number
375 ) => Effect.Effect<void, PlatformError>
376 /**
377 * Watch a directory or file for changes
378 */
379 readonly watch: (path: string) => Stream.Stream<WatchEvent, PlatformError>
380 /**
381 * Write data to a file at `path`.
382 */
383 readonly writeFile: (
384 path: string,
385 data: Uint8Array,
386 options?: {
387 readonly flag?: OpenFlag | undefined
388 readonly mode?: number | undefined
389 }
390 ) => Effect.Effect<void, PlatformError>
391 /**
392 * Write a string to a file at `path`.
393 */
394 readonly writeFileString: (
395 path: string,
396 data: string,
397 options?: {
398 readonly flag?: OpenFlag | undefined
399 readonly mode?: number | undefined
400 }
401 ) => Effect.Effect<void, PlatformError>
403​
404/**
405 * Represents a file size in bytes using a branded bigint.
406 *
407 * **Details**
408 *
409 * This type ensures type safety when working with file sizes, preventing
410 * accidental mixing of regular numbers with size values. The underlying
411 * bigint allows for handling very large file sizes beyond JavaScript's
412 * number precision limits.
413 *
414 * **Example** (Creating branded file sizes)
415 *
416 * ```ts
417 * import { Effect, FileSystem } from "effect"
418 *
419 * // Create sizes using the Size constructor
420 * const smallFile = FileSystem.Size(1024) // 1 KB
421 * const largeFile = FileSystem.Size(BigInt("9007199254740992")) // Very large
422 *
423 * // Use with file operations
424 * const truncateToSize = Effect.fnUntraced(function*(path: string, size: FileSystem.Size) {
425 * const fs = yield* FileSystem.FileSystem
426 * return yield* fs.truncate(path, size)
427 * })
428 * ```
429 *
430 * @category sizes
431 * @since 4.0.0
432 */
433export type Size = Brand.Branded<bigint, "Size">
434​
435/**
436 * Input type for size parameters that accepts multiple numeric types.
437 *
438 * **Details**
439 *
440 * This union type allows file system operations to accept size values in
441 * different formats for convenience, which are then normalized to the
442 * branded `Size` type internally.
443 *
444 * **Example** (Using size inputs)
445 *
446 * ```ts
447 * import { Effect, FileSystem } from "effect"
448 *
449 * const program = Effect.gen(function*() {
450 * const fs = yield* FileSystem.FileSystem
451 *
452 * // All of these are valid SizeInput values
453 * yield* fs.truncate("file1.txt", 1024) // number
454 * yield* fs.truncate("file2.txt", BigInt(2048)) // bigint
455 * yield* fs.truncate("file3.txt", FileSystem.Size(4096)) // Size
456 * })
457 * ```
458 *
459 * @category sizes
460 * @since 4.0.0
461 */
462export type SizeInput = bigint | number | Size
463​
464/**
465 * Creates a `Size` from various numeric input types.
466 *
467 * **Details**
468 *
469 * Converts numbers, bigints, or existing Size values into a properly
470 * branded Size type. This function handles the conversion and ensures
471 * type safety for file size operations.
472 *
473 * **Example** (Converting size inputs)
474 *
475 * ```ts
476 * import { Effect, FileSystem } from "effect"
477 *
478 * // From number
479 * const size1 = FileSystem.Size(1024)
480 * console.log(typeof size1) // "bigint"
481 *
482 * // From bigint
483 * const size2 = FileSystem.Size(BigInt(2048))
484 *
485 * // From existing Size (identity)
486 * const size3 = FileSystem.Size(size1)
487 *
488 * // Use in file operations
489 * const readChunk = (path: string, chunkSize: number) =>
490 * Effect.gen(function*() {
491 * const fs = yield* FileSystem.FileSystem
492 * return fs.stream(path, {
493 * chunkSize: FileSystem.Size(chunkSize)
494 * })
495 * })
496 * ```
497 *
498 * @category sizes
499 * @since 4.0.0
500 */
501export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? bytes as Size : BigInt(bytes) as Size
502​
503/**
504 * Creates a `Size` representing kilobytes (1024 bytes).
505 *
506 * **Details**
507 *
508 * Converts a number of kilobytes to the equivalent size in bytes.
509 * Uses binary kilobytes (1024 bytes) rather than decimal (1000 bytes).
510 *
511 * **Example** (Creating kibibyte sizes)
512 *
513 * ```ts
514 * import { Effect, FileSystem } from "effect"
515 *
516 * const program = Effect.gen(function*() {
517 * const fs = yield* FileSystem.FileSystem
518 *
519 * // Create a 64 KiB buffer size for streaming
520 * const bufferSize = FileSystem.KiB(64)
521 *
522 * const stream = fs.stream("large-file.txt", {
523 * chunkSize: bufferSize
524 * })
525 *
526 * // Truncate file to 100 KiB
527 * yield* fs.truncate("data.txt", FileSystem.KiB(100))
528 * })
529 * ```
530 *
531 * @category sizes
532 * @since 4.0.0
533 */
534export const KiB = (n: number): Size => Size(n * 1024)
535​
536/**
537 * Creates a `Size` representing mebibytes (1024² bytes).
538 *
539 * **Details**
540 *
541 * Converts a number of mebibytes to the equivalent size in bytes.
542 * Uses binary mebibytes (1,048,576 bytes) rather than decimal megabytes.
543 *
544 * **Example** (Creating mebibyte sizes)
545 *
546 * ```ts
547 * import { Effect, FileSystem } from "effect"
548 *
549 * const program = Effect.gen(function*() {
550 * const fs = yield* FileSystem.FileSystem
551 *
552 * // Set a 10 MiB chunk size for large file operations
553 * const largeChunkSize = FileSystem.MiB(10)
554 *
555 * const stream = fs.stream("video.mp4", {
556 * chunkSize: largeChunkSize
557 * })
558 *
559 * // Check if file is larger than 100 MiB
560 * const stats = yield* fs.stat("archive.zip")
561 * const maxSize = FileSystem.MiB(100)
562 * if (stats.size > maxSize) {
563 * yield* Effect.log("File is very large!")
564 * }
565 * })
566 * ```
567 *
568 * @category sizes
569 * @since 4.0.0
570 */
571export const MiB = (n: number): Size => Size(n * 1024 * 1024)
572​
573/**
574 * Creates a `Size` representing gibibytes (1024³ bytes).
575 *
576 * **Details**
577 *
578 * Converts a number of gibibytes to the equivalent size in bytes.
579 * Uses binary gibibytes (1,073,741,824 bytes) rather than decimal gigabytes.
580 *
581 * **Example** (Creating gibibyte sizes)
582 *
583 * ```ts
584 * import { Effect, FileSystem } from "effect"
585 *
586 * const program = Effect.gen(function*() {
587 * const fs = yield* FileSystem.FileSystem
588 *
589 * // Use GiB values as size thresholds
590 * const maxArchiveSize = FileSystem.GiB(1)
591 * console.log(maxArchiveSize.toString()) // "1073741824"
592 *
593 * const tempFile = yield* fs.makeTempFile({ prefix: "archive-" })
594 * yield* fs.writeFileString(tempFile, "backup data")
595 *
596 * const info = yield* fs.stat(tempFile)
597 * console.log(info.size < maxArchiveSize) // true
598 *
599 * yield* fs.remove(tempFile)
600 * })
601 * ```
602 *
603 * @category sizes
604 * @since 4.0.0
605 */
606export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024)
607​
608/**
609 * Creates a `Size` representing tebibytes (1024⁴ bytes).
610 *
611 * **Details**
612 *
613 * Converts a number of tebibytes to the equivalent size in bytes.
614 * Uses binary tebibytes (1,099,511,627,776 bytes) rather than decimal terabytes.
615 *
616 * **Example** (Creating tebibyte sizes)
617 *
618 * ```ts
619 * import { Console, Effect, FileSystem } from "effect"
620 *
621 * const program = Effect.gen(function*() {
622 * const fs = yield* FileSystem.FileSystem
623 *
624 * // Check if we're dealing with very large files
625 * const stats = yield* fs.stat("database-backup.sql")
626 * const oneTiB = FileSystem.TiB(1)
627 *
628 * if (stats.size > oneTiB) {
629 * yield* Console.log("This is a very large database backup!")
630 *
631 * // Use larger chunk sizes for such files
632 * const stream = fs.stream("database-backup.sql", {
633 * chunkSize: FileSystem.MiB(100) // 100 MiB chunks
634 * })
635 * }
636 * })
637 * ```
638 *
639 * @category sizes
640 * @since 4.0.0
641 */
642export const TiB = (n: number): Size => Size(n * 1024 * 1024 * 1024 * 1024)
643​
644const bigint1024 = BigInt(1024)
645const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024
646​
647/**
648 * Creates a `Size` representing pebibytes (1024⁵ bytes).
649 *
650 * **Details**
651 *
652 * Converts a number of pebibytes to the equivalent size in bytes.
653 * Uses binary pebibytes (1,125,899,906,842,624 bytes) rather than decimal petabytes.
654 * This function uses BigInt arithmetic to handle the very large numbers involved.
655 *
656 * **Example** (Creating pebibyte sizes)
657 *
658 * ```ts
659 * import { Console, Effect, FileSystem } from "effect"
660 *
661 * const program = Effect.gen(function*() {
662 * const fs = yield* FileSystem.FileSystem
663 *
664 * // For extremely large data processing scenarios
665 * const massiveDataset = FileSystem.PiB(2) // 2 PiB
666 *
667 * // This would typically be used in enterprise/cloud scenarios
668 * yield* Console.log(`Processing ${massiveDataset} bytes of data`)
669 *
670 * // Such large files would require specialized streaming
671 * const stream = fs.stream("massive-dataset.bin", {
672 * chunkSize: FileSystem.GiB(1), // 1 GiB chunks
673 * offset: FileSystem.TiB(100) // Start from 100 TiB offset
674 * })
675 * })
676 * ```
677 *
678 * @category sizes
679 * @since 4.0.0
680 */
681export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB)
682​
683/**
684 * File open flags that determine how a file is opened and what operations are allowed.
685 *
686 * **Details**
687 *
688 * These flags correspond to standard POSIX file open modes and control the file access
689 * permissions and behavior when opening files.
690 *
691 * - `"r"` - Read-only. File must exist.
692 * - `"r+"` - Read/write. File must exist.
693 * - `"w"` - Write-only. Truncates file to zero length or creates new file.
694 * - `"wx"` - Like 'w' but fails if file exists.
695 * - `"w+"` - Read/write. Truncates file to zero length or creates new file.
696 * - `"wx+"` - Like 'w+' but fails if file exists.
697 * - `"a"` - Write-only. Appends to file or creates new file.
698 * - `"ax"` - Like 'a' but fails if file exists.
699 * - `"a+"` - Read/write. Appends to file or creates new file.
700 * - `"ax+"` - Like 'a+' but fails if file exists.
701 *
702 * **Example** (Opening files with flags)
703 *
704 * ```ts
705 * import { Effect, FileSystem } from "effect"
706 *
707 * const program = Effect.gen(function*() {
708 * const fs = yield* FileSystem.FileSystem
709 *
710 * // Open for reading only
711 * const readFile = yield* fs.open("data.txt", { flag: "r" })
712 *
713 * // Open for writing, truncating existing content
714 * const writeFile = yield* fs.open("output.txt", { flag: "w" })
715 *
716 * // Open for appending
717 * const appendFile = yield* fs.open("log.txt", { flag: "a" })
718 *
719 * // Open for read/write, but fail if file doesn't exist
720 * const editFile = yield* fs.open("config.json", { flag: "r+" })
721 * })
722 * ```
723 *
724 * @category models
725 * @since 4.0.0
726 */
727export type OpenFlag =
728 | "r"
729 | "r+"
730 | "w"
731 | "wx"
732 | "w+"
733 | "wx+"
734 | "a"
735 | "ax"
736 | "a+"
737 | "ax+"
738​
739/**
740 * Service tag for platform file-system operations.
741 *
742 * **When to use**
743 *
744 * Use to access or provide operations for files, directories, permissions,
745 * streams, and sinks through the Effect context.
746 *
747 * **Details**
748 *
749 * This key is used to provide and access the FileSystem service in the Effect context.
750 *
751 * **Example** (Accessing and providing FileSystem)
752 *
753 * ```ts
754 * import { Effect, FileSystem } from "effect"
755 *
756 * // Access the FileSystem service
757 * const program = Effect.gen(function*() {
758 * const fs = yield* FileSystem.FileSystem
759 *
760 * const exists = yield* fs.exists("./data.txt")
761 * if (exists) {
762 * const content = yield* fs.readFileString("./data.txt")
763 * yield* Effect.log("File content:", content)
764 * }
765 * })
766 *
767 * // Provide a custom FileSystem implementation
768 * declare const platformImpl: Omit<
769 * FileSystem.FileSystem,
770 * "exists" | "readFileString" | "stream" | "sink" | "writeFileString"
771 * >
772 * const customFs = FileSystem.make(platformImpl)
773 *
774 * const withCustomFs = Effect.provideService(
775 * program,
776 * FileSystem.FileSystem,
777 * customFs
778 * )
779 * ```
780 *
781 * @category tags
782 * @since 4.0.0
783 */
784export const FileSystem: Context.Service<FileSystem, FileSystem> = Context.Service("effect/platform/FileSystem")
785​
786/**
787 * Creates a FileSystem implementation from a partial implementation.
788 *
789 * **When to use**
790 *
791 * Use to build a concrete `FileSystem` service from platform-specific core
792 * operations while deriving the convenience methods that can be implemented
793 * from them.
794 *
795 * **Details**
796 *
797 * This function takes a partial FileSystem implementation and automatically provides
798 * default implementations for `exists`, `readFileString`, `stream`, `sink`, and
799 * `writeFileString` methods based on the provided core methods.
800 *
801 * @see {@link makeNoop} for a testing stub that accepts method overrides without requiring a complete implementation
802 * @see {@link layerNoop} for providing a no-op `FileSystem` as a `Layer` in tests
803 *
804 * @category constructors
805 * @since 4.0.0
806 */
807export const make = (
808 impl: Omit<FileSystem, typeof TypeId | "exists" | "readFileString" | "stream" | "sink" | "writeFileString">
809): FileSystem =>
810 FileSystem.of({
811 ...impl,
812 [TypeId]: TypeId,
813 exists: (path) =>
814 pipe(
815 impl.access(path),
816 Effect.as(true),
817 Effect.catchTag(
818 "PlatformError",
819 (e) => e.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(e)
820 )
821 ),
822 readFileString: (path, encoding) =>
823 Effect.flatMap(impl.readFile(path), (_) =>
824 Effect.try({
825 try: () => new TextDecoder(encoding).decode(_),
826 catch: (cause) =>
827 badArgument({
828 module: "FileSystem",
829 method: "readFileString",
830 description: "invalid encoding",
831 cause
832 })
833 })),
834 stream: Effect.fnUntraced(function*(path, options) {
835 const file = yield* impl.open(path, { flag: "r" })
836 if (options?.offset) {
837 yield* file.seek(options.offset, "start")
838 }
839 const bytesToRead = options?.bytesToRead !== undefined ? Size(options.bytesToRead) : undefined
840 let totalBytesRead = BigInt(0)
841 const chunkSize = Size(options?.chunkSize ?? 64 * 1024)
842 const readChunk = file.readAlloc(chunkSize)
843 return Stream.fromPull(Effect.succeed(
844 Effect.flatMap(
845 Effect.suspend((): Pull.Pull<Option.Option<Uint8Array>, PlatformError> => {
846 if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) {
847 return Cause.done()
848 }
849 return bytesToRead !== undefined && (bytesToRead - totalBytesRead) < chunkSize
850 ? file.readAlloc(bytesToRead - totalBytesRead)
851 : readChunk
852 }),
853 Option.match({
854 onNone: () => Cause.done(),
855 onSome: (buf) => {
856 totalBytesRead += BigInt(buf.length)
857 return Effect.succeed(Arr.of(buf))
858 }
859 })
860 )
861 ))
862 }, Stream.unwrap),
863 sink: (path, options) =>
864 pipe(
865 impl.open(path, { flag: "w", ...options }),
866 Effect.map((file) => Sink.forEach((_: Uint8Array) => file.writeAll(_))),
867 Sink.unwrap
868 ),
869 writeFileString: (path, data, options) =>
870 Effect.flatMap(
871 Effect.try({
872 try: () => new TextEncoder().encode(data),
873 catch: (cause) =>
874 badArgument({
875 module: "FileSystem",
876 method: "writeFileString",
877 description: "could not encode string",
878 cause
879 })
880 }),
881 (_) => impl.writeFile(path, _, options)
882 )
883 })
884​
885const notFound = (method: string, path: string) =>
886 systemError({
887 module: "FileSystem",
888 method,
889 _tag: "NotFound",
890 description: "No such file or directory",
891 pathOrDescriptor: path
892 })
893​
894/**
895 * Creates a stub `FileSystem` implementation for tests.
896 *
897 * **Details**
898 *
899 * By default, `exists` returns `false`, `remove` succeeds, many file operations
900 * fail with `PlatformError` `NotFound`, and temporary-directory/file operations
901 * die as not implemented. Pass method overrides to provide the behavior needed
902 * by a specific test without touching the real file system.
903 *
904 * **Example** (Creating a no-op FileSystem)
905 *
906 * ```ts
907 * import { Effect, FileSystem, PlatformError } from "effect"
908 *
909 * // Create a test filesystem that only allows reading specific files
910 * const testFs = FileSystem.makeNoop({
911 * readFileString: (path) => {
912 * if (path === "test-config.json") {
913 * return Effect.succeed("{\"test\": true}")
914 * }
915 * return Effect.fail(
916 * PlatformError.systemError({
917 * _tag: "NotFound",
918 * module: "FileSystem",
919 * method: "readFileString",
920 * description: "File not found",
921 * pathOrDescriptor: path
922 * })
923 * )
924 * },
925 * exists: (path) => Effect.succeed(path === "test-config.json")
926 * })
927 *
928 * // Use in tests
929 * const program = Effect.gen(function*() {
930 * const content = yield* testFs.readFileString("test-config.json")
931 * // Will succeed with mocked content
932 * })
933 *
934 * // Test with the no-op filesystem
935 * const testProgram = Effect.provideService(
936 * program,
937 * FileSystem.FileSystem,
938 * testFs
939 * )
940 * ```
941 *
942 * @category constructors
943 * @since 4.0.0
944 */
945export const makeNoop = (fileSystem: Partial<FileSystem>): FileSystem =>
946 FileSystem.of({
947 [TypeId]: TypeId,
948 access(path) {
949 return Effect.fail(notFound("access", path))
950 },
951 chmod(path) {
952 return Effect.fail(notFound("chmod", path))
953 },
954 chown(path) {
955 return Effect.fail(notFound("chown", path))
956 },
957 copy(path) {
958 return Effect.fail(notFound("copy", path))
959 },
960 copyFile(path) {
961 return Effect.fail(notFound("copyFile", path))
962 },
963 exists() {
964 return Effect.succeed(false)
965 },
966 link(path) {
967 return Effect.fail(notFound("link", path))
968 },
969 makeDirectory() {
970 return Effect.die("not implemented")
971 },
972 makeTempDirectory() {
973 return Effect.die("not implemented")
974 },
975 makeTempDirectoryScoped() {
976 return Effect.die("not implemented")
977 },
978 makeTempFile() {
979 return Effect.die("not implemented")
980 },
981 makeTempFileScoped() {
982 return Effect.die("not implemented")
983 },
984 open(path) {
985 return Effect.fail(notFound("open", path))
986 },
987 readDirectory(path) {
988 return Effect.fail(notFound("readDirectory", path))
989 },
990 readFile(path) {
991 return Effect.fail(notFound("readFile", path))
992 },
993 readFileString(path) {
994 return Effect.fail(notFound("readFileString", path))
995 },
996 readLink(path) {
997 return Effect.fail(notFound("readLink", path))
998 },
999 realPath(path) {
1000 return Effect.fail(notFound("realPath", path))
1001 },
1002 remove() {
1003 return Effect.void
1004 },
1005 rename(oldPath) {
1006 return Effect.fail(notFound("rename", oldPath))
1007 },
1008 sink(path) {
1009 return Sink.fail(notFound("sink", path))
1010 },
1011 stat(path) {
1012 return Effect.fail(notFound("stat", path))
1013 },
1014 stream(path) {
1015 return Stream.fail(notFound("stream", path))
1016 },
1017 symlink(fromPath) {
1018 return Effect.fail(notFound("symlink", fromPath))
1019 },
1020 truncate(path) {
1021 return Effect.fail(notFound("truncate", path))
1022 },
1023 utimes(path) {
1024 return Effect.fail(notFound("utimes", path))
1025 },
1026 watch(path) {
1027 return Stream.fail(notFound("watch", path))
1028 },
1029 writeFile(path) {
1030 return Effect.fail(notFound("writeFile", path))
1031 },
1032 writeFileString(path) {
1033 return Effect.fail(notFound("writeFileString", path))
1034 },
1035 ...fileSystem
1036 })
1037​
1038/**
1039 * Creates a Layer that provides a no-op FileSystem implementation for testing.
1041 * **Details**
1043 * This is a convenience function that wraps `makeNoop` in a Layer, making it easy
1044 * to provide the test filesystem to your Effect programs.
1046 * **Example** (Providing a no-op FileSystem layer)
1048 * ```ts
1049 * import { Effect, FileSystem } from "effect"
1051 * // Create a test layer with specific behaviors
1052 * const testLayer = FileSystem.layerNoop({
1053 * readFileString: (path) => Effect.succeed("mocked content"),
1054 * exists: () => Effect.succeed(true)
1055 * })
1057 * const program = Effect.gen(function*() {
1058 * const fs = yield* FileSystem.FileSystem
1059 * const content = yield* fs.readFileString("any-file.txt")
1060 * return content
1061 * })
1063 * // Provide the test layer
1064 * const testProgram = Effect.provide(program, testLayer)
1065 * ```
1067 * @category layers
1068 * @since 4.0.0
1069 */
1070export const layerNoop = (fileSystem: Partial<FileSystem>): Layer.Layer<FileSystem> =>
1071 Layer.succeed(FileSystem)(makeNoop(fileSystem))
1072​
1073/**
1074 * Runtime type identifier attached to `FileSystem.File` handles and used by
1075 * `isFile` to recognize them.
1077 * **Details**
1079 * This marker is part of the runtime representation of file handles. Prefer
1080 * `isFile` when narrowing unknown values.
1082 * @see {@link File} for the open file handle shape that carries this marker
1083 * @see {@link isFile} for the public guard that checks this marker
1085 * @category type IDs
1086 * @since 4.0.0
1087 */
1088export const FileTypeId = "~effect/platform/FileSystem/File"
1089​
1090/**
1091 * Returns `true` if a value is a `File` handle by checking for the
1092 * `FileTypeId` marker.
1094 * **When to use**
1096 * Use when accepting an unknown value and you need to narrow it to a `File`
1097 * before calling file-handle operations.
1099 * **Details**
1101 * This is a structural marker check. It does not validate the marker value or
1102 * the shape of the file handle.
1104 * @see {@link File} for the file-handle interface narrowed by this guard
1105 * @see {@link FileTypeId} for the runtime marker checked by this guard
1107 * @category File
1108 * @since 4.0.0
1109 */
1110export const isFile = (u: unknown): u is File => hasProperty(u, FileTypeId)
1111​
1112/**
1113 * Interface representing an open file handle.
1115 * **Details**
1117 * Provides low-level file operations including reading, writing, seeking,
1118 * and retrieving file information. File handles are automatically managed
1119 * within scoped operations to ensure proper cleanup.
1121 * **Example** (Working with file handles)
1123 * ```ts
1124 * import { Console, Effect, FileSystem } from "effect"
1126 * const program = Effect.gen(function*() {
1127 * const fs = yield* FileSystem.FileSystem
1129 * // Open a file and work with the handle
1130 * yield* Effect.scoped(
1131 * Effect.gen(function*() {
1132 * const file = yield* fs.open("./data.txt", { flag: "r+" })
1134 * // Get file information
1135 * const stats = yield* file.stat
1136 * yield* Console.log(`File size: ${stats.size} bytes`)
1138 * // Read from specific position
1139 * yield* file.seek(10, "start")
1140 * const buffer = new Uint8Array(5)
1141 * const bytesRead = yield* file.read(buffer)
1142 * yield* Console.log(`Read ${bytesRead} bytes:`, buffer)
1144 * // Write data
1145 * const data = new TextEncoder().encode("Hello")
1146 * yield* file.write(data)
1147 * yield* file.sync // Flush to disk
1148 * })
1149 * )
1150 * })
1151 * ```
1153 * @category File
1154 * @since 4.0.0
1155 */
1156export interface File {
1157 readonly [FileTypeId]: typeof FileTypeId
1158 readonly fd: File.Descriptor
1159 readonly stat: Effect.Effect<File.Info, PlatformError>
1160 readonly seek: (offset: SizeInput, from: SeekMode) => Effect.Effect<void>
1161 readonly sync: Effect.Effect<void, PlatformError>
1162 readonly read: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>
1163 readonly readAlloc: (size: SizeInput) => Effect.Effect<Option.Option<Uint8Array>, PlatformError>
1164 readonly truncate: (length?: SizeInput) => Effect.Effect<void, PlatformError>
1165 readonly write: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>
1166 readonly writeAll: (buffer: Uint8Array) => Effect.Effect<void, PlatformError>
1168​
1169/**
1170 * Namespace containing types associated with open file handles, including file
1171 * descriptors, entry kinds, and stat information.
1173 * @since 4.0.0
1174 */
1175export declare namespace File {
1176 /**
1177 * Branded type for file descriptors.
1179 * **Details**
1181 * File descriptors are numeric handles used by the operating system
1182 * to identify open files. The branded type ensures type safety.
1184 * @category File
1185 * @since 4.0.0
1186 */
1187 export type Descriptor = Brand.Branded<number, "FileDescriptor">
1188​
1189 /**
1190 * Enumeration of possible file system entry types.
1192 * **Details**
1194 * Represents the different types of entries that can exist in a file system,
1195 * from regular files to special device files and symbolic links.
1197 * @category File
1198 * @since 4.0.0
1199 */
1200 export type Type =
1201 | "File"
1202 | "Directory"
1203 | "SymbolicLink"
1204 | "BlockDevice"
1205 | "CharacterDevice"
1206 | "FIFO"
1207 | "Socket"
1208 | "Unknown"
1209​
1210 /**
1211 * Comprehensive file information structure.
1213 * **Details**
1215 * Contains metadata about a file or directory including type, timestamps,
1216 * permissions, and size information. This structure is returned by file
1217 * stat operations.
1219 * **Example** (Inspecting file information)
1221 * ```ts
1222 * import { Effect, FileSystem, Option } from "effect"
1224 * const program = Effect.gen(function*() {
1225 * const fs = yield* FileSystem.FileSystem
1227 * const path = yield* fs.makeTempFile({ prefix: "info-" })
1228 * yield* fs.writeFileString(path, "hello")
1230 * const info: FileSystem.File.Info = yield* fs.stat(path)
1232 * console.log(`File type: ${info.type}`) // "File type: File"
1233 * console.log(`File size: ${info.size} bytes`) // "File size: 5 bytes"
1234 * console.log(`Mode: ${info.mode.toString(8)}`) // Octal permissions
1236 * // Handle optional timestamps without inventing a fallback date
1237 * const modified = Option.match(info.mtime, {
1238 * onNone: () => "unavailable",
1239 * onSome: (mtime) => mtime.toISOString()
1240 * })
1241 * console.log(`Modified: ${modified}`)
1243 * // Check if it's a regular file
1244 * if (info.type === "File") {
1245 * console.log("Processing regular file...") // "Processing regular file..."
1246 * }
1248 * yield* fs.remove(path)
1249 * })
1250 * ```
1252 * @category File
1253 * @since 4.0.0
1254 */
1255 export interface Info {
1256 readonly type: Type
1257 readonly mtime: Option.Option<Date>
1258 readonly atime: Option.Option<Date>
1259 readonly birthtime: Option.Option<Date>
1260 readonly dev: number
1261 readonly ino: Option.Option<number>
1262 readonly mode: number
1263 readonly nlink: Option.Option<number>
1264 readonly uid: Option.Option<number>
1265 readonly gid: Option.Option<number>
1266 readonly rdev: Option.Option<number>
1267 readonly size: Size
1268 readonly blksize: Option.Option<Size>
1269 readonly blocks: Option.Option<number>
1272​
1273/**
1274 * Creates a `File.Descriptor` from a number.
1276 * **When to use**
1278 * Use to brand an operating-system file descriptor number when implementing a
1279 * `FileSystem` that returns custom `File` handles.
1281 * **Details**
1283 * `File.Descriptor` is a branded integer handle used by operating systems to
1284 * identify open files.
1286 * **Gotchas**
1288 * This constructor is nominal and does not check that the number is an integer
1289 * or that it refers to an open file descriptor.
1291 * @see {@link File.Descriptor} for the branded descriptor type produced by this constructor
1292 * @see {@link File} for file handles that expose a descriptor through `fd`
1294 * @category constructors
1295 * @since 4.0.0
1296 */
1297export const FileDescriptor = Brand.nominal<File.Descriptor>()
1298​
1299/**
1300 * Specifies the reference point for seeking within an open file.
1302 * **When to use**
1304 * Use with `File` handles when positioning the cursor before a read or write
1305 * and the offset must be interpreted from either the start of the file or the
1306 * current cursor.
1308 * **Details**
1310 * - `"start"` seeks from the beginning of the file.
1311 * - `"current"` seeks from the current cursor position.
1313 * @see {@link File} for the open file handle API whose `seek` method consumes this mode
1315 * @category models
1316 * @since 4.0.0
1317 */
1318export type SeekMode = "start" | "current"
1319​
1320/**
1321 * Represents file system events emitted when watching files or directories.
1323 * **When to use**
1325 * Use when consuming file system watch streams and pattern matching on `_tag`
1326 * to handle created, updated, or removed paths.
1328 * **Details**
1330 * The union covers create, update, and remove events. Each event carries the
1331 * reported `path`.
1333 * @see {@link FileSystem} for the service interface whose `watch` operation emits these events
1335 * @category models
1336 * @since 4.0.0
1337 */
1338export type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove
1339​
1340/**
1341 * Namespace containing the concrete event shapes emitted by `FileSystem.watch`.
1343 * @since 4.0.0
1344 */
1345export declare namespace WatchEvent {
1346 /**
1347 * Event representing the creation of a new file or directory.
1349 * **Details**
1351 * This event is triggered when a new file or directory is created
1352 * in the watched location.
1354 * @category models
1355 * @since 4.0.0
1356 */
1357 export interface Create {
1358 readonly _tag: "Create"
1359 readonly path: string
1361​
1362 /**
1363 * Event representing the modification of an existing file or directory.
1365 * **Details**
1367 * This event is triggered when an existing file or directory is
1368 * modified in the watched location.
1370 * @category models
1371 * @since 4.0.0
1372 */
1373 export interface Update {
1374 readonly _tag: "Update"
1375 readonly path: string
1377​
1378 /**
1379 * Event representing the deletion of a file or directory.
1381 * **Details**
1383 * This event is triggered when a file or directory is deleted
1384 * from the watched location.
1386 * @category models
1387 * @since 4.0.0
1388 */
1389 export interface Remove {
1390 readonly _tag: "Remove"
1391 readonly path: string
1394​
1395/**
1396 * Service key for file system watch backend implementations.
1398 * **Details**
1400 * This service provides the low-level file watching capabilities that can be
1401 * implemented differently on various platforms (e.g., inotify on Linux,
1402 * FSEvents on macOS, etc.).
1404 * **Example** (Providing a custom watch backend)
1406 * ```ts
1407 * import { Effect, FileSystem, Option, Stream } from "effect"
1409 * // Custom watch backend implementation
1410 * const customWatchBackend = {
1411 * register: (path: string, stat: FileSystem.File.Info) => {
1412 * // Implementation would depend on platform
1413 * return Option.some(Stream.empty) // Placeholder implementation
1414 * }
1415 * }
1417 * // Provide custom watch backend
1418 * const program = Effect.gen(function*() {
1419 * const fs = yield* FileSystem.FileSystem
1421 * // File watching will use the custom backend
1422 * const watcher = fs.watch("./directory")
1423 * })
1425 * const withCustomBackend = Effect.provideService(
1426 * program,
1427 * FileSystem.WatchBackend,
1428 * customWatchBackend
1429 * )
1430 * ```
1432 * @category file watcher
1433 * @since 4.0.0
1434 */
1435export class WatchBackend extends Context.Service<WatchBackend, {
1436 readonly register: (path: string, stat: File.Info) => Option.Option<Stream.Stream<WatchEvent, PlatformError>>
1437}>()("effect/platform/FileSystem/WatchBackend") {}