/
utils.ts
62 lines (52 loc) 路 1.87 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
import { fileURLToPath as _fileURLToPath } from 'url'
import { promises as fsp } from 'fs'
import { normalizeSlash, BUILTIN_MODULES } from './_utils'
export function fileURLToPath (id: string): string {
if (typeof id === 'string' && !id.startsWith('file://')) {
return normalizeSlash(id)
}
return normalizeSlash(_fileURLToPath(id))
}
// https://datatracker.ietf.org/doc/html/rfc2396
// eslint-disable-next-line no-control-regex
const INVALID_CHAR_RE = /[\x00-\x1F\x7F<>*#"{}|^[\]`;/?:@&=+$,]+/g
export function sanitizeURIComponent (name: string = '', replacement: string = '_'): string {
return name.replace(INVALID_CHAR_RE, replacement)
}
export function sanitizeFilePath (filePath: string = '') {
return filePath.split(/[/\\]/g).map(p => sanitizeURIComponent(p)).join('/')
.replace(/^([a-zA-Z])_\//, '$1:/')
}
export function normalizeid (id: string): string {
if (typeof id !== 'string') {
// @ts-ignore
id = id.toString()
}
if (/(node|data|http|https|file):/.test(id)) {
return id
}
if (BUILTIN_MODULES.has(id)) {
return 'node:' + id
}
return 'file://' + normalizeSlash(encodeURI(id))
}
export async function loadURL (url: string): Promise<string> {
const code = await fsp.readFile(fileURLToPath(url), 'utf-8')
return code
}
export function toDataURL (code: string): string {
const base64 = Buffer.from(code).toString('base64')
return `data:text/javascript;base64,${base64}`
}
export function isNodeBuiltin (id: string = '') {
// node:fs/promises => fs
id = id.replace(/^node:/, '').split('/')[0]
return BUILTIN_MODULES.has(id)
}
// 2+ letters, to exclude Windows drive letters
// "{2,}?" to make in ungreedy and dont take "file://C" as protocol
const ProtocolRegex = /^(?<proto>.{2,}?):.+$/
export function getProtocol (id: string): string | null {
const proto = id.match(ProtocolRegex)
return proto ? proto.groups.proto : null
}