Open History to see the last commit
1/**
2 * Provides path operations through the Effect environment.
3 *
4 * The `Path` service works with file system paths without tying code to one
5 * concrete platform module. It exposes common operations such as joining,
6 * normalizing, parsing, formatting, resolving, and converting paths to or from
7 * file URLs. This module includes the service interface, parsed path type,
8 * service tag, runtime marker, and built-in POSIX path layer.
9 *
10 * @since 4.0.0
11 */
12import * as Context from "./Context.ts"
13import * as Effect from "./Effect.ts"
14import { identity } from "./Function.ts"
15import * as Layer from "./Layer.ts"
16import { BadArgument } from "./PlatformError.ts"
17
18/**
19 * Runtime type identifier used to mark implementations of the `Path` service.
20 *
21 * **Details**
22 *
23 * The marker is the exact string stored on `Path` service implementations.
24 * Most code should depend on the `Path` service instead of inspecting this
25 * value directly.
26 *
27 * @see {@link layer} for the built-in POSIX `Path` service layer
28 *
29 * @category type IDs
30 * @since 4.0.0
31 */
32export const TypeId = "~effect/platform/Path"
33
34/**
35 * Defines the service interface for platform-specific path manipulation.
36 *
37 * **When to use**
38 *
39 * Use to depend on path operations through the Effect environment instead of a
40 * concrete host path module.
41 *
42 * **Details**
43 *
44 * The service exposes operations for joining, normalizing, parsing,
45 * formatting, and converting file system paths. URL conversion methods return
46 * `Effect`s because invalid file URLs or paths can fail with `BadArgument`.
47 *
48 * **Example** (Using path operations)
49 *
50 * ```ts
51 * import { Effect, Path } from "effect"
52 *
53 * const program = Effect.gen(function*() {
54 * const path = yield* Path.Path
55 *
56 * // Use various path operations
57 * const joined = path.join("home", "user", "documents")
58 * const normalized = path.normalize("./path/../to/file.txt")
59 * const basename = path.basename("/path/to/file.txt")
60 * const dirname = path.dirname("/path/to/file.txt")
61 * const extname = path.extname("file.txt")
62 * const isAbs = path.isAbsolute("/absolute/path")
63 * const parsed = path.parse("/path/to/file.txt")
64 * const relative = path.relative("/from/path", "/to/path")
65 * const resolved = path.resolve("relative", "path")
66 *
67 * console.log({
68 * joined,
69 * normalized,
70 * basename,
71 * dirname,
72 * extname,
73 * isAbs,
74 * parsed,
75 * relative,
76 * resolved
77 * })
78 * })
79 * ```
80 *
81 * @category models
82 * @since 4.0.0
83 */
84export interface Path {
85 readonly [TypeId]: typeof TypeId
86 readonly sep: string
87 readonly basename: (path: string, suffix?: string) => string
88 readonly dirname: (path: string) => string
89 readonly extname: (path: string) => string
90 readonly format: (pathObject: Partial<Path.Parsed>) => string
91 readonly fromFileUrl: (url: URL) => Effect.Effect<string, BadArgument>
92 readonly isAbsolute: (path: string) => boolean
93 readonly join: (...paths: ReadonlyArray<string>) => string
94 readonly normalize: (path: string) => string
95 readonly parse: (path: string) => Path.Parsed
96 readonly relative: (from: string, to: string) => string
97 readonly resolve: (...pathSegments: ReadonlyArray<string>) => string
98 readonly toFileUrl: (path: string) => Effect.Effect<URL, BadArgument>
99 readonly toNamespacedPath: (path: string) => string
100}
101
102/**
103 * Namespace containing types associated with the `Path` service.
104 *
105 * **When to use**
106 *
107 * Use to reference types associated with path parsing and formatting.
108 *
109 * **Example** (Working with parsed paths)
110 *
111 * ```ts
112 * import { Effect, Path } from "effect"
113 *
114 * // Access types and utilities in the Path namespace
115 * const program = Effect.gen(function*() {
116 * const path = yield* Path.Path
117 *
118 * // Parse a path and get a Path.Parsed object
119 * const parsed = path.parse("/home/user/file.txt")
120 *
121 * // The parsed object conforms to the Path.Parsed interface
122 * const exampleParsed = {
123 * root: "/",
124 * dir: "/home/user",
125 * base: "file.txt",
126 * ext: ".txt",
127 * name: "file"
128 * }
129 *
130 * console.log(parsed, exampleParsed)
131 * })
132 * ```
133 *
134 * @since 4.0.0
135 */
136export declare namespace Path {
137 /**
138 * Structured representation of a parsed file system path.
139 *
140 * **When to use**
141 *
142 * Use to model the object form produced by `Path.parse` and consumed by
143 * `Path.format`.
144 *
145 * **Details**
146 *
147 * The fields correspond to the path root, directory, base filename,
148 * extension, and filename without extension, matching the shape consumed by
149 * `Path.format`.
150 *
151 * **Example** (Parsing and formatting paths)
152 *
153 * ```ts
154 * import { Effect, Path } from "effect"
155 *
156 * const program = Effect.gen(function*() {
157 * const path = yield* Path.Path
158 *
159 * // Parse a path into its components
160 * const parsed = path.parse("/home/user/documents/file.txt")
161 * console.log(parsed)
162 * // {
163 * // root: "/",
164 * // dir: "/home/user/documents",
165 * // base: "file.txt",
166 * // ext: ".txt",
167 * // name: "file"
168 * // }
169 *
170 * // Format a path from its components
171 * const formatted = path.format({
172 * dir: "/home/user",
173 * name: "newfile",
174 * ext: ".ts"
175 * })
176 * console.log(formatted) // "/home/user/newfile.ts"
177 * })
178 * ```
179 *
180 * @category models
181 * @since 4.0.0
182 */
183 export interface Parsed {
184 readonly root: string
185 readonly dir: string
186 readonly base: string
187 readonly ext: string
188 readonly name: string
189 }
190}
191
192/**
193 * Service tag for accessing the current `Path` implementation.
194 *
195 * **When to use**
196 *
197 * Use when you need path operations supplied by an effect's environment.
198 *
199 * **Example** (Providing a custom Path service)
200 *
201 * ```ts
202 * import { Effect, Layer, Path } from "effect"
203 *
204 * // Create a custom path implementation
205 * const customPath: Path.Path = {
206 * [Path.TypeId]: Path.TypeId,
207 * sep: "/",
208 * basename: (path: string, suffix?: string) => {
209 * const base = path.split("/").pop() || ""
210 * return suffix && base.endsWith(suffix)
211 * ? base.slice(0, -suffix.length)
212 * : base
213 * },
214 * dirname: (path: string) => path.split("/").slice(0, -1).join("/") || "/",
215 * extname: (path: string) => {
216 * const match = path.match(/\.[^.]*$/)
217 * return match ? match[0] : ""
218 * },
219 * format: (pathObject) => {
220 * const dir = pathObject.dir || ""
221 * const name = pathObject.name || ""
222 * const ext = pathObject.ext || ""
223 * return dir ? `${dir}/${name}${ext}` : `${name}${ext}`
224 * },
225 * fromFileUrl: (url: URL) => Effect.succeed(url.pathname),
226 * isAbsolute: (path: string) => path.startsWith("/"),
227 * join: (...paths: ReadonlyArray<string>) => paths.join("/"),
228 * normalize: (path: string) => path.replace(/\/+/g, "/"),
229 * parse: (path: string) => ({
230 * root: path.startsWith("/") ? "/" : "",
231 * dir: path.split("/").slice(0, -1).join("/") || "/",
232 * base: path.split("/").pop() || "",
233 * ext: path.match(/\.[^.]*$/)?.[0] || "",
234 * name: path.split("/").pop()?.replace(/\.[^.]*$/, "") || ""
235 * }),
236 * relative: (from: string, to: string) => to.replace(from, ""),
237 * resolve: (...pathSegments: ReadonlyArray<string>) => pathSegments.join("/"),
238 * toFileUrl: (path: string) => Effect.succeed(new URL(`file://${path}`)),
239 * toNamespacedPath: (path: string) => path
240 * }
241 *
242 * // Provide the path service
243 * const customPathLayer = Layer.succeed(Path.Path)(customPath)
244 *
245 * const program = Effect.gen(function*() {
246 * const path = yield* Path.Path
247 * const joined = path.join("home", "user", "file.txt")
248 * console.log(joined) // "home/user/file.txt"
249 * })
250 *
251 * // Run with custom path implementation
252 * const result = Effect.provide(program, customPathLayer)
253 * ```
254 *
255 * @category services
256 * @since 4.0.0
257 */
258export const Path: Context.Service<Path, Path> = Context.Service("effect/Path")
259
260/**
261 * The following functions are adapted from the Node.js source code:
262 * https://github.com/nodejs/node/blob/main/lib/internal/url.js
263 *
264 * The following license applies to these functions:
265 * - MIT
266 */
267
268// Resolves . and .. elements in a path with directory names
269function normalizeStringPosix(path: string, allowAboveRoot: boolean) {
270 let res = ""
271 let lastSegmentLength = 0
272 let lastSlash = -1
273 let dots = 0
274 let code
275 for (let i = 0; i <= path.length; ++i) {
276 if (i < path.length) {
277 code = path.charCodeAt(i)
278 } else if (code === 47 /*/*/) {
279 break
280 } else {
281 code = 47 /*/*/
282 }
283 if (code === 47 /*/*/) {
284 if (lastSlash === i - 1 || dots === 1) {
285 // NOOP
286 } else if (lastSlash !== i - 1 && dots === 2) {
287 if (
288 res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ ||
289 res.charCodeAt(res.length - 2) !== 46 /*.*/
290 ) {
291 if (res.length > 2) {
292 const lastSlashIndex = res.lastIndexOf("/")
293 if (lastSlashIndex !== res.length - 1) {
294 if (lastSlashIndex === -1) {
295 res = ""
296 lastSegmentLength = 0
297 } else {
298 res = res.slice(0, lastSlashIndex)
299 lastSegmentLength = res.length - 1 - res.lastIndexOf("/")
300 }
301 lastSlash = i
302 dots = 0
303 continue
304 }
305 } else if (res.length === 2 || res.length === 1) {
306 res = ""
307 lastSegmentLength = 0
308 lastSlash = i
309 dots = 0
310 continue
311 }
312 }
313 if (allowAboveRoot) {
314 if (res.length > 0) {
315 res += "/.."
316 } else {
317 res = ".."
318 }
319 lastSegmentLength = 2
320 }
321 } else {
322 if (res.length > 0) {
323 res += "/" + path.slice(lastSlash + 1, i)
324 } else {
325 res = path.slice(lastSlash + 1, i)
326 }
327 lastSegmentLength = i - lastSlash - 1
328 }
329 lastSlash = i
330 dots = 0
331 } else if (code === 46 /*.*/ && dots !== -1) {
332 ++dots
333 } else {
334 dots = -1
335 }
336 }
337 return res
338}
339
340function _format(sep: string, pathObject: Partial<Path.Parsed>) {
341 const dir = pathObject.dir || pathObject.root
342 const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "")
343 if (!dir) {
344 return base
345 }
346 if (dir === pathObject.root) {
347 return dir + base
348 }
349 return dir + sep + base
350}
351
352function fromFileUrl(url: URL): Effect.Effect<string, BadArgument> {
353 if (url.protocol !== "file:") {
354 return Effect.fail(
355 new BadArgument({
356 module: "Path",
357 method: "fromFileUrl",
358 description: "URL must be of scheme file"
359 })
360 )
361 } else if (url.hostname !== "") {
362 return Effect.fail(
363 new BadArgument({
364 module: "Path",
365 method: "fromFileUrl",
366 description: "Invalid file URL host"
367 })
368 )
369 }
370 const pathname = url.pathname
371 for (let n = 0; n < pathname.length; n++) {
372 if (pathname[n] === "%") {
373 const third = pathname.codePointAt(n + 2)! | 0x20
374 if (pathname[n + 1] === "2" && third === 102) {
375 return Effect.fail(
376 new BadArgument({
377 module: "Path",
378 method: "fromFileUrl",
379 description: "must not include encoded / characters"
380 })
381 )
382 }
383 }
384 }
385 return Effect.succeed(decodeURIComponent(pathname))
386}
387
388const resolve: Path["resolve"] = function resolve() {
389 let resolvedPath = ""
390 let resolvedAbsolute = false
391 let cwd: string | undefined = undefined
392
393 for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
394 let path: string
395 if (i >= 0) {
396 path = arguments[i]
397 } else {
398 const process = (globalThis as any).process
399 if (
400 cwd === undefined && "process" in globalThis &&
401 typeof process === "object" &&
402 process !== null &&
403 typeof process.cwd === "function"
404 ) {
405 cwd = process.cwd()
406 }
407 path = cwd!
408 }
409
410 // Skip empty entries
411 if (path.length === 0) {
412 continue
413 }
414
415 resolvedPath = path + "/" + resolvedPath
416 resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/
417 }
418
419 // At this point the path should be resolved to a full absolute path, but
420 // handle relative paths to be safe (might happen when process.cwd() fails)
421
422 // Normalize the path
423 resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute)
424
425 if (resolvedAbsolute) {
426 if (resolvedPath.length > 0) {
427 return "/" + resolvedPath
428 } else {
429 return "/"
430 }
431 } else if (resolvedPath.length > 0) {
432 return resolvedPath
433 } else {
434 return "."
435 }
436}
437
438const CHAR_FORWARD_SLASH = 47
439
440function toFileUrl(filepath: string) {
441 const outURL = new URL("file://")
442 let resolved = resolve(filepath)
443 // path.resolve strips trailing slashes so we must add them back
444 const filePathLast = filepath.charCodeAt(filepath.length - 1)
445 if (
446 (filePathLast === CHAR_FORWARD_SLASH) &&
447 resolved[resolved.length - 1] !== "/"
448 ) {
449 resolved += "/"
450 }
451 outURL.pathname = encodePathChars(resolved)
452 return Effect.succeed(outURL)
453}
454
455const percentRegExp = /%/g
456const backslashRegExp = /\\/g
457const newlineRegExp = /\n/g
458const carriageReturnRegExp = /\r/g
459const tabRegExp = /\t/g
460
461function encodePathChars(filepath: string) {
462 if (filepath.includes("%")) {
463 filepath = filepath.replace(percentRegExp, "%25")
464 }
465 if (filepath.includes("\\")) {
466 filepath = filepath.replace(backslashRegExp, "%5C")
467 }
468 if (filepath.includes("\n")) {
469 filepath = filepath.replace(newlineRegExp, "%0A")
470 }
471 if (filepath.includes("\r")) {
472 filepath = filepath.replace(carriageReturnRegExp, "%0D")
473 }
474 if (filepath.includes("\t")) {
475 filepath = filepath.replace(tabRegExp, "%09")
476 }
477 return filepath
478}
479
480const posixImpl = Path.of({
481 [TypeId]: TypeId,
482 resolve,
483 normalize(path) {
484 if (path.length === 0) return "."
485
486 const isAbsolute = path.charCodeAt(0) === 47 /*/*/
487 const trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/
488
489 // Normalize the path
490 path = normalizeStringPosix(path, !isAbsolute)
491
492 if (path.length === 0 && !isAbsolute) path = "."
493 if (path.length > 0 && trailingSeparator) path += "/"
494
495 if (isAbsolute) return "/" + path
496 return path
497 },
498
499 isAbsolute(path) {
500 return path.length > 0 && path.charCodeAt(0) === 47 /*/*/
501 },
502
503 join() {
504 if (arguments.length === 0) {
505 return "."
506 }
507 let joined
508 for (let i = 0; i < arguments.length; ++i) {
509 const arg = arguments[i]
510 if (arg.length > 0) {
511 if (joined === undefined) {
512 joined = arg
513 } else {
514 joined += "/" + arg
515 }
516 }
517 }
518 if (joined === undefined) {
519 return "."
520 }
521 return posixImpl.normalize(joined)
522 },
523
524 relative(from, to) {
525 if (from === to) return ""
526
527 from = posixImpl.resolve(from)
528 to = posixImpl.resolve(to)
529
530 if (from === to) return ""
531
532 // Trim any leading backslashes
533 let fromStart = 1
534 for (; fromStart < from.length; ++fromStart) {
535 if (from.charCodeAt(fromStart) !== 47 /*/*/) {
536 break
537 }
538 }
539 const fromEnd = from.length
540 const fromLen = fromEnd - fromStart
541
542 // Trim any leading backslashes
543 let toStart = 1
544 for (; toStart < to.length; ++toStart) {
545 if (to.charCodeAt(toStart) !== 47 /*/*/) {
546 break
547 }
548 }
549 const toEnd = to.length
550 const toLen = toEnd - toStart
551
552 // Compare paths to find the longest common path from root
553 const length = fromLen < toLen ? fromLen : toLen
554 let lastCommonSep = -1
555 let i = 0
556 for (; i <= length; ++i) {
557 if (i === length) {
558 if (toLen > length) {
559 if (to.charCodeAt(toStart + i) === 47 /*/*/) {
560 // We get here if `from` is the exact base path for `to`.
561 // For example: from='/foo/bar'; to='/foo/bar/baz'
562 return to.slice(toStart + i + 1)
563 } else if (i === 0) {
564 // We get here if `from` is the root
565 // For example: from='/'; to='/foo'
566 return to.slice(toStart + i)
567 }
568 } else if (fromLen > length) {
569 if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
570 // We get here if `to` is the exact base path for `from`.
571 // For example: from='/foo/bar/baz'; to='/foo/bar'
572 lastCommonSep = i
573 } else if (i === 0) {
574 // We get here if `to` is the root.
575 // For example: from='/foo'; to='/'
576 lastCommonSep = 0
577 }
578 }
579 break
580 }
581 const fromCode = from.charCodeAt(fromStart + i)
582 const toCode = to.charCodeAt(toStart + i)
583 if (fromCode !== toCode) {
584 break
585 } else if (fromCode === 47 /*/*/) {
586 lastCommonSep = i
587 }
588 }
589
590 let out = ""
591 // Generate the relative path based on the path difference between `to`
592 // and `from`
593 for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
594 if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
595 if (out.length === 0) {
596 out += ".."
597 } else {
598 out += "/.."
599 }
600 }
601 }
602
603 // Lastly, append the rest of the destination (`to`) path that comes after
604 // the common path parts
605 if (out.length > 0) {
606 return out + to.slice(toStart + lastCommonSep)
607 } else {
608 toStart += lastCommonSep
609 if (to.charCodeAt(toStart) === 47 /*/*/) {
610 ++toStart
611 }
612 return to.slice(toStart)
613 }
614 },
615
616 dirname(path) {
617 if (path.length === 0) return "."
618 let code = path.charCodeAt(0)
619 const hasRoot = code === 47 /*/*/
620 let end = -1
621 let matchedSlash = true
622 for (let i = path.length - 1; i >= 1; --i) {
623 code = path.charCodeAt(i)
624 if (code === 47 /*/*/) {
625 if (!matchedSlash) {
626 end = i
627 break
628 }
629 } else {
630 // We saw the first non-path separator
631 matchedSlash = false
632 }
633 }
634
635 if (end === -1) return hasRoot ? "/" : "."
636 if (hasRoot && end === 1) return "//"
637 return path.slice(0, end)
638 },
639
640 basename(path, ext) {
641 let start = 0
642 let end = -1
643 let matchedSlash = true
644 let i
645
646 if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
647 if (ext.length === path.length && ext === path) return ""
648 let extIdx = ext.length - 1
649 let firstNonSlashEnd = -1
650 for (i = path.length - 1; i >= 0; --i) {
651 const code = path.charCodeAt(i)
652 if (code === 47 /*/*/) {
653 // If we reached a path separator that was not part of a set of path
654 // separators at the end of the string, stop now
655 if (!matchedSlash) {
656 start = i + 1
657 break
658 }
659 } else {
660 if (firstNonSlashEnd === -1) {
661 // We saw the first non-path separator, remember this index in case
662 // we need it if the extension ends up not matching
663 matchedSlash = false
664 firstNonSlashEnd = i + 1
665 }
666 if (extIdx >= 0) {
667 // Try to match the explicit extension
668 if (code === ext.charCodeAt(extIdx)) {
669 if (--extIdx === -1) {
670 // We matched the extension, so mark this as the end of our path
671 // component
672 end = i
673 }
674 } else {
675 // Extension does not match, so our result is the entire path
676 // component
677 extIdx = -1
678 end = firstNonSlashEnd
679 }
680 }
681 }
682 }
683
684 if (start === end) end = firstNonSlashEnd
685 else if (end === -1) end = path.length
686 return path.slice(start, end)
687 } else {
688 for (i = path.length - 1; i >= 0; --i) {
689 if (path.charCodeAt(i) === 47 /*/*/) {
690 // If we reached a path separator that was not part of a set of path
691 // separators at the end of the string, stop now
692 if (!matchedSlash) {
693 start = i + 1
694 break
695 }
696 } else if (end === -1) {
697 // We saw the first non-path separator, mark this as the end of our
698 // path component
699 matchedSlash = false
700 end = i + 1
701 }
702 }
703
704 if (end === -1) return ""
705 return path.slice(start, end)
706 }
707 },
708
709 extname(path) {
710 let startDot = -1
711 let startPart = 0
712 let end = -1
713 let matchedSlash = true
714 // Track the state of characters (if any) we see before our first dot and
715 // after any path separator we find
716 let preDotState = 0
717 for (let i = path.length - 1; i >= 0; --i) {
718 const code = path.charCodeAt(i)
719 if (code === 47 /*/*/) {
720 // If we reached a path separator that was not part of a set of path
721 // separators at the end of the string, stop now
722 if (!matchedSlash) {
723 startPart = i + 1
724 break
725 }
726 continue
727 }
728 if (end === -1) {
729 // We saw the first non-path separator, mark this as the end of our
730 // extension
731 matchedSlash = false
732 end = i + 1
733 }
734 if (code === 46 /*.*/) {
735 // If this is our first dot, mark it as the start of our extension
736 if (startDot === -1) {
737 startDot = i
738 } else if (preDotState !== 1) {
739 preDotState = 1
740 }
741 } else if (startDot !== -1) {
742 // We saw a non-dot and non-path separator before our dot, so we should
743 // have a good chance at having a non-empty extension
744 preDotState = -1
745 }
746 }
747
748 if (
749 startDot === -1 || end === -1 ||
750 // We saw a non-dot character immediately before the dot
751 preDotState === 0 ||
752 // The (right-most) trimmed path component is exactly '..'
753 preDotState === 1 && startDot === end - 1 && startDot === startPart + 1
754 ) {
755 return ""
756 }
757 return path.slice(startDot, end)
758 },
759
760 format: function format(pathObject) {
761 if (pathObject === null || typeof pathObject !== "object") {
762 throw new TypeError("The \"pathObject\" argument must be of type Object. Received type " + typeof pathObject)
763 }
764 return _format("/", pathObject)
765 },
766
767 parse(path) {
768 const ret = { root: "", dir: "", base: "", ext: "", name: "" }
769 if (path.length === 0) return ret
770 let code = path.charCodeAt(0)
771 const isAbsolute = code === 47 /*/*/
772 let start
773 if (isAbsolute) {
774 ret.root = "/"
775 start = 1
776 } else {
777 start = 0
778 }
779 let startDot = -1
780 let startPart = 0
781 let end = -1
782 let matchedSlash = true
783 let i = path.length - 1
784
785 // Track the state of characters (if any) we see before our first dot and
786 // after any path separator we find
787 let preDotState = 0
788
789 // Get non-dir info
790 for (; i >= start; --i) {
791 code = path.charCodeAt(i)
792 if (code === 47 /*/*/) {
793 // If we reached a path separator that was not part of a set of path
794 // separators at the end of the string, stop now
795 if (!matchedSlash) {
796 startPart = i + 1
797 break
798 }
799 continue
800 }
801 if (end === -1) {
802 // We saw the first non-path separator, mark this as the end of our
803 // extension
804 matchedSlash = false
805 end = i + 1
806 }
807 if (code === 46 /*.*/) {
808 // If this is our first dot, mark it as the start of our extension
809 if (startDot === -1) startDot = i
810 else if (preDotState !== 1) preDotState = 1
811 } else if (startDot !== -1) {
812 // We saw a non-dot and non-path separator before our dot, so we should
813 // have a good chance at having a non-empty extension
814 preDotState = -1
815 }
816 }
817
818 if (
819 startDot === -1 || end === -1 ||
820 // We saw a non-dot character immediately before the dot
821 preDotState === 0 ||
822 // The (right-most) trimmed path component is exactly '..'
823 preDotState === 1 && startDot === end - 1 && startDot === startPart + 1
824 ) {
825 if (end !== -1) {
826 if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end)
827 else ret.base = ret.name = path.slice(startPart, end)
828 }
829 } else {
830 if (startPart === 0 && isAbsolute) {
831 ret.name = path.slice(1, startDot)
832 ret.base = path.slice(1, end)
833 } else {
834 ret.name = path.slice(startPart, startDot)
835 ret.base = path.slice(startPart, end)
836 }
837 ret.ext = path.slice(startDot, end)
838 }
839
840 if (startPart > 0) ret.dir = path.slice(0, startPart - 1)
841 else if (isAbsolute) ret.dir = "/"
842
843 return ret
844 },
845
846 sep: "/",
847 fromFileUrl,
848 toFileUrl,
849 toNamespacedPath: identity
850})
851
852/**
853 * Layer that provides the built-in POSIX `Path` implementation.
854 *
855 * **When to use**
856 *
857 * Use when you need an effect that requires the `Path` service to run with the
858 * built-in POSIX path implementation.
859 *
860 * **Details**
861 *
862 * The layer provides a static service whose separator is `/` and whose
863 * operations use POSIX path semantics.
864 *
865 * @see {@link Path} for accessing the `Path` service from an effect
866 *
867 * @category layers
868 * @since 4.0.0
869 */
870export const layer: Layer.Layer<Path> = Layer.succeed(Path)(posixImpl)