-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
utils.ts
265 lines (226 loc) · 6.89 KB
/
utils.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
import { fileURLToPath, pathToFileURL } from 'node:url'
import { builtinModules } from 'node:module'
import { existsSync, promises as fsp } from 'node:fs'
import { dirname, join, resolve } from 'pathe'
import type { Arrayable, Nullable } from './types'
export const isWindows = process.platform === 'win32'
const drive = isWindows ? process.cwd()[0] : null
const driveOpposite = drive
? (drive === drive.toUpperCase()
? drive.toLowerCase()
: drive.toUpperCase())
: null
const driveRegexp = drive ? new RegExp(`(?:^|/@fs/)${drive}(\:[\\/])`) : null
const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(\:[\\/])`) : null
export function slash(str: string) {
return str.replace(/\\/g, '/')
}
export const VALID_ID_PREFIX = '/@id/'
export function normalizeRequestId(id: string, base?: string): string {
if (base && id.startsWith(withTrailingSlash(base)))
id = `/${id.slice(base.length)}`
// keep drive the same as in process cwd
if (driveRegexp && !driveRegexp?.test(id) && driveOppositeRegext?.test(id))
id = id.replace(driveOppositeRegext, `${drive}$1`)
return id
.replace(/^\/@id\/__x00__/, '\0') // virtual modules start with `\0`
.replace(/^\/@id\//, '')
.replace(/^__vite-browser-external:/, '')
.replace(/^file:/, '')
.replace(/^\/+/, '/') // remove duplicate leading slashes
.replace(/\?v=\w+/, '?') // remove ?v= query
.replace(/&v=\w+/, '') // remove &v= query
.replace(/\?t=\w+/, '?') // remove ?t= query
.replace(/&t=\w+/, '') // remove &t= query
.replace(/\?import/, '?') // remove ?import query
.replace(/&import/, '') // remove &import query
.replace(/\?&/, '?') // replace ?& with just ?
.replace(/\?+$/, '') // remove end query mark
}
export const queryRE = /\?.*$/s
export const hashRE = /#.*$/s
export function cleanUrl(url: string): string {
return url.replace(hashRE, '').replace(queryRE, '')
}
const internalRequests = [
'@vite/client',
'@vite/env',
]
const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join('|')})$`)
export function isInternalRequest(id: string): boolean {
return internalRequestRegexp.test(id)
}
const prefixedBuiltins = new Set([
'node:test',
])
const builtins = new Set([
...builtinModules,
'assert/strict',
'diagnostics_channel',
'dns/promises',
'fs/promises',
'path/posix',
'path/win32',
'readline/promises',
'stream/consumers',
'stream/promises',
'stream/web',
'timers/promises',
'util/types',
'wasi',
])
export function normalizeModuleId(id: string) {
// unique id that is not available as "test"
if (prefixedBuiltins.has(id))
return id
return id
.replace(/\\/g, '/')
.replace(/^\/@fs\//, isWindows ? '' : '/')
.replace(/^file:\//, '/')
.replace(/^node:/, '')
.replace(/^\/+/, '/')
}
export function isPrimitive(v: any) {
return v !== Object(v)
}
export function toFilePath(id: string, root: string): { path: string; exists: boolean } {
let { absolute, exists } = (() => {
if (id.startsWith('/@fs/'))
return { absolute: id.slice(4), exists: true }
// check if /src/module.js -> <root>/src/module.js
if (!id.startsWith(withTrailingSlash(root)) && id.startsWith('/')) {
const resolved = resolve(root, id.slice(1))
if (existsSync(cleanUrl(resolved)))
return { absolute: resolved, exists: true }
}
else if (id.startsWith(withTrailingSlash(root)) && existsSync(cleanUrl(id))) {
return { absolute: id, exists: true }
}
return { absolute: id, exists: false }
})()
if (absolute.startsWith('//'))
absolute = absolute.slice(1)
// disambiguate the `<UNIT>:/` on windows: see nodejs/node#31710
return {
path: (isWindows && absolute.startsWith('/'))
? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href))
: absolute,
exists,
}
}
const NODE_BUILTIN_NAMESPACE = 'node:'
export function isNodeBuiltin(id: string): boolean {
if (prefixedBuiltins.has(id))
return true
return builtins.has(
id.startsWith(NODE_BUILTIN_NAMESPACE)
? id.slice(NODE_BUILTIN_NAMESPACE.length)
: id,
)
}
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
export function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T> {
if (array === null || array === undefined)
array = []
if (Array.isArray(array))
return array
return [array]
}
export function getCachedData<T>(
cache: Map<string, T>,
basedir: string,
originalBasedir: string,
) {
const pkgData = cache.get(getFnpdCacheKey(basedir))
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), pkgData)
})
return pkgData
}
}
export function setCacheData<T>(
cache: Map<string, T>,
data: T,
basedir: string,
originalBasedir: string,
) {
cache.set(getFnpdCacheKey(basedir), data)
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), data)
})
}
function getFnpdCacheKey(basedir: string) {
return `fnpd_${basedir}`
}
/**
* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
* @param shorterDir Shorter dir path, e.g. `/User/foo`
*/
function traverseBetweenDirs(
longerDir: string,
shorterDir: string,
cb: (dir: string) => void,
) {
while (longerDir !== shorterDir) {
cb(longerDir)
longerDir = dirname(longerDir)
}
}
export function withTrailingSlash(path: string): string {
if (path[path.length - 1] !== '/')
return `${path}/`
return path
}
export function createImportMetaEnvProxy() {
// packages/vitest/src/node/plugins/index.ts:146
const booleanKeys = [
'DEV',
'PROD',
'SSR',
]
return new Proxy(process.env, {
get(_, key) {
if (typeof key !== 'string')
return undefined
if (booleanKeys.includes(key))
return !!process.env[key]
return process.env[key]
},
set(_, key, value) {
if (typeof key !== 'string')
return true
if (booleanKeys.includes(key))
process.env[key] = value ? '1' : ''
else
process.env[key] = value
return true
},
})
}
const packageCache = new Map<string, { type?: 'module' | 'commonjs' }>()
export async function findNearestPackageData(basedir: string): Promise<{ type?: 'module' | 'commonjs' }> {
const originalBasedir = basedir
while (basedir) {
const cached = getCachedData(packageCache, basedir, originalBasedir)
if (cached)
return cached
const pkgPath = join(basedir, 'package.json')
if ((await fsp.stat(pkgPath).catch(() => {}))?.isFile()) {
const pkgData = JSON.parse(await fsp.readFile(pkgPath, 'utf8'))
if (packageCache)
setCacheData(packageCache, pkgData, basedir, originalBasedir)
return pkgData
}
const nextBasedir = dirname(basedir)
if (nextBasedir === basedir)
break
basedir = nextBasedir
}
return {}
}