vite 4.3.0-beta.0 → 4.3.0-beta.1

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.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

@@ -1,4 +1,5 @@
1
1
  import fs$l, { promises as promises$2 } from 'node:fs';
2
+ import fsp from 'node:fs/promises';
2
3
  import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
3
4
  import { URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
4
5
  import { performance as performance$1 } from 'node:perf_hooks';
@@ -18,14 +19,14 @@ import require$$0$7 from 'stream';
18
19
  import require$$2 from 'os';
19
20
  import require$$2$1 from 'child_process';
20
21
  import os$3 from 'node:os';
22
+ import { exec } from 'node:child_process';
21
23
  import { createHash as createHash$2 } from 'node:crypto';
22
- import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
23
24
  import { promises } from 'node:dns';
24
25
  import resolve$4 from 'resolve';
25
26
  import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, SPECIAL_QUERY_RE, DEP_VERSION_RE, CSS_LANGS_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION as VERSION$1, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
26
27
  import require$$5$1 from 'crypto';
27
28
  import { Buffer as Buffer$1 } from 'node:buffer';
28
- import fsp from 'node:fs/promises';
29
+ import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
29
30
  import require$$0$8, { createRequire as createRequire$2 } from 'module';
30
31
  import assert$1 from 'node:assert';
31
32
  import process$1 from 'node:process';
@@ -40,7 +41,6 @@ import { createServer as createServer$2 } from 'node:https';
40
41
  import { VERSION } from 'rollup';
41
42
  import * as qs from 'querystring';
42
43
  import readline from 'node:readline';
43
- import { exec } from 'node:child_process';
44
44
  import zlib$1, { gzip } from 'node:zlib';
45
45
 
46
46
  import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
@@ -11596,6 +11596,9 @@ function isBuiltin(id) {
11596
11596
  ? id.slice(NODE_BUILTIN_NAMESPACE.length)
11597
11597
  : id);
11598
11598
  }
11599
+ function isInNodeModules(id) {
11600
+ return id.includes('node_modules');
11601
+ }
11599
11602
  function moduleListContains(moduleList, id) {
11600
11603
  return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
11601
11604
  }
@@ -11687,8 +11690,10 @@ function ensureVolumeInPath(file) {
11687
11690
  return isWindows$4 ? path$o.resolve(file) : file;
11688
11691
  }
11689
11692
  const queryRE = /\?.*$/s;
11690
- const hashRE = /#.*$/s;
11691
- const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, '');
11693
+ const postfixRE = /[?#].*$/s;
11694
+ function cleanUrl(url) {
11695
+ return url.replace(postfixRE, '');
11696
+ }
11692
11697
  const externalRE = /^(https?:)?\/\//;
11693
11698
  const isExternalUrl = (url) => externalRE.test(url);
11694
11699
  const dataUrlRE = /^\s*data:/i;
@@ -11706,19 +11711,8 @@ const isJSRequest = (url) => {
11706
11711
  }
11707
11712
  return false;
11708
11713
  };
11709
- const knownTsRE = /\.(?:ts|mts|cts|tsx)$/;
11710
- const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
11714
+ const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
11711
11715
  const isTsRequest = (url) => knownTsRE.test(url);
11712
- const isPossibleTsOutput = (url) => knownTsOutputRE.test(cleanUrl(url));
11713
- const splitFilePathAndQueryRE = /(\.(?:[cm]?js|jsx))(\?.*)?$/;
11714
- function getPotentialTsSrcPaths(filePath) {
11715
- const [name, type, query = ''] = filePath.split(splitFilePathAndQueryRE);
11716
- const paths = [name + type.replace('js', 'ts') + query];
11717
- if (type[type.length - 1] !== 'x') {
11718
- paths.push(name + type.replace('js', 'tsx') + query);
11719
- }
11720
- return paths;
11721
- }
11722
11716
  const importQueryRE = /(\?|&)import=?(?:&|$)/;
11723
11717
  const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
11724
11718
  const internalPrefixes = [
@@ -11796,22 +11790,25 @@ function isObject$2(value) {
11796
11790
  function isDefined(value) {
11797
11791
  return value != null;
11798
11792
  }
11799
- function lookupFile(dir, formats, options) {
11800
- for (const format of formats) {
11801
- const fullPath = path$o.join(dir, format);
11802
- if (fs$l.existsSync(fullPath) && fs$l.statSync(fullPath).isFile()) {
11803
- const result = options?.pathOnly
11804
- ? fullPath
11805
- : fs$l.readFileSync(fullPath, 'utf-8');
11806
- if (!options?.predicate || options.predicate(result)) {
11807
- return result;
11808
- }
11809
- }
11793
+ function tryStatSync(file) {
11794
+ try {
11795
+ return fs$l.statSync(file, { throwIfNoEntry: false });
11796
+ }
11797
+ catch {
11798
+ // Ignore errors
11810
11799
  }
11811
- const parentDir = path$o.dirname(dir);
11812
- if (parentDir !== dir &&
11813
- (!options?.rootDir || parentDir.startsWith(options?.rootDir))) {
11814
- return lookupFile(parentDir, formats, options);
11800
+ }
11801
+ function lookupFile(dir, fileNames) {
11802
+ while (dir) {
11803
+ for (const fileName of fileNames) {
11804
+ const fullPath = path$o.join(dir, fileName);
11805
+ if (tryStatSync(fullPath)?.isFile())
11806
+ return fullPath;
11807
+ }
11808
+ const parentDir = path$o.dirname(dir);
11809
+ if (parentDir === dir)
11810
+ return;
11811
+ dir = parentDir;
11815
11812
  }
11816
11813
  }
11817
11814
  const splitRE = /\r?\n/;
@@ -11885,13 +11882,6 @@ function generateCodeFrame(source, start = 0, end) {
11885
11882
  }
11886
11883
  return res.join('\n');
11887
11884
  }
11888
- function writeFile(filename, content) {
11889
- const dir = path$o.dirname(filename);
11890
- if (!fs$l.existsSync(dir)) {
11891
- fs$l.mkdirSync(dir, { recursive: true });
11892
- }
11893
- fs$l.writeFileSync(filename, content);
11894
- }
11895
11885
  function isFileReadable(filename) {
11896
11886
  try {
11897
11887
  fs$l.accessSync(filename, fs$l.constants.R_OK);
@@ -11960,23 +11950,54 @@ function copyDir(srcDir, destDir) {
11960
11950
  }
11961
11951
  }
11962
11952
  }
11963
- const removeDir = isWindows$4
11964
- ? promisify$4(gracefulRemoveDir)
11965
- : function removeDirSync(dir) {
11966
- // when removing `.vite/deps`, if it doesn't exist, nodejs may also remove
11967
- // other directories within `.vite/`, including `.vite/deps_temp` (bug).
11968
- // workaround by checking for directory existence before removing for now.
11969
- if (fs$l.existsSync(dir)) {
11970
- fs$l.rmSync(dir, { recursive: true, force: true });
11971
- }
11972
- };
11973
- const renameDir = isWindows$4 ? promisify$4(gracefulRename) : fs$l.renameSync;
11974
11953
  // `fs.realpathSync.native` resolves differently in Windows network drive,
11975
11954
  // causing file read errors. skip for now.
11976
11955
  // https://github.com/nodejs/node/issues/37737
11977
- const safeRealpathSync = isWindows$4
11978
- ? fs$l.realpathSync
11956
+ let safeRealpathSync = isWindows$4
11957
+ ? windowsSafeRealPathSync
11979
11958
  : fs$l.realpathSync.native;
11959
+ // Based on https://github.com/larrybahr/windows-network-drive
11960
+ // MIT License, Copyright (c) 2017 Larry Bahr
11961
+ const windowsNetworkMap = new Map();
11962
+ function windowsMappedRealpathSync(path) {
11963
+ const realPath = fs$l.realpathSync.native(path);
11964
+ if (realPath.startsWith('\\\\')) {
11965
+ for (const [network, volume] of windowsNetworkMap) {
11966
+ if (realPath.startsWith(network))
11967
+ return realPath.replace(network, volume);
11968
+ }
11969
+ }
11970
+ return realPath;
11971
+ }
11972
+ const parseNetUseRE = /^(\w+) +(\w:) +([^ ]+)\s/;
11973
+ let firstSafeRealPathSyncRun = false;
11974
+ function windowsSafeRealPathSync(path) {
11975
+ if (!firstSafeRealPathSyncRun) {
11976
+ optimizeSafeRealPathSync();
11977
+ firstSafeRealPathSyncRun = true;
11978
+ }
11979
+ return fs$l.realpathSync(path);
11980
+ }
11981
+ function optimizeSafeRealPathSync() {
11982
+ exec('net use', (error, stdout) => {
11983
+ if (error)
11984
+ return;
11985
+ const lines = stdout.split('\n');
11986
+ // OK Y: \\NETWORKA\Foo Microsoft Windows Network
11987
+ // OK Z: \\NETWORKA\Bar Microsoft Windows Network
11988
+ for (const line of lines) {
11989
+ const m = line.match(parseNetUseRE);
11990
+ if (m)
11991
+ windowsNetworkMap.set(m[3], m[2]);
11992
+ }
11993
+ if (windowsNetworkMap.size === 0) {
11994
+ safeRealpathSync = fs$l.realpathSync.native;
11995
+ }
11996
+ else {
11997
+ safeRealpathSync = windowsMappedRealpathSync;
11998
+ }
11999
+ });
12000
+ }
11980
12001
  function ensureWatchedFile(watcher, file, root) {
11981
12002
  if (file &&
11982
12003
  // only need to watch if out of root
@@ -12244,63 +12265,6 @@ const requireResolveFromRootWithFallback = (root, id) => {
12244
12265
  // Use `require.resolve` again as the `resolve` package doesn't support the `exports` field
12245
12266
  return _require$3.resolve(id, { paths });
12246
12267
  };
12247
- // Based on node-graceful-fs
12248
- // The ISC License
12249
- // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
12250
- // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
12251
- // On Windows, A/V software can lock the directory, causing this
12252
- // to fail with an EACCES or EPERM if the directory contains newly
12253
- // created files. The original tried for up to 60 seconds, we only
12254
- // wait for 5 seconds, as a longer time would be seen as an error
12255
- const GRACEFUL_RENAME_TIMEOUT = 5000;
12256
- function gracefulRename(from, to, cb) {
12257
- const start = Date.now();
12258
- let backoff = 0;
12259
- fs$l.rename(from, to, function CB(er) {
12260
- if (er &&
12261
- (er.code === 'EACCES' || er.code === 'EPERM') &&
12262
- Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
12263
- setTimeout(function () {
12264
- fs$l.stat(to, function (stater, st) {
12265
- if (stater && stater.code === 'ENOENT')
12266
- fs$l.rename(from, to, CB);
12267
- else
12268
- CB(er);
12269
- });
12270
- }, backoff);
12271
- if (backoff < 100)
12272
- backoff += 10;
12273
- return;
12274
- }
12275
- if (cb)
12276
- cb(er);
12277
- });
12278
- }
12279
- const GRACEFUL_REMOVE_DIR_TIMEOUT = 5000;
12280
- function gracefulRemoveDir(dir, cb) {
12281
- const start = Date.now();
12282
- let backoff = 0;
12283
- fs$l.rm(dir, { recursive: true }, function CB(er) {
12284
- if (er) {
12285
- if ((er.code === 'ENOTEMPTY' ||
12286
- er.code === 'EACCES' ||
12287
- er.code === 'EPERM') &&
12288
- Date.now() - start < GRACEFUL_REMOVE_DIR_TIMEOUT) {
12289
- setTimeout(function () {
12290
- fs$l.rm(dir, { recursive: true }, CB);
12291
- }, backoff);
12292
- if (backoff < 100)
12293
- backoff += 10;
12294
- return;
12295
- }
12296
- if (er.code === 'ENOENT') {
12297
- er = null;
12298
- }
12299
- }
12300
- if (cb)
12301
- cb(er);
12302
- });
12303
- }
12304
12268
  function emptyCssComments(raw) {
12305
12269
  return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length));
12306
12270
  }
@@ -12608,6 +12572,7 @@ const groups = [
12608
12572
  { name: 'CSS', color: picocolorsExports.magenta },
12609
12573
  { name: 'JS', color: picocolorsExports.cyan },
12610
12574
  ];
12575
+ const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
12611
12576
  function buildReporterPlugin(config) {
12612
12577
  const compress = promisify$4(gzip);
12613
12578
  const chunkLimit = config.build.chunkSizeWarningLimit;
@@ -12714,12 +12679,13 @@ function buildReporterPlugin(config) {
12714
12679
  if (chunk.fileName.endsWith('.map'))
12715
12680
  return null;
12716
12681
  const isCSS = chunk.fileName.endsWith('.css');
12682
+ const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
12717
12683
  return {
12718
12684
  name: chunk.fileName,
12719
12685
  group: isCSS ? 'CSS' : 'Assets',
12720
12686
  size: chunk.source.length,
12721
12687
  mapSize: null,
12722
- compressedSize: isCSS
12688
+ compressedSize: isCompressible
12723
12689
  ? await getCompressedSize(chunk.source)
12724
12690
  : null,
12725
12691
  };
@@ -13416,7 +13382,7 @@ var TSConfckParseError = class extends Error {
13416
13382
  }
13417
13383
  };
13418
13384
 
13419
- const isDebug$6 = process.env.DEBUG;
13385
+ const isDebug$7 = process.env.DEBUG;
13420
13386
  const debug$e = createDebugger('vite:esbuild');
13421
13387
  const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s;
13422
13388
  const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s;
@@ -13760,7 +13726,7 @@ function initTSConfck(root, force = false) {
13760
13726
  });
13761
13727
  }
13762
13728
  async function initTSConfckParseOptions(workspaceRoot) {
13763
- const start = isDebug$6 ? performance.now() : 0;
13729
+ const start = isDebug$7 ? performance.now() : 0;
13764
13730
  const options = {
13765
13731
  cache: new Map(),
13766
13732
  root: workspaceRoot,
@@ -13769,7 +13735,7 @@ async function initTSConfckParseOptions(workspaceRoot) {
13769
13735
  })),
13770
13736
  resolveWithEmptyIfConfigNotFound: true,
13771
13737
  };
13772
- isDebug$6 && debug$e(timeFrom(start), 'tsconfck init', picocolorsExports.dim(workspaceRoot));
13738
+ isDebug$7 && debug$e(timeFrom(start), 'tsconfck init', picocolorsExports.dim(workspaceRoot));
13773
13739
  return options;
13774
13740
  }
13775
13741
  async function loadTsconfigJsonForFile(filename) {
@@ -16045,7 +16011,7 @@ function dataURIPlugin() {
16045
16011
  /* es-module-lexer 1.2.0 */
16046
16012
  const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const D=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let K;C.ip()&&(K=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),D.push({n:K,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],K=B<0?void 0:E.slice(B,g),D=K?K[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===D||"'"===D?J(K):K});}function J(A){try{return (0, eval)(A)}catch(A){}}return [D,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gAn9/AAMvLgABAQICAgICAgICAgICAgICAgIAAwMDBAQAAAADAAAAAAMDAAUGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwdwEwZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAmFpAAgCaWQACQJpcAAKAmVzAAsCZWUADANlbHMADQNlbGUADgJyaQAPAnJlABABZgARBXBhcnNlABILX19oZWFwX2Jhc2UDAQrAOy5o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A0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKgChAiQQAPC0EAIAI2AqAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+IBAgBBgAgLxAEAAHgAcABvAHIAdABtAHAAbwByAHQAZQB0AGEAcgBvAG0AdQBuAGMAdABpAG8AbgBzAHMAZQByAHQAdgBvAHkAaQBlAGQAZQBsAGUAYwBvAG4AdABpAG4AaQBuAHMAdABhAG4AdAB5AGIAcgBlAGEAcgBlAHQAdQByAGQAZQBiAHUAZwBnAGUAYQB3AGEAaQB0AGgAcgB3AGgAaQBsAGUAZgBvAHIAaQBmAGMAYQB0AGMAZgBpAG4AYQBsAGwAZQBsAHMAAEHECQsQAQAAAAIAAAAABAAAMDkAAA==","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E;
16047
16013
 
16048
- const isDebug$5 = !!process.env.DEBUG;
16014
+ const isDebug$6 = !!process.env.DEBUG;
16049
16015
  const debug$d = createDebugger('vite:sourcemap', {
16050
16016
  onlyWhenFocused: true,
16051
16017
  });
@@ -16079,7 +16045,7 @@ async function injectSourcesContent(map, file, logger) {
16079
16045
  // …to log the missing sources.
16080
16046
  if (missingSources.length) {
16081
16047
  logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
16082
- isDebug$5 && debug$d(`Missing sources:\n ` + missingSources.join(`\n `));
16048
+ isDebug$6 && debug$d(`Missing sources:\n ` + missingSources.join(`\n `));
16083
16049
  }
16084
16050
  }
16085
16051
  function genSourceMapUrl(map) {
@@ -16089,7 +16055,7 @@ function genSourceMapUrl(map) {
16089
16055
  return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
16090
16056
  }
16091
16057
  function getCodeWithSourcemap(type, code, map) {
16092
- if (isDebug$5) {
16058
+ if (isDebug$6) {
16093
16059
  code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
16094
16060
  }
16095
16061
  if (type === 'js') {
@@ -16100,6 +16066,30 @@ function getCodeWithSourcemap(type, code, map) {
16100
16066
  }
16101
16067
  return code;
16102
16068
  }
16069
+ function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
16070
+ let { x_google_ignoreList } = map;
16071
+ if (x_google_ignoreList === undefined) {
16072
+ x_google_ignoreList = [];
16073
+ }
16074
+ for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
16075
+ const sourcePath = map.sources[sourcesIndex];
16076
+ if (!sourcePath)
16077
+ continue;
16078
+ const ignoreList = sourcemapIgnoreList(path$o.isAbsolute(sourcePath)
16079
+ ? sourcePath
16080
+ : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath);
16081
+ if (logger && typeof ignoreList !== 'boolean') {
16082
+ logger.warn('sourcemapIgnoreList function must return a boolean.');
16083
+ }
16084
+ if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
16085
+ x_google_ignoreList.push(sourcesIndex);
16086
+ }
16087
+ }
16088
+ if (x_google_ignoreList.length > 0) {
16089
+ if (!map.x_google_ignoreList)
16090
+ map.x_google_ignoreList = x_google_ignoreList;
16091
+ }
16092
+ }
16103
16093
 
16104
16094
  // eslint-disable-next-line @typescript-eslint/consistent-type-imports
16105
16095
  let pnp;
@@ -16182,6 +16172,14 @@ function findNearestPackageData(basedir, packageCache) {
16182
16172
  }
16183
16173
  return null;
16184
16174
  }
16175
+ // Finds the nearest package.json with a `name` field
16176
+ function findNearestMainPackageData(basedir, packageCache) {
16177
+ const nearestPackage = findNearestPackageData(basedir, packageCache);
16178
+ return (nearestPackage &&
16179
+ (nearestPackage.data.name
16180
+ ? nearestPackage
16181
+ : findNearestMainPackageData(path$o.dirname(nearestPackage.dir), packageCache)));
16182
+ }
16185
16183
  function loadPackageData(pkgPath) {
16186
16184
  const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8'));
16187
16185
  const pkgDir = path$o.dirname(pkgPath);
@@ -22387,302 +22385,6 @@ function hasESMSyntax(code) {
22387
22385
  return ESM_RE.test(code);
22388
22386
  }
22389
22387
 
22390
- const WORKER_FILE_ID = 'worker_file';
22391
- const workerCache = new WeakMap();
22392
- function isWorkerRequest(id) {
22393
- const query = parseRequest(id);
22394
- if (query && query[WORKER_FILE_ID] != null) {
22395
- return true;
22396
- }
22397
- return false;
22398
- }
22399
- function saveEmitWorkerAsset(config, asset) {
22400
- const fileName = asset.fileName;
22401
- const workerMap = workerCache.get(config.mainConfig || config);
22402
- workerMap.assets.set(fileName, asset);
22403
- }
22404
- // Ensure that only one rollup build is called at the same time to avoid
22405
- // leaking state in plugins between worker builds.
22406
- // TODO: Review if we can parallelize the bundling of workers.
22407
- const workerConfigSemaphore = new WeakMap();
22408
- async function bundleWorkerEntry(config, id, query) {
22409
- const processing = workerConfigSemaphore.get(config);
22410
- if (processing) {
22411
- await processing;
22412
- return bundleWorkerEntry(config, id, query);
22413
- }
22414
- const promise = serialBundleWorkerEntry(config, id, query);
22415
- workerConfigSemaphore.set(config, promise);
22416
- promise.then(() => workerConfigSemaphore.delete(config));
22417
- return promise;
22418
- }
22419
- async function serialBundleWorkerEntry(config, id, query) {
22420
- // bundle the file as entry to support imports
22421
- const { rollup } = await import('rollup');
22422
- const { plugins, rollupOptions, format } = config.worker;
22423
- const bundle = await rollup({
22424
- ...rollupOptions,
22425
- input: cleanUrl(id),
22426
- plugins,
22427
- onwarn(warning, warn) {
22428
- onRollupWarning(warning, warn, config);
22429
- },
22430
- preserveEntrySignatures: false,
22431
- });
22432
- let chunk;
22433
- try {
22434
- const workerOutputConfig = config.worker.rollupOptions.output;
22435
- const workerConfig = workerOutputConfig
22436
- ? Array.isArray(workerOutputConfig)
22437
- ? workerOutputConfig[0] || {}
22438
- : workerOutputConfig
22439
- : {};
22440
- const { output: [outputChunk, ...outputChunks], } = await bundle.generate({
22441
- entryFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
22442
- chunkFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
22443
- assetFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
22444
- ...workerConfig,
22445
- format,
22446
- sourcemap: config.build.sourcemap,
22447
- });
22448
- chunk = outputChunk;
22449
- outputChunks.forEach((outputChunk) => {
22450
- if (outputChunk.type === 'asset') {
22451
- saveEmitWorkerAsset(config, outputChunk);
22452
- }
22453
- else if (outputChunk.type === 'chunk') {
22454
- saveEmitWorkerAsset(config, {
22455
- fileName: outputChunk.fileName,
22456
- source: outputChunk.code,
22457
- type: 'asset',
22458
- });
22459
- }
22460
- });
22461
- }
22462
- finally {
22463
- await bundle.close();
22464
- }
22465
- return emitSourcemapForWorkerEntry(config, query, chunk);
22466
- }
22467
- function emitSourcemapForWorkerEntry(config, query, chunk) {
22468
- const { map: sourcemap } = chunk;
22469
- if (sourcemap) {
22470
- if (config.build.sourcemap === 'hidden' ||
22471
- config.build.sourcemap === true) {
22472
- const data = sourcemap.toString();
22473
- const mapFileName = chunk.fileName + '.map';
22474
- saveEmitWorkerAsset(config, {
22475
- fileName: mapFileName,
22476
- type: 'asset',
22477
- source: data,
22478
- });
22479
- }
22480
- }
22481
- return chunk;
22482
- }
22483
- const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
22484
- function encodeWorkerAssetFileName(fileName, workerCache) {
22485
- const { fileNameHash } = workerCache;
22486
- const hash = getHash(fileName);
22487
- if (!fileNameHash.get(hash)) {
22488
- fileNameHash.set(hash, fileName);
22489
- }
22490
- return `__VITE_WORKER_ASSET__${hash}__`;
22491
- }
22492
- async function workerFileToUrl(config, id, query) {
22493
- const workerMap = workerCache.get(config.mainConfig || config);
22494
- let fileName = workerMap.bundle.get(id);
22495
- if (!fileName) {
22496
- const outputChunk = await bundleWorkerEntry(config, id, query);
22497
- fileName = outputChunk.fileName;
22498
- saveEmitWorkerAsset(config, {
22499
- fileName,
22500
- source: outputChunk.code,
22501
- type: 'asset',
22502
- });
22503
- workerMap.bundle.set(id, fileName);
22504
- }
22505
- return encodeWorkerAssetFileName(fileName, workerMap);
22506
- }
22507
- function webWorkerPlugin(config) {
22508
- const isBuild = config.command === 'build';
22509
- let server;
22510
- const isWorker = config.isWorker;
22511
- const isWorkerQueryId = (id) => {
22512
- const parsedQuery = parseRequest(id);
22513
- if (parsedQuery &&
22514
- (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
22515
- return true;
22516
- }
22517
- return false;
22518
- };
22519
- return {
22520
- name: 'vite:worker',
22521
- configureServer(_server) {
22522
- server = _server;
22523
- },
22524
- buildStart() {
22525
- if (isWorker) {
22526
- return;
22527
- }
22528
- workerCache.set(config, {
22529
- assets: new Map(),
22530
- bundle: new Map(),
22531
- fileNameHash: new Map(),
22532
- });
22533
- },
22534
- load(id) {
22535
- if (isBuild && isWorkerQueryId(id)) {
22536
- return '';
22537
- }
22538
- },
22539
- shouldTransformCachedModule({ id }) {
22540
- if (isBuild && isWorkerQueryId(id) && config.build.watch) {
22541
- return true;
22542
- }
22543
- return false;
22544
- },
22545
- async transform(raw, id, options) {
22546
- const ssr = options?.ssr === true;
22547
- const query = parseRequest(id);
22548
- if (query && query[WORKER_FILE_ID] != null) {
22549
- // if import worker by worker constructor will have query.type
22550
- // other type will be import worker by esm
22551
- const workerType = query['type'];
22552
- let injectEnv = '';
22553
- if (workerType === 'classic') {
22554
- injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
22555
- }
22556
- else if (workerType === 'module') {
22557
- injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
22558
- }
22559
- else if (workerType === 'ignore') {
22560
- if (isBuild) {
22561
- injectEnv = '';
22562
- }
22563
- else if (server) {
22564
- // dynamic worker type we can't know how import the env
22565
- // so we copy /@vite/env code of server transform result into file header
22566
- const { moduleGraph } = server;
22567
- const module = moduleGraph.getModuleById(ENV_ENTRY);
22568
- injectEnv = module?.transformResult?.code || '';
22569
- }
22570
- }
22571
- return {
22572
- code: injectEnv + raw,
22573
- };
22574
- }
22575
- if (query == null ||
22576
- (query && (query.worker ?? query.sharedworker) == null)) {
22577
- return;
22578
- }
22579
- // stringified url or `new URL(...)`
22580
- let url;
22581
- const { format } = config.worker;
22582
- const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
22583
- const workerType = isBuild
22584
- ? format === 'es'
22585
- ? 'module'
22586
- : 'classic'
22587
- : 'module';
22588
- const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
22589
- if (isBuild) {
22590
- getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
22591
- if (query.inline != null) {
22592
- const chunk = await bundleWorkerEntry(config, id, query);
22593
- const encodedJs = `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";`;
22594
- const code =
22595
- // Using blob URL for SharedWorker results in multiple instances of a same worker
22596
- workerConstructor === 'Worker'
22597
- ? `${encodedJs}
22598
- const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
22599
- export default function WorkerWrapper() {
22600
- let objURL;
22601
- try {
22602
- objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
22603
- if (!objURL) throw ''
22604
- return new ${workerConstructor}(objURL)
22605
- } catch(e) {
22606
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
22607
- } finally {
22608
- objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
22609
- }
22610
- }`
22611
- : `${encodedJs}
22612
- export default function WorkerWrapper() {
22613
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
22614
- }
22615
- `;
22616
- return {
22617
- code,
22618
- // Empty sourcemap to suppress Rollup warning
22619
- map: { mappings: '' },
22620
- };
22621
- }
22622
- else {
22623
- url = await workerFileToUrl(config, id, query);
22624
- }
22625
- }
22626
- else {
22627
- url = await fileToUrl(cleanUrl(id), config, this);
22628
- url = injectQuery(url, WORKER_FILE_ID);
22629
- url = injectQuery(url, `type=${workerType}`);
22630
- }
22631
- if (query.url != null) {
22632
- return {
22633
- code: `export default ${JSON.stringify(url)}`,
22634
- map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
22635
- };
22636
- }
22637
- return {
22638
- code: `export default function WorkerWrapper() {
22639
- return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
22640
- }`,
22641
- map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
22642
- };
22643
- },
22644
- renderChunk(code, chunk, outputOptions) {
22645
- let s;
22646
- const result = () => {
22647
- return (s && {
22648
- code: s.toString(),
22649
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
22650
- });
22651
- };
22652
- if (code.match(workerAssetUrlRE) || code.includes('import.meta.url')) {
22653
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format);
22654
- let match;
22655
- s = new MagicString(code);
22656
- workerAssetUrlRE.lastIndex = 0;
22657
- // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
22658
- const workerMap = workerCache.get(config.mainConfig || config);
22659
- const { fileNameHash } = workerMap;
22660
- while ((match = workerAssetUrlRE.exec(code))) {
22661
- const [full, hash] = match;
22662
- const filename = fileNameHash.get(hash);
22663
- const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
22664
- const replacementString = typeof replacement === 'string'
22665
- ? JSON.stringify(replacement).slice(1, -1)
22666
- : `"+${replacement.runtime}+"`;
22667
- s.update(match.index, match.index + full.length, replacementString);
22668
- }
22669
- }
22670
- return result();
22671
- },
22672
- generateBundle(opts) {
22673
- // @ts-expect-error asset emits are skipped in legacy bundle
22674
- if (opts.__vite_skip_asset_emit__ || isWorker) {
22675
- return;
22676
- }
22677
- const workerMap = workerCache.get(config);
22678
- workerMap.assets.forEach((asset) => {
22679
- this.emitFile(asset);
22680
- workerMap.assets.delete(asset.fileName);
22681
- });
22682
- },
22683
- };
22684
- }
22685
-
22686
22388
  const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
22687
22389
  const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
22688
22390
  // special id for paths marked with browser: false
@@ -22690,10 +22392,9 @@ const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
22690
22392
  const browserExternalId = '__vite-browser-external';
22691
22393
  // special id for packages that are optional peer deps
22692
22394
  const optionalPeerDepId = '__vite-optional-peer-dep';
22693
- const nodeModulesInPathRE = /(?:^|\/)node_modules\//;
22694
22395
  const subpathImportsPrefix = '#';
22695
22396
  const startsWithWordCharRE = /^\w/;
22696
- const isDebug$4 = process.env.DEBUG;
22397
+ const isDebug$5 = process.env.DEBUG;
22697
22398
  const debug$c = createDebugger('vite:resolve-details', {
22698
22399
  onlyWhenFocused: true,
22699
22400
  });
@@ -22729,15 +22430,12 @@ function resolvePlugin(resolveOptions) {
22729
22430
  id = resolvedImports;
22730
22431
  }
22731
22432
  if (importer) {
22732
- const _importer = isWorkerRequest(importer)
22733
- ? splitFileAndPostfix(importer).file
22734
- : importer;
22735
- if (isTsRequest(_importer) ||
22433
+ if (isTsRequest(importer) ||
22736
22434
  resolveOpts.custom?.depScan?.loader?.startsWith('ts')) {
22737
22435
  options.isFromTsImporter = true;
22738
22436
  }
22739
22437
  else {
22740
- const moduleLang = this.getModuleInfo(_importer)?.meta?.vite?.lang;
22438
+ const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang;
22741
22439
  options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
22742
22440
  }
22743
22441
  }
@@ -22755,7 +22453,7 @@ function resolvePlugin(resolveOptions) {
22755
22453
  if (asSrc && id.startsWith(FS_PREFIX)) {
22756
22454
  const fsPath = fsPathFromId(id);
22757
22455
  res = tryFsResolve(fsPath, options);
22758
- isDebug$4 && debug$c(`[@fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22456
+ isDebug$5 && debug$c(`[@fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22759
22457
  // always return here even if res doesn't exist since /@fs/ is explicit
22760
22458
  // if the file doesn't exist it should be a 404
22761
22459
  return ensureVersionQuery(res || fsPath, id, options, depsOptimizer);
@@ -22765,7 +22463,7 @@ function resolvePlugin(resolveOptions) {
22765
22463
  if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
22766
22464
  const fsPath = path$o.resolve(root, id.slice(1));
22767
22465
  if ((res = tryFsResolve(fsPath, options))) {
22768
- isDebug$4 && debug$c(`[url] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22466
+ isDebug$5 && debug$c(`[url] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22769
22467
  return ensureVersionQuery(res, id, options, depsOptimizer);
22770
22468
  }
22771
22469
  }
@@ -22794,18 +22492,16 @@ function resolvePlugin(resolveOptions) {
22794
22492
  return res;
22795
22493
  }
22796
22494
  if ((res = tryFsResolve(fsPath, options))) {
22495
+ const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
22797
22496
  res = ensureVersionQuery(res, id, options, depsOptimizer);
22798
- isDebug$4 &&
22497
+ isDebug$5 &&
22799
22498
  debug$c(`[relative] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22800
- const pkg = importer != null && idToPkgMap.get(importer);
22801
- if (pkg) {
22802
- idToPkgMap.set(res, pkg);
22803
- return {
22499
+ return resPkg
22500
+ ? {
22804
22501
  id: res,
22805
- moduleSideEffects: pkg.hasSideEffects(res),
22806
- };
22807
- }
22808
- return res;
22502
+ moduleSideEffects: resPkg.hasSideEffects(res),
22503
+ }
22504
+ : res;
22809
22505
  }
22810
22506
  }
22811
22507
  // drive relative fs paths (only windows)
@@ -22813,7 +22509,7 @@ function resolvePlugin(resolveOptions) {
22813
22509
  const basedir = importer ? path$o.dirname(importer) : process.cwd();
22814
22510
  const fsPath = path$o.resolve(basedir, id);
22815
22511
  if ((res = tryFsResolve(fsPath, options))) {
22816
- isDebug$4 &&
22512
+ isDebug$5 &&
22817
22513
  debug$c(`[drive-relative] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22818
22514
  return ensureVersionQuery(res, id, options, depsOptimizer);
22819
22515
  }
@@ -22821,7 +22517,7 @@ function resolvePlugin(resolveOptions) {
22821
22517
  // absolute fs paths
22822
22518
  if (isNonDriveRelativeAbsolutePath(id) &&
22823
22519
  (res = tryFsResolve(id, options))) {
22824
- isDebug$4 && debug$c(`[fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22520
+ isDebug$5 && debug$c(`[fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22825
22521
  return ensureVersionQuery(res, id, options, depsOptimizer);
22826
22522
  }
22827
22523
  // external
@@ -22882,7 +22578,7 @@ function resolvePlugin(resolveOptions) {
22882
22578
  }
22883
22579
  }
22884
22580
  }
22885
- isDebug$4 && debug$c(`[fallthrough] ${picocolorsExports.dim(id)}`);
22581
+ isDebug$5 && debug$c(`[fallthrough] ${picocolorsExports.dim(id)}`);
22886
22582
  },
22887
22583
  load(id) {
22888
22584
  if (id.startsWith(browserExternalId)) {
@@ -22936,8 +22632,7 @@ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
22936
22632
  // as if they would have been imported through a bare import
22937
22633
  // Use the original id to do the check as the resolved id may be the real
22938
22634
  // file path after symlinks resolution
22939
- const isNodeModule = nodeModulesInPathRE.test(normalizePath$3(id)) ||
22940
- nodeModulesInPathRE.test(normalizePath$3(resolved));
22635
+ const isNodeModule = isInNodeModules(id) || isInNodeModules(resolved);
22941
22636
  if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
22942
22637
  const versionHash = depsOptimizer.metadata.browserHash;
22943
22638
  if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
@@ -22948,41 +22643,31 @@ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
22948
22643
  return resolved;
22949
22644
  }
22950
22645
  function splitFileAndPostfix(path) {
22951
- let file = path;
22952
- let postfix = '';
22953
- let postfixIndex = path.indexOf('?');
22954
- if (postfixIndex < 0) {
22955
- postfixIndex = path.indexOf('#');
22956
- }
22957
- if (postfixIndex > 0) {
22958
- file = path.slice(0, postfixIndex);
22959
- postfix = path.slice(postfixIndex);
22960
- }
22961
- return { file, postfix };
22646
+ const file = cleanUrl(path);
22647
+ return { file, postfix: path.slice(file.length) };
22962
22648
  }
22963
22649
  function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
22964
- let postfixIndex = fsPath.indexOf('?');
22965
- if (postfixIndex < 0) {
22966
- postfixIndex = fsPath.indexOf('#');
22967
- // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user
22968
- // source code so we only need to perform the check for dependencies.
22969
- // We don't support `?` in node_modules paths, so we only need to check in this branch.
22970
- if (postfixIndex >= 0 && fsPath.includes('node_modules')) {
22971
- const res = tryCleanFsResolve(fsPath, options, tryIndex, targetWeb, skipPackageJson);
22650
+ // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user
22651
+ // source code so we only need to perform the check for dependencies.
22652
+ // We don't support `?` in node_modules paths, so we only need to check in this branch.
22653
+ const hashIndex = fsPath.indexOf('#');
22654
+ if (hashIndex >= 0 && isInNodeModules(fsPath)) {
22655
+ const queryIndex = fsPath.indexOf('?');
22656
+ // We only need to check foo#bar?baz and foo#bar, ignore foo?bar#baz
22657
+ if (queryIndex < 0 || queryIndex > hashIndex) {
22658
+ const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
22659
+ const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
22972
22660
  if (res)
22973
- return res;
22661
+ return res + fsPath.slice(file.length);
22974
22662
  }
22975
22663
  }
22976
- let file = fsPath;
22977
- let postfix = '';
22978
- if (postfixIndex >= 0) {
22979
- file = fsPath.slice(0, postfixIndex);
22980
- postfix = fsPath.slice(postfixIndex);
22981
- }
22664
+ const { file, postfix } = splitFileAndPostfix(fsPath);
22982
22665
  const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
22983
22666
  if (res)
22984
22667
  return res + postfix;
22985
22668
  }
22669
+ const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
22670
+ const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
22986
22671
  function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
22987
22672
  const { tryPrefix, extensions, preserveSymlinks } = options;
22988
22673
  const fileStat = tryStatSync(file);
@@ -22997,12 +22682,15 @@ function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, ski
22997
22682
  const dirStat = tryStatSync(dirPath);
22998
22683
  if (dirStat?.isDirectory()) {
22999
22684
  if (possibleJsToTs) {
23000
- // try resolve .js, .mjs, .mts or .jsx import to typescript file
23001
- const tsSrcPaths = getPotentialTsSrcPaths(file);
23002
- for (const srcPath of tsSrcPaths) {
23003
- if ((res = tryResolveRealFile(srcPath, preserveSymlinks)))
23004
- return res;
23005
- }
22685
+ // try resolve .js, .mjs, .cjs or .jsx import to typescript file
22686
+ const fileExt = path$o.extname(file);
22687
+ const fileName = file.slice(0, -fileExt.length);
22688
+ if ((res = tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
22689
+ return res;
22690
+ // for .js, also try .tsx
22691
+ if (fileExt === '.js' &&
22692
+ (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
22693
+ return res;
23006
22694
  }
23007
22695
  if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
23008
22696
  return res;
@@ -23055,15 +22743,6 @@ function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks
23055
22743
  return res;
23056
22744
  }
23057
22745
  }
23058
- function tryStatSync(file) {
23059
- try {
23060
- return fs$l.statSync(file, { throwIfNoEntry: false });
23061
- }
23062
- catch {
23063
- // Ignore errors
23064
- }
23065
- }
23066
- const idToPkgMap = new Map();
23067
22746
  function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
23068
22747
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
23069
22748
  // check for deep import, e.g. "my-lib/foo"
@@ -23089,12 +22768,8 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23089
22768
  !isBuiltin(id) &&
23090
22769
  !id.includes('\0') &&
23091
22770
  bareImportRE.test(id)) {
23092
- // find package.json with `name` as main
23093
- const mainPackageJson = lookupFile(basedir, ['package.json'], {
23094
- predicate: (content) => !!JSON.parse(content).name,
23095
- });
23096
- if (mainPackageJson) {
23097
- const mainPkg = JSON.parse(mainPackageJson);
22771
+ const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
22772
+ if (mainPkg) {
23098
22773
  if (mainPkg.peerDependencies?.[id] &&
23099
22774
  mainPkg.peerDependenciesMeta?.[id]?.optional) {
23100
22775
  return {
@@ -23132,7 +22807,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23132
22807
  return resolved;
23133
22808
  }
23134
22809
  // don't external symlink packages
23135
- if (!allowLinkedExternal && !resolved.id.includes('node_modules')) {
22810
+ if (!allowLinkedExternal && !isInNodeModules(resolved.id)) {
23136
22811
  return resolved;
23137
22812
  }
23138
22813
  const resolvedExt = path$o.extname(resolved.id);
@@ -23146,13 +22821,11 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23146
22821
  let resolvedId = id;
23147
22822
  if (deepMatch && !pkg?.data.exports && path$o.extname(id) !== resolvedExt) {
23148
22823
  resolvedId = resolved.id.slice(resolved.id.indexOf(id));
23149
- isDebug$4 &&
22824
+ isDebug$5 &&
23150
22825
  debug$c(`[processResult] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolvedId)}`);
23151
22826
  }
23152
22827
  return { ...resolved, id: resolvedId, external: true };
23153
22828
  };
23154
- // link id to pkg for browser field mapping check
23155
- idToPkgMap.set(resolved, pkg);
23156
22829
  if ((isBuild && !depsOptimizer) || externalize) {
23157
22830
  // Resolve package side effects for build so that rollup can better
23158
22831
  // perform tree-shaking
@@ -23163,7 +22836,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23163
22836
  }
23164
22837
  const ext = path$o.extname(resolved);
23165
22838
  if (!options.ssrOptimizeCheck &&
23166
- (!resolved.includes('node_modules') || // linked
22839
+ (!isInNodeModules(resolved) || // linked
23167
22840
  !depsOptimizer || // resolving before listening to the server
23168
22841
  options.scan) // initial esbuild scan phase
23169
22842
  ) {
@@ -23181,7 +22854,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23181
22854
  include = options.ssrConfig?.optimizeDeps?.include;
23182
22855
  }
23183
22856
  const skipOptimization = !isJsType ||
23184
- importer?.includes('node_modules') ||
22857
+ (importer && isInNodeModules(importer)) ||
23185
22858
  exclude?.includes(pkgId) ||
23186
22859
  exclude?.includes(id) ||
23187
22860
  SPECIAL_QUERY_RE.test(resolved) ||
@@ -23367,7 +23040,7 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
23367
23040
  const entryPointPath = path$o.join(dir, entry);
23368
23041
  const resolvedEntryPoint = tryFsResolve(entryPointPath, options, true, true, skipPackageJson);
23369
23042
  if (resolvedEntryPoint) {
23370
- isDebug$4 &&
23043
+ isDebug$5 &&
23371
23044
  debug$c(`[package entry] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolvedEntryPoint)}`);
23372
23045
  setResolvedCache('.', resolvedEntryPoint, targetWeb);
23373
23046
  return resolvedEntryPoint;
@@ -23460,7 +23133,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
23460
23133
  const resolved = tryFsResolve(path$o.join(dir, relativeId), options, !exportsField, // try index only if no exports field
23461
23134
  targetWeb);
23462
23135
  if (resolved) {
23463
- isDebug$4 &&
23136
+ isDebug$5 &&
23464
23137
  debug$c(`[node/deep-import] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolved)}`);
23465
23138
  setResolvedCache(id, resolved, targetWeb);
23466
23139
  return resolved;
@@ -23470,8 +23143,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
23470
23143
  function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
23471
23144
  let res;
23472
23145
  const pkg = importer &&
23473
- (idToPkgMap.get(importer) ||
23474
- findNearestPackageData(path$o.dirname(importer), options.packageCache));
23146
+ findNearestPackageData(path$o.dirname(importer), options.packageCache);
23475
23147
  if (pkg && isObject$2(pkg.data.browser)) {
23476
23148
  const mapId = isFilePath ? './' + slash$1(path$o.relative(pkg.dir, id)) : id;
23477
23149
  const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
@@ -23479,13 +23151,15 @@ function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize
23479
23151
  if ((res = bareImportRE.test(browserMappedPath)
23480
23152
  ? tryNodeResolve(browserMappedPath, importer, options, true)?.id
23481
23153
  : tryFsResolve(path$o.join(pkg.dir, browserMappedPath), options))) {
23482
- isDebug$4 &&
23154
+ isDebug$5 &&
23483
23155
  debug$c(`[browser mapped] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
23484
- idToPkgMap.set(res, pkg);
23485
- const result = {
23486
- id: res,
23487
- moduleSideEffects: pkg.hasSideEffects(res),
23488
- };
23156
+ const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
23157
+ const result = resPkg
23158
+ ? {
23159
+ id: res,
23160
+ moduleSideEffects: resPkg.hasSideEffects(res),
23161
+ }
23162
+ : { id: res };
23489
23163
  return externalize ? { ...result, external: true } : result;
23490
23164
  }
23491
23165
  }
@@ -28454,7 +28128,11 @@ function createIsSsrExternal(config) {
28454
28128
  // When config.experimental.buildSsrCjsExternalHeuristics is enabled, this function
28455
28129
  // is used reverting to the Vite 2.9 SSR externalization heuristics
28456
28130
  function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger) {
28457
- const rootPkgContent = lookupFile(root, ['package.json']);
28131
+ const rootPkgPath = lookupFile(root, ['package.json']);
28132
+ if (!rootPkgPath) {
28133
+ return;
28134
+ }
28135
+ const rootPkgContent = fs$l.readFileSync(rootPkgPath, 'utf-8');
28458
28136
  if (!rootPkgContent) {
28459
28137
  return;
28460
28138
  }
@@ -28487,7 +28165,7 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
28487
28165
  // no main entry, but deep imports may be allowed
28488
28166
  const pkgDir = resolvePackageData(id, root)?.dir;
28489
28167
  if (pkgDir) {
28490
- if (pkgDir.includes('node_modules')) {
28168
+ if (isInNodeModules(pkgDir)) {
28491
28169
  ssrExternals.add(id);
28492
28170
  }
28493
28171
  else {
@@ -28504,7 +28182,7 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
28504
28182
  ssrExternals.add(id);
28505
28183
  }
28506
28184
  // trace the dependencies of linked packages
28507
- else if (!esmEntry.includes('node_modules')) {
28185
+ else if (!isInNodeModules(esmEntry)) {
28508
28186
  const pkgDir = resolvePackageData(id, root)?.dir;
28509
28187
  if (pkgDir) {
28510
28188
  depsToTrace.add(pkgDir);
@@ -28625,7 +28303,7 @@ function jsonPlugin(options = {}, isBuild) {
28625
28303
 
28626
28304
  const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
28627
28305
  const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
28628
- const isDebug$3 = process.env.DEBUG;
28306
+ const isDebug$4 = process.env.DEBUG;
28629
28307
  const debug$a = createDebugger('vite:optimize-deps');
28630
28308
  function optimizedDepsPlugin(config) {
28631
28309
  return {
@@ -28673,12 +28351,12 @@ function optimizedDepsPlugin(config) {
28673
28351
  }
28674
28352
  }
28675
28353
  }
28676
- isDebug$3 && debug$a(`load ${picocolorsExports.cyan(file)}`);
28354
+ isDebug$4 && debug$a(`load ${picocolorsExports.cyan(file)}`);
28677
28355
  // Load the file from the cache instead of waiting for other plugin
28678
28356
  // load hooks to avoid race conditions, once processing is resolved,
28679
28357
  // we are sure that the file has been properly save to disk
28680
28358
  try {
28681
- return await promises$2.readFile(file, 'utf-8');
28359
+ return await fsp.readFile(file, 'utf-8');
28682
28360
  }
28683
28361
  catch (e) {
28684
28362
  // Outdated non-entry points (CHUNK), loaded after a rerun
@@ -28721,33 +28399,16 @@ function optimizedDepsBuildPlugin(config) {
28721
28399
  // If all the inputs are dependencies, we aren't going to get any
28722
28400
  const info = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
28723
28401
  if (info) {
28724
- try {
28725
- // This is an entry point, it may still not be bundled
28726
- await info.processing;
28727
- }
28728
- catch {
28729
- // If the refresh has not happened after timeout, Vite considers
28730
- // something unexpected has happened. In this case, Vite
28731
- // returns an empty response that will error.
28732
- // throwProcessingError(id)
28733
- return;
28734
- }
28735
- isDebug$3 && debug$a(`load ${picocolorsExports.cyan(file)}`);
28402
+ await info.processing;
28403
+ isDebug$4 && debug$a(`load ${picocolorsExports.cyan(file)}`);
28736
28404
  }
28737
28405
  else {
28738
- // TODO: error
28739
- return;
28406
+ throw new Error(`Something unexpected happened while optimizing "${id}".`);
28740
28407
  }
28741
28408
  // Load the file from the cache instead of waiting for other plugin
28742
28409
  // load hooks to avoid race conditions, once processing is resolved,
28743
28410
  // we are sure that the file has been properly save to disk
28744
- try {
28745
- return await promises$2.readFile(file, 'utf-8');
28746
- }
28747
- catch (e) {
28748
- // Outdated non-entry points (CHUNK), loaded after a rerun
28749
- return '';
28750
- }
28411
+ return fsp.readFile(file, 'utf-8');
28751
28412
  },
28752
28413
  };
28753
28414
  }
@@ -36904,13 +36565,10 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
36904
36565
  /** mode local file */ `.env.${mode}.local`,
36905
36566
  ];
36906
36567
  const parsed = Object.fromEntries(envFiles.flatMap((file) => {
36907
- const path = lookupFile(envDir, [file], {
36908
- pathOnly: true,
36909
- rootDir: envDir,
36910
- });
36911
- if (!path)
36568
+ const filePath = path$o.join(envDir, file);
36569
+ if (!tryStatSync(filePath)?.isFile())
36912
36570
  return [];
36913
- return Object.entries(parse_1$1(fs$l.readFileSync(path)));
36571
+ return Object.entries(parse_1$1(fs$l.readFileSync(filePath)));
36914
36572
  }));
36915
36573
  // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
36916
36574
  if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
@@ -38422,7 +38080,7 @@ async function compileCSS(id, code, config, urlReplacer) {
38422
38080
  }));
38423
38081
  }
38424
38082
  if (isModule) {
38425
- postcssPlugins.unshift((await import('./dep-be7bf3d1.js').then(function (n) { return n.i; })).default({
38083
+ postcssPlugins.unshift((await import('./dep-afd6d5c5.js').then(function (n) { return n.i; })).default({
38426
38084
  ...modulesOptions,
38427
38085
  localsConvention: modulesOptions?.localsConvention,
38428
38086
  getJSON(cssFileName, _modules, outputFileName) {
@@ -38740,6 +38398,7 @@ async function minifyCSS(css, config) {
38740
38398
  const { code, warnings } = await transform$2(css, {
38741
38399
  loader: 'css',
38742
38400
  target: config.build.cssTarget || undefined,
38401
+ charset: 'utf8',
38743
38402
  ...resolveEsbuildMinifyOptions(config.esbuild || {}),
38744
38403
  });
38745
38404
  if (warnings.length) {
@@ -38941,7 +38600,7 @@ async function rebaseUrls(file, rootFile, alias, variablePrefix) {
38941
38600
  if (fileDir === rootDir) {
38942
38601
  return { file };
38943
38602
  }
38944
- const content = fs$l.readFileSync(file, 'utf-8');
38603
+ const content = await fsp.readFile(file, 'utf-8');
38945
38604
  // no url()
38946
38605
  const hasUrls = cssUrlRE.test(content);
38947
38606
  // data-uri() calls
@@ -39054,7 +38713,7 @@ function createViteLessPlugin(less, rootFile, alias, resolvers) {
39054
38713
  contents = result.contents;
39055
38714
  }
39056
38715
  else {
39057
- contents = fs$l.readFileSync(resolved, 'utf-8');
38716
+ contents = await fsp.readFile(resolved, 'utf-8');
39058
38717
  }
39059
38718
  return {
39060
38719
  filename: path$o.resolve(resolved),
@@ -40243,14 +39902,14 @@ function error$1(pos) {
40243
39902
  // change event and sometimes this can be too early and get an empty buffer.
40244
39903
  // Poll until the file's modified time has changed before reading again.
40245
39904
  async function readModifiedFile(file) {
40246
- const content = fs$l.readFileSync(file, 'utf-8');
39905
+ const content = await fsp.readFile(file, 'utf-8');
40247
39906
  if (!content) {
40248
- const mtime = fs$l.statSync(file).mtimeMs;
39907
+ const mtime = (await fsp.stat(file)).mtimeMs;
40249
39908
  await new Promise((r) => {
40250
39909
  let n = 0;
40251
39910
  const poll = async () => {
40252
39911
  n++;
40253
- const newMtime = fs$l.statSync(file).mtimeMs;
39912
+ const newMtime = (await fsp.stat(file)).mtimeMs;
40254
39913
  if (newMtime !== mtime || n > 10) {
40255
39914
  r(0);
40256
39915
  }
@@ -40260,7 +39919,7 @@ async function readModifiedFile(file) {
40260
39919
  };
40261
39920
  setTimeout(poll, 10);
40262
39921
  });
40263
- return fs$l.readFileSync(file, 'utf-8');
39922
+ return await fsp.readFile(file, 'utf-8');
40264
39923
  }
40265
39924
  else {
40266
39925
  return content;
@@ -41044,7 +40703,7 @@ const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
41044
40703
  const debugLoad = createDebugger('vite:load');
41045
40704
  const debugTransform = createDebugger('vite:transform');
41046
40705
  const debugCache$1 = createDebugger('vite:cache');
41047
- const isDebug$2 = !!process.env.DEBUG;
40706
+ const isDebug$3 = !!process.env.DEBUG;
41048
40707
  function transformRequest(url, server, options = {}) {
41049
40708
  const cacheKey = (options.ssr ? 'ssr:' : options.html ? 'html:' : '') + url;
41050
40709
  // This module may get invalidated while we are processing it. For example
@@ -41109,7 +40768,7 @@ function transformRequest(url, server, options = {}) {
41109
40768
  async function doTransform(url, server, options, timestamp) {
41110
40769
  url = removeTimestampQuery(url);
41111
40770
  const { config, pluginContainer } = server;
41112
- const prettyUrl = isDebug$2 ? prettifyUrl(url, config.root) : '';
40771
+ const prettyUrl = isDebug$3 ? prettifyUrl(url, config.root) : '';
41113
40772
  const ssr = !!options.ssr;
41114
40773
  const module = await server.moduleGraph.getModuleByUrl(url, ssr);
41115
40774
  // check if we have a fresh cache
@@ -41120,7 +40779,7 @@ async function doTransform(url, server, options, timestamp) {
41120
40779
  // content has not changed.
41121
40780
  // in this case, we can reuse its previous cached result and only update
41122
40781
  // its import timestamps.
41123
- isDebug$2 && debugCache$1(`[memory] ${prettyUrl}`);
40782
+ isDebug$3 && debugCache$1(`[memory] ${prettyUrl}`);
41124
40783
  return cached;
41125
40784
  }
41126
40785
  // resolve
@@ -41132,13 +40791,13 @@ async function doTransform(url, server, options, timestamp) {
41132
40791
  async function loadAndTransform(id, url, server, options, timestamp) {
41133
40792
  const { config, pluginContainer, moduleGraph, watcher } = server;
41134
40793
  const { root, logger } = config;
41135
- const prettyUrl = isDebug$2 ? prettifyUrl(url, config.root) : '';
40794
+ const prettyUrl = isDebug$3 ? prettifyUrl(url, config.root) : '';
41136
40795
  const ssr = !!options.ssr;
41137
40796
  const file = cleanUrl(id);
41138
40797
  let code = null;
41139
40798
  let map = null;
41140
40799
  // load
41141
- const loadStart = isDebug$2 ? performance$1.now() : 0;
40800
+ const loadStart = isDebug$3 ? performance$1.now() : 0;
41142
40801
  const loadResult = await pluginContainer.load(id, { ssr });
41143
40802
  if (loadResult == null) {
41144
40803
  // if this is an html request and there is no load result, skip ahead to
@@ -41154,7 +40813,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41154
40813
  if (options.ssr || isFileServingAllowed(file, server)) {
41155
40814
  try {
41156
40815
  code = await promises$2.readFile(file, 'utf-8');
41157
- isDebug$2 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
40816
+ isDebug$3 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
41158
40817
  }
41159
40818
  catch (e) {
41160
40819
  if (e.code !== 'ENOENT') {
@@ -41176,7 +40835,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41176
40835
  }
41177
40836
  }
41178
40837
  else {
41179
- isDebug$2 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
40838
+ isDebug$3 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
41180
40839
  if (isObject$2(loadResult)) {
41181
40840
  code = loadResult.code;
41182
40841
  map = loadResult.map;
@@ -41205,7 +40864,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41205
40864
  const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
41206
40865
  ensureWatchedFile(watcher, mod.file, root);
41207
40866
  // transform
41208
- const transformStart = isDebug$2 ? performance$1.now() : 0;
40867
+ const transformStart = isDebug$3 ? performance$1.now() : 0;
41209
40868
  const transformResult = await pluginContainer.transform(code, id, {
41210
40869
  inMap: map,
41211
40870
  ssr,
@@ -41214,11 +40873,11 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41214
40873
  if (transformResult == null ||
41215
40874
  (isObject$2(transformResult) && transformResult.code == null)) {
41216
40875
  // no transform applied, keep code as-is
41217
- isDebug$2 &&
40876
+ isDebug$3 &&
41218
40877
  debugTransform(timeFrom(transformStart) + picocolorsExports.dim(` [skipped] ${prettyUrl}`));
41219
40878
  }
41220
40879
  else {
41221
- isDebug$2 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
40880
+ isDebug$3 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
41222
40881
  code = transformResult.code;
41223
40882
  map = transformResult.map;
41224
40883
  }
@@ -41227,31 +40886,20 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41227
40886
  if (map.mappings && !map.sourcesContent) {
41228
40887
  await injectSourcesContent(map, mod.file, logger);
41229
40888
  }
41230
- for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
41231
- const sourcePath = map.sources[sourcesIndex];
41232
- if (!sourcePath)
41233
- continue;
41234
- const sourcemapPath = `${mod.file}.map`;
41235
- const ignoreList = config.server.sourcemapIgnoreList(path$o.isAbsolute(sourcePath)
41236
- ? sourcePath
41237
- : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath);
41238
- if (typeof ignoreList !== 'boolean') {
41239
- logger.warn('sourcemapIgnoreList function must return a boolean.');
41240
- }
41241
- if (ignoreList) {
41242
- if (map.x_google_ignoreList === undefined) {
41243
- map.x_google_ignoreList = [];
41244
- }
41245
- if (!map.x_google_ignoreList.includes(sourcesIndex)) {
41246
- map.x_google_ignoreList.push(sourcesIndex);
40889
+ const sourcemapPath = `${mod.file}.map`;
40890
+ applySourcemapIgnoreList(map, sourcemapPath, config.server.sourcemapIgnoreList, logger);
40891
+ if (path$o.isAbsolute(mod.file)) {
40892
+ for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
40893
+ const sourcePath = map.sources[sourcesIndex];
40894
+ if (sourcePath) {
40895
+ // Rewrite sources to relative paths to give debuggers the chance
40896
+ // to resolve and display them in a meaningful way (rather than
40897
+ // with absolute paths).
40898
+ if (path$o.isAbsolute(sourcePath)) {
40899
+ map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
40900
+ }
41247
40901
  }
41248
40902
  }
41249
- // Rewrite sources to relative paths to give debuggers the chance
41250
- // to resolve and display them in a meaningful way (rather than
41251
- // with absolute paths).
41252
- if (path$o.isAbsolute(sourcePath) && path$o.isAbsolute(mod.file)) {
41253
- map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
41254
- }
41255
40903
  }
41256
40904
  }
41257
40905
  const result = ssr && !server.config.experimental.skipSsrTransform
@@ -41277,7 +40925,7 @@ function createConvertSourceMapReadMap(originalFileName) {
41277
40925
  };
41278
40926
  }
41279
40927
 
41280
- const isDebug$1 = !!process.env.DEBUG;
40928
+ const isDebug$2 = !!process.env.DEBUG;
41281
40929
  const debug$9 = createDebugger('vite:import-analysis');
41282
40930
  const clientDir = normalizePath$3(CLIENT_DIR);
41283
40931
  const skipRE = /\.(?:map|json)(?:$|\?)/;
@@ -41396,7 +41044,7 @@ function importAnalysisPlugin(config) {
41396
41044
  const ssr = options?.ssr === true;
41397
41045
  const prettyImporter = prettifyUrl(importer, root);
41398
41046
  if (canSkipImportAnalysis(importer)) {
41399
- isDebug$1 && debug$9(picocolorsExports.dim(`[skipped] ${prettyImporter}`));
41047
+ isDebug$2 && debug$9(picocolorsExports.dim(`[skipped] ${prettyImporter}`));
41400
41048
  return null;
41401
41049
  }
41402
41050
  const start = performance$1.now();
@@ -41436,7 +41084,7 @@ function importAnalysisPlugin(config) {
41436
41084
  }
41437
41085
  if (!imports.length && !this._addedImports) {
41438
41086
  importerModule.isSelfAccepting = false;
41439
- isDebug$1 &&
41087
+ isDebug$2 &&
41440
41088
  debug$9(`${timeFrom(start)} ${picocolorsExports.dim(`[no imports] ${prettyImporter}`)}`);
41441
41089
  return source;
41442
41090
  }
@@ -41493,7 +41141,7 @@ function importAnalysisPlugin(config) {
41493
41141
  // in root: infer short absolute path from root
41494
41142
  url = resolved.id.slice(root.length);
41495
41143
  }
41496
- else if (resolved.id.startsWith(getDepsCacheDirPrefix(config)) ||
41144
+ else if (depsOptimizer?.isOptimizedDepFile(resolved.id) ||
41497
41145
  fs$l.existsSync(cleanUrl(resolved.id))) {
41498
41146
  // an optimized deps may not yet exists in the filesystem, or
41499
41147
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
@@ -41694,7 +41342,7 @@ function importAnalysisPlugin(config) {
41694
41342
  }
41695
41343
  }
41696
41344
  else if (!importer.startsWith(clientDir)) {
41697
- if (!importer.includes('node_modules')) {
41345
+ if (!isInNodeModules(importer)) {
41698
41346
  // check @vite-ignore which suppresses dynamic import warning
41699
41347
  const hasViteIgnore = hasViteIgnoreRE.test(
41700
41348
  // complete expression inside parens
@@ -41777,7 +41425,7 @@ function importAnalysisPlugin(config) {
41777
41425
  handlePrunedModules(prunedImports, server);
41778
41426
  }
41779
41427
  }
41780
- isDebug$1 &&
41428
+ isDebug$2 &&
41781
41429
  debug$9(`${timeFrom(start)} ${picocolorsExports.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
41782
41430
  // pre-transform known direct imports
41783
41431
  // These requests will also be registered in transformRequest to be awaited
@@ -42080,6 +41728,295 @@ const wasmFallbackPlugin = () => {
42080
41728
  };
42081
41729
  };
42082
41730
 
41731
+ const WORKER_FILE_ID = 'worker_file';
41732
+ const workerCache = new WeakMap();
41733
+ function saveEmitWorkerAsset(config, asset) {
41734
+ const fileName = asset.fileName;
41735
+ const workerMap = workerCache.get(config.mainConfig || config);
41736
+ workerMap.assets.set(fileName, asset);
41737
+ }
41738
+ // Ensure that only one rollup build is called at the same time to avoid
41739
+ // leaking state in plugins between worker builds.
41740
+ // TODO: Review if we can parallelize the bundling of workers.
41741
+ const workerConfigSemaphore = new WeakMap();
41742
+ async function bundleWorkerEntry(config, id, query) {
41743
+ const processing = workerConfigSemaphore.get(config);
41744
+ if (processing) {
41745
+ await processing;
41746
+ return bundleWorkerEntry(config, id, query);
41747
+ }
41748
+ const promise = serialBundleWorkerEntry(config, id, query);
41749
+ workerConfigSemaphore.set(config, promise);
41750
+ promise.then(() => workerConfigSemaphore.delete(config));
41751
+ return promise;
41752
+ }
41753
+ async function serialBundleWorkerEntry(config, id, query) {
41754
+ // bundle the file as entry to support imports
41755
+ const { rollup } = await import('rollup');
41756
+ const { plugins, rollupOptions, format } = config.worker;
41757
+ const bundle = await rollup({
41758
+ ...rollupOptions,
41759
+ input: cleanUrl(id),
41760
+ plugins,
41761
+ onwarn(warning, warn) {
41762
+ onRollupWarning(warning, warn, config);
41763
+ },
41764
+ preserveEntrySignatures: false,
41765
+ });
41766
+ let chunk;
41767
+ try {
41768
+ const workerOutputConfig = config.worker.rollupOptions.output;
41769
+ const workerConfig = workerOutputConfig
41770
+ ? Array.isArray(workerOutputConfig)
41771
+ ? workerOutputConfig[0] || {}
41772
+ : workerOutputConfig
41773
+ : {};
41774
+ const { output: [outputChunk, ...outputChunks], } = await bundle.generate({
41775
+ entryFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
41776
+ chunkFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
41777
+ assetFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
41778
+ ...workerConfig,
41779
+ format,
41780
+ sourcemap: config.build.sourcemap,
41781
+ });
41782
+ chunk = outputChunk;
41783
+ outputChunks.forEach((outputChunk) => {
41784
+ if (outputChunk.type === 'asset') {
41785
+ saveEmitWorkerAsset(config, outputChunk);
41786
+ }
41787
+ else if (outputChunk.type === 'chunk') {
41788
+ saveEmitWorkerAsset(config, {
41789
+ fileName: outputChunk.fileName,
41790
+ source: outputChunk.code,
41791
+ type: 'asset',
41792
+ });
41793
+ }
41794
+ });
41795
+ }
41796
+ finally {
41797
+ await bundle.close();
41798
+ }
41799
+ return emitSourcemapForWorkerEntry(config, query, chunk);
41800
+ }
41801
+ function emitSourcemapForWorkerEntry(config, query, chunk) {
41802
+ const { map: sourcemap } = chunk;
41803
+ if (sourcemap) {
41804
+ if (config.build.sourcemap === 'hidden' ||
41805
+ config.build.sourcemap === true) {
41806
+ const data = sourcemap.toString();
41807
+ const mapFileName = chunk.fileName + '.map';
41808
+ saveEmitWorkerAsset(config, {
41809
+ fileName: mapFileName,
41810
+ type: 'asset',
41811
+ source: data,
41812
+ });
41813
+ }
41814
+ }
41815
+ return chunk;
41816
+ }
41817
+ const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
41818
+ function encodeWorkerAssetFileName(fileName, workerCache) {
41819
+ const { fileNameHash } = workerCache;
41820
+ const hash = getHash(fileName);
41821
+ if (!fileNameHash.get(hash)) {
41822
+ fileNameHash.set(hash, fileName);
41823
+ }
41824
+ return `__VITE_WORKER_ASSET__${hash}__`;
41825
+ }
41826
+ async function workerFileToUrl(config, id, query) {
41827
+ const workerMap = workerCache.get(config.mainConfig || config);
41828
+ let fileName = workerMap.bundle.get(id);
41829
+ if (!fileName) {
41830
+ const outputChunk = await bundleWorkerEntry(config, id, query);
41831
+ fileName = outputChunk.fileName;
41832
+ saveEmitWorkerAsset(config, {
41833
+ fileName,
41834
+ source: outputChunk.code,
41835
+ type: 'asset',
41836
+ });
41837
+ workerMap.bundle.set(id, fileName);
41838
+ }
41839
+ return encodeWorkerAssetFileName(fileName, workerMap);
41840
+ }
41841
+ function webWorkerPlugin(config) {
41842
+ const isBuild = config.command === 'build';
41843
+ let server;
41844
+ const isWorker = config.isWorker;
41845
+ const isWorkerQueryId = (id) => {
41846
+ const parsedQuery = parseRequest(id);
41847
+ if (parsedQuery &&
41848
+ (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
41849
+ return true;
41850
+ }
41851
+ return false;
41852
+ };
41853
+ return {
41854
+ name: 'vite:worker',
41855
+ configureServer(_server) {
41856
+ server = _server;
41857
+ },
41858
+ buildStart() {
41859
+ if (isWorker) {
41860
+ return;
41861
+ }
41862
+ workerCache.set(config, {
41863
+ assets: new Map(),
41864
+ bundle: new Map(),
41865
+ fileNameHash: new Map(),
41866
+ });
41867
+ },
41868
+ load(id) {
41869
+ if (isBuild && isWorkerQueryId(id)) {
41870
+ return '';
41871
+ }
41872
+ },
41873
+ shouldTransformCachedModule({ id }) {
41874
+ if (isBuild && isWorkerQueryId(id) && config.build.watch) {
41875
+ return true;
41876
+ }
41877
+ return false;
41878
+ },
41879
+ async transform(raw, id, options) {
41880
+ const ssr = options?.ssr === true;
41881
+ const query = parseRequest(id);
41882
+ if (query && query[WORKER_FILE_ID] != null) {
41883
+ // if import worker by worker constructor will have query.type
41884
+ // other type will be import worker by esm
41885
+ const workerType = query['type'];
41886
+ let injectEnv = '';
41887
+ if (workerType === 'classic') {
41888
+ injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
41889
+ }
41890
+ else if (workerType === 'module') {
41891
+ injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
41892
+ }
41893
+ else if (workerType === 'ignore') {
41894
+ if (isBuild) {
41895
+ injectEnv = '';
41896
+ }
41897
+ else if (server) {
41898
+ // dynamic worker type we can't know how import the env
41899
+ // so we copy /@vite/env code of server transform result into file header
41900
+ const { moduleGraph } = server;
41901
+ const module = moduleGraph.getModuleById(ENV_ENTRY);
41902
+ injectEnv = module?.transformResult?.code || '';
41903
+ }
41904
+ }
41905
+ return {
41906
+ code: injectEnv + raw,
41907
+ };
41908
+ }
41909
+ if (query == null ||
41910
+ (query && (query.worker ?? query.sharedworker) == null)) {
41911
+ return;
41912
+ }
41913
+ // stringified url or `new URL(...)`
41914
+ let url;
41915
+ const { format } = config.worker;
41916
+ const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
41917
+ const workerType = isBuild
41918
+ ? format === 'es'
41919
+ ? 'module'
41920
+ : 'classic'
41921
+ : 'module';
41922
+ const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
41923
+ if (isBuild) {
41924
+ getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
41925
+ if (query.inline != null) {
41926
+ const chunk = await bundleWorkerEntry(config, id, query);
41927
+ const encodedJs = `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";`;
41928
+ const code =
41929
+ // Using blob URL for SharedWorker results in multiple instances of a same worker
41930
+ workerConstructor === 'Worker'
41931
+ ? `${encodedJs}
41932
+ const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
41933
+ export default function WorkerWrapper() {
41934
+ let objURL;
41935
+ try {
41936
+ objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
41937
+ if (!objURL) throw ''
41938
+ return new ${workerConstructor}(objURL)
41939
+ } catch(e) {
41940
+ return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
41941
+ } finally {
41942
+ objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
41943
+ }
41944
+ }`
41945
+ : `${encodedJs}
41946
+ export default function WorkerWrapper() {
41947
+ return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
41948
+ }
41949
+ `;
41950
+ return {
41951
+ code,
41952
+ // Empty sourcemap to suppress Rollup warning
41953
+ map: { mappings: '' },
41954
+ };
41955
+ }
41956
+ else {
41957
+ url = await workerFileToUrl(config, id, query);
41958
+ }
41959
+ }
41960
+ else {
41961
+ url = await fileToUrl(cleanUrl(id), config, this);
41962
+ url = injectQuery(url, WORKER_FILE_ID);
41963
+ url = injectQuery(url, `type=${workerType}`);
41964
+ }
41965
+ if (query.url != null) {
41966
+ return {
41967
+ code: `export default ${JSON.stringify(url)}`,
41968
+ map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
41969
+ };
41970
+ }
41971
+ return {
41972
+ code: `export default function WorkerWrapper() {
41973
+ return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
41974
+ }`,
41975
+ map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
41976
+ };
41977
+ },
41978
+ renderChunk(code, chunk, outputOptions) {
41979
+ let s;
41980
+ const result = () => {
41981
+ return (s && {
41982
+ code: s.toString(),
41983
+ map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
41984
+ });
41985
+ };
41986
+ if (code.match(workerAssetUrlRE) || code.includes('import.meta.url')) {
41987
+ const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format);
41988
+ let match;
41989
+ s = new MagicString(code);
41990
+ workerAssetUrlRE.lastIndex = 0;
41991
+ // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
41992
+ const workerMap = workerCache.get(config.mainConfig || config);
41993
+ const { fileNameHash } = workerMap;
41994
+ while ((match = workerAssetUrlRE.exec(code))) {
41995
+ const [full, hash] = match;
41996
+ const filename = fileNameHash.get(hash);
41997
+ const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
41998
+ const replacementString = typeof replacement === 'string'
41999
+ ? JSON.stringify(replacement).slice(1, -1)
42000
+ : `"+${replacement.runtime}+"`;
42001
+ s.update(match.index, match.index + full.length, replacementString);
42002
+ }
42003
+ }
42004
+ return result();
42005
+ },
42006
+ generateBundle(opts) {
42007
+ // @ts-expect-error asset emits are skipped in legacy bundle
42008
+ if (opts.__vite_skip_asset_emit__ || isWorker) {
42009
+ return;
42010
+ }
42011
+ const workerMap = workerCache.get(config);
42012
+ workerMap.assets.forEach((asset) => {
42013
+ this.emitFile(asset);
42014
+ workerMap.assets.delete(asset.fileName);
42015
+ });
42016
+ },
42017
+ };
42018
+ }
42019
+
42083
42020
  /**
42084
42021
  * A plugin to avoid an aliased AND optimized dep from being aliased in src
42085
42022
  */
@@ -42115,7 +42052,7 @@ function preAliasPlugin(config) {
42115
42052
  fs$l.existsSync(resolvedId) &&
42116
42053
  !moduleListContains(optimizeDeps.exclude, id) &&
42117
42054
  path$o.isAbsolute(resolvedId) &&
42118
- (resolvedId.includes('node_modules') ||
42055
+ (isInNodeModules(resolvedId) ||
42119
42056
  optimizeDeps.include?.includes(id)) &&
42120
42057
  isOptimizable(resolvedId, optimizeDeps) &&
42121
42058
  !(isBuild && ssr && isConfiguredAsExternal(id)) &&
@@ -43554,6 +43491,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43554
43491
  return container;
43555
43492
  }
43556
43493
 
43494
+ const isDebug$1 = process.env.DEBUG;
43557
43495
  const debug$8 = createDebugger('vite:deps');
43558
43496
  const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
43559
43497
  // A simple regex to detect import sources. This is only used on
@@ -43584,7 +43522,9 @@ function scanImports(config) {
43584
43522
  }
43585
43523
  if (scanContext.cancelled)
43586
43524
  return;
43587
- debug$8(`Crawling dependencies using entries:\n ${entries.join('\n ')}`);
43525
+ debug$8(`Crawling dependencies using entries: ${entries
43526
+ .map((entry) => `\n ${picocolorsExports.dim(entry)}`)
43527
+ .join('')}`);
43588
43528
  return prepareEsbuildScanner(config, entries, deps, missing, scanContext);
43589
43529
  });
43590
43530
  const result = esbuildContext
@@ -43635,7 +43575,14 @@ function scanImports(config) {
43635
43575
  throw e;
43636
43576
  })
43637
43577
  .finally(() => {
43638
- debug$8(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms:`, deps);
43578
+ if (isDebug$1) {
43579
+ const duration = (performance$1.now() - start).toFixed(2);
43580
+ const depsStr = Object.keys(orderedDependencies(deps))
43581
+ .sort()
43582
+ .map((id) => `\n ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(deps[id])}`)
43583
+ .join('') || picocolorsExports.dim('no dependencies found');
43584
+ debug$8(`Scan completed in ${duration}ms: ${depsStr}`);
43585
+ }
43639
43586
  });
43640
43587
  return {
43641
43588
  cancel: async () => {
@@ -43793,7 +43740,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
43793
43740
  // It is possible for the scanner to scan html types in node_modules.
43794
43741
  // If we can optimize this html type, skip it so it's handled by the
43795
43742
  // bare import resolve, and recorded as optimization dep.
43796
- if (resolved.includes('node_modules') &&
43743
+ if (isInNodeModules(resolved) &&
43797
43744
  isOptimizable(resolved, config.optimizeDeps))
43798
43745
  return;
43799
43746
  return {
@@ -43803,7 +43750,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
43803
43750
  });
43804
43751
  // extract scripts inside HTML-like files and treat it as a js module
43805
43752
  build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
43806
- let raw = fs$l.readFileSync(path, 'utf-8');
43753
+ let raw = await fsp.readFile(path, 'utf-8');
43807
43754
  // Avoid matching the content of the comment
43808
43755
  raw = raw.replace(commentRE, '<!---->');
43809
43756
  const isHtml = path.endsWith('.html');
@@ -43913,7 +43860,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
43913
43860
  if (shouldExternalizeDep(resolved, id)) {
43914
43861
  return externalUnlessEntry({ path: id });
43915
43862
  }
43916
- if (resolved.includes('node_modules') || include?.includes(id)) {
43863
+ if (isInNodeModules(resolved) || include?.includes(id)) {
43917
43864
  // dependency or forced included, externalize and stop crawling
43918
43865
  if (isOptimizable(resolved, config.optimizeDeps)) {
43919
43866
  depImports[id] = resolved;
@@ -43986,7 +43933,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
43986
43933
  let ext = path$o.extname(id).slice(1);
43987
43934
  if (ext === 'mjs')
43988
43935
  ext = 'js';
43989
- let contents = fs$l.readFileSync(id, 'utf-8');
43936
+ let contents = await fsp.readFile(id, 'utf-8');
43990
43937
  if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
43991
43938
  contents = config.esbuild.jsxInject + `\n` + contents;
43992
43939
  }
@@ -44089,7 +44036,7 @@ async function createDepsOptimizer(config, server) {
44089
44036
  const isBuild = config.command === 'build';
44090
44037
  const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
44091
44038
  const sessionTimestamp = Date.now().toString();
44092
- const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr);
44039
+ const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr);
44093
44040
  let handle;
44094
44041
  let closed = false;
44095
44042
  let metadata = cachedMetadata || initDepsOptimizerMetadata(config, ssr, sessionTimestamp);
@@ -44097,7 +44044,7 @@ async function createDepsOptimizer(config, server) {
44097
44044
  metadata,
44098
44045
  registerMissingImport,
44099
44046
  run: () => debouncedProcessing(0),
44100
- isOptimizedDepFile: (id) => isOptimizedDepFile(id, config),
44047
+ isOptimizedDepFile: createIsOptimizedDepFile(config),
44101
44048
  isOptimizedDepUrl: createIsOptimizedDepUrl(config),
44102
44049
  getOptimizedDepId: (depInfo) => isBuild ? depInfo.file : `${depInfo.file}?v=${depInfo.browserHash}`,
44103
44050
  registerWorkersSource,
@@ -44106,6 +44053,7 @@ async function createDepsOptimizer(config, server) {
44106
44053
  ensureFirstRun,
44107
44054
  close,
44108
44055
  options: getDepOptimizationConfig(config, ssr),
44056
+ server,
44109
44057
  };
44110
44058
  depsOptimizerMap.set(config, depsOptimizer);
44111
44059
  let newDepsDiscovered = false;
@@ -44150,7 +44098,7 @@ async function createDepsOptimizer(config, server) {
44150
44098
  // Initialize discovered deps with manually added optimizeDeps.include info
44151
44099
  const deps = {};
44152
44100
  await addManuallyIncludedOptimizeDeps(deps, config, ssr);
44153
- const discovered = await toDiscoveredDependencies(config, deps, ssr, sessionTimestamp);
44101
+ const discovered = toDiscoveredDependencies(config, deps, ssr, sessionTimestamp);
44154
44102
  for (const depInfo of Object.values(discovered)) {
44155
44103
  addOptimizedDepInfo(metadata, 'discovered', {
44156
44104
  ...depInfo,
@@ -44168,9 +44116,6 @@ async function createDepsOptimizer(config, server) {
44168
44116
  discover = discoverProjectDependencies(config);
44169
44117
  const deps = await discover.result;
44170
44118
  discover = undefined;
44171
- debuggerViteDeps(picocolorsExports.green(Object.keys(deps).length > 0
44172
- ? `dependencies found by scanner: ${depsLogString(Object.keys(deps))}`
44173
- : `no dependencies found by scanner`));
44174
44119
  // Add these dependencies to the discovered list, as these are currently
44175
44120
  // used by the preAliasPlugin to support aliased and optimized deps.
44176
44121
  // This is also used by the CJS externalization heuristics in legacy mode
@@ -44361,12 +44306,12 @@ async function createDepsOptimizer(config, server) {
44361
44306
  enqueuedRerun?.();
44362
44307
  }
44363
44308
  function fullReload() {
44364
- if (server) {
44309
+ if (depsOptimizer.server) {
44365
44310
  // Cached transform results have stale imports (resolved to
44366
44311
  // old locations) so they need to be invalidated before the page is
44367
44312
  // reloaded.
44368
- server.moduleGraph.invalidateAll();
44369
- server.ws.send({
44313
+ depsOptimizer.server.moduleGraph.invalidateAll();
44314
+ depsOptimizer.server.ws.send({
44370
44315
  type: 'full-reload',
44371
44316
  path: '*',
44372
44317
  });
@@ -44509,13 +44454,13 @@ async function createDepsOptimizer(config, server) {
44509
44454
  let registeredIds = [];
44510
44455
  let seenIds = new Set();
44511
44456
  let workersSources = new Set();
44512
- let waitingOn;
44457
+ const waitingOn = new Set();
44513
44458
  let firstRunEnsured = false;
44514
44459
  function resetRegisteredIds() {
44515
44460
  registeredIds = [];
44516
44461
  seenIds = new Set();
44517
44462
  workersSources = new Set();
44518
- waitingOn = undefined;
44463
+ waitingOn.clear();
44519
44464
  firstRunEnsured = false;
44520
44465
  }
44521
44466
  // If all the inputs are dependencies, we aren't going to get any
@@ -44536,8 +44481,8 @@ async function createDepsOptimizer(config, server) {
44536
44481
  // Avoid waiting for this id, as it may be blocked by the rollup
44537
44482
  // bundling process of the worker that also depends on the optimizer
44538
44483
  registeredIds = registeredIds.filter((registered) => registered.id !== id);
44539
- if (waitingOn === id) {
44540
- waitingOn = undefined;
44484
+ if (waitingOn.has(id)) {
44485
+ waitingOn.delete(id);
44541
44486
  runOptimizerWhenIdle();
44542
44487
  }
44543
44488
  }
@@ -44548,29 +44493,41 @@ async function createDepsOptimizer(config, server) {
44548
44493
  runOptimizerWhenIdle();
44549
44494
  }
44550
44495
  }
44551
- function runOptimizerWhenIdle() {
44552
- if (!waitingOn) {
44553
- const next = registeredIds.pop();
44554
- if (next) {
44555
- waitingOn = next.id;
44556
- const afterLoad = () => {
44557
- waitingOn = undefined;
44558
- if (!closed && !workersSources.has(next.id)) {
44559
- if (registeredIds.length > 0) {
44560
- runOptimizerWhenIdle();
44561
- }
44562
- else {
44563
- onCrawlEnd();
44564
- }
44565
- }
44566
- };
44567
- next
44568
- .done()
44569
- .then(() => {
44570
- setTimeout(afterLoad, registeredIds.length > 0 ? 0 : runOptimizerIfIdleAfterMs);
44571
- })
44572
- .catch(afterLoad);
44496
+ async function runOptimizerWhenIdle() {
44497
+ if (waitingOn.size > 0)
44498
+ return;
44499
+ const processingRegisteredIds = registeredIds;
44500
+ registeredIds = [];
44501
+ const donePromises = processingRegisteredIds.map(async (registeredId) => {
44502
+ waitingOn.add(registeredId.id);
44503
+ try {
44504
+ await registeredId.done();
44505
+ }
44506
+ finally {
44507
+ waitingOn.delete(registeredId.id);
44573
44508
  }
44509
+ });
44510
+ const afterLoad = () => {
44511
+ if (closed)
44512
+ return;
44513
+ if (registeredIds.length > 0 &&
44514
+ registeredIds.every((registeredId) => workersSources.has(registeredId.id))) {
44515
+ return;
44516
+ }
44517
+ if (registeredIds.length > 0) {
44518
+ runOptimizerWhenIdle();
44519
+ }
44520
+ else {
44521
+ onCrawlEnd();
44522
+ }
44523
+ };
44524
+ const results = await Promise.allSettled(donePromises);
44525
+ if (registeredIds.length > 0 ||
44526
+ results.some((result) => result.status === 'rejected')) {
44527
+ afterLoad();
44528
+ }
44529
+ else {
44530
+ setTimeout(afterLoad, runOptimizerIfIdleAfterMs);
44574
44531
  }
44575
44532
  }
44576
44533
  }
@@ -44578,7 +44535,7 @@ async function createDevSsrDepsOptimizer(config) {
44578
44535
  const metadata = await optimizeServerSsrDeps(config);
44579
44536
  const depsOptimizer = {
44580
44537
  metadata,
44581
- isOptimizedDepFile: (id) => isOptimizedDepFile(id, config),
44538
+ isOptimizedDepFile: createIsOptimizedDepFile(config),
44582
44539
  isOptimizedDepUrl: createIsOptimizedDepUrl(config),
44583
44540
  getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
44584
44541
  registerMissingImport: () => {
@@ -44627,7 +44584,7 @@ const reExportRE = /export\s+\*\s+from/;
44627
44584
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
44628
44585
  const log = asCommand ? config.logger.info : debug$7;
44629
44586
  const ssr = config.command === 'build' && !!config.build.ssr;
44630
- const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
44587
+ const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
44631
44588
  if (cachedMetadata) {
44632
44589
  return cachedMetadata;
44633
44590
  }
@@ -44642,7 +44599,7 @@ async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand
44642
44599
  }
44643
44600
  async function optimizeServerSsrDeps(config) {
44644
44601
  const ssr = true;
44645
- const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr, config.optimizeDeps.force, false);
44602
+ const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, config.optimizeDeps.force, false);
44646
44603
  if (cachedMetadata) {
44647
44604
  return cachedMetadata;
44648
44605
  }
@@ -44686,19 +44643,24 @@ function addOptimizedDepInfo(metadata, type, depInfo) {
44686
44643
  * Creates the initial dep optimization metadata, loading it from the deps cache
44687
44644
  * if it exists and pre-bundling isn't forced
44688
44645
  */
44689
- function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
44646
+ async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
44690
44647
  const log = asCommand ? config.logger.info : debug$7;
44691
- // Before Vite 2.9, dependencies were cached in the root of the cacheDir
44692
- // For compat, we remove the cache if we find the old structure
44693
- if (fs$l.existsSync(path$o.join(config.cacheDir, '_metadata.json'))) {
44694
- emptyDir(config.cacheDir);
44695
- }
44648
+ setTimeout(() => {
44649
+ // Before Vite 2.9, dependencies were cached in the root of the cacheDir
44650
+ // For compat, we remove the cache if we find the old structure
44651
+ if (fs$l.existsSync(path$o.join(config.cacheDir, '_metadata.json'))) {
44652
+ emptyDir(config.cacheDir);
44653
+ }
44654
+ // Fire a clean up of stale cache dirs, in case old processes didn't
44655
+ // terminate correctly
44656
+ cleanupDepsCacheStaleDirs(config);
44657
+ }, 100);
44696
44658
  const depsCacheDir = getDepsCacheDir(config, ssr);
44697
44659
  if (!force) {
44698
44660
  let cachedMetadata;
44699
44661
  try {
44700
44662
  const cachedMetadataPath = path$o.join(depsCacheDir, '_metadata.json');
44701
- cachedMetadata = parseDepsOptimizerMetadata(fs$l.readFileSync(cachedMetadataPath, 'utf-8'), depsCacheDir);
44663
+ cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, 'utf-8'), depsCacheDir);
44702
44664
  }
44703
44665
  catch (e) { }
44704
44666
  // hash is consistent, no need to re-bundle
@@ -44713,7 +44675,7 @@ function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeD
44713
44675
  config.logger.info('Forced re-optimization of dependencies');
44714
44676
  }
44715
44677
  // Start with a fresh cache
44716
- fs$l.rmSync(depsCacheDir, { recursive: true, force: true });
44678
+ await fsp.rm(depsCacheDir, { recursive: true, force: true });
44717
44679
  }
44718
44680
  /**
44719
44681
  * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
@@ -44778,15 +44740,10 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44778
44740
  // Create a temporal directory so we don't need to delete optimized deps
44779
44741
  // until they have been processed. This also avoids leaving the deps cache
44780
44742
  // directory in a corrupted state if there is an error
44781
- if (fs$l.existsSync(processingCacheDir)) {
44782
- emptyDir(processingCacheDir);
44783
- }
44784
- else {
44785
- fs$l.mkdirSync(processingCacheDir, { recursive: true });
44786
- }
44743
+ fs$l.mkdirSync(processingCacheDir, { recursive: true });
44787
44744
  // a hint for Node.js
44788
44745
  // all files in the cache directory should be recognized as ES modules
44789
- writeFile(path$o.resolve(processingCacheDir, 'package.json'), JSON.stringify({ type: 'module' }));
44746
+ fs$l.writeFileSync(path$o.resolve(processingCacheDir, 'package.json'), `{\n "type": "module"\n}\n`);
44790
44747
  const metadata = initDepsOptimizerMetadata(config, ssr);
44791
44748
  metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
44792
44749
  // We prebundle dependencies with esbuild and cache them, but there is no need
@@ -44797,32 +44754,63 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44797
44754
  const cleanUp = () => {
44798
44755
  if (!cleaned) {
44799
44756
  cleaned = true;
44800
- fs$l.rmSync(processingCacheDir, { recursive: true, force: true });
44757
+ // No need to wait, we can clean up in the background because temp folders
44758
+ // are unique per run
44759
+ fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
44760
+ // Ignore errors
44761
+ });
44801
44762
  }
44802
44763
  };
44803
- const createProcessingResult = () => ({
44764
+ const succesfulResult = {
44804
44765
  metadata,
44805
- async commit() {
44806
- if (cleaned) {
44807
- throw new Error(`Vite Internal Error: Can't commit optimizeDeps processing result, it has already been cancelled.`);
44808
- }
44809
- // Write metadata file, delete `deps` folder and rename the `processing` folder to `deps`
44810
- // Processing is done, we can now replace the depsCacheDir with processingCacheDir
44766
+ cancel: cleanUp,
44767
+ commit: async () => {
44768
+ // Write metadata file, then commit the processing folder to the global deps cache
44811
44769
  // Rewire the file paths from the temporal processing dir to the final deps cache dir
44812
- await removeDir(depsCacheDir);
44813
- await renameDir(processingCacheDir, depsCacheDir);
44770
+ const dataPath = path$o.join(processingCacheDir, '_metadata.json');
44771
+ fs$l.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
44772
+ // In order to minimize the time where the deps folder isn't in a consistent state,
44773
+ // we first rename the old depsCacheDir to a temporal path, then we rename the
44774
+ // new processing cache dir to the depsCacheDir. In systems where doing so in sync
44775
+ // is safe, we do an atomic operation (at least for this thread). For Windows, we
44776
+ // found there are cases where the rename operation may finish before it's done
44777
+ // so we do a graceful rename checking that the folder has been properly renamed.
44778
+ // We found that the rename-rename (then delete the old folder in the background)
44779
+ // is safer than a delete-rename operation.
44780
+ const temporalPath = depsCacheDir + getTempSuffix();
44781
+ const depsCacheDirPresent = fs$l.existsSync(depsCacheDir);
44782
+ if (isWindows$4) {
44783
+ if (depsCacheDirPresent)
44784
+ await safeRename(depsCacheDir, temporalPath);
44785
+ await safeRename(processingCacheDir, depsCacheDir);
44786
+ }
44787
+ else {
44788
+ if (depsCacheDirPresent)
44789
+ fs$l.renameSync(depsCacheDir, temporalPath);
44790
+ fs$l.renameSync(processingCacheDir, depsCacheDir);
44791
+ }
44792
+ // Delete temporal path in the background
44793
+ if (depsCacheDirPresent)
44794
+ fsp.rm(temporalPath, { recursive: true, force: true });
44814
44795
  },
44815
- cancel: cleanUp,
44816
- });
44796
+ };
44817
44797
  if (!qualifiedIds.length) {
44798
+ // No deps to optimize, we still commit the processing cache dir to remove
44799
+ // the previous optimized deps if they exist, and let the next server start
44800
+ // skip the scanner step if the lockfile hasn't changed
44818
44801
  return {
44819
44802
  cancel: async () => cleanUp(),
44820
- result: Promise.resolve(createProcessingResult()),
44803
+ result: Promise.resolve(succesfulResult),
44821
44804
  };
44822
44805
  }
44806
+ const cancelledResult = {
44807
+ metadata,
44808
+ commit: async () => cleanUp(),
44809
+ cancel: cleanUp,
44810
+ };
44823
44811
  const start = performance$1.now();
44824
44812
  const preparedRun = prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext);
44825
- const result = preparedRun.then(({ context, idToExports }) => {
44813
+ const runResult = preparedRun.then(({ context, idToExports }) => {
44826
44814
  function disposeContext() {
44827
44815
  return context?.dispose().catch((e) => {
44828
44816
  config.logger.error('Failed to dispose esbuild context', { error: e });
@@ -44830,7 +44818,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44830
44818
  }
44831
44819
  if (!context || optimizerContext.cancelled) {
44832
44820
  disposeContext();
44833
- return createProcessingResult();
44821
+ return cancelledResult;
44834
44822
  }
44835
44823
  return context
44836
44824
  .rebuild()
@@ -44870,16 +44858,14 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44870
44858
  }
44871
44859
  }
44872
44860
  }
44873
- const dataPath = path$o.join(processingCacheDir, '_metadata.json');
44874
- writeFile(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
44875
- debug$7(`deps bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
44876
- return createProcessingResult();
44861
+ debug$7(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
44862
+ return succesfulResult;
44877
44863
  })
44878
44864
  .catch((e) => {
44879
44865
  if (e.errors && e.message.includes('The build was canceled')) {
44880
44866
  // esbuild logs an error when cancelling, but this is expected so
44881
44867
  // return an empty result instead
44882
- return createProcessingResult();
44868
+ return cancelledResult;
44883
44869
  }
44884
44870
  throw e;
44885
44871
  })
@@ -44887,7 +44873,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44887
44873
  return disposeContext();
44888
44874
  });
44889
44875
  });
44890
- result.catch(() => {
44876
+ runResult.catch(() => {
44891
44877
  cleanUp();
44892
44878
  });
44893
44879
  return {
@@ -44897,7 +44883,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44897
44883
  await context?.cancel();
44898
44884
  cleanUp();
44899
44885
  },
44900
- result,
44886
+ result: runResult,
44901
44887
  };
44902
44888
  }
44903
44889
  async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext) {
@@ -45102,14 +45088,20 @@ function getDepsCacheDir(config, ssr) {
45102
45088
  function getProcessingDepsCacheDir(config, ssr) {
45103
45089
  return (getDepsCacheDirPrefix(config) +
45104
45090
  getDepsCacheSuffix(config, ssr) +
45105
- '_temp_' +
45106
- getHash(Date.now().toString()));
45091
+ getTempSuffix());
45092
+ }
45093
+ function getTempSuffix() {
45094
+ return ('_temp_' +
45095
+ getHash(`${process.pid}:${Date.now().toString()}:${Math.random()
45096
+ .toString(16)
45097
+ .slice(2)}`));
45107
45098
  }
45108
45099
  function getDepsCacheDirPrefix(config) {
45109
45100
  return normalizePath$3(path$o.resolve(config.cacheDir, 'deps'));
45110
45101
  }
45111
- function isOptimizedDepFile(id, config) {
45112
- return id.startsWith(getDepsCacheDirPrefix(config));
45102
+ function createIsOptimizedDepFile(config) {
45103
+ const depsCacheDirPrefix = getDepsCacheDirPrefix(config);
45104
+ return (id) => id.startsWith(depsCacheDirPrefix);
45113
45105
  }
45114
45106
  function createIsOptimizedDepUrl(config) {
45115
45107
  const { root } = config;
@@ -45235,7 +45227,7 @@ async function extractExportsData(filePath, config, ssr) {
45235
45227
  }
45236
45228
  let parseResult;
45237
45229
  let usedJsxLoader = false;
45238
- const entryContent = fs$l.readFileSync(filePath, 'utf-8');
45230
+ const entryContent = await fsp.readFile(filePath, 'utf-8');
45239
45231
  try {
45240
45232
  parseResult = parse$e(entryContent);
45241
45233
  }
@@ -45298,8 +45290,9 @@ const lockfileFormats = [
45298
45290
  { name: 'pnpm-lock.yaml', checkPatches: false },
45299
45291
  { name: 'bun.lockb', checkPatches: true },
45300
45292
  ];
45293
+ const lockfileNames = lockfileFormats.map((l) => l.name);
45301
45294
  function getDepHash(config, ssr) {
45302
- const lockfilePath = lookupFile(config.root, lockfileFormats.map((l) => l.name), { pathOnly: true });
45295
+ const lockfilePath = lookupFile(config.root, lockfileNames);
45303
45296
  let content = lockfilePath ? fs$l.readFileSync(lockfilePath, 'utf-8') : '';
45304
45297
  if (lockfilePath) {
45305
45298
  const lockfileName = path$o.basename(lockfilePath);
@@ -45307,11 +45300,9 @@ function getDepHash(config, ssr) {
45307
45300
  if (checkPatches) {
45308
45301
  // Default of https://github.com/ds300/patch-package
45309
45302
  const fullPath = path$o.join(path$o.dirname(lockfilePath), 'patches');
45310
- if (fs$l.existsSync(fullPath)) {
45311
- const stats = fs$l.statSync(fullPath);
45312
- if (stats.isDirectory()) {
45313
- content += stats.mtimeMs.toString();
45314
- }
45303
+ const stat = tryStatSync(fullPath);
45304
+ if (stat?.isDirectory()) {
45305
+ content += stat.mtimeMs.toString();
45315
45306
  }
45316
45307
  }
45317
45308
  }
@@ -45378,7 +45369,7 @@ async function cleanupDepsCacheStaleDirs(config) {
45378
45369
  const stats = await fsp.stat(tempDirPath).catch((_) => null);
45379
45370
  if (stats?.mtime &&
45380
45371
  Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
45381
- await removeDir(tempDirPath);
45372
+ await fsp.rm(tempDirPath, { recursive: true, force: true });
45382
45373
  }
45383
45374
  }
45384
45375
  }
@@ -45388,12 +45379,47 @@ async function cleanupDepsCacheStaleDirs(config) {
45388
45379
  config.logger.error(err);
45389
45380
  }
45390
45381
  }
45382
+ // We found issues with renaming folders in some systems. This is a custom
45383
+ // implementation for the optimizer. It isn't intended to be a general utility
45384
+ // Based on node-graceful-fs
45385
+ // The ISC License
45386
+ // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
45387
+ // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
45388
+ // On Windows, A/V software can lock the directory, causing this
45389
+ // to fail with an EACCES or EPERM if the directory contains newly
45390
+ // created files. The original tried for up to 60 seconds, we only
45391
+ // wait for 5 seconds, as a longer time would be seen as an error
45392
+ const GRACEFUL_RENAME_TIMEOUT = 5000;
45393
+ const safeRename = promisify$4(function gracefulRename(from, to, cb) {
45394
+ const start = Date.now();
45395
+ let backoff = 0;
45396
+ fs$l.rename(from, to, function CB(er) {
45397
+ if (er &&
45398
+ (er.code === 'EACCES' || er.code === 'EPERM') &&
45399
+ Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
45400
+ setTimeout(function () {
45401
+ fs$l.stat(to, function (stater, st) {
45402
+ if (stater && stater.code === 'ENOENT')
45403
+ fs$l.rename(from, to, CB);
45404
+ else
45405
+ CB(er);
45406
+ });
45407
+ }, backoff);
45408
+ if (backoff < 100)
45409
+ backoff += 10;
45410
+ return;
45411
+ }
45412
+ if (cb)
45413
+ cb(er);
45414
+ });
45415
+ });
45391
45416
 
45392
45417
  var index$1 = {
45393
45418
  __proto__: null,
45394
45419
  addManuallyIncludedOptimizeDeps: addManuallyIncludedOptimizeDeps,
45395
45420
  addOptimizedDepInfo: addOptimizedDepInfo,
45396
45421
  cleanupDepsCacheStaleDirs: cleanupDepsCacheStaleDirs,
45422
+ createIsOptimizedDepFile: createIsOptimizedDepFile,
45397
45423
  createIsOptimizedDepUrl: createIsOptimizedDepUrl,
45398
45424
  debuggerViteDeps: debuggerViteDeps,
45399
45425
  depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
@@ -45403,13 +45429,11 @@ var index$1 = {
45403
45429
  findKnownImports: findKnownImports,
45404
45430
  getDepHash: getDepHash,
45405
45431
  getDepsCacheDir: getDepsCacheDir,
45406
- getDepsCacheDirPrefix: getDepsCacheDirPrefix,
45407
45432
  getDepsOptimizer: getDepsOptimizer,
45408
45433
  getOptimizedDepPath: getOptimizedDepPath,
45409
45434
  initDepsOptimizer: initDepsOptimizer,
45410
45435
  initDepsOptimizerMetadata: initDepsOptimizerMetadata,
45411
45436
  initDevSsrDepsOptimizer: initDevSsrDepsOptimizer,
45412
- isOptimizedDepFile: isOptimizedDepFile,
45413
45437
  loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
45414
45438
  newDepOptimizationProcessing: newDepOptimizationProcessing,
45415
45439
  optimizeDeps: optimizeDeps,
@@ -45549,8 +45573,7 @@ function buildImportAnalysisPlugin(config) {
45549
45573
  }
45550
45574
  },
45551
45575
  async transform(source, importer) {
45552
- if (importer.includes('node_modules') &&
45553
- !dynamicImportPrefixRE.test(source)) {
45576
+ if (isInNodeModules(importer) && !dynamicImportPrefixRE.test(source)) {
45554
45577
  return;
45555
45578
  }
45556
45579
  await init;
@@ -46300,7 +46323,8 @@ async function build(inlineConfig = {}) {
46300
46323
  const cjsSsrBuild = ssr && config.ssr.format === 'cjs';
46301
46324
  const format = output.format || (cjsSsrBuild ? 'cjs' : 'es');
46302
46325
  const jsExt = ssrNodeBuild || libOptions
46303
- ? resolveOutputJsExtension(format, getPkgJson(config.root)?.type)
46326
+ ? resolveOutputJsExtension(format, findNearestPackageData(config.root, config.packageCache)?.data
46327
+ .type)
46304
46328
  : 'js';
46305
46329
  return {
46306
46330
  dir: outDir,
@@ -46316,7 +46340,7 @@ async function build(inlineConfig = {}) {
46316
46340
  entryFileNames: ssr
46317
46341
  ? `[name].${jsExt}`
46318
46342
  : libOptions
46319
- ? ({ name }) => resolveLibFilename(libOptions, format, name, config.root, jsExt)
46343
+ ? ({ name }) => resolveLibFilename(libOptions, format, name, config.root, jsExt, config.packageCache)
46320
46344
  : path$o.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
46321
46345
  chunkFileNames: libOptions
46322
46346
  ? `[name]-[hash].${jsExt}`
@@ -46432,9 +46456,6 @@ function prepareOutDir(outDirs, emptyOutDir, config) {
46432
46456
  }
46433
46457
  }
46434
46458
  }
46435
- function getPkgJson(root) {
46436
- return JSON.parse(lookupFile(root, ['package.json']) || `{}`);
46437
- }
46438
46459
  function getPkgName(name) {
46439
46460
  return name?.[0] === '@' ? name.split('/')[1] : name;
46440
46461
  }
@@ -46446,18 +46467,18 @@ function resolveOutputJsExtension(format, type = 'commonjs') {
46446
46467
  return format === 'es' ? 'mjs' : 'js';
46447
46468
  }
46448
46469
  }
46449
- function resolveLibFilename(libOptions, format, entryName, root, extension) {
46470
+ function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
46450
46471
  if (typeof libOptions.fileName === 'function') {
46451
46472
  return libOptions.fileName(format, entryName);
46452
46473
  }
46453
- const packageJson = getPkgJson(root);
46474
+ const packageJson = findNearestPackageData(root, packageCache)?.data;
46454
46475
  const name = libOptions.fileName ||
46455
- (typeof libOptions.entry === 'string'
46476
+ (packageJson && typeof libOptions.entry === 'string'
46456
46477
  ? getPkgName(packageJson.name)
46457
46478
  : entryName);
46458
46479
  if (!name)
46459
46480
  throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
46460
- extension ?? (extension = resolveOutputJsExtension(format, packageJson.type));
46481
+ extension ?? (extension = resolveOutputJsExtension(format, packageJson?.type));
46461
46482
  if (format === 'cjs' || format === 'es') {
46462
46483
  return `${name}.${extension}`;
46463
46484
  }
@@ -51299,7 +51320,8 @@ _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
51299
51320
  if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
51300
51321
  const opts = this.fsw.options;
51301
51322
  const watchCallback = async (fullPath, flags, info) => {
51302
- if (this.fsw.closed) return;
51323
+ // PATCH: bypass the callback for better perf when fullPath hit the ignored file list
51324
+ if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
51303
51325
  if (
51304
51326
  opts.depth !== undefined &&
51305
51327
  calcDepth(fullPath, realPath) > opts.depth
@@ -53152,20 +53174,20 @@ async function resolveHttpServer({ proxy }, app, httpsOptions) {
53152
53174
  async function resolveHttpsConfig(https) {
53153
53175
  if (!https)
53154
53176
  return undefined;
53155
- const httpsOption = isObject$2(https) ? { ...https } : {};
53156
- const { ca, cert, key, pfx } = httpsOption;
53157
- Object.assign(httpsOption, {
53158
- ca: readFileIfExists(ca),
53159
- cert: readFileIfExists(cert),
53160
- key: readFileIfExists(key),
53161
- pfx: readFileIfExists(pfx),
53162
- });
53163
- return httpsOption;
53177
+ if (!isObject$2(https))
53178
+ return {};
53179
+ const [ca, cert, key, pfx] = await Promise.all([
53180
+ readFileIfExists(https.ca),
53181
+ readFileIfExists(https.cert),
53182
+ readFileIfExists(https.key),
53183
+ readFileIfExists(https.pfx),
53184
+ ]);
53185
+ return { ...https, ca, cert, key, pfx };
53164
53186
  }
53165
- function readFileIfExists(value) {
53187
+ async function readFileIfExists(value) {
53166
53188
  if (typeof value === 'string') {
53167
53189
  try {
53168
- return fs$l.readFileSync(path$o.resolve(value));
53190
+ return fsp.readFile(path$o.resolve(value));
53169
53191
  }
53170
53192
  catch (e) {
53171
53193
  return value;
@@ -54156,7 +54178,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
54156
54178
  // In node@12+ we can use dynamic import to load CJS and ESM
54157
54179
  async function nodeImport(id, importer, resolveOptions) {
54158
54180
  let url;
54159
- if (id.startsWith('node:') || isBuiltin(id)) {
54181
+ if (id.startsWith('node:') || id.startsWith('data:') || isBuiltin(id)) {
54160
54182
  url = id;
54161
54183
  }
54162
54184
  else {
@@ -61197,12 +61219,13 @@ function transformMiddleware(server) {
61197
61219
  if (depsOptimizer?.isOptimizedDepUrl(url)) {
61198
61220
  // If the browser is requesting a source map for an optimized dep, it
61199
61221
  // means that the dependency has already been pre-bundled and loaded
61200
- const mapFile = url.startsWith(FS_PREFIX)
61222
+ const sourcemapPath = url.startsWith(FS_PREFIX)
61201
61223
  ? fsPathFromId(url)
61202
61224
  : normalizePath$3(ensureVolumeInPath(path$o.resolve(root, url.slice(1))));
61203
61225
  try {
61204
- const map = await promises$2.readFile(mapFile, 'utf-8');
61205
- return send$1(req, res, map, 'json', {
61226
+ const map = JSON.parse(await fsp.readFile(sourcemapPath, 'utf-8'));
61227
+ applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, logger);
61228
+ return send$1(req, res, JSON.stringify(map), 'json', {
61206
61229
  headers: server.config.server.headers,
61207
61230
  });
61208
61231
  }
@@ -61212,7 +61235,7 @@ function transformMiddleware(server) {
61212
61235
  // Send back an empty source map so the browser doesn't issue warnings
61213
61236
  const dummySourceMap = {
61214
61237
  version: 3,
61215
- file: mapFile.replace(/\.map$/, ''),
61238
+ file: sourcemapPath.replace(/\.map$/, ''),
61216
61239
  sources: [],
61217
61240
  sourcesContent: [],
61218
61241
  names: [],
@@ -61367,27 +61390,35 @@ function getHtmlFilename(url, server) {
61367
61390
  return decodeURIComponent(normalizePath$3(path$o.join(server.config.root, url.slice(1))));
61368
61391
  }
61369
61392
  }
61370
- const startsWithSingleSlashRE = /^\/(?!\/)/;
61371
- const processNodeUrl = (attr, sourceCodeLocation, s, config, htmlPath, originalUrl, moduleGraph) => {
61393
+ const processNodeUrl = (attr, sourceCodeLocation, s, config, htmlPath, originalUrl, server) => {
61372
61394
  let url = attr.value || '';
61373
- if (moduleGraph) {
61374
- const mod = moduleGraph.urlToModuleMap.get(url);
61395
+ if (server?.moduleGraph) {
61396
+ const mod = server.moduleGraph.urlToModuleMap.get(url);
61375
61397
  if (mod && mod.lastHMRTimestamp > 0) {
61376
61398
  url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
61377
61399
  }
61378
61400
  }
61379
61401
  const devBase = config.base;
61380
- if (startsWithSingleSlashRE.test(url)) {
61402
+ if (url[0] === '/' && url[1] !== '/') {
61381
61403
  // prefix with base (dev only, base is never relative)
61382
61404
  const fullUrl = path$o.posix.join(devBase, url);
61383
61405
  overwriteAttrValue(s, sourceCodeLocation, fullUrl);
61406
+ if (server && !checkPublicFile(url, config)) {
61407
+ preTransformRequest(server, fullUrl, devBase);
61408
+ }
61384
61409
  }
61385
61410
  else if (url[0] === '.' &&
61386
61411
  originalUrl &&
61387
61412
  originalUrl !== '/' &&
61388
61413
  htmlPath === '/index.html') {
61389
61414
  // prefix with base (dev only, base is never relative)
61390
- const replacer = (url) => path$o.posix.join(devBase, url);
61415
+ const replacer = (url) => {
61416
+ const fullUrl = path$o.posix.join(devBase, url);
61417
+ if (server && !checkPublicFile(url, config)) {
61418
+ preTransformRequest(server, fullUrl, devBase);
61419
+ }
61420
+ return fullUrl;
61421
+ };
61391
61422
  // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
61392
61423
  // path will add `/a/` prefix, it will caused 404.
61393
61424
  // rewrite before `./index.js` -> `localhost:5173/a/index.js`.
@@ -61444,6 +61475,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
61444
61475
  server?.moduleGraph.invalidateModule(module);
61445
61476
  }
61446
61477
  s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"></script>`);
61478
+ preTransformRequest(server, modulePath, base);
61447
61479
  };
61448
61480
  await traverseHtml(html, filename, (node) => {
61449
61481
  if (!nodeIsElement(node)) {
@@ -61453,7 +61485,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
61453
61485
  if (node.nodeName === 'script') {
61454
61486
  const { src, sourceCodeLocation, isModule } = getScriptInfo(node);
61455
61487
  if (src) {
61456
- processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, moduleGraph);
61488
+ processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, server);
61457
61489
  }
61458
61490
  else if (isModule && node.childNodes.length) {
61459
61491
  addInlineModule(node, 'js');
@@ -61513,7 +61545,7 @@ function indexHtmlMiddleware(server) {
61513
61545
  const filename = getHtmlFilename(url, server);
61514
61546
  if (fs$l.existsSync(filename)) {
61515
61547
  try {
61516
- let html = fs$l.readFileSync(filename, 'utf-8');
61548
+ let html = await fsp.readFile(filename, 'utf-8');
61517
61549
  html = await server.transformIndexHtml(url, html, req.originalUrl);
61518
61550
  return send$1(req, res, html, 'html', {
61519
61551
  headers: server.config.server.headers,
@@ -61527,6 +61559,16 @@ function indexHtmlMiddleware(server) {
61527
61559
  next();
61528
61560
  };
61529
61561
  }
61562
+ function preTransformRequest(server, url, base) {
61563
+ if (!server.config.server.preTransformRequests)
61564
+ return;
61565
+ url = unwrapId(stripBase(url, base));
61566
+ // transform all url as non-ssr as html includes client-side assets only
61567
+ server.transformRequest(url).catch((e) => {
61568
+ // Unexpected error, log the issue but avoid an unhandled exception
61569
+ server.config.logger.error(e);
61570
+ });
61571
+ }
61530
61572
 
61531
61573
  const logTime = createDebugger('vite:time');
61532
61574
  function timeMiddleware(root) {
@@ -62904,6 +62946,10 @@ function execAsync(command, options) {
62904
62946
 
62905
62947
  async function createServer(inlineConfig = {}) {
62906
62948
  const config = await resolveConfig(inlineConfig, 'serve');
62949
+ if (isDepsOptimizerEnabled(config, false)) {
62950
+ // start optimizer in the background, we still need to await the setup
62951
+ await initDepsOptimizer(config);
62952
+ }
62907
62953
  const { root, server: serverConfig } = config;
62908
62954
  const httpsOptions = await resolveHttpsConfig(config.server.https);
62909
62955
  const { middlewareMode } = serverConfig;
@@ -62921,7 +62967,7 @@ async function createServer(inlineConfig = {}) {
62921
62967
  }
62922
62968
  const watcher = chokidar.watch(
62923
62969
  // config file dependencies and env file might be outside of root
62924
- [root, ...config.configFileDependencies, config.envDir], resolvedWatchOptions);
62970
+ [root, ...config.configFileDependencies, path$o.join(config.envDir, '.env*')], resolvedWatchOptions);
62925
62971
  const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr }));
62926
62972
  const container = await createPluginContainer(config, moduleGraph, watcher);
62927
62973
  const closeHttpServer = createServerCloseFn(httpServer);
@@ -63153,21 +63199,24 @@ async function createServer(inlineConfig = {}) {
63153
63199
  }
63154
63200
  // error handler
63155
63201
  middlewares.use(errorMiddleware(server, middlewareMode));
63202
+ // when the optimizer is ready, hook server so that it can reload the page
63203
+ // or invalidate the module graph when needed
63204
+ const depsOptimizer = getDepsOptimizer(config);
63205
+ if (depsOptimizer) {
63206
+ depsOptimizer.server = server;
63207
+ }
63208
+ // httpServer.listen can be called multiple times
63209
+ // when port when using next port number
63210
+ // this code is to avoid calling buildStart multiple times
63156
63211
  let initingServer;
63157
63212
  let serverInited = false;
63158
63213
  const initServer = async () => {
63159
- if (serverInited) {
63214
+ if (serverInited)
63160
63215
  return;
63161
- }
63162
- if (initingServer) {
63216
+ if (initingServer)
63163
63217
  return initingServer;
63164
- }
63165
63218
  initingServer = (async function () {
63166
63219
  await container.buildStart({});
63167
- if (isDepsOptimizerEnabled(config, false)) {
63168
- // non-ssr
63169
- await initDepsOptimizer(config, server);
63170
- }
63171
63220
  initingServer = undefined;
63172
63221
  serverInited = true;
63173
63222
  })();
@@ -63190,9 +63239,6 @@ async function createServer(inlineConfig = {}) {
63190
63239
  else {
63191
63240
  await initServer();
63192
63241
  }
63193
- // Fire a clean up of stale cache dirs, in case old processes didn't
63194
- // terminate correctly. Don't await this promise
63195
- cleanupDepsCacheStaleDirs(config);
63196
63242
  return server;
63197
63243
  }
63198
63244
  async function startServer(server, inlinePort) {
@@ -63251,8 +63297,7 @@ function resolveServerOptions(root, raw, logger) {
63251
63297
  ...raw,
63252
63298
  sourcemapIgnoreList: raw?.sourcemapIgnoreList === false
63253
63299
  ? () => false
63254
- : raw?.sourcemapIgnoreList ||
63255
- ((sourcePath) => sourcePath.includes('node_modules')),
63300
+ : raw?.sourcemapIgnoreList || isInNodeModules,
63256
63301
  middlewareMode: !!raw?.middlewareMode,
63257
63302
  };
63258
63303
  let allowDirs = server.fs?.allow;
@@ -63490,10 +63535,26 @@ async function preview(inlineConfig = {}) {
63490
63535
  const app = connect();
63491
63536
  const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https));
63492
63537
  setClientErrorHandler(httpServer, config.logger);
63538
+ const options = config.preview;
63539
+ const logger = config.logger;
63540
+ const server = {
63541
+ config,
63542
+ middlewares: app,
63543
+ httpServer,
63544
+ resolvedUrls: null,
63545
+ printUrls() {
63546
+ if (server.resolvedUrls) {
63547
+ printServerUrls(server.resolvedUrls, options.host, logger.info);
63548
+ }
63549
+ else {
63550
+ throw new Error('cannot print server URLs before server is listening.');
63551
+ }
63552
+ },
63553
+ };
63493
63554
  // apply server hooks from plugins
63494
63555
  const postHooks = [];
63495
63556
  for (const hook of config.getSortedPluginHooks('configurePreviewServer')) {
63496
- postHooks.push(await hook({ middlewares: app, httpServer }));
63557
+ postHooks.push(await hook(server));
63497
63558
  }
63498
63559
  // cors
63499
63560
  const { cors } = config.preview;
@@ -63527,32 +63588,23 @@ async function preview(inlineConfig = {}) {
63527
63588
  app.use(previewBase, assetServer);
63528
63589
  // apply post server hooks from plugins
63529
63590
  postHooks.forEach((fn) => fn && fn());
63530
- const options = config.preview;
63531
63591
  const hostname = await resolveHostname(options.host);
63532
63592
  const port = options.port ?? DEFAULT_PREVIEW_PORT;
63533
63593
  const protocol = options.https ? 'https' : 'http';
63534
- const logger = config.logger;
63535
63594
  const serverPort = await httpServerStart(httpServer, {
63536
63595
  port,
63537
63596
  strictPort: options.strictPort,
63538
63597
  host: hostname.host,
63539
63598
  logger,
63540
63599
  });
63541
- const resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
63600
+ server.resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
63542
63601
  if (options.open) {
63543
63602
  const path = typeof options.open === 'string' ? options.open : previewBase;
63544
63603
  openBrowser(path.startsWith('http')
63545
63604
  ? path
63546
63605
  : new URL(path, `${protocol}://${hostname.name}:${serverPort}`).href, true, logger);
63547
63606
  }
63548
- return {
63549
- config,
63550
- httpServer,
63551
- resolvedUrls,
63552
- printUrls() {
63553
- printServerUrls(resolvedUrls, options.host, logger.info);
63554
- },
63555
- };
63607
+ return server;
63556
63608
  }
63557
63609
 
63558
63610
  var preview$1 = {
@@ -63605,6 +63657,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
63605
63657
  let configFileDependencies = [];
63606
63658
  let mode = inlineConfig.mode || defaultMode;
63607
63659
  const isNodeEnvSet = !!process.env.NODE_ENV;
63660
+ const packageCache = new Map();
63608
63661
  // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
63609
63662
  // production-specific behavior, so set it early on
63610
63663
  if (!isNodeEnvSet) {
@@ -63716,11 +63769,11 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
63716
63769
  : resolveBaseUrl(config.base, isBuild, logger) ?? '/';
63717
63770
  const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot);
63718
63771
  // resolve cache directory
63719
- const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true });
63772
+ const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
63720
63773
  const cacheDir = normalizePath$3(config.cacheDir
63721
63774
  ? path$o.resolve(resolvedRoot, config.cacheDir)
63722
- : pkgPath
63723
- ? path$o.join(path$o.dirname(pkgPath), `node_modules/.vite`)
63775
+ : pkgDir
63776
+ ? path$o.join(pkgDir, `node_modules/.vite`)
63724
63777
  : path$o.join(resolvedRoot, `.vite`));
63725
63778
  const assetsFilter = config.assetsInclude &&
63726
63779
  (!Array.isArray(config.assetsInclude) || config.assetsInclude.length)
@@ -63832,7 +63885,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
63832
63885
  return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
63833
63886
  },
63834
63887
  logger,
63835
- packageCache: new Map(),
63888
+ packageCache,
63836
63889
  createResolver,
63837
63890
  optimizeDeps: {
63838
63891
  disabled: 'build',
@@ -63997,7 +64050,8 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
63997
64050
  // check package.json for type: "module" and set `isESM` to true
63998
64051
  try {
63999
64052
  const pkg = lookupFile(configRoot, ['package.json']);
64000
- isESM = !!pkg && JSON.parse(pkg).type === 'module';
64053
+ isESM =
64054
+ !!pkg && JSON.parse(fs$l.readFileSync(pkg, 'utf-8')).type === 'module';
64001
64055
  }
64002
64056
  catch (e) { }
64003
64057
  }
@@ -64118,23 +64172,18 @@ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
64118
64172
  .slice(2)})}`;
64119
64173
  const fileNameTmp = `${fileBase}.mjs`;
64120
64174
  const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
64121
- fs$l.writeFileSync(fileNameTmp, bundledCode);
64175
+ await fsp.writeFile(fileNameTmp, bundledCode);
64122
64176
  try {
64123
64177
  return (await dynamicImport(fileUrl)).default;
64124
64178
  }
64125
64179
  finally {
64126
- try {
64127
- fs$l.unlinkSync(fileNameTmp);
64128
- }
64129
- catch {
64130
- // already removed if this function is called twice simultaneously
64131
- }
64180
+ fs$l.unlink(fileNameTmp, () => { }); // Ignore errors
64132
64181
  }
64133
64182
  }
64134
64183
  // for cjs, we can register a custom loader via `_require.extensions`
64135
64184
  else {
64136
64185
  const extension = path$o.extname(fileName);
64137
- const realFileName = fs$l.realpathSync(fileName);
64186
+ const realFileName = await fsp.realpath(fileName);
64138
64187
  const loaderExt = extension in _require.extensions ? extension : '.js';
64139
64188
  const defaultLoader = _require.extensions[loaderExt];
64140
64189
  _require.extensions[loaderExt] = (module, filename) => {
@@ -64177,4 +64226,4 @@ function isDepsOptimizerEnabled(config, ssr) {
64177
64226
  (command === 'serve' && disabled === 'dev'));
64178
64227
  }
64179
64228
 
64180
- export { picocolorsExports as A, bindShortcuts as B, commonjsGlobal as C, index$1 as D, build$1 as E, index as F, preview$1 as G, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, resolveBaseUrl as i, getDepOptimizationConfig as j, isDepsOptimizerEnabled as k, loadConfigFromFile as l, mergeConfig as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeAlias as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, createFilter as u, send$1 as v, createLogger as w, searchForWorkspaceRoot as x, loadEnv as y, resolveEnvPrefix as z };
64229
+ export { resolveEnvPrefix as A, picocolorsExports as B, bindShortcuts as C, commonjsGlobal as D, index$1 as E, build$1 as F, index as G, preview$1 as H, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$1 as w, createLogger as x, searchForWorkspaceRoot as y, loadEnv as z };