/**
* A read-only, synchronous `FileSystem` over `node:fs`'s sync API, for
* programs that must run under `Effect.runSync` — a config loader called from
* a synchronous entry point, a build-script shim — yet still take
* `FileSystem.FileSystem` from context.
*
* Deliberately a separate subpath (`@effected/memfs/node-sync`): the main
* entry imports nothing from `node:*`, and this module is the one place that
* does. Import it only where Node's filesystem is the platform you mean.
*
* @packageDocumentation
*/
import * as NFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeUrl from "node:url";
import type { PlatformError as PlatformErrorNs } from "effect";
import { BigInt as BI, ByteSize, Effect, FileSystem, Layer, Option, Path, PlatformError, Stream } from "effect";
import { errnoTag } from "./internal/errno.js";
type PlatformErrorType = PlatformErrorNs.PlatformError;
// Mirrors @effect/platform-node-shared's `handleErrnoException`: the tag comes
// from the code through the shared `errnoTag` mapping (anything unmapped,
// including node's `ERR_*` argument codes, is Unknown) and the node error rides
// as `cause`.
const errnoException = (method: string, path: string, err: unknown): PlatformErrorType => {
const error = err as NodeJS.ErrnoException | undefined;
return PlatformError.systemError({
_tag: errnoTag(error?.code),
module: "FileSystem",
method,
pathOrDescriptor: path,
syscall: error?.syscall,
cause: error,
});
};
// Mirrors the adapter's `effectify(…, handleErrnoException, handleBadArgument)`
// split: a failure from the syscall itself (it carries a numeric `errno` or a
// `syscall`) is a system error; anything node throws BEFORE the syscall — its
// argument validation, whose errors also carry string codes such as
// ERR_INVALID_ARG_VALUE (a NUL byte) or ERR_INVALID_ARG_TYPE — is BadArgument.
const fail = (method: string, path: string, err: unknown): PlatformErrorType => {
const error = err as NodeJS.ErrnoException | undefined;
return typeof error?.errno === "number" || error?.syscall !== undefined
? errnoException(method, path, err)
: PlatformError.badArgument({
module: "FileSystem",
method,
description: error?.message ?? String(err),
});
};
const attempt = (method: string, path: string, f: () => A): Effect.Effect =>
Effect.try({ try: f, catch: (err) => fail(method, path, err) });
const bigintToNumber = (value: bigint, field: string): number => {
const number = Number(value);
if (!Number.isSafeInteger(number)) {
throw new RangeError(`${field} exceeds the safe integer range: ${value}`);
}
return number;
};
const bigintToNumberOption = (value: bigint | undefined): Option.Option =>
Option.flatMap(Option.fromNullishOr(value), BI.toNumber);
// Node fills bigint stats from a BigInt64Array, so unsigned 64-bit values such
// as dev_t and ino_t at or above 2^63 are reported as negative.
const toUint64 = (value: bigint): bigint => BigInt.asUintN(64, value);
const toUint64Option = (value: bigint | undefined): Option.Option =>
Option.map(Option.fromNullishOr(value), toUint64);
// The node adapter's `fileType`, shared by stats and directory entries.
const fileType = (entry: NFS.BigIntStats | NFS.Dirent): FileSystem.File.Type =>
entry.isFile()
? "File"
: entry.isDirectory()
? "Directory"
: entry.isSymbolicLink()
? "SymbolicLink"
: entry.isBlockDevice()
? "BlockDevice"
: entry.isCharacterDevice()
? "CharacterDevice"
: entry.isFIFO()
? "FIFO"
: entry.isSocket()
? "Socket"
: "Unknown";
// The node adapter's `makeFileInfo`, field for field.
const fileInfo = (stat: NFS.BigIntStats): FileSystem.File.Info => ({
type: fileType(stat),
mtime: Option.fromNullishOr(stat.mtime),
atime: Option.fromNullishOr(stat.atime),
birthtime: Option.fromNullishOr(stat.birthtime),
dev: toUint64(stat.dev),
rdev: toUint64Option(stat.rdev),
ino: toUint64Option(stat.ino),
mode: bigintToNumber(stat.mode, "mode"),
nlink: toUint64Option(stat.nlink),
uid: bigintToNumberOption(stat.uid),
gid: bigintToNumberOption(stat.gid),
size: ByteSize.bytes(stat.size),
blksize: stat.blksize !== undefined ? Option.some(ByteSize.bytes(stat.blksize)) : Option.none(),
blocks: Option.fromNullishOr(stat.blocks),
});
// Every member outside the read set is a DEFECT, never a typed failure: a
// program handed this filesystem that tries to write has a wiring bug, and a
// typed failure (what `FileSystem.makeNoop` answers) could be caught and
// silently absorbed as "not found".
const readOnly = (member: string) => new Error(`NodeSyncFileSystem is read-only: ${member} is not supported`);
const unsupported = (member: string) => () => Effect.die(readOnly(member));
// The adapter's `statFactory`: `stat` and `lstat` differ only in the node call
// and the method an error names.
const statWith =
(method: "stat" | "lstat", nodeStat: (path: string, options: { bigint: true }) => NFS.BigIntStats) =>
(path: string) =>
Effect.flatMap(
attempt(method, path, () => nodeStat(path, { bigint: true })),
(stat) =>
Effect.try({
try: () => fileInfo(stat),
catch: (err) =>
PlatformError.badArgument({ module: "FileSystem", method, description: (err as Error).message }),
}),
);
// `make` derives `glob`, but it forks fibers, which the runs-under-`runSync`
// promise does not cover, so it stays outside the read set.
const make: FileSystem.FileSystem = FileSystem.FileSystem.of({
...FileSystem.make({
access: (path, options) =>
attempt("access", path, () => {
let mode = NFS.constants.F_OK;
if (options?.readable) mode |= NFS.constants.R_OK;
if (options?.writable) mode |= NFS.constants.W_OK;
NFS.accessSync(path, mode);
}),
lstat: statWith("lstat", NFS.lstatSync),
stat: statWith("stat", NFS.statSync),
// The adapter's own value: node's Buffer (a Uint8Array), not a copy. A
// non-string path never reaches `readFileSync`, which would read it as a
// file DESCRIPTOR; the adapter's async `readFile` rejects it in its callback,
// so it surfaces there as a system error (Unknown, ERR_INVALID_ARG_TYPE).
readFile: (path) =>
typeof path === "string"
? attempt("readFile", path, () => NFS.readFileSync(path))
: Effect.fail(
errnoException(
"readFile",
path,
Object.assign(new TypeError(`The "path" argument must be of type string. Received ${typeof path}`), {
code: "ERR_INVALID_ARG_TYPE",
}),
),
),
// The adapter wraps `readdir` in `Effect.tryPromise` whose catch is
// `handleErrnoException` alone, so EVERY failure — argument errors too — is
// a system error (an `ERR_*` code maps to Unknown). Matched here ON PURPOSE:
// a NUL byte or non-string path is `Unknown`/`ERR_INVALID_ARG_*` for
// readDirectory but `BadArgument` for every other member, exactly as on the
// adapter. Do not "fix" it: it is the parity with the adapter.
readDirectory: (path, options) =>
Effect.try({
try: () => NFS.readdirSync(path, { encoding: "utf8", recursive: options?.recursive === true }),
catch: (err) => errnoException("readDirectory", path, err),
}),
// The adapter's `readdir` with file types, under the same catch-all as
// readDirectory above.
readDirectoryEntries: (path) =>
Effect.try({
try: () =>
NFS.readdirSync(path, { withFileTypes: true }).map((entry) => ({ name: entry.name, type: fileType(entry) })),
catch: (err) => errnoException("readDirectoryEntries", path, err),
}),
readLink: (path) => attempt("readLink", path, () => NFS.readlinkSync(path)),
// The JS `realpathSync`, NOT `.native`: the node adapter wraps the JS
// `fs.realpath`, which resolves links but never canonicalizes case.
realPath: (path) => attempt("realPath", path, () => NFS.realpathSync(path)),
copy: unsupported("copy"),
copyFile: unsupported("copyFile"),
chmod: unsupported("chmod"),
chown: unsupported("chown"),
link: unsupported("link"),
makeDirectory: unsupported("makeDirectory"),
makeTempDirectory: unsupported("makeTempDirectory"),
makeTempDirectoryScoped: unsupported("makeTempDirectoryScoped"),
makeTempFile: unsupported("makeTempFile"),
makeTempFileScoped: unsupported("makeTempFileScoped"),
open: unsupported("open"),
remove: unsupported("remove"),
rename: unsupported("rename"),
symlink: unsupported("symlink"),
truncate: unsupported("truncate"),
utimes: unsupported("utimes"),
watch: () => Stream.die(readOnly("watch")),
writeFile: unsupported("writeFile"),
}),
glob: unsupported("glob"),
});
const layer: Layer.Layer = Layer.succeed(FileSystem.FileSystem, make);
// The host's `Path`: `node:path` plus the two URL members it lacks. Typed so
// the exported static is a plain layer, not `typeof` a local.
const hostPath: Path.Path = Path.make({
sep: NodePath.sep,
basename: NodePath.basename,
dirname: NodePath.dirname,
extname: NodePath.extname,
format: NodePath.format,
isAbsolute: NodePath.isAbsolute,
join: NodePath.join,
normalize: NodePath.normalize,
parse: NodePath.parse,
relative: NodePath.relative,
resolve: NodePath.resolve,
toNamespacedPath: NodePath.toNamespacedPath,
fromFileUrl: (url) =>
Effect.try({
try: () => NodeUrl.fileURLToPath(url),
catch: (cause) => new PlatformError.BadArgument({ module: "Path", method: "fromFileUrl", cause }),
}),
toFileUrl: (path) =>
Effect.try({
try: () => NodeUrl.pathToFileURL(path),
catch: (cause) => new PlatformError.BadArgument({ module: "Path", method: "toFileUrl", cause }),
}),
});
const hostPathLayer: Layer.Layer = Layer.succeed(Path.Path, hostPath);
/**
* A read-only, synchronous `FileSystem` over `node:fs`.
*
* @remarks
* Every read member (`access`, `exists`, `stat`, `readFile`,
* `readFileString`, `readDirectory`, `readLink`, `realPath`) calls `node:fs`'s
* sync API, so a program using only those runs under `Effect.runSync`.
* Successes and failures match `@effect/platform-node`'s `NodeFileSystem`:
* the same `File.Info`, the same error tag, method and errno (on `cause`).
* `realPath` resolves links but keeps the queried case, as the node adapter
* does. The adapter's quirks are copied too: an invalid path argument (a NUL
* byte, a non-string) is `BadArgument` for every member EXCEPT
* `readDirectory`, which reports it as `Unknown` carrying node's
* `ERR_INVALID_ARG_*` code, because that is what the adapter does. Every
* other member — writes, `open` and the streams built on it, `glob`, `watch`,
* temp files — is a defect (`Effect.die`), not a typed failure: this
* filesystem never writes, and a caller that tries has a wiring bug
* `Effect.catch` must not absorb.
*
* @example
* ```ts
* import { NodeSyncFileSystem } from "@effected/memfs/node-sync";
* import { Effect, FileSystem } from "effect";
*
* const program = Effect.gen(function* () {
* const fs = yield* FileSystem.FileSystem;
* return yield* fs.readFileString("package.json");
* });
*
* const text = Effect.runSync(program.pipe(Effect.provide(NodeSyncFileSystem.layer)));
* ```
*
* @public
*/
export class NodeSyncFileSystem {
/**
* The filesystem itself, for code that takes a `FileSystem` argument. A
* plain value (not an `Effect`, unlike `MemoryFileSystem.make`): there is no
* volume to build.
*/
static readonly fileSystem: FileSystem.FileSystem = make;
/** The filesystem as a layer providing `FileSystem.FileSystem`. */
static readonly layer: Layer.Layer = layer;
/**
* {@link NodeSyncFileSystem.layer} with the host's own `Path` merged in:
* provides `FileSystem.FileSystem` and `Path.Path` from one layer.
*
* @remarks
* The `Path` is built from `node:path` (win32 rules on Windows, POSIX
* elsewhere), with `fromFileUrl` and `toFileUrl` from `node:url` failing as
* `BadArgument`, the same shape the platform's own `Path` layer has. Every
* member is synchronous, so a program using both services still runs under
* `Effect.runSync`. It is not core's POSIX-only `Path.layer`, which would
* misread Windows paths beside the real filesystem.
*/
static readonly layerWithPath: Layer.Layer = Layer.merge(layer, hostPathLayer);
private constructor() {}
}
// This module is the `./node-sync` ENTRY POINT, so it re-exports the other
// Node-only concept, and every type that concept's signature names:
// api-extractor models each entry point as its own surface.
export type {
MemoryFileSystemSeed,
MemoryFileSystemSeedDirectory,
MemoryFileSystemSeedEntry,
MemoryFileSystemSeedFile,
MemoryFileSystemSeedSymlink,
} from "./MemoryFileSystem.js";
export { NodeDirectorySeed, type NodeDirectorySeedOptions } from "./NodeDirectorySeed.js";