Open History to see the last commit
1/**
2 * Node-backed provider for Effect's `Path` service.
3 *
4 * This module turns Node's `node:path` and `node:url` APIs into `Layer`s for
5 * programs that depend on `Path`. Use it when code should receive path
6 * operations from the Effect environment instead of importing `node:path`
7 * directly, including configuration loading, filesystem composition, and file
8 * URL conversion.
9 *
10 * **Mental model**
11 *
12 * `layer` follows the platform semantics of the current Node runtime. The
13 * `layerPosix` and `layerWin32` variants pin the syntax rules to POSIX or
14 * Windows, which is useful for deterministic parsing, formatting, and tests.
15 * All three layers include `fromFileUrl` and `toFileUrl` behavior backed by
16 * Node's URL conversion functions.
17 *
18 * **Gotchas**
19 *
20 * Path operations are syntactic: they normalize separators, roots, drive
21 * letters, UNC segments, extensions, and relative segments without checking the
22 * filesystem. File URL conversion follows Node's validation and encoding
23 * rules, and invalid conversions fail with `BadArgument`.
24 *
25 * @since 4.0.0
26 */
27import * as Effect from "effect/Effect"
28import * as Layer from "effect/Layer"
29import { Path, TypeId } from "effect/Path"
30import { BadArgument } from "effect/PlatformError"
31import * as NodePath from "node:path"
32import * as NodeUrl from "node:url"
33
34const fromFileUrl = (url: URL): Effect.Effect<string, BadArgument> =>
35 Effect.try({
36 try: () => NodeUrl.fileURLToPath(url),
37 catch: (cause) =>
38 new BadArgument({
39 module: "Path",
40 method: "fromFileUrl",
41 cause
42 })
43 })
44
45const toFileUrl = (path: string): Effect.Effect<URL, BadArgument> =>
46 Effect.try({
47 try: () => NodeUrl.pathToFileURL(path),
48 catch: (cause) =>
49 new BadArgument({
50 module: "Path",
51 method: "toFileUrl",
52 cause
53 })
54 })
55
56/**
57 * Provides the `Path` service using Node's POSIX path implementation plus
58 * file URL conversion helpers.
59 *
60 * @category layers
61 * @since 4.0.0
62 */
63export const layerPosix: Layer.Layer<Path> = Layer.succeed(Path)({
64 [TypeId]: TypeId,
65 ...NodePath.posix,
66 fromFileUrl,
67 toFileUrl
68})
69
70/**
71 * Provides the `Path` service using Node's Windows path implementation plus
72 * file URL conversion helpers.
73 *
74 * @category layers
75 * @since 4.0.0
76 */
77export const layerWin32: Layer.Layer<Path> = Layer.succeed(Path)({
78 [TypeId]: TypeId,
79 ...NodePath.win32,
80 fromFileUrl,
81 toFileUrl
82})
83
84/**
85 * Provides the default `Path` service using the host platform's Node path
86 * implementation plus file URL conversion helpers.
87 *
88 * @category layers
89 * @since 4.0.0
90 */
91export const layer: Layer.Layer<Path> = Layer.succeed(Path)({
92 [TypeId]: TypeId,
93 ...NodePath,
94 fromFileUrl,
95 toFileUrl
96})