vite 5.0.7 → 5.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7709,7 +7709,7 @@ function getPackageEntryPoint(dirPath) {
7709
7709
  return entryPoint;
7710
7710
  }
7711
7711
 
7712
- function isDirectory(path) {
7712
+ function isDirectory$1(path) {
7713
7713
  try {
7714
7714
  if (statSync$1(path).isDirectory()) return true;
7715
7715
  } catch (ignored) {
@@ -7730,7 +7730,7 @@ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
7730
7730
  for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) {
7731
7731
  const resolvedPath = resolve$3(path);
7732
7732
  const requirePath = normalizePathSlashes(resolvedPath);
7733
- if (isDirectory(resolvedPath)) {
7733
+ if (isDirectory$1(resolvedPath)) {
7734
7734
  dirNames.add(resolvedPath);
7735
7735
  const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path)));
7736
7736
  modifyMap(requirePath, modulePath);
@@ -28480,6 +28480,324 @@ function hasESMSyntax(code) {
28480
28480
  return ESM_RE.test(code);
28481
28481
  }
28482
28482
 
28483
+ // An implementation of fsUtils without caching
28484
+ const commonFsUtils = {
28485
+ existsSync: fs$l.existsSync,
28486
+ isDirectory,
28487
+ tryResolveRealFile,
28488
+ tryResolveRealFileWithExtensions,
28489
+ tryResolveRealFileOrType,
28490
+ };
28491
+ const cachedFsUtilsMap = new WeakMap();
28492
+ function getFsUtils(config) {
28493
+ let fsUtils = cachedFsUtilsMap.get(config);
28494
+ if (!fsUtils) {
28495
+ if (config.command !== 'serve' || !config.server.fs.cachedChecks) {
28496
+ // cached fsUtils is only used in the dev server for now, and only when the watcher isn't configured
28497
+ // we can support custom ignored patterns later
28498
+ fsUtils = commonFsUtils;
28499
+ } /* TODO: Enabling for testing, we need to review if this guard is needed
28500
+ else if (config.server.watch === null || config.server.watch?.ignored) {
28501
+ config.logger.warn(
28502
+ colors.yellow(
28503
+ `${colors.bold(
28504
+ `(!)`,
28505
+ )} server.fs.cachedChecks isn't supported if server.watch is null or a custom server.watch.ignored is configured\n`,
28506
+ ),
28507
+ )
28508
+ fsUtils = commonFsUtils
28509
+ } */
28510
+ else if (!config.resolve.preserveSymlinks &&
28511
+ config.root !== getRealPath(config.root)) {
28512
+ config.logger.warn(colors$1.yellow(`${colors$1.bold(`(!)`)} server.fs.cachedChecks isn't supported when resolve.preserveSymlinks is false and root is symlinked\n`));
28513
+ fsUtils = commonFsUtils;
28514
+ }
28515
+ else {
28516
+ fsUtils = createCachedFsUtils(config);
28517
+ }
28518
+ cachedFsUtilsMap.set(config, fsUtils);
28519
+ }
28520
+ return fsUtils;
28521
+ }
28522
+ function readDirCacheSync(file) {
28523
+ let dirents;
28524
+ try {
28525
+ dirents = fs$l.readdirSync(file, { withFileTypes: true });
28526
+ }
28527
+ catch {
28528
+ return;
28529
+ }
28530
+ return direntsToDirentMap(dirents);
28531
+ }
28532
+ function direntsToDirentMap(fsDirents) {
28533
+ const dirents = new Map();
28534
+ for (const dirent of fsDirents) {
28535
+ // We ignore non directory, file, and symlink entries
28536
+ const type = dirent.isDirectory()
28537
+ ? 'directory'
28538
+ : dirent.isSymbolicLink()
28539
+ ? 'symlink'
28540
+ : dirent.isFile()
28541
+ ? 'file'
28542
+ : undefined;
28543
+ if (type) {
28544
+ dirents.set(dirent.name, { type });
28545
+ }
28546
+ }
28547
+ return dirents;
28548
+ }
28549
+ function ensureFileMaybeSymlinkIsResolved(direntCache, filePath) {
28550
+ if (direntCache.type !== 'file_maybe_symlink')
28551
+ return;
28552
+ const isSymlink = fs$l
28553
+ .lstatSync(filePath, { throwIfNoEntry: false })
28554
+ ?.isSymbolicLink();
28555
+ direntCache.type =
28556
+ isSymlink === undefined ? 'error' : isSymlink ? 'symlink' : 'file';
28557
+ }
28558
+ function pathUntilPart(root, parts, i) {
28559
+ let p = root;
28560
+ for (let k = 0; k < i; k++)
28561
+ p += '/' + parts[k];
28562
+ return p;
28563
+ }
28564
+ function createCachedFsUtils(config) {
28565
+ const root = config.root; // root is resolved and normalized, so it doesn't have a trailing slash
28566
+ const rootDirPath = `${root}/`;
28567
+ const rootCache = { type: 'directory' }; // dirents will be computed lazily
28568
+ const getDirentCacheSync = (parts) => {
28569
+ let direntCache = rootCache;
28570
+ for (let i = 0; i < parts.length; i++) {
28571
+ if (direntCache.type === 'directory') {
28572
+ let dirPath;
28573
+ if (!direntCache.dirents) {
28574
+ dirPath = pathUntilPart(root, parts, i);
28575
+ const dirents = readDirCacheSync(dirPath);
28576
+ if (!dirents) {
28577
+ direntCache.type = 'error';
28578
+ return;
28579
+ }
28580
+ direntCache.dirents = dirents;
28581
+ }
28582
+ const nextDirentCache = direntCache.dirents.get(parts[i]);
28583
+ if (!nextDirentCache) {
28584
+ return;
28585
+ }
28586
+ if (nextDirentCache.type === 'directory_maybe_symlink') {
28587
+ dirPath ??= pathUntilPart(root, parts, i);
28588
+ const isSymlink = fs$l
28589
+ .lstatSync(dirPath, { throwIfNoEntry: false })
28590
+ ?.isSymbolicLink();
28591
+ direntCache.type = isSymlink ? 'symlink' : 'directory';
28592
+ }
28593
+ direntCache = nextDirentCache;
28594
+ }
28595
+ else if (direntCache.type === 'symlink') {
28596
+ // early return if we encounter a symlink
28597
+ return direntCache;
28598
+ }
28599
+ else if (direntCache.type === 'error') {
28600
+ return direntCache;
28601
+ }
28602
+ else {
28603
+ if (i !== parts.length - 1) {
28604
+ return;
28605
+ }
28606
+ if (direntCache.type === 'file_maybe_symlink') {
28607
+ ensureFileMaybeSymlinkIsResolved(direntCache, pathUntilPart(root, parts, i));
28608
+ return direntCache;
28609
+ }
28610
+ else if (direntCache.type === 'file') {
28611
+ return direntCache;
28612
+ }
28613
+ else {
28614
+ return;
28615
+ }
28616
+ }
28617
+ }
28618
+ return direntCache;
28619
+ };
28620
+ function getDirentCacheFromPath(normalizedFile) {
28621
+ if (normalizedFile === root) {
28622
+ return rootCache;
28623
+ }
28624
+ if (!normalizedFile.startsWith(rootDirPath)) {
28625
+ return undefined;
28626
+ }
28627
+ const pathFromRoot = normalizedFile.slice(rootDirPath.length);
28628
+ const parts = pathFromRoot.split('/');
28629
+ const direntCache = getDirentCacheSync(parts);
28630
+ if (!direntCache || direntCache.type === 'error') {
28631
+ return false;
28632
+ }
28633
+ return direntCache;
28634
+ }
28635
+ function onPathAdd(file, type) {
28636
+ const direntCache = getDirentCacheFromPath(path$o.dirname(file));
28637
+ if (direntCache &&
28638
+ direntCache.type === 'directory' &&
28639
+ direntCache.dirents) {
28640
+ direntCache.dirents.set(path$o.basename(file), { type });
28641
+ }
28642
+ }
28643
+ function onPathUnlink(file) {
28644
+ const direntCache = getDirentCacheFromPath(path$o.dirname(file));
28645
+ if (direntCache &&
28646
+ direntCache.type === 'directory' &&
28647
+ direntCache.dirents) {
28648
+ direntCache.dirents.delete(path$o.basename(file));
28649
+ }
28650
+ }
28651
+ return {
28652
+ existsSync(file) {
28653
+ if (isInNodeModules$1(file)) {
28654
+ return fs$l.existsSync(file);
28655
+ }
28656
+ const normalizedFile = normalizePath$3(file);
28657
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28658
+ if (direntCache === undefined ||
28659
+ (direntCache && direntCache.type === 'symlink')) {
28660
+ // fallback to built-in fs for out-of-root and symlinked files
28661
+ return fs$l.existsSync(file);
28662
+ }
28663
+ return !!direntCache;
28664
+ },
28665
+ tryResolveRealFile(file, preserveSymlinks) {
28666
+ if (isInNodeModules$1(file)) {
28667
+ return tryResolveRealFile(file, preserveSymlinks);
28668
+ }
28669
+ const normalizedFile = normalizePath$3(file);
28670
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28671
+ if (direntCache === undefined ||
28672
+ (direntCache && direntCache.type === 'symlink')) {
28673
+ // fallback to built-in fs for out-of-root and symlinked files
28674
+ return tryResolveRealFile(file, preserveSymlinks);
28675
+ }
28676
+ if (!direntCache || direntCache.type === 'directory') {
28677
+ return;
28678
+ }
28679
+ // We can avoid getRealPath even if preserveSymlinks is false because we know it's
28680
+ // a file without symlinks in its path
28681
+ return normalizedFile;
28682
+ },
28683
+ tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks) {
28684
+ if (isInNodeModules$1(file)) {
28685
+ return tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks);
28686
+ }
28687
+ const normalizedFile = normalizePath$3(file);
28688
+ const dirPath = path$o.posix.dirname(normalizedFile);
28689
+ const direntCache = getDirentCacheFromPath(dirPath);
28690
+ if (direntCache === undefined ||
28691
+ (direntCache && direntCache.type === 'symlink')) {
28692
+ // fallback to built-in fs for out-of-root and symlinked files
28693
+ return tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks);
28694
+ }
28695
+ if (!direntCache || direntCache.type !== 'directory') {
28696
+ return;
28697
+ }
28698
+ if (!direntCache.dirents) {
28699
+ const dirents = readDirCacheSync(dirPath);
28700
+ if (!dirents) {
28701
+ direntCache.type = 'error';
28702
+ return;
28703
+ }
28704
+ direntCache.dirents = dirents;
28705
+ }
28706
+ const base = path$o.posix.basename(normalizedFile);
28707
+ for (const ext of extensions) {
28708
+ const fileName = base + ext;
28709
+ const fileDirentCache = direntCache.dirents.get(fileName);
28710
+ if (fileDirentCache) {
28711
+ const filePath = dirPath + '/' + fileName;
28712
+ ensureFileMaybeSymlinkIsResolved(fileDirentCache, filePath);
28713
+ if (fileDirentCache.type === 'symlink') {
28714
+ // fallback to built-in fs for symlinked files
28715
+ return tryResolveRealFile(filePath, preserveSymlinks);
28716
+ }
28717
+ if (fileDirentCache.type === 'file') {
28718
+ return filePath;
28719
+ }
28720
+ }
28721
+ }
28722
+ },
28723
+ tryResolveRealFileOrType(file, preserveSymlinks) {
28724
+ if (isInNodeModules$1(file)) {
28725
+ return tryResolveRealFileOrType(file, preserveSymlinks);
28726
+ }
28727
+ const normalizedFile = normalizePath$3(file);
28728
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28729
+ if (direntCache === undefined ||
28730
+ (direntCache && direntCache.type === 'symlink')) {
28731
+ // fallback to built-in fs for out-of-root and symlinked files
28732
+ return tryResolveRealFileOrType(file, preserveSymlinks);
28733
+ }
28734
+ if (!direntCache) {
28735
+ return;
28736
+ }
28737
+ if (direntCache.type === 'directory') {
28738
+ return { type: 'directory' };
28739
+ }
28740
+ // We can avoid getRealPath even if preserveSymlinks is false because we know it's
28741
+ // a file without symlinks in its path
28742
+ return { path: normalizedFile, type: 'file' };
28743
+ },
28744
+ isDirectory(dirPath) {
28745
+ if (isInNodeModules$1(dirPath)) {
28746
+ return isDirectory(dirPath);
28747
+ }
28748
+ const direntCache = getDirentCacheFromPath(normalizePath$3(dirPath));
28749
+ if (direntCache === undefined ||
28750
+ (direntCache && direntCache.type === 'symlink')) {
28751
+ // fallback to built-in fs for out-of-root and symlinked files
28752
+ return isDirectory(dirPath);
28753
+ }
28754
+ return direntCache && direntCache.type === 'directory';
28755
+ },
28756
+ initWatcher(watcher) {
28757
+ watcher.on('add', (file) => {
28758
+ onPathAdd(file, 'file_maybe_symlink');
28759
+ });
28760
+ watcher.on('addDir', (dir) => {
28761
+ onPathAdd(dir, 'directory_maybe_symlink');
28762
+ });
28763
+ watcher.on('unlink', onPathUnlink);
28764
+ watcher.on('unlinkDir', onPathUnlink);
28765
+ },
28766
+ };
28767
+ }
28768
+ function tryResolveRealFile(file, preserveSymlinks) {
28769
+ const stat = tryStatSync(file);
28770
+ if (stat?.isFile())
28771
+ return getRealPath(file, preserveSymlinks);
28772
+ }
28773
+ function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
28774
+ for (const ext of extensions) {
28775
+ const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
28776
+ if (res)
28777
+ return res;
28778
+ }
28779
+ }
28780
+ function tryResolveRealFileOrType(file, preserveSymlinks) {
28781
+ const fileStat = tryStatSync(file);
28782
+ if (fileStat?.isFile()) {
28783
+ return { path: getRealPath(file, preserveSymlinks), type: 'file' };
28784
+ }
28785
+ if (fileStat?.isDirectory()) {
28786
+ return { type: 'directory' };
28787
+ }
28788
+ return;
28789
+ }
28790
+ function getRealPath(resolved, preserveSymlinks) {
28791
+ if (!preserveSymlinks) {
28792
+ resolved = safeRealpathSync(resolved);
28793
+ }
28794
+ return normalizePath$3(resolved);
28795
+ }
28796
+ function isDirectory(path) {
28797
+ const stat = tryStatSync(path);
28798
+ return stat?.isDirectory() ?? false;
28799
+ }
28800
+
28483
28801
  const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
28484
28802
  const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
28485
28803
  const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = 'ERR_RESOLVE_PACKAGE_ENTRY_FAIL';
@@ -28786,46 +29104,46 @@ const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
28786
29104
  const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
28787
29105
  function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
28788
29106
  const { tryPrefix, extensions, preserveSymlinks } = options;
28789
- const fileStat = tryStatSync(file);
28790
- // Try direct match first
28791
- if (fileStat?.isFile())
28792
- return getRealPath(file, options.preserveSymlinks);
29107
+ const fsUtils = options.fsUtils ?? commonFsUtils;
29108
+ // Optimization to get the real type or file type (directory, file, other)
29109
+ const fileResult = fsUtils.tryResolveRealFileOrType(file, options.preserveSymlinks);
29110
+ if (fileResult?.path)
29111
+ return fileResult.path;
28793
29112
  let res;
28794
29113
  // If path.dirname is a valid directory, try extensions and ts resolution logic
28795
29114
  const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
28796
- if (possibleJsToTs || extensions.length || tryPrefix) {
29115
+ if (possibleJsToTs || options.extensions.length || tryPrefix) {
28797
29116
  const dirPath = path$o.dirname(file);
28798
- const dirStat = tryStatSync(dirPath);
28799
- if (dirStat?.isDirectory()) {
29117
+ if (fsUtils.isDirectory(dirPath)) {
28800
29118
  if (possibleJsToTs) {
28801
29119
  // try resolve .js, .mjs, .cjs or .jsx import to typescript file
28802
29120
  const fileExt = path$o.extname(file);
28803
29121
  const fileName = file.slice(0, -fileExt.length);
28804
- if ((res = tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
29122
+ if ((res = fsUtils.tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
28805
29123
  return res;
28806
29124
  // for .js, also try .tsx
28807
29125
  if (fileExt === '.js' &&
28808
- (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
29126
+ (res = fsUtils.tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
28809
29127
  return res;
28810
29128
  }
28811
- if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
29129
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
28812
29130
  return res;
28813
29131
  if (tryPrefix) {
28814
29132
  const prefixed = `${dirPath}/${options.tryPrefix}${path$o.basename(file)}`;
28815
- if ((res = tryResolveRealFile(prefixed, preserveSymlinks)))
29133
+ if ((res = fsUtils.tryResolveRealFile(prefixed, preserveSymlinks)))
28816
29134
  return res;
28817
- if ((res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
29135
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
28818
29136
  return res;
28819
29137
  }
28820
29138
  }
28821
29139
  }
28822
- if (tryIndex && fileStat) {
29140
+ if (tryIndex && fileResult?.type === 'directory') {
28823
29141
  // Path points to a directory, check for package.json and entry and /index file
28824
29142
  const dirPath = file;
28825
29143
  if (!skipPackageJson) {
28826
29144
  let pkgPath = `${dirPath}/package.json`;
28827
29145
  try {
28828
- if (fs$l.existsSync(pkgPath)) {
29146
+ if (fsUtils.existsSync(pkgPath)) {
28829
29147
  if (!options.preserveSymlinks) {
28830
29148
  pkgPath = safeRealpathSync(pkgPath);
28831
29149
  }
@@ -28840,26 +29158,14 @@ function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, ski
28840
29158
  throw e;
28841
29159
  }
28842
29160
  }
28843
- if ((res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
29161
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
28844
29162
  return res;
28845
29163
  if (tryPrefix) {
28846
- if ((res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
29164
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
28847
29165
  return res;
28848
29166
  }
28849
29167
  }
28850
29168
  }
28851
- function tryResolveRealFile(file, preserveSymlinks) {
28852
- const stat = tryStatSync(file);
28853
- if (stat?.isFile())
28854
- return getRealPath(file, preserveSymlinks);
28855
- }
28856
- function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
28857
- for (const ext of extensions) {
28858
- const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
28859
- if (res)
28860
- return res;
28861
- }
28862
- }
28863
29169
  function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
28864
29170
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
28865
29171
  // check for deep import, e.g. "my-lib/foo"
@@ -29313,12 +29619,6 @@ function mapWithBrowserField(relativePathInPkgDir, map) {
29313
29619
  function equalWithoutSuffix(path, key, suffix) {
29314
29620
  return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
29315
29621
  }
29316
- function getRealPath(resolved, preserveSymlinks) {
29317
- if (!preserveSymlinks) {
29318
- resolved = safeRealpathSync(resolved);
29319
- }
29320
- return normalizePath$3(resolved);
29321
- }
29322
29622
 
29323
29623
  var dist = {};
29324
29624
 
@@ -39025,26 +39325,27 @@ function cssPlugin(config) {
39025
39325
  }
39026
39326
  const ssr = options?.ssr === true;
39027
39327
  const urlReplacer = async (url, importer) => {
39028
- if (checkPublicFile(url, config)) {
39328
+ const decodedUrl = decodeURI(url);
39329
+ if (checkPublicFile(decodedUrl, config)) {
39029
39330
  if (encodePublicUrlsInCSS(config)) {
39030
- return publicFileToBuiltUrl(url, config);
39331
+ return publicFileToBuiltUrl(decodedUrl, config);
39031
39332
  }
39032
39333
  else {
39033
- return joinUrlSegments(config.base, url);
39334
+ return joinUrlSegments(config.base, decodedUrl);
39034
39335
  }
39035
39336
  }
39036
- const resolved = await resolveUrl(url, importer);
39337
+ const resolved = await resolveUrl(decodedUrl, importer);
39037
39338
  if (resolved) {
39038
39339
  return fileToUrl$1(resolved, config, this);
39039
39340
  }
39040
39341
  if (config.command === 'build') {
39041
39342
  const isExternal = config.build.rollupOptions.external
39042
- ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
39343
+ ? resolveUserExternal(config.build.rollupOptions.external, decodedUrl, // use URL as id since id could not be resolved
39043
39344
  id, false)
39044
39345
  : false;
39045
39346
  if (!isExternal) {
39046
39347
  // #9800 If we cannot resolve the css url, leave a warning.
39047
- config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
39348
+ config.logger.warnOnce(`\n${decodedUrl} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
39048
39349
  }
39049
39350
  }
39050
39351
  return url;
@@ -39775,8 +40076,8 @@ function createCachedImport(imp) {
39775
40076
  return cached;
39776
40077
  };
39777
40078
  }
39778
- const importPostcssImport = createCachedImport(() => import('./dep-tttr_ygS.js').then(function (n) { return n.i; }));
39779
- const importPostcssModules = createCachedImport(() => import('./dep-iw_F17O-.js').then(function (n) { return n.i; }));
40079
+ const importPostcssImport = createCachedImport(() => import('./dep-rzQTjkv_.js').then(function (n) { return n.i; }));
40080
+ const importPostcssModules = createCachedImport(() => import('./dep-riInLuGl.js').then(function (n) { return n.i; }));
39780
40081
  const importPostcss = createCachedImport(() => import('postcss'));
39781
40082
  /**
39782
40083
  * @experimental
@@ -41163,7 +41464,7 @@ function throwOutdatedRequest(id) {
41163
41464
  throw err;
41164
41465
  }
41165
41466
 
41166
- // AST walker module for Mozilla Parser API compatible trees
41467
+ // AST walker module for ESTree compatible trees
41167
41468
 
41168
41469
 
41169
41470
  function makeTest(test) {
@@ -50224,8 +50525,8 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50224
50525
  // In node@12+ we can use dynamic import to load CJS and ESM
50225
50526
  async function nodeImport(id, importer, resolveOptions, metadata) {
50226
50527
  let url;
50227
- const isRuntimeHandled = id.startsWith('data:') || isBuiltin(id);
50228
- if (isRuntimeHandled) {
50528
+ let filePath;
50529
+ if (id.startsWith('data:') || isBuiltin(id)) {
50229
50530
  url = id;
50230
50531
  }
50231
50532
  else {
@@ -50235,18 +50536,19 @@ async function nodeImport(id, importer, resolveOptions, metadata) {
50235
50536
  err.code = 'ERR_MODULE_NOT_FOUND';
50236
50537
  throw err;
50237
50538
  }
50539
+ filePath = resolved.id;
50238
50540
  url = pathToFileURL(resolved.id).toString();
50239
50541
  }
50240
50542
  const mod = await import(url);
50241
50543
  if (resolveOptions.legacyProxySsrExternalModules) {
50242
50544
  return proxyESM(mod);
50243
50545
  }
50244
- else if (isRuntimeHandled) {
50245
- return mod;
50546
+ else if (filePath) {
50547
+ analyzeImportedModDifference(mod, filePath, id, metadata, resolveOptions.packageCache);
50548
+ return proxyGuardOnlyEsm(mod, id);
50246
50549
  }
50247
50550
  else {
50248
- analyzeImportedModDifference(mod, url, id, metadata, resolveOptions.packageCache);
50249
- return proxyGuardOnlyEsm(mod, id);
50551
+ return mod;
50250
50552
  }
50251
50553
  }
50252
50554
  // rollup-style default import interop for cjs
@@ -52517,6 +52819,9 @@ let Receiver$1 = class Receiver extends Writable$1 {
52517
52819
  * Creates a Receiver instance.
52518
52820
  *
52519
52821
  * @param {Object} [options] Options object
52822
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
52823
+ * whether or not to process more than one of the `'message'`, `'ping'`,
52824
+ * and `'pong'` events per microtask
52520
52825
  * @param {String} [options.binaryType=nodebuffer] The type for binary data
52521
52826
  * @param {Object} [options.extensions] An object containing the negotiated
52522
52827
  * extensions
@@ -52529,6 +52834,8 @@ let Receiver$1 = class Receiver extends Writable$1 {
52529
52834
  constructor(options = {}) {
52530
52835
  super();
52531
52836
 
52837
+ this._allowMultipleEventsPerMicrotask =
52838
+ !!options.allowMultipleEventsPerMicrotask;
52532
52839
  this._binaryType = options.binaryType || BINARY_TYPES$1[0];
52533
52840
  this._extensions = options.extensions || {};
52534
52841
  this._isServer = !!options.isServer;
@@ -53039,7 +53346,9 @@ let Receiver$1 = class Receiver extends Writable$1 {
53039
53346
  }
53040
53347
  }
53041
53348
 
53042
- this._state = WAIT_MICROTASK;
53349
+ this._state = this._allowMultipleEventsPerMicrotask
53350
+ ? GET_INFO
53351
+ : WAIT_MICROTASK;
53043
53352
  }
53044
53353
 
53045
53354
  /**
@@ -53056,8 +53365,6 @@ let Receiver$1 = class Receiver extends Writable$1 {
53056
53365
  if (data.length === 0) {
53057
53366
  this.emit('conclude', 1005, EMPTY_BUFFER$2);
53058
53367
  this.end();
53059
-
53060
- this._state = GET_INFO;
53061
53368
  } else {
53062
53369
  const code = data.readUInt16BE(0);
53063
53370
 
@@ -53089,16 +53396,16 @@ let Receiver$1 = class Receiver extends Writable$1 {
53089
53396
 
53090
53397
  this.emit('conclude', code, buf);
53091
53398
  this.end();
53092
-
53093
- this._state = GET_INFO;
53094
53399
  }
53095
- } else if (this._opcode === 0x09) {
53096
- this.emit('ping', data);
53097
- this._state = WAIT_MICROTASK;
53098
- } else {
53099
- this.emit('pong', data);
53100
- this._state = WAIT_MICROTASK;
53400
+
53401
+ this._state = GET_INFO;
53402
+ return;
53101
53403
  }
53404
+
53405
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
53406
+ this._state = this._allowMultipleEventsPerMicrotask
53407
+ ? GET_INFO
53408
+ : WAIT_MICROTASK;
53102
53409
  }
53103
53410
  };
53104
53411
 
@@ -54314,6 +54621,9 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
54314
54621
  * @param {Duplex} socket The network socket between the server and client
54315
54622
  * @param {Buffer} head The first packet of the upgraded stream
54316
54623
  * @param {Object} options Options object
54624
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
54625
+ * whether or not to process more than one of the `'message'`, `'ping'`,
54626
+ * and `'pong'` events per microtask
54317
54627
  * @param {Function} [options.generateMask] The function used to generate the
54318
54628
  * masking key
54319
54629
  * @param {Number} [options.maxPayload=0] The maximum allowed message size
@@ -54323,6 +54633,7 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
54323
54633
  */
54324
54634
  setSocket(socket, head, options) {
54325
54635
  const receiver = new Receiver({
54636
+ allowMultipleEventsPerMicrotask: options.allowMultipleEventsPerMicrotask,
54326
54637
  binaryType: this.binaryType,
54327
54638
  extensions: this._extensions,
54328
54639
  isServer: this._isServer,
@@ -54740,6 +55051,11 @@ var websocket = WebSocket$1;
54740
55051
  * @param {(String|URL)} address The URL to which to connect
54741
55052
  * @param {Array} protocols The subprotocols
54742
55053
  * @param {Object} [options] Connection options
55054
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
55055
+ * whether or not to process more than one of the `'message'`, `'ping'`,
55056
+ * and `'pong'` events per microtask
55057
+ * @param {Function} [options.finishRequest] A function which can be used to
55058
+ * customize the headers of each http request before it is sent
54743
55059
  * @param {Boolean} [options.followRedirects=false] Whether or not to follow
54744
55060
  * redirects
54745
55061
  * @param {Function} [options.generateMask] The function used to generate the
@@ -54762,6 +55078,7 @@ var websocket = WebSocket$1;
54762
55078
  */
54763
55079
  function initAsClient(websocket, address, protocols, options) {
54764
55080
  const opts = {
55081
+ allowMultipleEventsPerMicrotask: false,
54765
55082
  protocolVersion: protocolVersions[1],
54766
55083
  maxPayload: 100 * 1024 * 1024,
54767
55084
  skipUTF8Validation: false,
@@ -54928,8 +55245,8 @@ function initAsClient(websocket, address, protocols, options) {
54928
55245
  ? opts.socketPath === websocket._originalHostOrSocketPath
54929
55246
  : false
54930
55247
  : websocket._originalIpc
54931
- ? false
54932
- : parsedUrl.host === websocket._originalHostOrSocketPath;
55248
+ ? false
55249
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
54933
55250
 
54934
55251
  if (!isSameHost || (websocket._originalSecure && !isSecure)) {
54935
55252
  //
@@ -55113,6 +55430,7 @@ function initAsClient(websocket, address, protocols, options) {
55113
55430
  }
55114
55431
 
55115
55432
  websocket.setSocket(socket, head, {
55433
+ allowMultipleEventsPerMicrotask: opts.allowMultipleEventsPerMicrotask,
55116
55434
  generateMask: opts.generateMask,
55117
55435
  maxPayload: opts.maxPayload,
55118
55436
  skipUTF8Validation: opts.skipUTF8Validation
@@ -55529,6 +55847,9 @@ class WebSocketServer extends EventEmitter {
55529
55847
  * Create a `WebSocketServer` instance.
55530
55848
  *
55531
55849
  * @param {Object} options Configuration options
55850
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
55851
+ * whether or not to process more than one of the `'message'`, `'ping'`,
55852
+ * and `'pong'` events per microtask
55532
55853
  * @param {Number} [options.backlog=511] The maximum length of the queue of
55533
55854
  * pending connections
55534
55855
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
@@ -55555,6 +55876,7 @@ class WebSocketServer extends EventEmitter {
55555
55876
  super();
55556
55877
 
55557
55878
  options = {
55879
+ allowMultipleEventsPerMicrotask: false,
55558
55880
  maxPayload: 100 * 1024 * 1024,
55559
55881
  skipUTF8Validation: false,
55560
55882
  perMessageDeflate: false,
@@ -55909,6 +56231,8 @@ class WebSocketServer extends EventEmitter {
55909
56231
  socket.removeListener('error', socketOnError);
55910
56232
 
55911
56233
  ws.setSocket(socket, head, {
56234
+ allowMultipleEventsPerMicrotask:
56235
+ this.options.allowMultipleEventsPerMicrotask,
55912
56236
  maxPayload: this.options.maxPayload,
55913
56237
  skipUTF8Validation: this.options.skipUTF8Validation
55914
56238
  });
@@ -58448,12 +58772,14 @@ function doesProxyContextMatchUrl(context, url) {
58448
58772
  }
58449
58773
 
58450
58774
  const debug$6 = createDebugger('vite:html-fallback');
58451
- function htmlFallbackMiddleware(root, spaFallback) {
58775
+ function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
58452
58776
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
58453
58777
  return function viteHtmlFallbackMiddleware(req, res, next) {
58454
58778
  if (
58455
58779
  // Only accept GET or HEAD
58456
58780
  (req.method !== 'GET' && req.method !== 'HEAD') ||
58781
+ // Exclude default favicon requests
58782
+ req.url === '/favicon.ico' ||
58457
58783
  // Require Accept: text/html or */*
58458
58784
  !(req.headers.accept === undefined || // equivalent to `Accept: */*`
58459
58785
  req.headers.accept === '' || // equivalent to `Accept: */*`
@@ -58467,7 +58793,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58467
58793
  // so we need to check if the file exists
58468
58794
  if (pathname.endsWith('.html')) {
58469
58795
  const filePath = path$o.join(root, pathname);
58470
- if (fs$l.existsSync(filePath)) {
58796
+ if (fsUtils.existsSync(filePath)) {
58471
58797
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`);
58472
58798
  req.url = url;
58473
58799
  return next();
@@ -58476,7 +58802,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58476
58802
  // trailing slash should check for fallback index.html
58477
58803
  else if (pathname[pathname.length - 1] === '/') {
58478
58804
  const filePath = path$o.join(root, pathname, 'index.html');
58479
- if (fs$l.existsSync(filePath)) {
58805
+ if (fsUtils.existsSync(filePath)) {
58480
58806
  const newUrl = url + 'index.html';
58481
58807
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
58482
58808
  req.url = newUrl;
@@ -58486,7 +58812,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58486
58812
  // non-trailing slash should check for fallback .html
58487
58813
  else {
58488
58814
  const filePath = path$o.join(root, pathname + '.html');
58489
- if (fs$l.existsSync(filePath)) {
58815
+ if (fsUtils.existsSync(filePath)) {
58490
58816
  const newUrl = url + '.html';
58491
58817
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
58492
58818
  req.url = newUrl;
@@ -58561,6 +58887,11 @@ const debugCache = createDebugger('vite:cache');
58561
58887
  const knownIgnoreList = new Set(['/', '/favicon.ico']);
58562
58888
  function transformMiddleware(server) {
58563
58889
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
58890
+ // check if public dir is inside root dir
58891
+ const { root } = server.config;
58892
+ const publicDir = normalizePath$3(server.config.publicDir);
58893
+ const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
58894
+ const publicPath = `${publicDir.slice(root.length)}/`;
58564
58895
  return async function viteTransformMiddleware(req, res, next) {
58565
58896
  if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
58566
58897
  return next();
@@ -58622,35 +58953,8 @@ function transformMiddleware(server) {
58622
58953
  }
58623
58954
  }
58624
58955
  }
58625
- // check if public dir is inside root dir
58626
- const publicDir = normalizePath$3(server.config.publicDir);
58627
- const rootDir = normalizePath$3(server.config.root);
58628
- if (publicDir.startsWith(withTrailingSlash(rootDir))) {
58629
- const publicPath = `${publicDir.slice(rootDir.length)}/`;
58630
- // warn explicit public paths
58631
- if (url.startsWith(withTrailingSlash(publicPath))) {
58632
- let warning;
58633
- if (isImportRequest(url)) {
58634
- const rawUrl = removeImportQuery(url);
58635
- if (urlRE.test(url)) {
58636
- warning =
58637
- `Assets in the public directory are served at the root path.\n` +
58638
- `Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(rawUrl.replace(publicPath, '/'))}.`;
58639
- }
58640
- else {
58641
- warning =
58642
- 'Assets in public directory cannot be imported from JavaScript.\n' +
58643
- `If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead of ${colors$1.cyan(rawUrl)}.\n` +
58644
- `If you intend to use the URL of that asset, use ${colors$1.cyan(injectQuery(rawUrl.replace(publicPath, '/'), 'url'))}.`;
58645
- }
58646
- }
58647
- else {
58648
- warning =
58649
- `Files in the public directory are served at the root path.\n` +
58650
- `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`;
58651
- }
58652
- server.config.logger.warn(colors$1.yellow(warning));
58653
- }
58956
+ if (publicDirInRoot && url.startsWith(publicPath)) {
58957
+ warnAboutExplicitPublicPathInUrl(url);
58654
58958
  }
58655
58959
  if (isJSRequest(url) ||
58656
58960
  isImportRequest(url) ||
@@ -58745,6 +59049,29 @@ function transformMiddleware(server) {
58745
59049
  }
58746
59050
  next();
58747
59051
  };
59052
+ function warnAboutExplicitPublicPathInUrl(url) {
59053
+ let warning;
59054
+ if (isImportRequest(url)) {
59055
+ const rawUrl = removeImportQuery(url);
59056
+ if (urlRE.test(url)) {
59057
+ warning =
59058
+ `Assets in the public directory are served at the root path.\n` +
59059
+ `Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(rawUrl.replace(publicPath, '/'))}.`;
59060
+ }
59061
+ else {
59062
+ warning =
59063
+ 'Assets in public directory cannot be imported from JavaScript.\n' +
59064
+ `If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead of ${colors$1.cyan(rawUrl)}.\n` +
59065
+ `If you intend to use the URL of that asset, use ${colors$1.cyan(injectQuery(rawUrl.replace(publicPath, '/'), 'url'))}.`;
59066
+ }
59067
+ }
59068
+ else {
59069
+ warning =
59070
+ `Files in the public directory are served at the root path.\n` +
59071
+ `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`;
59072
+ }
59073
+ server.config.logger.warn(colors$1.yellow(warning));
59074
+ }
58748
59075
  }
58749
59076
 
58750
59077
  function createDevHtmlTransformFn(config) {
@@ -58778,6 +59105,9 @@ function shouldPreTransform(url, config) {
58778
59105
  return (!checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url)));
58779
59106
  }
58780
59107
  const wordCharRE = /\w/;
59108
+ function isBareRelative(url) {
59109
+ return wordCharRE.test(url[0]) && !url.includes(':');
59110
+ }
58781
59111
  const isSrcSet = (attr) => attr.name === 'srcset' && attr.prefix === undefined;
58782
59112
  const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server) => {
58783
59113
  // prefix with base (dev only, base is never relative)
@@ -58797,20 +59127,25 @@ const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, s
58797
59127
  // rewrite `./index.js` -> `localhost:5173/a/index.js`.
58798
59128
  // rewrite `../index.js` -> `localhost:5173/index.js`.
58799
59129
  // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`.
58800
- ((url[0] === '.' || (wordCharRE.test(url[0]) && !url.includes(':'))) &&
59130
+ ((url[0] === '.' || isBareRelative(url)) &&
58801
59131
  originalUrl &&
58802
59132
  originalUrl !== '/' &&
58803
59133
  htmlPath === '/index.html')) {
58804
- const devBase = config.base;
58805
- const fullUrl = path$o.posix.join(devBase, url);
58806
- if (server && shouldPreTransform(url, config)) {
58807
- preTransformRequest(server, fullUrl, devBase);
58808
- }
58809
- return fullUrl;
59134
+ url = path$o.posix.join(config.base, url);
58810
59135
  }
58811
- else {
58812
- return url;
59136
+ if (server && shouldPreTransform(url, config)) {
59137
+ let preTransformUrl;
59138
+ if (url[0] === '/') {
59139
+ preTransformUrl = url;
59140
+ }
59141
+ else if (url[0] === '.' || isBareRelative(url)) {
59142
+ preTransformUrl = path$o.posix.join(config.base, path$o.posix.dirname(htmlPath), url);
59143
+ }
59144
+ if (preTransformUrl) {
59145
+ preTransformRequest(server, preTransformUrl, config.base);
59146
+ }
58813
59147
  }
59148
+ return url;
58814
59149
  };
58815
59150
  const processedUrl = useSrcSetReplacer
58816
59151
  ? processSrcSetSync(url, ({ url }) => replacer(url))
@@ -58823,7 +59158,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
58823
59158
  let proxyModulePath;
58824
59159
  let proxyModuleUrl;
58825
59160
  const trailingSlash = htmlPath.endsWith('/');
58826
- if (!trailingSlash && fs$l.existsSync(filename)) {
59161
+ if (!trailingSlash && getFsUtils(config).existsSync(filename)) {
58827
59162
  proxyModulePath = htmlPath;
58828
59163
  proxyModuleUrl = joinUrlSegments(base, htmlPath);
58829
59164
  }
@@ -58974,6 +59309,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
58974
59309
  };
58975
59310
  function indexHtmlMiddleware(root, server) {
58976
59311
  const isDev = isDevServer(server);
59312
+ const fsUtils = getFsUtils(server.config);
58977
59313
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
58978
59314
  return async function viteIndexHtmlMiddleware(req, res, next) {
58979
59315
  if (res.writableEnded) {
@@ -58989,7 +59325,7 @@ function indexHtmlMiddleware(root, server) {
58989
59325
  else {
58990
59326
  filePath = path$o.join(root, decodeURIComponent(url));
58991
59327
  }
58992
- if (fs$l.existsSync(filePath)) {
59328
+ if (fsUtils.existsSync(filePath)) {
58993
59329
  const headers = isDev
58994
59330
  ? server.config.server.headers
58995
59331
  : server.config.preview.headers;
@@ -59653,7 +59989,7 @@ async function _createServer(inlineConfig = {}, options) {
59653
59989
  const watcher = watchEnabled
59654
59990
  ? chokidar.watch(
59655
59991
  // config file dependencies and env file might be outside of root
59656
- [root, ...config.configFileDependencies, config.envDir], resolvedWatchOptions)
59992
+ [...new Set([root, ...config.configFileDependencies, config.envDir])], resolvedWatchOptions)
59657
59993
  : createNoopWatcher(resolvedWatchOptions);
59658
59994
  const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr }));
59659
59995
  const container = await createPluginContainer(config, moduleGraph, watcher);
@@ -59845,11 +60181,14 @@ async function _createServer(inlineConfig = {}, options) {
59845
60181
  }
59846
60182
  }
59847
60183
  };
60184
+ const normalizedPublicDir = normalizePath$3(config.publicDir);
59848
60185
  const onFileAddUnlink = async (file, isUnlink) => {
59849
60186
  file = normalizePath$3(file);
59850
60187
  await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' });
59851
- if (publicFiles && config.publicDir && file.startsWith(config.publicDir)) {
59852
- publicFiles[isUnlink ? 'delete' : 'add'](file.slice(config.publicDir.length));
60188
+ if (config.publicDir && publicFiles) {
60189
+ if (file.startsWith(normalizedPublicDir)) {
60190
+ publicFiles[isUnlink ? 'delete' : 'add'](file.slice(normalizedPublicDir.length));
60191
+ }
59853
60192
  }
59854
60193
  await handleFileAddUnlink(file, server, isUnlink);
59855
60194
  await onHMRUpdate(file, true);
@@ -59861,8 +60200,13 @@ async function _createServer(inlineConfig = {}, options) {
59861
60200
  moduleGraph.onFileChange(file);
59862
60201
  await onHMRUpdate(file, false);
59863
60202
  });
59864
- watcher.on('add', (file) => onFileAddUnlink(file, false));
59865
- watcher.on('unlink', (file) => onFileAddUnlink(file, true));
60203
+ getFsUtils(config).initWatcher?.(watcher);
60204
+ watcher.on('add', (file) => {
60205
+ onFileAddUnlink(file, false);
60206
+ });
60207
+ watcher.on('unlink', (file) => {
60208
+ onFileAddUnlink(file, true);
60209
+ });
59866
60210
  ws.on('vite:invalidate', async ({ path, message }) => {
59867
60211
  const mod = moduleGraph.urlToModuleMap.get(path);
59868
60212
  if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
@@ -59931,7 +60275,7 @@ async function _createServer(inlineConfig = {}, options) {
59931
60275
  middlewares.use(serveStaticMiddleware(server));
59932
60276
  // html fallback
59933
60277
  if (config.appType === 'spa' || config.appType === 'mpa') {
59934
- middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'));
60278
+ middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa', getFsUtils(config)));
59935
60279
  }
59936
60280
  // run post config hooks
59937
60281
  // This is applied before the html middleware so that user middleware can
@@ -60073,6 +60417,7 @@ function resolveServerOptions(root, raw, logger) {
60073
60417
  strict: server.fs?.strict ?? true,
60074
60418
  allow: allowDirs,
60075
60419
  deny,
60420
+ cachedChecks: server.fs?.cachedChecks ?? !!process.env.VITE_SERVER_FS_CACHED_CHECKS,
60076
60421
  };
60077
60422
  if (server.origin?.endsWith('/')) {
60078
60423
  server.origin = server.origin.slice(0, -1);
@@ -60899,10 +61244,21 @@ async function workerFileToUrl(config, id, query) {
60899
61244
  function webWorkerPostPlugin() {
60900
61245
  return {
60901
61246
  name: 'vite:worker-post',
60902
- resolveImportMeta(property, { chunkId, format }) {
61247
+ resolveImportMeta(property, { format }) {
60903
61248
  // document is undefined in the worker, so we need to avoid it in iife
60904
- if (property === 'url' && format === 'iife') {
60905
- return 'self.location.href';
61249
+ if (format === 'iife') {
61250
+ // compiling import.meta
61251
+ if (!property) {
61252
+ // rollup only supports `url` property. we only support `url` property as well.
61253
+ // https://github.com/rollup/rollup/blob/62b648e1cc6a1f00260bb85aa2050097bb4afd2b/src/ast/nodes/MetaProperty.ts#L164-L173
61254
+ return `{
61255
+ url: self.location.href
61256
+ }`;
61257
+ }
61258
+ // compiling import.meta.url
61259
+ if (property === 'url') {
61260
+ return 'self.location.href';
61261
+ }
60906
61262
  }
60907
61263
  return null;
60908
61264
  },
@@ -61204,6 +61560,7 @@ function extractImportedBindings(id, source, importSpec, importedBindings) {
61204
61560
  */
61205
61561
  function importAnalysisPlugin(config) {
61206
61562
  const { root, base } = config;
61563
+ const fsUtils = getFsUtils(config);
61207
61564
  const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH);
61208
61565
  const enablePartialAccept = config.experimental?.hmrPartialAccept;
61209
61566
  let server;
@@ -61331,8 +61688,12 @@ function importAnalysisPlugin(config) {
61331
61688
  url = resolved.id.slice(root.length);
61332
61689
  }
61333
61690
  else if (depsOptimizer?.isOptimizedDepFile(resolved.id) ||
61334
- (path$o.isAbsolute(cleanUrl(resolved.id)) &&
61335
- fs$l.existsSync(cleanUrl(resolved.id)))) {
61691
+ // vite-plugin-react isn't following the leading \0 virtual module convention.
61692
+ // This is a temporary hack to avoid expensive fs checks for React apps.
61693
+ // We'll remove this as soon we're able to fix the react plugins.
61694
+ (resolved.id !== '/@react-refresh' &&
61695
+ path$o.isAbsolute(resolved.id) &&
61696
+ fsUtils.existsSync(cleanUrl(resolved.id)))) {
61336
61697
  // an optimized deps may not yet exists in the filesystem, or
61337
61698
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
61338
61699
  url = path$o.posix.join(FS_PREFIX, resolved.id);
@@ -61986,6 +62347,7 @@ function preAliasPlugin(config) {
61986
62347
  const findPatterns = getAliasPatterns(config.resolve.alias);
61987
62348
  const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
61988
62349
  const isBuild = config.command === 'build';
62350
+ const fsUtils = getFsUtils(config);
61989
62351
  return {
61990
62352
  name: 'vite:pre-alias',
61991
62353
  async resolveId(id, importer, options) {
@@ -62014,7 +62376,7 @@ function preAliasPlugin(config) {
62014
62376
  const resolvedId = cleanUrl(resolved.id);
62015
62377
  const isVirtual = resolvedId === id || resolvedId.includes('\0');
62016
62378
  if (!isVirtual &&
62017
- fs$l.existsSync(resolvedId) &&
62379
+ fsUtils.existsSync(resolvedId) &&
62018
62380
  !moduleListContains(optimizeDeps.exclude, id) &&
62019
62381
  path$o.isAbsolute(resolvedId) &&
62020
62382
  (isInNodeModules$1(resolvedId) ||
@@ -62712,6 +63074,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
62712
63074
  packageCache: config.packageCache,
62713
63075
  ssrConfig: config.ssr,
62714
63076
  asSrc: true,
63077
+ fsUtils: getFsUtils(config),
62715
63078
  getDepsOptimizer: (ssr) => getDepsOptimizer(config, ssr),
62716
63079
  shouldExternalize: isBuild && config.build.ssr
62717
63080
  ? (id, importer) => shouldExternalizeForSSR(id, importer, config)
@@ -63798,16 +64161,6 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
63798
64161
  external: doExternalize(path),
63799
64162
  };
63800
64163
  });
63801
- // onResolve is not called for glob imports.
63802
- // we need to add that here as well until esbuild calls onResolve for glob imports.
63803
- // https://github.com/evanw/esbuild/issues/3317
63804
- build.onLoad({ filter, namespace: 'file' }, () => {
63805
- const externalOnLoadResult = {
63806
- loader: 'js',
63807
- contents: 'export default {}',
63808
- };
63809
- return externalOnLoadResult;
63810
- });
63811
64164
  };
63812
64165
  // css
63813
64166
  setupExternalize(CSS_LANGS_RE, isUnlessEntry);
@@ -63867,6 +64220,15 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
63867
64220
  contents,
63868
64221
  };
63869
64222
  });
64223
+ // onResolve is not called for glob imports.
64224
+ // we need to add that here as well until esbuild calls onResolve for glob imports.
64225
+ // https://github.com/evanw/esbuild/issues/3317
64226
+ build.onLoad({ filter: /.*/, namespace: 'file' }, () => {
64227
+ return {
64228
+ loader: 'js',
64229
+ contents: 'export default {}',
64230
+ };
64231
+ });
63870
64232
  },
63871
64233
  };
63872
64234
  }
@@ -64710,9 +65072,11 @@ async function optimizeServerSsrDeps(config) {
64710
65072
  return result.metadata;
64711
65073
  }
64712
65074
  function initDepsOptimizerMetadata(config, ssr, timestamp) {
64713
- const hash = getDepHash(config, ssr);
65075
+ const { lockfileHash, configHash, hash } = getDepHash(config, ssr);
64714
65076
  return {
64715
65077
  hash,
65078
+ lockfileHash,
65079
+ configHash,
64716
65080
  browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
64717
65081
  optimized: {},
64718
65082
  chunks: {},
@@ -64746,11 +65110,19 @@ async function loadCachedDepOptimizationMetadata(config, ssr, force = config.opt
64746
65110
  }
64747
65111
  catch (e) { }
64748
65112
  // hash is consistent, no need to re-bundle
64749
- if (cachedMetadata && cachedMetadata.hash === getDepHash(config, ssr)) {
64750
- log?.('Hash is consistent. Skipping. Use --force to override.');
64751
- // Nothing to commit or cancel as we are using the cache, we only
64752
- // need to resolve the processing promise so requests can move on
64753
- return cachedMetadata;
65113
+ if (cachedMetadata) {
65114
+ if (cachedMetadata.lockfileHash !== getLockfileHash(config)) {
65115
+ config.logger.info('Re-optimizing dependencies because lockfile has changed');
65116
+ }
65117
+ else if (cachedMetadata.configHash !== getConfigHash(config, ssr)) {
65118
+ config.logger.info('Re-optimizing dependencies because vite config has changed');
65119
+ }
65120
+ else {
65121
+ log?.('Hash is consistent. Skipping. Use --force to override.');
65122
+ // Nothing to commit or cancel as we are using the cache, we only
65123
+ // need to resolve the processing promise so requests can move on
65124
+ return cachedMetadata;
65125
+ }
64754
65126
  }
64755
65127
  }
64756
65128
  else {
@@ -64780,7 +65152,7 @@ function discoverProjectDependencies(config) {
64780
65152
  };
64781
65153
  }
64782
65154
  function toDiscoveredDependencies(config, deps, ssr, timestamp) {
64783
- const browserHash = getOptimizedBrowserHash(getDepHash(config, ssr), deps, timestamp);
65155
+ const browserHash = getOptimizedBrowserHash(getDepHash(config, ssr).hash, deps, timestamp);
64784
65156
  const discovered = {};
64785
65157
  for (const id in deps) {
64786
65158
  const src = deps[id];
@@ -64810,7 +65182,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
64810
65182
  };
64811
65183
  const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr);
64812
65184
  const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr);
64813
- // Create a temporal directory so we don't need to delete optimized deps
65185
+ // Create a temporary directory so we don't need to delete optimized deps
64814
65186
  // until they have been processed. This also avoids leaving the deps cache
64815
65187
  // directory in a corrupted state if there is an error
64816
65188
  fs$l.mkdirSync(processingCacheDir, { recursive: true });
@@ -64850,40 +65222,40 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
64850
65222
  // we finish commiting the new deps cache files to the deps folder
64851
65223
  committed = true;
64852
65224
  // Write metadata file, then commit the processing folder to the global deps cache
64853
- // Rewire the file paths from the temporal processing dir to the final deps cache dir
65225
+ // Rewire the file paths from the temporary processing dir to the final deps cache dir
64854
65226
  const dataPath = path$o.join(processingCacheDir, '_metadata.json');
64855
65227
  debug$1?.(colors$1.green(`creating _metadata.json in ${processingCacheDir}`));
64856
65228
  fs$l.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
64857
65229
  // In order to minimize the time where the deps folder isn't in a consistent state,
64858
- // we first rename the old depsCacheDir to a temporal path, then we rename the
65230
+ // we first rename the old depsCacheDir to a temporary path, then we rename the
64859
65231
  // new processing cache dir to the depsCacheDir. In systems where doing so in sync
64860
65232
  // is safe, we do an atomic operation (at least for this thread). For Windows, we
64861
65233
  // found there are cases where the rename operation may finish before it's done
64862
65234
  // so we do a graceful rename checking that the folder has been properly renamed.
64863
65235
  // We found that the rename-rename (then delete the old folder in the background)
64864
65236
  // is safer than a delete-rename operation.
64865
- const temporalPath = depsCacheDir + getTempSuffix();
65237
+ const temporaryPath = depsCacheDir + getTempSuffix();
64866
65238
  const depsCacheDirPresent = fs$l.existsSync(depsCacheDir);
64867
65239
  if (isWindows$4) {
64868
65240
  if (depsCacheDirPresent) {
64869
- debug$1?.(colors$1.green(`renaming ${depsCacheDir} to ${temporalPath}`));
64870
- await safeRename(depsCacheDir, temporalPath);
65241
+ debug$1?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
65242
+ await safeRename(depsCacheDir, temporaryPath);
64871
65243
  }
64872
65244
  debug$1?.(colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
64873
65245
  await safeRename(processingCacheDir, depsCacheDir);
64874
65246
  }
64875
65247
  else {
64876
65248
  if (depsCacheDirPresent) {
64877
- debug$1?.(colors$1.green(`renaming ${depsCacheDir} to ${temporalPath}`));
64878
- fs$l.renameSync(depsCacheDir, temporalPath);
65249
+ debug$1?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
65250
+ fs$l.renameSync(depsCacheDir, temporaryPath);
64879
65251
  }
64880
65252
  debug$1?.(colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
64881
65253
  fs$l.renameSync(processingCacheDir, depsCacheDir);
64882
65254
  }
64883
- // Delete temporal path in the background
65255
+ // Delete temporary path in the background
64884
65256
  if (depsCacheDirPresent) {
64885
- debug$1?.(colors$1.green(`removing cache temp dir ${temporalPath}`));
64886
- fsp.rm(temporalPath, { recursive: true, force: true });
65257
+ debug$1?.(colors$1.green(`removing cache temp dir ${temporaryPath}`));
65258
+ fsp.rm(temporaryPath, { recursive: true, force: true });
64887
65259
  }
64888
65260
  },
64889
65261
  };
@@ -65182,7 +65554,7 @@ function createIsOptimizedDepUrl(config) {
65182
65554
  };
65183
65555
  }
65184
65556
  function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
65185
- const { hash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
65557
+ const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
65186
65558
  // Paths can be absolute or relative to the deps cache dir where
65187
65559
  // the _metadata.json is located
65188
65560
  if (key === 'file' || key === 'src') {
@@ -65197,6 +65569,8 @@ function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
65197
65569
  }
65198
65570
  const metadata = {
65199
65571
  hash,
65572
+ lockfileHash,
65573
+ configHash,
65200
65574
  browserHash,
65201
65575
  optimized: {},
65202
65576
  discovered: {},
@@ -65227,9 +65601,11 @@ function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
65227
65601
  * browserHash to allow long term caching
65228
65602
  */
65229
65603
  function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
65230
- const { hash, browserHash, optimized, chunks } = metadata;
65604
+ const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
65231
65605
  return JSON.stringify({
65232
65606
  hash,
65607
+ configHash,
65608
+ lockfileHash,
65233
65609
  browserHash,
65234
65610
  optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop }) => [
65235
65611
  id,
@@ -65343,25 +65719,11 @@ const lockfileFormats = [
65343
65719
  return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
65344
65720
  });
65345
65721
  const lockfileNames = lockfileFormats.map((l) => l.name);
65346
- function getDepHash(config, ssr) {
65347
- const lockfilePath = lookupFile(config.root, lockfileNames);
65348
- let content = lockfilePath ? fs$l.readFileSync(lockfilePath, 'utf-8') : '';
65349
- if (lockfilePath) {
65350
- const lockfileName = path$o.basename(lockfilePath);
65351
- const { checkPatches } = lockfileFormats.find((f) => f.name === lockfileName);
65352
- if (checkPatches) {
65353
- // Default of https://github.com/ds300/patch-package
65354
- const fullPath = path$o.join(path$o.dirname(lockfilePath), 'patches');
65355
- const stat = tryStatSync(fullPath);
65356
- if (stat?.isDirectory()) {
65357
- content += stat.mtimeMs.toString();
65358
- }
65359
- }
65360
- }
65361
- // also take config into account
65722
+ function getConfigHash(config, ssr) {
65723
+ // Take config into account
65362
65724
  // only a subset of config options that can affect dep optimization
65363
65725
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
65364
- content += JSON.stringify({
65726
+ const content = JSON.stringify({
65365
65727
  mode: process.env.NODE_ENV || config.mode,
65366
65728
  root: config.root,
65367
65729
  resolve: config.resolve,
@@ -65369,8 +65731,12 @@ function getDepHash(config, ssr) {
65369
65731
  assetsInclude: config.assetsInclude,
65370
65732
  plugins: config.plugins.map((p) => p.name),
65371
65733
  optimizeDeps: {
65372
- include: optimizeDeps?.include,
65373
- exclude: optimizeDeps?.exclude,
65734
+ include: optimizeDeps?.include
65735
+ ? Array.from(new Set(optimizeDeps.include)).sort()
65736
+ : undefined,
65737
+ exclude: optimizeDeps?.exclude
65738
+ ? Array.from(new Set(optimizeDeps.exclude)).sort()
65739
+ : undefined,
65374
65740
  esbuildOptions: {
65375
65741
  ...optimizeDeps?.esbuildOptions,
65376
65742
  plugins: optimizeDeps?.esbuildOptions?.plugins?.map((p) => p.name),
@@ -65384,6 +65750,33 @@ function getDepHash(config, ssr) {
65384
65750
  });
65385
65751
  return getHash(content);
65386
65752
  }
65753
+ function getLockfileHash(config, ssr) {
65754
+ const lockfilePath = lookupFile(config.root, lockfileNames);
65755
+ let content = lockfilePath ? fs$l.readFileSync(lockfilePath, 'utf-8') : '';
65756
+ if (lockfilePath) {
65757
+ const lockfileName = path$o.basename(lockfilePath);
65758
+ const { checkPatches } = lockfileFormats.find((f) => f.name === lockfileName);
65759
+ if (checkPatches) {
65760
+ // Default of https://github.com/ds300/patch-package
65761
+ const fullPath = path$o.join(path$o.dirname(lockfilePath), 'patches');
65762
+ const stat = tryStatSync(fullPath);
65763
+ if (stat?.isDirectory()) {
65764
+ content += stat.mtimeMs.toString();
65765
+ }
65766
+ }
65767
+ }
65768
+ return getHash(content);
65769
+ }
65770
+ function getDepHash(config, ssr) {
65771
+ const lockfileHash = getLockfileHash(config);
65772
+ const configHash = getConfigHash(config, ssr);
65773
+ const hash = getHash(lockfileHash + configHash);
65774
+ return {
65775
+ hash,
65776
+ lockfileHash,
65777
+ configHash,
65778
+ };
65779
+ }
65387
65780
  function getOptimizedBrowserHash(hash, deps, timestamp = '') {
65388
65781
  return getHash(hash + JSON.stringify(deps) + timestamp);
65389
65782
  }
@@ -65478,7 +65871,6 @@ var index = {
65478
65871
  depsLogString: depsLogString,
65479
65872
  discoverProjectDependencies: discoverProjectDependencies,
65480
65873
  extractExportsData: extractExportsData,
65481
- getDepHash: getDepHash,
65482
65874
  getDepsCacheDir: getDepsCacheDir,
65483
65875
  getDepsOptimizer: getDepsOptimizer,
65484
65876
  getOptimizedDepPath: getOptimizedDepPath,
@@ -67235,6 +67627,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
67235
67627
  tryIndex: true,
67236
67628
  ...options,
67237
67629
  idOnly: true,
67630
+ fsUtils: getFsUtils(resolved),
67238
67631
  }),
67239
67632
  ],
67240
67633
  }));