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