forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
1201 lines (1078 loc) · 32.7 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
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
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { promisify } from 'node:util'
import { URL, URLSearchParams } from 'node:url'
import { builtinModules, createRequire } from 'node:module'
import { promises as dns } from 'node:dns'
import { performance } from 'node:perf_hooks'
import type { AddressInfo, Server } from 'node:net'
import resolve from 'resolve'
import type { FSWatcher } from 'chokidar'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
import colors from 'picocolors'
import debug from 'debug'
import type { Alias, AliasOptions } from 'dep-types/alias'
import type MagicString from 'magic-string'
import type { TransformResult } from 'rollup'
import { createFilter as _createFilter } from '@rollup/pluginutils'
import {
CLIENT_ENTRY,
CLIENT_PUBLIC_PATH,
DEFAULT_EXTENSIONS,
ENV_PUBLIC_PATH,
FS_PREFIX,
NULL_BYTE_PLACEHOLDER,
OPTIMIZABLE_ENTRY_RE,
VALID_ID_PREFIX,
loopbackHosts,
wildcardHosts
} from './constants'
import type { DepOptimizationConfig } from './optimizer'
import type { ResolvedConfig } from './config'
import type { ResolvedServerUrls } from './server'
import type { CommonServerOptions } from '.'
/**
* Inlined to keep `@rollup/pluginutils` in devDependencies
*/
export type FilterPattern =
| ReadonlyArray<string | RegExp>
| string
| RegExp
| null
export const createFilter = _createFilter as (
include?: FilterPattern,
exclude?: FilterPattern,
options?: { resolve?: string | false | null }
) => (id: string | unknown) => boolean
export function slash(p: string): string {
return p.replace(/\\/g, '/')
}
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
* This is prepended to resolved ids that are not valid browser
* import specifiers by the importAnalysis plugin.
*/
export function wrapId(id: string): string {
return id.startsWith(VALID_ID_PREFIX)
? id
: VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER)
}
/**
* Undo {@link wrapId}'s `/@id/` and null byte replacements.
*/
export function unwrapId(id: string): string {
return id.startsWith(VALID_ID_PREFIX)
? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0')
: id
}
export const flattenId = (id: string): string =>
id
.replace(/[\/:]/g, '_')
.replace(/[\.]/g, '__')
.replace(/(\s*>\s*)/g, '___')
export const normalizeId = (id: string): string =>
id.replace(/(\s*>\s*)/g, ' > ')
//TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
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 isBuiltin(id: string): boolean {
return builtins.has(id.replace(/^node:/, ''))
}
export function moduleListContains(
moduleList: string[] | undefined,
id: string
): boolean | undefined {
return moduleList?.some((m) => m === id || id.startsWith(m + '/'))
}
export function isOptimizable(
id: string,
optimizeDeps: DepOptimizationConfig
): boolean {
const { extensions } = optimizeDeps
return (
OPTIMIZABLE_ENTRY_RE.test(id) ||
(extensions?.some((ext) => id.endsWith(ext)) ?? false)
)
}
export const bareImportRE = /^[\w@](?!.*:\/\/)/
export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
export let isRunningWithYarnPnp: boolean
// TODO: use import()
const _require = createRequire(import.meta.url)
try {
isRunningWithYarnPnp = Boolean(_require('pnpapi'))
} catch {}
const ssrExtensions = ['.js', '.cjs', '.json', '.node']
export function resolveFrom(
id: string,
basedir: string,
preserveSymlinks = false,
ssr = false
): string {
return resolve.sync(id, {
basedir,
paths: [],
extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS,
// necessary to work with pnpm
preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false
})
}
/**
* like `resolveFrom` but supports resolving `>` path in `id`,
* for example: `foo > bar > baz`
*/
export function nestedResolveFrom(
id: string,
basedir: string,
preserveSymlinks = false
): string {
const pkgs = id.split('>').map((pkg) => pkg.trim())
try {
for (const pkg of pkgs) {
basedir = resolveFrom(pkg, basedir, preserveSymlinks)
}
} catch {}
return basedir
}
// set in bin/vite.js
const filter = process.env.VITE_DEBUG_FILTER
const DEBUG = process.env.DEBUG
interface DebuggerOptions {
onlyWhenFocused?: boolean | string
}
export type ViteDebugScope = `vite:${string}`
export function createDebugger(
namespace: ViteDebugScope,
options: DebuggerOptions = {}
): debug.Debugger['log'] {
const log = debug(namespace)
const { onlyWhenFocused } = options
const focus =
typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace
return (msg: string, ...args: any[]) => {
if (filter && !msg.includes(filter)) {
return
}
if (onlyWhenFocused && !DEBUG?.includes(focus)) {
return
}
log(msg, ...args)
}
}
function testCaseInsensitiveFS() {
if (!CLIENT_ENTRY.endsWith('client.mjs')) {
throw new Error(
`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
)
}
if (!fs.existsSync(CLIENT_ENTRY)) {
throw new Error(
'cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
CLIENT_ENTRY
)
}
return fs.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'))
}
export const isCaseInsensitiveFS = testCaseInsensitiveFS()
export const isWindows = os.platform() === 'win32'
const VOLUME_RE = /^[A-Z]:/i
export function normalizePath(id: string): string {
return path.posix.normalize(isWindows ? slash(id) : id)
}
export function fsPathFromId(id: string): string {
const fsPath = normalizePath(
id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
)
return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
? fsPath
: `/${fsPath}`
}
export function fsPathFromUrl(url: string): string {
return fsPathFromId(cleanUrl(url))
}
/**
* Check if dir is a parent of file
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param dir - normalized absolute path
* @param file - normalized absolute path
* @returns true if dir is a parent of file
*/
export function isParentDirectory(dir: string, file: string): boolean {
if (!dir.endsWith('/')) {
dir = `${dir}/`
}
return (
file.startsWith(dir) ||
(isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))
)
}
export function ensureVolumeInPath(file: string): string {
return isWindows ? path.resolve(file) : file
}
export const queryRE = /\?.*$/s
export const hashRE = /#.*$/s
export const cleanUrl = (url: string): string =>
url.replace(hashRE, '').replace(queryRE, '')
export const externalRE = /^(https?:)?\/\//
export const isExternalUrl = (url: string): boolean => externalRE.test(url)
export const dataUrlRE = /^\s*data:/i
export const isDataUrl = (url: string): boolean => dataUrlRE.test(url)
export const virtualModuleRE = /^virtual-module:.*/
export const virtualModulePrefix = 'virtual-module:'
const knownJsSrcRE = /\.((j|t)sx?|m[jt]s|vue|marko|svelte|astro|imba)($|\?)/
export const isJSRequest = (url: string): boolean => {
url = cleanUrl(url)
if (knownJsSrcRE.test(url)) {
return true
}
if (!path.extname(url) && !url.endsWith('/')) {
return true
}
return false
}
const knownTsRE = /\.(ts|mts|cts|tsx)$/
const knownTsOutputRE = /\.(js|mjs|cjs|jsx)$/
export const isTsRequest = (url: string): boolean => knownTsRE.test(url)
export const isPossibleTsOutput = (url: string): boolean =>
knownTsOutputRE.test(cleanUrl(url))
export function getPotentialTsSrcPaths(filePath: string): string[] {
const [name, type, query = ''] = filePath.split(/(\.(?:[cm]?js|jsx))(\?.*)?$/)
const paths = [name + type.replace('js', 'ts') + query]
if (!type.endsWith('x')) {
paths.push(name + type.replace('js', 'tsx') + query)
}
return paths
}
const importQueryRE = /(\?|&)import=?(?:&|$)/
const directRequestRE = /(\?|&)direct=?(?:&|$)/
const internalPrefixes = [
FS_PREFIX,
VALID_ID_PREFIX,
CLIENT_PUBLIC_PATH,
ENV_PUBLIC_PATH
]
const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`)
const trailingSeparatorRE = /[\?&]$/
export const isImportRequest = (url: string): boolean => importQueryRE.test(url)
export const isInternalRequest = (url: string): boolean =>
InternalPrefixRE.test(url)
export function removeImportQuery(url: string): string {
return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '')
}
export function removeDirectQuery(url: string): string {
return url.replace(directRequestRE, '$1').replace(trailingSeparatorRE, '')
}
export function injectQuery(url: string, queryToInject: string): string {
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
const resolvedUrl = new URL(url.replace(/%/g, '%25'), 'relative:///')
const { search, hash } = resolvedUrl
let pathname = cleanUrl(url)
pathname = isWindows ? slash(pathname) : pathname
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
hash ?? ''
}`
}
const timestampRE = /\bt=\d{13}&?\b/
export function removeTimestampQuery(url: string): string {
return url.replace(timestampRE, '').replace(trailingSeparatorRE, '')
}
export async function asyncReplace(
input: string,
re: RegExp,
replacer: (match: RegExpExecArray) => string | Promise<string>
): Promise<string> {
let match: RegExpExecArray | null
let remaining = input
let rewritten = ''
while ((match = re.exec(remaining))) {
rewritten += remaining.slice(0, match.index)
rewritten += await replacer(match)
remaining = remaining.slice(match.index + match[0].length)
}
rewritten += remaining
return rewritten
}
export function timeFrom(start: number, subtract = 0): string {
const time: number | string = performance.now() - start - subtract
const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ')
if (time < 10) {
return colors.green(timeString)
} else if (time < 50) {
return colors.yellow(timeString)
} else {
return colors.red(timeString)
}
}
/**
* pretty url for logging.
*/
export function prettifyUrl(url: string, root: string): string {
url = removeTimestampQuery(url)
const isAbsoluteFile = url.startsWith(root)
if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
let file = path.relative(root, isAbsoluteFile ? url : fsPathFromId(url))
const seg = file.split('/')
const npmIndex = seg.indexOf(`node_modules`)
const isSourceMap = file.endsWith('.map')
if (npmIndex > 0) {
file = seg[npmIndex + 1]
if (file.startsWith('@')) {
file = `${file}/${seg[npmIndex + 2]}`
}
file = `npm: ${colors.dim(file)}${isSourceMap ? ` (source map)` : ``}`
}
return colors.dim(file)
} else {
return colors.dim(url)
}
}
export function isObject(value: unknown): value is Record<string, any> {
return Object.prototype.toString.call(value) === '[object Object]'
}
export function isDefined<T>(value: T | undefined | null): value is T {
return value != null
}
interface LookupFileOptions {
pathOnly?: boolean
rootDir?: string
predicate?: (file: string) => boolean
}
export function lookupFile(
dir: string,
formats: string[],
options?: LookupFileOptions
): string | undefined {
for (const format of formats) {
const fullPath = path.join(dir, format)
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
const result = options?.pathOnly
? fullPath
: fs.readFileSync(fullPath, 'utf-8')
if (!options?.predicate || options.predicate(result)) {
return result
}
}
}
const parentDir = path.dirname(dir)
if (
parentDir !== dir &&
(!options?.rootDir || parentDir.startsWith(options?.rootDir))
) {
return lookupFile(parentDir, formats, options)
}
}
const splitRE = /\r?\n/
const range: number = 2
export function pad(source: string, n = 2): string {
const lines = source.split(splitRE)
return lines.map((l) => ` `.repeat(n) + l).join(`\n`)
}
export function posToNumber(
source: string,
pos: number | { line: number; column: number }
): number {
if (typeof pos === 'number') return pos
const lines = source.split(splitRE)
const { line, column } = pos
let start = 0
for (let i = 0; i < line - 1 && i < lines.length; i++) {
start += lines[i].length + 1
}
return start + column
}
export function numberToPos(
source: string,
offset: number | { line: number; column: number }
): { line: number; column: number } {
if (typeof offset !== 'number') return offset
if (offset > source.length) {
throw new Error(
`offset is longer than source length! offset ${offset} > length ${source.length}`
)
}
const lines = source.split(splitRE)
let counted = 0
let line = 0
let column = 0
for (; line < lines.length; line++) {
const lineLength = lines[line].length + 1
if (counted + lineLength >= offset) {
column = offset - counted + 1
break
}
counted += lineLength
}
return { line: line + 1, column }
}
export function generateCodeFrame(
source: string,
start: number | { line: number; column: number } = 0,
end?: number
): string {
start = posToNumber(source, start)
end = end || start
const lines = source.split(splitRE)
let count = 0
const res: string[] = []
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1
if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) continue
const line = j + 1
res.push(
`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${
lines[j]
}`
)
const lineLength = lines[j].length
if (j === i) {
// push underline
const pad = Math.max(start - (count - lineLength) + 1, 0)
const length = Math.max(
1,
end > count ? lineLength - pad : end - start
)
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
} else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1)
res.push(` | ` + '^'.repeat(length))
}
count += lineLength + 1
}
}
break
}
}
return res.join('\n')
}
export function writeFile(
filename: string,
content: string | Uint8Array
): void {
const dir = path.dirname(filename)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
fs.writeFileSync(filename, content)
}
export function isFileReadable(filename: string): boolean {
try {
fs.accessSync(filename, fs.constants.R_OK)
return true
} catch {
return false
}
}
const splitFirstDirRE = /(.+?)[\\/](.+)/
/**
* Delete every file and subdirectory. **The given directory must exist.**
* Pass an optional `skip` array to preserve files under the root directory.
*/
export function emptyDir(dir: string, skip?: string[]): void {
const skipInDir: string[] = []
let nested: Map<string, string[]> | null = null
if (skip?.length) {
for (const file of skip) {
if (path.dirname(file) !== '.') {
const matched = file.match(splitFirstDirRE)
if (matched) {
nested ??= new Map()
const [, nestedDir, skipPath] = matched
let nestedSkip = nested.get(nestedDir)
if (!nestedSkip) {
nestedSkip = []
nested.set(nestedDir, nestedSkip)
}
if (!nestedSkip.includes(skipPath)) {
nestedSkip.push(skipPath)
}
}
} else {
skipInDir.push(file)
}
}
}
for (const file of fs.readdirSync(dir)) {
if (skipInDir.includes(file)) {
continue
}
if (nested?.has(file)) {
emptyDir(path.resolve(dir, file), nested.get(file))
} else {
fs.rmSync(path.resolve(dir, file), { recursive: true, force: true })
}
}
}
export function copyDir(srcDir: string, destDir: string): void {
fs.mkdirSync(destDir, { recursive: true })
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file)
if (srcFile === destDir) {
continue
}
const destFile = path.resolve(destDir, file)
const stat = fs.statSync(srcFile)
if (stat.isDirectory()) {
copyDir(srcFile, destFile)
} else {
fs.copyFileSync(srcFile, destFile)
}
}
}
export const removeDir = isWindows
? promisify(gracefulRemoveDir)
: function removeDirSync(dir: string) {
fs.rmSync(dir, { recursive: true, force: true })
}
export const renameDir = isWindows ? promisify(gracefulRename) : fs.renameSync
export function ensureWatchedFile(
watcher: FSWatcher,
file: string | null,
root: string
): void {
if (
file &&
// only need to watch if out of root
!file.startsWith(root + '/') &&
// some rollup plugins use null bytes for private resolved Ids
!file.includes('\0') &&
fs.existsSync(file)
) {
// resolve file to normalized system path
watcher.add(path.resolve(file))
}
}
interface ImageCandidate {
url: string
descriptor: string
}
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/
function reduceSrcset(ret: { url: string; descriptor: string }[]) {
return ret.reduce((prev, { url, descriptor }, index) => {
descriptor ??= ''
return (prev +=
url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`)
}, '')
}
function splitSrcSetDescriptor(srcs: string): ImageCandidate[] {
return splitSrcSet(srcs)
.map((s) => {
const src = s.replace(escapedSpaceCharacters, ' ').trim()
const [url] = imageSetUrlRE.exec(src) || []
return {
url,
descriptor: src?.slice(url.length).trim()
}
})
.filter(({ url }) => !!url)
}
export function processSrcSet(
srcs: string,
replacer: (arg: ImageCandidate) => Promise<string>
): Promise<string> {
return Promise.all(
splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({
url: await replacer({ url, descriptor }),
descriptor
}))
).then((ret) => reduceSrcset(ret))
}
export function processSrcSetSync(
srcs: string,
replacer: (arg: ImageCandidate) => string
): string {
return reduceSrcset(
splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({
url: replacer({ url, descriptor }),
descriptor
}))
)
}
function splitSrcSet(srcs: string) {
const parts: string[] = []
// There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..."
const cleanedSrcs = srcs.replace(
/(?:url|image|gradient|cross-fade)\([^\)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g,
blankReplacer
)
let startIndex = 0
let splitIndex: number
do {
splitIndex = cleanedSrcs.indexOf(',', startIndex)
parts.push(
srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined)
)
startIndex = splitIndex + 1
} while (splitIndex !== -1)
return parts
}
function escapeToLinuxLikePath(path: string) {
if (/^[A-Z]:/.test(path)) {
return path.replace(/^([A-Z]):\//, '/windows/$1/')
}
if (/^\/[^/]/.test(path)) {
return `/linux${path}`
}
return path
}
function unescapeToLinuxLikePath(path: string) {
if (path.startsWith('/linux/')) {
return path.slice('/linux'.length)
}
if (path.startsWith('/windows/')) {
return path.replace(/^\/windows\/([A-Z])\//, '$1:/')
}
return path
}
// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
const nullSourceMap: RawSourceMap = {
names: [],
sources: [],
mappings: '',
version: 3
}
export function combineSourcemaps(
filename: string,
sourcemapList: Array<DecodedSourceMap | RawSourceMap>,
excludeContent = true
): RawSourceMap {
if (
sourcemapList.length === 0 ||
sourcemapList.every((m) => m.sources.length === 0)
) {
return { ...nullSourceMap }
}
// hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
// escape them to linux like paths
// also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
sourcemapList = sourcemapList.map((sourcemap) => {
const newSourcemaps = { ...sourcemap }
newSourcemaps.sources = sourcemap.sources.map((source) =>
source ? escapeToLinuxLikePath(source) : null
)
if (sourcemap.sourceRoot) {
newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot)
}
return newSourcemaps
})
const escapedFilename = escapeToLinuxLikePath(filename)
// We don't declare type here so we can convert/fake/map as RawSourceMap
let map //: SourceMap
let mapIndex = 1
const useArrayInterface =
sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined
if (useArrayInterface) {
map = remapping(sourcemapList, () => null, excludeContent)
} else {
map = remapping(
sourcemapList[0],
function loader(sourcefile) {
if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
return sourcemapList[mapIndex++]
} else {
return null
}
},
excludeContent
)
}
if (!map.file) {
delete map.file
}
// unescape the previous hack
map.sources = map.sources.map((source) =>
source ? unescapeToLinuxLikePath(source) : source
)
map.file = filename
return map as RawSourceMap
}
export function unique<T>(arr: T[]): T[] {
return Array.from(new Set(arr))
}
/**
* Returns resolved localhost address when `dns.lookup` result differs from DNS
*
* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
* For example, when IPv6 is not supported on that machine/network.
*/
export async function getLocalhostAddressIfDiffersFromDNS(): Promise<
string | undefined
> {
const [nodeResult, dnsResult] = await Promise.all([
dns.lookup('localhost'),
dns.lookup('localhost', { verbatim: true })
])
const isSame =
nodeResult.family === dnsResult.family &&
nodeResult.address === dnsResult.address
return isSame ? undefined : nodeResult.address
}
export interface Hostname {
/** undefined sets the default behaviour of server.listen */
host: string | undefined
/** resolve to localhost when possible */
name: string
}
export async function resolveHostname(
optionsHost: string | boolean | undefined
): Promise<Hostname> {
let host: string | undefined
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = 'localhost'
} else if (optionsHost === true) {
// If passed --host in the CLI without arguments
host = undefined // undefined typically means 0.0.0.0 or :: (listen on all IPs)
} else {
host = optionsHost
}
// Set host name to localhost when possible
let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host
if (host === 'localhost') {
// See #8647 for more details.
const localhostAddr = await getLocalhostAddressIfDiffersFromDNS()
if (localhostAddr) {
name = localhostAddr
}
}
return { host, name }
}
export async function resolveServerUrls(
server: Server,
options: CommonServerOptions,
config: ResolvedConfig
): Promise<ResolvedServerUrls> {
const address = server.address()
const isAddressInfo = (x: any): x is AddressInfo => x?.address
if (!isAddressInfo(address)) {
return { local: [], network: [] }
}
const local: string[] = []
const network: string[] = []
const hostname = await resolveHostname(options.host)
const protocol = options.https ? 'https' : 'http'
const port = address.port
const base = config.base === './' || config.base === '' ? '/' : config.base
if (hostname.host && loopbackHosts.has(hostname.host)) {
let hostnameName = hostname.name
if (
hostnameName === '::1' ||
hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001'
) {
hostnameName = `[${hostnameName}]`
}
local.push(`${protocol}://${hostnameName}:${port}${base}`)
} else {
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
detail &&
detail.address &&
// Node < v18
((typeof detail.family === 'string' && detail.family === 'IPv4') ||
// Node >= v18
(typeof detail.family === 'number' && detail.family === 4))
)
.forEach((detail) => {
const host = detail.address.replace('127.0.0.1', hostname.name)
const url = `${protocol}://${host}:${port}${base}`
if (detail.address.includes('127.0.0.1')) {
local.push(url)
} else {
network.push(url)
}
})
}
return { local, network }
}
export function arraify<T>(target: T | T[]): T[] {
return Array.isArray(target) ? target : [target]
}
export function toUpperCaseDriveLetter(pathName: string): string {
return pathName.replace(/^\w:/, (letter) => letter.toUpperCase())
}
// Taken from https://stackoverflow.com/a/36328890
export const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//gm
export const singlelineCommentsRE = /\/\/.*/g
export const requestQuerySplitRE = /\?(?!.*[\/|\}])/
// @ts-expect-error
export const usingDynamicImport = typeof jest === 'undefined'
/**
* Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
*
* As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
* if we're in a Jest environment.
* See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
*
* @param file File path to import.
*/
export const dynamicImport = usingDynamicImport
? new Function('file', 'return import(file)')
: _require
export function parseRequest(id: string): Record<string, string> | null {
const [_, search] = id.split(requestQuerySplitRE, 2)
if (!search) {
return null
}
return Object.fromEntries(new URLSearchParams(search))
}
export const blankReplacer = (match: string): string => ' '.repeat(match.length)
export function getHash(text: Buffer | string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
export const requireResolveFromRootWithFallback = (
root: string,
id: string
): string => {
// Search in the root directory first, and fallback to the default require paths.
const fallbackPaths = _require.resolve.paths?.(id) || []
const path = _require.resolve(id, {
paths: [root, ...fallbackPaths]
})
return path
}
// Based on node-graceful-fs
// The ISC License
// Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
// https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
// On Windows, A/V software can lock the directory, causing this
// to fail with an EACCES or EPERM if the directory contains newly
// created files. The original tried for up to 60 seconds, we only
// wait for 5 seconds, as a longer time would be seen as an error
const GRACEFUL_RENAME_TIMEOUT = 5000
function gracefulRename(
from: string,
to: string,
cb: (error: NodeJS.ErrnoException | null) => void
) {
const start = Date.now()
let backoff = 0
fs.rename(from, to, function CB(er) {
if (
er &&
(er.code === 'EACCES' || er.code === 'EPERM') &&
Date.now() - start < GRACEFUL_RENAME_TIMEOUT
) {
setTimeout(function () {
fs.stat(to, function (stater, st) {
if (stater && stater.code === 'ENOENT') fs.rename(from, to, CB)
else CB(er)
})
}, backoff)
if (backoff < 100) backoff += 10
return
}
if (cb) cb(er)
})
}
const GRACEFUL_REMOVE_DIR_TIMEOUT = 5000
function gracefulRemoveDir(
dir: string,
cb: (error: NodeJS.ErrnoException | null) => void
) {
const start = Date.now()
let backoff = 0