-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalize.ts
More file actions
1229 lines (1161 loc) · 42.6 KB
/
normalize.ts
File metadata and controls
1229 lines (1161 loc) · 42.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Path manipulation utilities with cross-platform support.
* Provides path normalization, validation, and file extension handling.
*/
import { WIN32 } from '../constants/platform'
import { search } from '../strings'
// Character code constants.
// '\'
const CHAR_BACKWARD_SLASH = 92
// ':'
const CHAR_COLON = 58
// '/'
const CHAR_FORWARD_SLASH = 47
// 'a'
const CHAR_LOWERCASE_A = 97
// 'z'
const CHAR_LOWERCASE_Z = 122
// 'A'
const CHAR_UPPERCASE_A = 65
// 'Z'
const CHAR_UPPERCASE_Z = 90
// Regular expressions.
const slashRegExp = /[/\\]/
const nodeModulesPathRegExp = /(?:^|[/\\])node_modules(?:[/\\]|$)/
/**
* Check if a character code represents a path separator.
*
* Determines whether the given character code is either a forward slash (/) or
* backslash (\), which are used as path separators across different platforms.
*
* @param {number} code - The character code to check
* @returns {boolean} `true` if the code represents a path separator, `false` otherwise
*
* @example
* ```typescript
* isPathSeparator(47) // true - forward slash '/'
* isPathSeparator(92) // true - backslash '\'
* isPathSeparator(65) // false - letter 'A'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
function isPathSeparator(code: number): boolean {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}
/**
* Check if a character code represents a Windows device root letter.
*
* Tests whether the given character code falls within the valid range for
* Windows drive letters (A-Z or a-z). These letters are used at the start
* of Windows absolute paths (e.g., `C:\`, `D:\`).
*
* @param {number} code - The character code to check
* @returns {boolean} `true` if the code is a valid drive letter, `false` otherwise
*
* @example
* ```typescript
* isWindowsDeviceRoot(67) // true - letter 'C'
* isWindowsDeviceRoot(99) // true - letter 'c'
* isWindowsDeviceRoot(58) // false - colon ':'
* isWindowsDeviceRoot(47) // false - forward slash '/'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
function isWindowsDeviceRoot(code: number): boolean {
return (
(code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
(code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
)
}
let _buffer: typeof import('node:buffer') | undefined
/**
* Lazily load the buffer module.
*
* Performs on-demand loading of Node.js buffer module to avoid initialization
* overhead and potential Webpack bundling errors.
*
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getBuffer() {
if (_buffer === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_buffer = /*@__PURE__*/ require('buffer')
}
return _buffer as typeof import('node:buffer')
}
let _url: typeof import('node:url') | undefined
/**
* Lazily load the url module.
*
* Performs on-demand loading of Node.js url module to avoid initialization
* overhead and potential Webpack bundling errors.
*
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getUrl() {
if (_url === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_url = /*@__PURE__*/ require('url')
}
return _url as typeof import('node:url')
}
/**
* Check if a path contains node_modules directory.
*
* Detects whether a given path includes a `node_modules` directory segment.
* This is useful for identifying npm package dependencies and filtering
* dependency-related paths.
*
* The check matches `node_modules` appearing as a complete path segment,
* ensuring it is either at the start, end, or surrounded by path separators.
*
* @param {string | Buffer | URL} pathLike - The path to check
* @returns {boolean} `true` if the path contains `node_modules`, `false` otherwise
*
* @example
* ```typescript
* isNodeModules('/project/node_modules/package') // true
* isNodeModules('node_modules/package/index.js') // true
* isNodeModules('/src/my_node_modules_backup') // false
* isNodeModules('/project/src/index.js') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNodeModules(pathLike: string | Buffer | URL): boolean {
const filepath = pathLikeToString(pathLike)
return nodeModulesPathRegExp.test(filepath)
}
/**
* Check if a path is absolute.
*
* An absolute path is one that specifies a location from the root of the file system.
* This function handles both POSIX and Windows path formats.
*
* POSIX absolute paths:
* - Start with forward slash '/'
* - Examples: '/home/user', '/usr/bin/node'
*
* Windows absolute paths (3 types):
* 1. Drive-letter paths: Start with drive letter + colon + separator
* - Format: [A-Za-z]:[\\/]
* - Examples: 'C:\Windows', 'D:/data', 'c:\Program Files'
* - Reference: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#file-and-directory-names
*
* 2. UNC paths: Start with double backslash (handled by backslash check)
* - Format: \\server\share
* - Examples: '\\server\share\file', '\\?\C:\path'
* - Reference: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#unc-names
*
* 3. Device paths: Start with backslash
* - Examples: '\Windows', '\\.\device'
* - Note: Single backslash paths are relative to current drive
*
* @param {string | Buffer | URL} pathLike - The path to check
* @returns {boolean} `true` if the path is absolute, `false` otherwise
*
* @example
* ```typescript
* // POSIX paths
* isAbsolute('/home/user') // true
* isAbsolute('/usr/bin/node') // true
*
* // Windows paths
* isAbsolute('C:\\Windows') // true
* isAbsolute('D:/data') // true
* isAbsolute('\\\\server\\share') // true
*
* // Relative paths
* isAbsolute('../relative') // false
* isAbsolute('relative/path') // false
* isAbsolute('.') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isAbsolute(pathLike: string | Buffer | URL): boolean {
const filepath = pathLikeToString(pathLike)
const { length } = filepath
// Empty paths are not absolute.
if (length === 0) {
return false
}
const code = filepath.charCodeAt(0)
// POSIX: absolute paths start with forward slash '/'.
// This is the simplest case and works for all UNIX-like systems.
if (code === CHAR_FORWARD_SLASH) {
return true
}
// Windows: absolute paths can start with backslash '\'.
// This includes UNC paths (\\server\share) and device paths (\\.\ or \\?\).
// Single backslash is technically relative to current drive, but treated as absolute.
if (code === CHAR_BACKWARD_SLASH) {
return true
}
// Windows: drive-letter absolute paths (e.g., C:\, D:\).
// Format: [A-Za-z]:[\\/]
// Requires at least 3 characters: drive letter + colon + separator.
// Only treat as absolute on Windows platforms.
if (WIN32 && length > 2) {
// Check if first character is a letter (A-Z or a-z).
// Check if second character is colon ':'.
// Check if third character is a path separator (forward or backslash).
// This matches patterns like 'C:\', 'D:/', 'c:\Users', etc.
if (
isWindowsDeviceRoot(code) &&
filepath.charCodeAt(1) === CHAR_COLON &&
isPathSeparator(filepath.charCodeAt(2))
) {
return true
}
}
// Not an absolute path.
return false
}
/**
* Check if a value is a valid file path (absolute or relative).
*
* Determines whether a given value represents a valid file system path.
* This function distinguishes between file paths and other string formats
* like package names, URLs, or bare module specifiers.
*
* Valid paths include:
* - Absolute paths (e.g., `/usr/bin`, `C:\Windows`)
* - Relative paths with separators (e.g., `./src`, `../lib`)
* - Special relative paths (`.`, `..`)
* - Paths starting with `@` that have subpaths (e.g., `@scope/name/file`)
*
* Not considered paths:
* - URLs with protocols (e.g., `http://`, `file://`, `git:`)
* - Bare package names (e.g., `lodash`, `react`)
* - Scoped package names without subpaths (e.g., `@scope/name`)
*
* @param {string | Buffer | URL} pathLike - The value to check
* @returns {boolean} `true` if the value is a valid file path, `false` otherwise
*
* @example
* ```typescript
* // Valid paths
* isPath('/absolute/path') // true
* isPath('./relative/path') // true
* isPath('../parent/dir') // true
* isPath('.') // true
* isPath('..') // true
* isPath('@scope/name/subpath') // true
* isPath('C:\\Windows') // true (Windows)
*
* // Not paths
* isPath('lodash') // false - bare package name
* isPath('@scope/package') // false - scoped package name
* isPath('http://example.com') // false - URL
* isPath('file://path') // false - file URL
* isPath('') // false - empty string
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isPath(pathLike: string | Buffer | URL): boolean {
const filepath = pathLikeToString(pathLike)
if (typeof filepath !== 'string' || filepath.length === 0) {
return false
}
// Exclude URLs with protocols (file:, http:, https:, git:, etc.).
// These should be handled by package spec parsers, not treated as file paths.
// Require at least 2 characters before colon to exclude Windows drive letters (C:, D:).
if (/^[a-z][a-z0-9+.-]+:/i.test(filepath)) {
return false
}
// Special relative paths.
if (filepath === '.' || filepath === '..') {
return true
}
// Absolute paths are always valid paths.
if (isAbsolute(filepath)) {
return true
}
// Contains path separators, so it's a path.
if (filepath.includes('/') || filepath.includes('\\')) {
// Distinguish scoped package names from paths starting with '@'.
// Scoped packages: @scope/name (exactly 2 parts, no backslashes).
// Paths: @scope/name/subpath (3+ parts) or @scope\name (Windows backslash).
// Special case: '@/' is a valid path (already handled by separator check).
if (filepath.startsWith('@') && !filepath.startsWith('@/')) {
const parts = filepath.split('/')
// If exactly @scope/name with no Windows separators, it's a package name.
if (parts.length <= 2 && !parts[1]?.includes('\\')) {
return false
}
}
return true
}
// Bare names without separators are package names, not paths.
return false
}
/**
* Check if a path is relative.
*
* Determines whether a given path is relative (i.e., not absolute). A path
* is considered relative if it does not specify a location from the root of
* the file system.
*
* Relative paths include:
* - Paths starting with `.` or `..` (e.g., `./src`, `../lib`)
* - Paths without leading separators (e.g., `src/file.js`)
* - Empty strings (treated as relative)
*
* @param {string | Buffer | URL} pathLike - The path to check
* @returns {boolean} `true` if the path is relative, `false` if absolute
*
* @example
* ```typescript
* // Relative paths
* isRelative('./src/index.js') // true
* isRelative('../lib/util.js') // true
* isRelative('src/file.js') // true
* isRelative('') // true
*
* // Absolute paths
* isRelative('/home/user') // false
* isRelative('C:\\Windows') // false (Windows)
* isRelative('\\\\server\\share') // false (Windows UNC)
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isRelative(pathLike: string | Buffer | URL): boolean {
const filepath = pathLikeToString(pathLike)
if (typeof filepath !== 'string') {
return false
}
// Empty string is considered relative.
if (filepath.length === 0) {
return true
}
// A path is relative if it's not absolute.
return !isAbsolute(filepath)
}
/**
* Convert Unix-style POSIX paths (MSYS/Git Bash format) back to native Windows paths.
*
* This is the inverse of {@link toUnixPath}. MSYS-style paths use `/c/` notation
* for drive letters, which PowerShell and cmd.exe cannot resolve. This function
* converts them back to native Windows format.
*
* Conversion rules:
* - On Windows: Converts Unix drive notation to Windows drive letters
* - `/c/path/to/file` becomes `C:/path/to/file`
* - `/d/projects/app` becomes `D:/projects/app`
* - Drive letters are always uppercase in the output
* - On Unix: Returns the path unchanged (passes through normalization)
*
* This is particularly important for:
* - GitHub Actions runners where `command -v` returns MSYS paths
* - Tools like sfw that need to resolve real binary paths on Windows
* - Scripts that receive paths from Git Bash but need to pass them to native Windows tools
*
* @param {string | Buffer | URL} pathLike - The MSYS/Unix-style path to convert
* @returns {string} Native Windows path (e.g., `C:/path/to/file`) or normalized Unix path
*
* @example
* ```typescript
* // MSYS drive letter paths
* fromUnixPath('/c/projects/app/file.txt') // 'C:/projects/app/file.txt'
* fromUnixPath('/d/projects/foo/bar') // 'D:/projects/foo/bar'
*
* // Non-drive Unix paths (unchanged)
* fromUnixPath('/tmp/build/output') // '/tmp/build/output'
* fromUnixPath('/usr/local/bin') // '/usr/local/bin'
*
* // Already Windows paths (unchanged)
* fromUnixPath('C:/Windows/System32') // 'C:/Windows/System32'
*
* // Edge cases
* fromUnixPath('/c') // 'C:/'
* fromUnixPath('') // '.'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function fromUnixPath(pathLike: string | Buffer | URL): string {
const normalized = normalizePath(pathLike)
// On Windows, convert MSYS drive notation back to native: /c/path → C:/path
if (WIN32) {
return normalized.replace(
/^\/([a-zA-Z])(\/|$)/,
(_, letter, sep) => `${letter.toUpperCase()}:${sep || '/'}`,
)
}
// On Unix, just return the normalized path
return normalized
}
/**
* Normalize a path by converting backslashes to forward slashes and collapsing segments.
*
* This function performs several normalization operations:
* - Converts all backslashes (`\`) to forward slashes (`/`)
* - Collapses repeated slashes into single slashes
* - Resolves `.` (current directory) segments
* - Resolves `..` (parent directory) segments
* - Preserves UNC path prefixes (`//server/share`)
* - Preserves Windows namespace prefixes (`//./`, `//?/`)
* - Returns `.` for empty or collapsed paths
*
* Special handling:
* - UNC paths: Maintains double leading slashes for `//server/share` format
* - Windows namespaces: Preserves `//./` and `//?/` prefixes
* - Leading `..` segments: Preserved in relative paths without prefix
* - Trailing components: Properly handled when resolving `..`
*
* @param {string | Buffer | URL} pathLike - The path to normalize
* @returns {string} The normalized path with forward slashes and collapsed segments
*
* @security
* **WARNING**: This function resolves `..` patterns as part of normalization, which means
* paths like `/../etc/passwd` become `/etc/passwd`. When processing untrusted user input
* (HTTP requests, file uploads, URL parameters), you MUST validate for path traversal
* attacks BEFORE calling this function. Check for patterns like `..`, `%2e%2e`, `\..`,
* and other traversal encodings first.
*
* @example
* ```typescript
* // Basic normalization
* normalizePath('foo/bar//baz') // 'foo/bar/baz'
* normalizePath('foo/./bar') // 'foo/bar'
* normalizePath('foo/bar/../baz') // 'foo/baz'
*
* // Windows paths
* normalizePath('C:\\Users\\username\\file.txt') // 'C:/Users/username/file.txt'
* normalizePath('foo\\bar\\baz') // 'foo/bar/baz'
*
* // UNC paths
* normalizePath('\\\\server\\share\\file') // '//server/share/file'
*
* // Edge cases
* normalizePath('') // '.'
* normalizePath('.') // '.'
* normalizePath('..') // '..'
* normalizePath('///foo///bar///') // '/foo/bar'
* normalizePath('foo/../..') // '..'
*
* // Security: Path traversal is resolved (intended behavior for trusted paths)
* normalizePath('/../etc/passwd') // '/etc/passwd' ⚠️
* normalizePath('/safe/../../unsafe') // '/unsafe' ⚠️
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function normalizePath(pathLike: string | Buffer | URL): string {
const filepath = pathLikeToString(pathLike)
const { length } = filepath
if (length === 0) {
return '.'
}
if (length < 2) {
return length === 1 && filepath.charCodeAt(0) === 92 /*'\\'*/
? '/'
: filepath
}
let code = 0
let start = 0
// Ensure win32 namespaces have two leading slashes so they are handled properly
// by path.win32.parse() after being normalized.
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#namespaces
// UNC paths, paths starting with double slashes, e.g. "\\\\wsl.localhost\\Ubuntu\home\\",
// are okay to convert to forward slashes.
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
let prefix = ''
if (length > 4 && filepath.charCodeAt(3) === 92 /*'\\'*/) {
const code2 = filepath.charCodeAt(2)
// Look for \\?\ or \\.\
if (
(code2 === 63 /*'?'*/ || code2 === 46) /*'.'*/ &&
filepath.charCodeAt(0) === 92 /*'\\'*/ &&
filepath.charCodeAt(1) === 92 /*'\\'*/
) {
start = 2
prefix = '//'
}
}
if (start === 0) {
// Check for UNC paths first (\\server\share or //server/share)
// UNC paths must start with exactly two slashes, not more
if (
length > 2 &&
((filepath.charCodeAt(0) === 92 /*'\\'*/ &&
filepath.charCodeAt(1) === 92 /*'\\'*/ &&
filepath.charCodeAt(2) !== 92) /*'\\'*/ ||
(filepath.charCodeAt(0) === 47 /*'/'*/ &&
filepath.charCodeAt(1) === 47 /*'/'*/ &&
filepath.charCodeAt(2) !== 47)) /*'/'*/
) {
// Check if this is a valid UNC path: must have server/share format
// Find the first segment (server name) and second segment (share name)
let firstSegmentEnd = -1
let hasSecondSegment = false
// Skip leading slashes after the initial double slash
let i = 2
while (
i < length &&
(filepath.charCodeAt(i) === 47 /*'/'*/ ||
filepath.charCodeAt(i) === 92) /*'\\'*/
) {
i++
}
// Find the end of first segment (server name)
while (i < length) {
const char = filepath.charCodeAt(i)
if (char === 47 /*'/'*/ || char === 92 /*'\\'*/) {
firstSegmentEnd = i
break
}
i++
}
if (firstSegmentEnd > 2) {
// Skip slashes after server name
i = firstSegmentEnd
while (
i < length &&
(filepath.charCodeAt(i) === 47 /*'/'*/ ||
filepath.charCodeAt(i) === 92) /*'\\'*/
) {
i++
}
// Check if there's a share name (second segment)
if (i < length) {
hasSecondSegment = true
}
}
if (firstSegmentEnd > 2 && hasSecondSegment) {
// Valid UNC path - preserve double leading slashes
start = 2
prefix = '//'
} else {
// Just repeated slashes, treat as regular path
code = filepath.charCodeAt(start)
while (code === 47 /*'/'*/ || code === 92 /*'\\'*/) {
start += 1
code = filepath.charCodeAt(start)
}
if (start) {
prefix = '/'
}
}
} else {
// Trim leading slashes for regular paths
code = filepath.charCodeAt(start)
while (code === 47 /*'/'*/ || code === 92 /*'\\'*/) {
start += 1
code = filepath.charCodeAt(start)
}
if (start) {
prefix = '/'
}
}
}
let nextIndex = search(filepath, slashRegExp, { fromIndex: start })
if (nextIndex === -1) {
const segment = filepath.slice(start)
if (segment === '.' || segment.length === 0) {
return prefix || '.'
}
if (segment === '..') {
return prefix ? prefix.slice(0, -1) || '/' : '..'
}
return prefix + segment
}
// Process segments and handle '.', '..', and empty segments.
let collapsed = ''
let segmentCount = 0
let leadingDotDots = 0
while (nextIndex !== -1) {
const segment = filepath.slice(start, nextIndex)
if (segment.length > 0 && segment !== '.') {
if (segment === '..') {
// Handle '..' by removing the last segment if possible.
if (segmentCount > 0) {
// Find the last separator and remove the last segment.
const lastSeparatorIndex = collapsed.lastIndexOf('/')
if (lastSeparatorIndex === -1) {
// Only one segment, remove it entirely.
collapsed = ''
segmentCount = 0
// Check if this was a leading '..', restore it.
if (leadingDotDots > 0 && !prefix) {
collapsed = '..'
leadingDotDots = 1
}
} else {
const lastSegmentStart = lastSeparatorIndex + 1
const lastSegmentValue = collapsed.slice(lastSegmentStart)
// Don't collapse leading '..' segments.
if (lastSegmentValue === '..') {
// Preserve the '..' and add another one.
collapsed = `${collapsed}/${segment}`
leadingDotDots += 1
} else {
// Normal collapse: remove the last segment.
collapsed = collapsed.slice(0, lastSeparatorIndex)
segmentCount -= 1
}
}
} else if (!prefix) {
// Preserve '..' for relative paths.
collapsed = collapsed + (collapsed.length === 0 ? '' : '/') + segment
leadingDotDots += 1
}
} else {
collapsed = collapsed + (collapsed.length === 0 ? '' : '/') + segment
segmentCount += 1
}
}
start = nextIndex + 1
code = filepath.charCodeAt(start)
while (code === 47 /*'/'*/ || code === 92 /*'\\'*/) {
start += 1
code = filepath.charCodeAt(start)
}
nextIndex = search(filepath, slashRegExp, { fromIndex: start })
}
const lastSegment = filepath.slice(start)
if (lastSegment.length > 0 && lastSegment !== '.') {
if (lastSegment === '..') {
if (segmentCount > 0) {
const lastSeparatorIndex = collapsed.lastIndexOf('/')
if (lastSeparatorIndex === -1) {
collapsed = ''
segmentCount = 0
// Check if this was a leading '..', restore it.
if (leadingDotDots > 0 && !prefix) {
collapsed = '..'
leadingDotDots = 1
}
} else {
const lastSegmentStart = lastSeparatorIndex + 1
const lastSegmentValue = collapsed.slice(lastSegmentStart)
// Don't collapse leading '..' segments.
if (lastSegmentValue === '..') {
// Preserve the '..' and add another one.
collapsed = `${collapsed}/${lastSegment}`
leadingDotDots += 1
} else {
// Normal collapse: remove the last segment.
collapsed = collapsed.slice(0, lastSeparatorIndex)
segmentCount -= 1
}
}
} else if (!prefix) {
collapsed =
collapsed + (collapsed.length === 0 ? '' : '/') + lastSegment
leadingDotDots += 1
}
} else {
collapsed = collapsed + (collapsed.length === 0 ? '' : '/') + lastSegment
segmentCount += 1
}
}
if (collapsed.length === 0) {
return prefix || '.'
}
return prefix + collapsed
}
/**
* Convert a path-like value to a string.
*
* Converts various path-like types (string, Buffer, URL) into a normalized
* string representation. This function handles different input formats and
* provides consistent string output for path operations.
*
* Supported input types:
* - `string`: Returned as-is
* - `Buffer`: Decoded as UTF-8 string
* - `URL`: Converted using `fileURLToPath()`, with fallback for malformed URLs
* - `null` / `undefined`: Returns empty string
*
* URL handling:
* - Valid file URLs are converted via `url.fileURLToPath()`
* - Malformed URLs fall back to pathname extraction with decoding
* - Windows drive letters in URLs are handled specially
* - Percent-encoded characters are decoded (e.g., `%20` becomes space)
*
* @param {string | Buffer | URL | null | undefined} pathLike - The path-like value to convert
* @returns {string} The string representation of the path, or empty string for null/undefined
*
* @example
* ```typescript
* // String input
* pathLikeToString('/home/user') // '/home/user'
*
* // Buffer input
* pathLikeToString(Buffer.from('/tmp/file')) // '/tmp/file'
*
* // URL input
* pathLikeToString(new URL('file:///home/user')) // '/home/user'
* pathLikeToString(new URL('file:///C:/Windows')) // 'C:/Windows' (Windows)
*
* // Null/undefined input
* pathLikeToString(null) // ''
* pathLikeToString(undefined) // ''
*
* // Percent-encoded URLs
* pathLikeToString(new URL('file:///path%20with%20spaces')) // '/path with spaces'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function pathLikeToString(
pathLike: string | Buffer | URL | null | undefined,
): string {
if (pathLike === null || pathLike === undefined) {
return ''
}
if (typeof pathLike === 'string') {
return pathLike
}
const { Buffer } = getBuffer()
if (Buffer.isBuffer(pathLike)) {
return pathLike.toString('utf8')
}
const url = getUrl()
if (pathLike instanceof URL) {
try {
return url.fileURLToPath(pathLike)
} catch {
// On Windows, file URLs like `file:///C:/path` include drive letters.
// If a file URL is missing its drive letter (malformed), fileURLToPath() throws an error.
// This fallback extracts the pathname directly from the URL object.
//
// Example flows:
// - Unix: file:///home/user → pathname '/home/user' → keep as-is
// - Windows valid: file:///C:/path → handled by fileURLToPath()
// - Windows invalid: file:///path → pathname '/path' → strips to 'path'
const pathname = pathLike.pathname
// Decode percent-encoded characters (e.g., %20 → space).
// The pathname property keeps URL encoding, but file paths need decoded characters.
// This is not platform-specific; all URLs use percent-encoding regardless of OS.
const decodedPathname = decodeURIComponent(pathname)
// URL pathnames always start with `/`.
// On Windows, strip the leading slash only for malformed URLs that lack drive letters
// (e.g., `/path` should be `path`, but `/C:/path` should be `C:/path`).
// On Unix, keep the leading slash for absolute paths (e.g., `/home/user`).
if (WIN32 && decodedPathname.startsWith('/')) {
// Check for drive letter pattern following Node.js source: /[a-zA-Z]:/
// Character at index 1 should be a letter, character at index 2 should be ':'
// Convert to lowercase
const letter = decodedPathname.charCodeAt(1) | 0x20
const hasValidDriveLetter =
decodedPathname.length >= 3 &&
letter >= 97 &&
// 'a' to 'z'
letter <= 122 &&
decodedPathname.charAt(2) === ':'
if (!hasValidDriveLetter) {
// On Windows, preserve Unix-style absolute paths that don't start with a drive letter.
// Only strip the leading slash for truly malformed Windows paths.
// Since fileURLToPath() failed, this is likely a valid Unix-style absolute path.
return decodedPathname
}
}
return decodedPathname
}
}
return String(pathLike)
}
/**
* Split a path into an array of segments.
*
* Divides a path into individual components by splitting on path separators
* (both forward slashes and backslashes). This is useful for path traversal,
* analysis, and manipulation.
*
* The function handles:
* - Forward slashes (`/`) on all platforms
* - Backslashes (`\`) on Windows
* - Mixed separators in a single path
* - Empty paths (returns empty array)
*
* Note: The resulting array may contain empty strings if the path has leading,
* trailing, or consecutive separators (e.g., `/foo//bar/` becomes `['', 'foo', '', 'bar', '']`).
*
* @param {string | Buffer | URL} pathLike - The path to split
* @returns {string[]} Array of path segments, or empty array for empty paths
*
* @example
* ```typescript
* // POSIX paths
* splitPath('/home/user/file.txt') // ['', 'home', 'user', 'file.txt']
* splitPath('src/lib/util.js') // ['src', 'lib', 'util.js']
*
* // Windows paths
* splitPath('C:\\Users\\John') // ['C:', 'Users', 'John']
* splitPath('folder\\file.txt') // ['folder', 'file.txt']
*
* // Mixed separators
* splitPath('path/to\\file') // ['path', 'to', 'file']
*
* // Edge cases
* splitPath('') // []
* splitPath('/') // ['', '']
* splitPath('/foo//bar/') // ['', 'foo', '', 'bar', '']
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function splitPath(pathLike: string | Buffer | URL): string[] {
const filepath = pathLikeToString(pathLike)
if (filepath === '') {
return []
}
return filepath.split(slashRegExp)
}
/**
* Remove leading ./ or ../ from a path.
*
* Strips the `./` or `.\` prefix from relative paths. This is useful for
* normalizing paths when the current directory reference is implicit or
* unwanted.
*
* Note: This function only removes a single leading `./` or `.\`. It does
* not remove `../` prefixes or process the rest of the path.
*
* @param {string | Buffer | URL} pathLike - The path to process
* @returns {string} The path without leading `./` or `.\`, or unchanged if no such prefix
*
* @example
* ```typescript
* // Remove ./ prefix
* trimLeadingDotSlash('./src/index.js') // 'src/index.js'
* trimLeadingDotSlash('.\\src\\file.txt') // 'src\\file.txt'
*
* // Preserve ../ prefix
* trimLeadingDotSlash('../lib/util.js') // '../lib/util.js'
*
* // No change for other paths
* trimLeadingDotSlash('/absolute/path') // '/absolute/path'
* trimLeadingDotSlash('relative/path') // 'relative/path'
* trimLeadingDotSlash('.') // '.'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function trimLeadingDotSlash(pathLike: string | Buffer | URL): string {
const filepath = pathLikeToString(pathLike)
// Only trim ./ not ../
if (filepath.startsWith('./') || filepath.startsWith('.\\')) {
return filepath.slice(2)
}
return filepath
}
/**
* Resolve an absolute path from path segments.
*
* This function mimics Node.js `path.resolve()` behavior by building an
* absolute path from the given segments. It processes segments from right
* to left, stopping when an absolute path is encountered. If no absolute
* path is found, it prepends the current working directory.
*
* Algorithm:
* 1. Process segments from right to left
* 2. Stop when an absolute path is found
* 3. Prepend current working directory if no absolute path found
* 4. Normalize the final path
*
* Key behaviors:
* - Later segments override earlier ones (e.g., `resolve('/foo', '/bar')` returns `/bar`)
* - Empty or non-string segments are skipped
* - Result is always an absolute path
* - Path separators are normalized to forward slashes
*
* @param {...string} segments - Path segments to resolve
* @returns {string} The resolved absolute path
*
* @example
* ```typescript
* // Basic resolution
* resolve('foo', 'bar', 'baz') // '/cwd/foo/bar/baz' (assuming cwd is '/cwd')
* resolve('/foo', 'bar', 'baz') // '/foo/bar/baz'
* resolve('foo', '/bar', 'baz') // '/bar/baz'
*
* // Windows paths
* resolve('C:\\foo', 'bar') // 'C:/foo/bar'
*
* // Empty segments
* resolve('foo', '', 'bar') // '/cwd/foo/bar'
* resolve() // '/cwd' (current directory)
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
function resolve(...segments: string[]): string {
let resolvedPath = ''
let resolvedAbsolute = false
// Process segments from right to left until we find an absolute path.
// This allows later segments to override earlier ones.
// Example: resolve('/foo', '/bar') returns '/bar', not '/foo/bar'.
for (let i = segments.length - 1; i >= 0 && !resolvedAbsolute; i -= 1) {
const segment = segments[i]
// Skip empty or non-string segments.
if (typeof segment !== 'string' || segment.length === 0) {
continue
}
// Prepend the segment to the resolved path.
// Use forward slashes as separators (normalized later).
resolvedPath =
segment + (resolvedPath.length === 0 ? '' : `/${resolvedPath}`)
// Check if this segment is absolute.
// Absolute paths stop the resolution process.
resolvedAbsolute = isAbsolute(segment)
}
// If no absolute path was found in segments, prepend current working directory.
// This ensures the final path is always absolute.
if (!resolvedAbsolute) {
const cwd = /*@__PURE__*/ require('process').cwd()
resolvedPath = cwd + (resolvedPath.length === 0 ? '' : `/${resolvedPath}`)
}
// Normalize the resolved path (collapse '..' and '.', convert separators).
return normalizePath(resolvedPath)
}
/**
* Calculate the relative path from one path to another.
*
* This function computes how to get from the `from` path to the `to` path
* using relative path notation. Both paths are first resolved to absolute
* paths, then compared to find the common base path, and finally a relative
* path is constructed using `../` for parent directory traversal.
*
* Algorithm:
* 1. Resolve both paths to absolute
* 2. Find the longest common path prefix (up to a separator)
* 3. For each remaining directory in `from`, add `../` to go up
* 4. Append the remaining path from `to`
*
* Windows-specific behavior:
* - File system paths are case-insensitive on Windows (NTFS, FAT32)
* - `C:\Foo` and `c:\foo` are considered the same path
* - Reference: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
* - Case is preserved but not significant for comparison
*
* @param {string} from - The source path (starting point)
* @param {string} to - The destination path (target)
* @returns {string} The relative path from `from` to `to`, or empty string if paths are identical
*
* @example
* ```typescript
* // Basic relative paths
* relative('/foo/bar', '/foo/baz') // '../baz'
* relative('/foo/bar/baz', '/foo') // '../..'
* relative('/foo', '/foo/bar') // 'bar'
*
* // Same paths
* relative('/foo/bar', '/foo/bar') // ''
*
* // Windows case-insensitive
* relative('C:\\Foo\\bar', 'C:\\foo\\baz') // '../baz' (Windows)
*
* // Root paths
* relative('/', '/foo/bar') // 'foo/bar'
* relative('/foo/bar', '/') // '../..'
* ```
*/