-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
fsUtils.ts
431 lines (403 loc) · 12.4 KB
/
fsUtils.ts
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
import fs from 'node:fs'
import path from 'node:path'
import type { FSWatcher } from 'dep-types/chokidar'
import type { ResolvedConfig } from './config'
import {
isInNodeModules,
normalizePath,
safeRealpathSync,
tryStatSync,
} from './utils'
export interface FsUtils {
existsSync: (path: string) => boolean
isDirectory: (path: string) => boolean
tryResolveRealFile: (
path: string,
preserveSymlinks?: boolean,
) => string | undefined
tryResolveRealFileWithExtensions: (
path: string,
extensions: string[],
preserveSymlinks?: boolean,
) => string | undefined
tryResolveRealFileOrType: (
path: string,
preserveSymlinks?: boolean,
) => { path?: string; type: 'directory' | 'file' } | undefined
initWatcher?: (watcher: FSWatcher) => void
}
// An implementation of fsUtils without caching
export const commonFsUtils: FsUtils = {
existsSync: fs.existsSync,
isDirectory,
tryResolveRealFile,
tryResolveRealFileWithExtensions,
tryResolveRealFileOrType,
}
const cachedFsUtilsMap = new WeakMap<ResolvedConfig, FsUtils>()
export function getFsUtils(config: ResolvedConfig): FsUtils {
let fsUtils = cachedFsUtilsMap.get(config)
if (!fsUtils) {
if (
config.command !== 'serve' ||
config.server.fs.cachedChecks === false ||
config.server.watch?.ignored ||
process.versions.pnp
) {
// cached fsUtils is only used in the dev server for now
// it is enabled by default only when there aren't custom watcher ignored patterns configured
// and if yarn pnp isn't used
fsUtils = commonFsUtils
} else if (
!config.resolve.preserveSymlinks &&
config.root !== getRealPath(config.root)
) {
fsUtils = commonFsUtils
} else {
fsUtils = createCachedFsUtils(config)
}
cachedFsUtilsMap.set(config, fsUtils)
}
return fsUtils
}
type DirentsMap = Map<string, DirentCache>
type DirentCacheType =
| 'directory'
| 'file'
| 'symlink'
| 'error'
| 'directory_maybe_symlink'
| 'file_maybe_symlink'
interface DirentCache {
dirents?: DirentsMap
type: DirentCacheType
}
function readDirCacheSync(file: string): undefined | DirentsMap {
let dirents: fs.Dirent[]
try {
dirents = fs.readdirSync(file, { withFileTypes: true })
} catch {
return
}
return direntsToDirentMap(dirents)
}
function direntsToDirentMap(fsDirents: fs.Dirent[]): DirentsMap {
const dirents: DirentsMap = new Map()
for (const dirent of fsDirents) {
// We ignore non directory, file, and symlink entries
const type = dirent.isDirectory()
? 'directory'
: dirent.isSymbolicLink()
? 'symlink'
: dirent.isFile()
? 'file'
: undefined
if (type) {
dirents.set(dirent.name, { type })
}
}
return dirents
}
function ensureFileMaybeSymlinkIsResolved(
direntCache: DirentCache,
filePath: string,
) {
if (direntCache.type !== 'file_maybe_symlink') return
const isSymlink = fs
.lstatSync(filePath, { throwIfNoEntry: false })
?.isSymbolicLink()
direntCache.type =
isSymlink === undefined ? 'error' : isSymlink ? 'symlink' : 'file'
}
function pathUntilPart(root: string, parts: string[], i: number): string {
let p = root
for (let k = 0; k < i; k++) p += '/' + parts[k]
return p
}
export function createCachedFsUtils(config: ResolvedConfig): FsUtils {
const root = config.root // root is resolved and normalized, so it doesn't have a trailing slash
const rootDirPath = `${root}/`
const rootCache: DirentCache = { type: 'directory' } // dirents will be computed lazily
const getDirentCacheSync = (parts: string[]): DirentCache | undefined => {
let direntCache: DirentCache = rootCache
for (let i = 0; i < parts.length; i++) {
if (direntCache.type === 'directory') {
let dirPath
if (!direntCache.dirents) {
dirPath = pathUntilPart(root, parts, i)
const dirents = readDirCacheSync(dirPath)
if (!dirents) {
direntCache.type = 'error'
return
}
direntCache.dirents = dirents
}
const nextDirentCache = direntCache.dirents!.get(parts[i])
if (!nextDirentCache) {
return
}
if (nextDirentCache.type === 'directory_maybe_symlink') {
dirPath ??= pathUntilPart(root, parts, i + 1)
const isSymlink = fs
.lstatSync(dirPath, { throwIfNoEntry: false })
?.isSymbolicLink()
nextDirentCache.type = isSymlink ? 'symlink' : 'directory'
}
direntCache = nextDirentCache
} else if (direntCache.type === 'symlink') {
// early return if we encounter a symlink
return direntCache
} else if (direntCache.type === 'error') {
return direntCache
} else {
if (i !== parts.length - 1) {
return
}
if (direntCache.type === 'file_maybe_symlink') {
ensureFileMaybeSymlinkIsResolved(
direntCache,
pathUntilPart(root, parts, i),
)
return direntCache
} else if (direntCache.type === 'file') {
return direntCache
} else {
return
}
}
}
return direntCache
}
function getDirentCacheFromPath(
normalizedFile: string,
): DirentCache | false | undefined {
// path.posix.normalize may return a path either with / or without /
if (normalizedFile[normalizedFile.length - 1] === '/') {
normalizedFile = normalizedFile.slice(0, -1)
}
if (normalizedFile === root) {
return rootCache
}
if (!normalizedFile.startsWith(rootDirPath)) {
return undefined
}
const pathFromRoot = normalizedFile.slice(rootDirPath.length)
const parts = pathFromRoot.split('/')
const direntCache = getDirentCacheSync(parts)
if (!direntCache || direntCache.type === 'error') {
return false
}
return direntCache
}
function onPathAdd(
file: string,
type: 'directory_maybe_symlink' | 'file_maybe_symlink',
) {
const direntCache = getDirentCacheFromPath(
normalizePath(path.dirname(file)),
)
if (
direntCache &&
direntCache.type === 'directory' &&
direntCache.dirents
) {
direntCache.dirents.set(path.basename(file), { type })
}
}
function onPathUnlink(file: string) {
const direntCache = getDirentCacheFromPath(
normalizePath(path.dirname(file)),
)
if (
direntCache &&
direntCache.type === 'directory' &&
direntCache.dirents
) {
direntCache.dirents.delete(path.basename(file))
}
}
return {
existsSync(file: string) {
if (isInNodeModules(file)) {
return fs.existsSync(file)
}
const normalizedFile = normalizePath(file)
const direntCache = getDirentCacheFromPath(normalizedFile)
if (
direntCache === undefined ||
(direntCache && direntCache.type === 'symlink')
) {
// fallback to built-in fs for out-of-root and symlinked files
return fs.existsSync(file)
}
return !!direntCache
},
tryResolveRealFile(
file: string,
preserveSymlinks?: boolean,
): string | undefined {
if (isInNodeModules(file)) {
return tryResolveRealFile(file, preserveSymlinks)
}
const normalizedFile = normalizePath(file)
const direntCache = getDirentCacheFromPath(normalizedFile)
if (
direntCache === undefined ||
(direntCache && direntCache.type === 'symlink')
) {
// fallback to built-in fs for out-of-root and symlinked files
return tryResolveRealFile(file, preserveSymlinks)
}
if (!direntCache || direntCache.type === 'directory') {
return
}
// We can avoid getRealPath even if preserveSymlinks is false because we know it's
// a file without symlinks in its path
return normalizedFile
},
tryResolveRealFileWithExtensions(
file: string,
extensions: string[],
preserveSymlinks?: boolean,
): string | undefined {
if (isInNodeModules(file)) {
return tryResolveRealFileWithExtensions(
file,
extensions,
preserveSymlinks,
)
}
const normalizedFile = normalizePath(file)
const dirPath = path.posix.dirname(normalizedFile)
const direntCache = getDirentCacheFromPath(dirPath)
if (
direntCache === undefined ||
(direntCache && direntCache.type === 'symlink')
) {
// fallback to built-in fs for out-of-root and symlinked files
return tryResolveRealFileWithExtensions(
file,
extensions,
preserveSymlinks,
)
}
if (!direntCache || direntCache.type !== 'directory') {
return
}
if (!direntCache.dirents) {
const dirents = readDirCacheSync(dirPath)
if (!dirents) {
direntCache.type = 'error'
return
}
direntCache.dirents = dirents
}
const base = path.posix.basename(normalizedFile)
for (const ext of extensions) {
const fileName = base + ext
const fileDirentCache = direntCache.dirents.get(fileName)
if (fileDirentCache) {
const filePath = dirPath + '/' + fileName
ensureFileMaybeSymlinkIsResolved(fileDirentCache, filePath)
if (fileDirentCache.type === 'symlink') {
// fallback to built-in fs for symlinked files
return tryResolveRealFile(filePath, preserveSymlinks)
}
if (fileDirentCache.type === 'file') {
return filePath
}
}
}
},
tryResolveRealFileOrType(
file: string,
preserveSymlinks?: boolean,
): { path?: string; type: 'directory' | 'file' } | undefined {
if (isInNodeModules(file)) {
return tryResolveRealFileOrType(file, preserveSymlinks)
}
const normalizedFile = normalizePath(file)
const direntCache = getDirentCacheFromPath(normalizedFile)
if (
direntCache === undefined ||
(direntCache && direntCache.type === 'symlink')
) {
// fallback to built-in fs for out-of-root and symlinked files
return tryResolveRealFileOrType(file, preserveSymlinks)
}
if (!direntCache) {
return
}
if (direntCache.type === 'directory') {
return { type: 'directory' }
}
// We can avoid getRealPath even if preserveSymlinks is false because we know it's
// a file without symlinks in its path
return { path: normalizedFile, type: 'file' }
},
isDirectory(dirPath: string) {
if (isInNodeModules(dirPath)) {
return isDirectory(dirPath)
}
const direntCache = getDirentCacheFromPath(normalizePath(dirPath))
if (
direntCache === undefined ||
(direntCache && direntCache.type === 'symlink')
) {
// fallback to built-in fs for out-of-root and symlinked files
return isDirectory(dirPath)
}
return direntCache && direntCache.type === 'directory'
},
initWatcher(watcher: FSWatcher) {
watcher.on('add', (file) => {
onPathAdd(file, 'file_maybe_symlink')
})
watcher.on('addDir', (dir) => {
onPathAdd(dir, 'directory_maybe_symlink')
})
watcher.on('unlink', onPathUnlink)
watcher.on('unlinkDir', onPathUnlink)
},
}
}
function tryResolveRealFile(
file: string,
preserveSymlinks?: boolean,
): string | undefined {
const stat = tryStatSync(file)
if (stat?.isFile()) return getRealPath(file, preserveSymlinks)
}
function tryResolveRealFileWithExtensions(
filePath: string,
extensions: string[],
preserveSymlinks?: boolean,
): string | undefined {
for (const ext of extensions) {
const res = tryResolveRealFile(filePath + ext, preserveSymlinks)
if (res) return res
}
}
function tryResolveRealFileOrType(
file: string,
preserveSymlinks?: boolean,
): { path?: string; type: 'directory' | 'file' } | undefined {
const fileStat = tryStatSync(file)
if (fileStat?.isFile()) {
return { path: getRealPath(file, preserveSymlinks), type: 'file' }
}
if (fileStat?.isDirectory()) {
return { type: 'directory' }
}
return
}
function getRealPath(resolved: string, preserveSymlinks?: boolean): string {
if (!preserveSymlinks) {
resolved = safeRealpathSync(resolved)
}
return normalizePath(resolved)
}
function isDirectory(path: string): boolean {
const stat = tryStatSync(path)
return stat?.isDirectory() ?? false
}