vite 4.4.9 → 5.0.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.
@@ -11861,7 +11861,7 @@ function isInNodeModules(id) {
11861
11861
  return id.includes('node_modules');
11862
11862
  }
11863
11863
  function moduleListContains(moduleList, id) {
11864
- return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
11864
+ return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
11865
11865
  }
11866
11866
  function isOptimizable(id, optimizeDeps) {
11867
11867
  const { extensions } = optimizeDeps;
@@ -11901,15 +11901,17 @@ function testCaseInsensitiveFS() {
11901
11901
  }
11902
11902
  return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
11903
11903
  }
11904
- function isUrl(path) {
11905
- try {
11906
- new URL$3(path);
11907
- return true;
11908
- }
11909
- catch {
11910
- return false;
11911
- }
11912
- }
11904
+ const urlCanParse = URL$3.canParse ??
11905
+ // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
11906
+ ((path, base) => {
11907
+ try {
11908
+ new URL$3(path, base);
11909
+ return true;
11910
+ }
11911
+ catch {
11912
+ return false;
11913
+ }
11914
+ });
11913
11915
  const isCaseInsensitiveFS = testCaseInsensitiveFS();
11914
11916
  const isWindows$4 = os$4.platform() === 'win32';
11915
11917
  const VOLUME_RE = /^[A-Z]:/i;
@@ -11923,6 +11925,12 @@ function fsPathFromId(id) {
11923
11925
  function fsPathFromUrl(url) {
11924
11926
  return fsPathFromId(cleanUrl(url));
11925
11927
  }
11928
+ function withTrailingSlash(path) {
11929
+ if (path[path.length - 1] !== '/') {
11930
+ return `${path}/`;
11931
+ }
11932
+ return path;
11933
+ }
11926
11934
  /**
11927
11935
  * Check if dir is a parent of file
11928
11936
  *
@@ -11933,9 +11941,7 @@ function fsPathFromUrl(url) {
11933
11941
  * @returns true if dir is a parent of file
11934
11942
  */
11935
11943
  function isParentDirectory(dir, file) {
11936
- if (dir[dir.length - 1] !== '/') {
11937
- dir = `${dir}/`;
11938
- }
11944
+ dir = withTrailingSlash(dir);
11939
11945
  return (file.startsWith(dir) ||
11940
11946
  (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
11941
11947
  }
@@ -12172,7 +12178,7 @@ function emptyDir(dir, skip) {
12172
12178
  if (path$o.dirname(file) !== '.') {
12173
12179
  const matched = file.match(splitFirstDirRE);
12174
12180
  if (matched) {
12175
- nested ?? (nested = new Map());
12181
+ nested ??= new Map();
12176
12182
  const [, nestedDir, skipPath] = matched;
12177
12183
  let nestedSkip = nested.get(nestedDir);
12178
12184
  if (!nestedSkip) {
@@ -12287,7 +12293,7 @@ function optimizeSafeRealPathSync() {
12287
12293
  function ensureWatchedFile(watcher, file, root) {
12288
12294
  if (file &&
12289
12295
  // only need to watch if out of root
12290
- !file.startsWith(root + '/') &&
12296
+ !file.startsWith(withTrailingSlash(root)) &&
12291
12297
  // some rollup plugins use null bytes for private resolved Ids
12292
12298
  !file.includes('\0') &&
12293
12299
  fs$l.existsSync(file)) {
@@ -12299,7 +12305,7 @@ const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
12299
12305
  const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
12300
12306
  function reduceSrcset(ret) {
12301
12307
  return ret.reduce((prev, { url, descriptor }, index) => {
12302
- descriptor ?? (descriptor = '');
12308
+ descriptor ??= '';
12303
12309
  return (prev +=
12304
12310
  url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
12305
12311
  }, '');
@@ -12727,7 +12733,7 @@ function stripBase(path, base) {
12727
12733
  if (path === base) {
12728
12734
  return '/';
12729
12735
  }
12730
- const devBase = base[base.length - 1] === '/' ? base : base + '/';
12736
+ const devBase = withTrailingSlash(base);
12731
12737
  return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
12732
12738
  }
12733
12739
  function arrayEqual(a, b) {
@@ -13084,9 +13090,10 @@ function buildReporterPlugin(config) {
13084
13090
  if (isLarge)
13085
13091
  hasLargeChunks = true;
13086
13092
  const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
13087
- let log = colors$1.dim(relativeOutDir + '/');
13093
+ let log = colors$1.dim(withTrailingSlash(relativeOutDir));
13088
13094
  log +=
13089
- !config.build.lib && entry.name.startsWith(assetsDir)
13095
+ !config.build.lib &&
13096
+ entry.name.startsWith(withTrailingSlash(assetsDir))
13090
13097
  ? colors$1.dim(assetsDir) +
13091
13098
  group.color(entry.name
13092
13099
  .slice(assetsDir.length)
@@ -13112,7 +13119,7 @@ function buildReporterPlugin(config) {
13112
13119
  config.build.minify &&
13113
13120
  !config.build.lib &&
13114
13121
  !config.build.ssr) {
13115
- config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
13122
+ config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n` +
13116
13123
  `- Using dynamic import() to code-split the application\n` +
13117
13124
  `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
13118
13125
  `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
@@ -13794,8 +13801,8 @@ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
13794
13801
  }
13795
13802
 
13796
13803
  const debug$f = createDebugger('vite:esbuild');
13797
- const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{\s*"use strict";)/s;
13798
- const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{\s*"use strict";)/s;
13804
+ // IIFE content looks like `var MyLib = function() {`. Spaces are removed when minified
13805
+ const IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\(\)\s*\{.*"use strict";/s;
13799
13806
  const validExtensionRE = /\.\w+$/;
13800
13807
  const jsxExtensionsRE = /\.(?:j|t)sx\b/;
13801
13808
  let server;
@@ -14028,16 +14035,26 @@ const buildEsbuildPlugin = (config) => {
14028
14035
  if (config.build.lib) {
14029
14036
  // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
14030
14037
  // names are minified potentially causing collision with other globals.
14031
- // We use a regex to inject the helpers inside the wrappers.
14038
+ // We inject the helpers inside the wrappers.
14039
+ // e.g. turn:
14040
+ // <esbuild helpers> (function(){ /*actual content/* })()
14041
+ // into:
14042
+ // (function(){ <esbuild helpers> /*actual content/* })()
14043
+ // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065
14044
+ // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant
14032
14045
  // We don't need to create a MagicString here because both the helpers and
14033
14046
  // the headers don't modify the sourcemap
14034
- const injectHelpers = opts.format === 'umd'
14035
- ? INJECT_HELPERS_UMD_RE
14036
- : opts.format === 'iife'
14037
- ? INJECT_HELPERS_IIFE_RE
14038
- : undefined;
14039
- if (injectHelpers) {
14040
- res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers);
14047
+ const esbuildCode = res.code;
14048
+ const contentIndex = opts.format === 'iife'
14049
+ ? esbuildCode.match(IIFE_BEGIN_RE)?.index || 0
14050
+ : opts.format === 'umd'
14051
+ ? esbuildCode.indexOf(`(function(`) // same for minified or not
14052
+ : 0;
14053
+ if (contentIndex > 0) {
14054
+ const esbuildHelpers = esbuildCode.slice(0, contentIndex);
14055
+ res.code = esbuildCode
14056
+ .slice(contentIndex)
14057
+ .replace(`"use strict";`, `"use strict";` + esbuildHelpers);
14041
14058
  }
14042
14059
  }
14043
14060
  return res;
@@ -14353,7 +14370,7 @@ function terserPlugin(config) {
14353
14370
  return null;
14354
14371
  }
14355
14372
  // Lazy load worker.
14356
- worker || (worker = makeWorker());
14373
+ worker ||= makeWorker();
14357
14374
  const terserPath = loadTerserPath(config.root);
14358
14375
  const res = await worker.run(terserPath, code, {
14359
14376
  safari10: true,
@@ -16072,7 +16089,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16072
16089
  // In both cases, the wrapping should already be fine
16073
16090
  assetUrlRE.lastIndex = 0;
16074
16091
  while ((match = assetUrlRE.exec(code))) {
16075
- s || (s = new MagicString(code));
16092
+ s ||= new MagicString(code);
16076
16093
  const [full, referenceId, postfix = ''] = match;
16077
16094
  const file = ctx.getFileName(referenceId);
16078
16095
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
@@ -16087,7 +16104,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16087
16104
  const publicAssetUrlMap = publicAssetUrlCache.get(config);
16088
16105
  publicAssetUrlRE.lastIndex = 0;
16089
16106
  while ((match = publicAssetUrlRE.exec(code))) {
16090
- s || (s = new MagicString(code));
16107
+ s ||= new MagicString(code);
16091
16108
  const [full, hash] = match;
16092
16109
  const publicUrl = publicAssetUrlMap.get(hash).slice(1);
16093
16110
  const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime);
@@ -16098,6 +16115,9 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16098
16115
  }
16099
16116
  return s;
16100
16117
  }
16118
+ // During build, if we don't use a virtual file for public assets, rollup will
16119
+ // watch for these ids resulting in watching the root of the file system in Windows,
16120
+ const viteBuildPublicIdPrefix = '\0vite:asset:public';
16101
16121
  /**
16102
16122
  * Also supports loading plain strings with import text from './foo.txt?raw'
16103
16123
  */
@@ -16117,10 +16137,15 @@ function assetPlugin(config) {
16117
16137
  // will fail to resolve in the main resolver. handle them here.
16118
16138
  const publicFile = checkPublicFile(id, config);
16119
16139
  if (publicFile) {
16120
- return id;
16140
+ return config.command === 'build'
16141
+ ? `${viteBuildPublicIdPrefix}${id}`
16142
+ : id;
16121
16143
  }
16122
16144
  },
16123
16145
  async load(id) {
16146
+ if (id.startsWith(viteBuildPublicIdPrefix)) {
16147
+ id = id.slice(viteBuildPublicIdPrefix.length);
16148
+ }
16124
16149
  if (id[0] === '\0') {
16125
16150
  // Rollup convention, this id should be handled by the
16126
16151
  // plugin that marked it with \0
@@ -16176,7 +16201,7 @@ function checkPublicFile(url, { publicDir }) {
16176
16201
  return;
16177
16202
  }
16178
16203
  const publicFile = path$o.join(publicDir, cleanUrl(url));
16179
- if (!publicFile.startsWith(publicDir)) {
16204
+ if (!normalizePath$3(publicFile).startsWith(withTrailingSlash(normalizePath$3(publicDir)))) {
16180
16205
  // can happen if URL starts with '../'
16181
16206
  return;
16182
16207
  }
@@ -16198,10 +16223,10 @@ async function fileToUrl(id, config, ctx) {
16198
16223
  function fileToDevUrl(id, config) {
16199
16224
  let rtn;
16200
16225
  if (checkPublicFile(id, config)) {
16201
- // in public dir, keep the url as-is
16226
+ // in public dir during dev, keep the url as-is
16202
16227
  rtn = id;
16203
16228
  }
16204
- else if (id.startsWith(config.root)) {
16229
+ else if (id.startsWith(withTrailingSlash(config.root))) {
16205
16230
  // in project root, infer short public path
16206
16231
  rtn = '/' + path$o.posix.relative(config.root, id);
16207
16232
  }
@@ -28086,7 +28111,9 @@ function resolvePlugin(resolveOptions) {
28086
28111
  }
28087
28112
  // URL
28088
28113
  // /foo -> /fs-root/foo
28089
- if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
28114
+ if (asSrc &&
28115
+ id[0] === '/' &&
28116
+ (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
28090
28117
  const fsPath = path$o.resolve(root, id.slice(1));
28091
28118
  if ((res = tryFsResolve(fsPath, options))) {
28092
28119
  debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
@@ -28580,7 +28607,7 @@ async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks
28580
28607
  idPkgDir = normalizePath$3(idPkgDir);
28581
28608
  }
28582
28609
  // match by src to correctly identify if id belongs to nested dependency
28583
- if (optimizedData.src.startsWith(idPkgDir)) {
28610
+ if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
28584
28611
  return depsOptimizer.getOptimizedDepId(optimizedData);
28585
28612
  }
28586
28613
  }
@@ -28652,7 +28679,7 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
28652
28679
  }
28653
28680
  }
28654
28681
  }
28655
- entryPoint || (entryPoint = data.main);
28682
+ entryPoint ||= data.main;
28656
28683
  // try default entry when entry is not define
28657
28684
  // https://nodejs.org/api/modules.html#all-together
28658
28685
  const entryPoints = entryPoint
@@ -37561,9 +37588,9 @@ function buildHtmlPlugin(config) {
37561
37588
  js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
37562
37589
  shouldRemove = true;
37563
37590
  }
37564
- everyScriptIsAsync && (everyScriptIsAsync = isAsync);
37565
- someScriptsAreAsync || (someScriptsAreAsync = isAsync);
37566
- someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
37591
+ everyScriptIsAsync &&= isAsync;
37592
+ someScriptsAreAsync ||= isAsync;
37593
+ someScriptsAreDefer ||= !isAsync;
37567
37594
  }
37568
37595
  else if (url && !isPublicFile) {
37569
37596
  if (!isExcludedUrl(url)) {
@@ -37864,7 +37891,7 @@ function buildHtmlPlugin(config) {
37864
37891
  let s;
37865
37892
  inlineCSSRE$1.lastIndex = 0;
37866
37893
  while ((match = inlineCSSRE$1.exec(result))) {
37867
- s || (s = new MagicString(result));
37894
+ s ||= new MagicString(result);
37868
37895
  const { 0: full, 1: scopedName } = match;
37869
37896
  const cssTransformedCode = htmlProxyResult.get(scopedName);
37870
37897
  s.update(match.index, match.index + full.length, cssTransformedCode);
@@ -37884,7 +37911,7 @@ function buildHtmlPlugin(config) {
37884
37911
  });
37885
37912
  result = result.replace(publicAssetUrlRE, (_, fileHash) => {
37886
37913
  const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
37887
- return isUrl(publicAssetPath)
37914
+ return urlCanParse(publicAssetPath)
37888
37915
  ? publicAssetPath
37889
37916
  : normalizePath$3(publicAssetPath);
37890
37917
  });
@@ -38345,7 +38372,7 @@ function cssPostPlugin(config) {
38345
38372
  };
38346
38373
  return {
38347
38374
  name: 'vite:css-post',
38348
- buildStart() {
38375
+ renderStart() {
38349
38376
  // Ensure new caches for every build (i.e. rebuilding in watch mode)
38350
38377
  pureCssChunks = new Set();
38351
38378
  outputToExtractedCSSMap = new Map();
@@ -38426,7 +38453,7 @@ function cssPostPlugin(config) {
38426
38453
  else {
38427
38454
  let content = css;
38428
38455
  if (config.build.cssMinify) {
38429
- content = await minifyCSS(content, config);
38456
+ content = await minifyCSS(content, config, true);
38430
38457
  }
38431
38458
  code = `export default ${JSON.stringify(content)}`;
38432
38459
  }
@@ -38506,9 +38533,10 @@ function cssPostPlugin(config) {
38506
38533
  pureCssChunks.add(chunk);
38507
38534
  }
38508
38535
  if (opts.format === 'es' || opts.format === 'cjs') {
38509
- const cssAssetName = chunk.facadeModuleId
38510
- ? normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId))
38511
- : chunk.name;
38536
+ const isEntry = chunk.isEntry && isPureCssChunk;
38537
+ const cssAssetName = normalizePath$3(!isEntry && chunk.facadeModuleId
38538
+ ? path$o.relative(config.root, chunk.facadeModuleId)
38539
+ : chunk.name);
38512
38540
  const lang = path$o.extname(cssAssetName).slice(1);
38513
38541
  const cssFileName = ensureFileExt(cssAssetName, '.css');
38514
38542
  chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
@@ -38532,7 +38560,6 @@ function cssPostPlugin(config) {
38532
38560
  source: chunkCSS,
38533
38561
  });
38534
38562
  const originalName = isPreProcessor(lang) ? cssAssetName : cssFileName;
38535
- const isEntry = chunk.isEntry && isPureCssChunk;
38536
38563
  generatedAssets
38537
38564
  .get(config)
38538
38565
  .set(referenceId, { originalName, isEntry });
@@ -38605,19 +38632,12 @@ function cssPostPlugin(config) {
38605
38632
  // remove empty css chunks and their imports
38606
38633
  if (pureCssChunks.size) {
38607
38634
  // map each pure css chunk (rendered chunk) to it's corresponding bundle
38608
- // chunk. we check that by comparing the `moduleIds` as they have different
38609
- // filenames (rendered chunk has the !~{XXX}~ placeholder)
38610
- const pureCssChunkNames = [];
38611
- for (const pureCssChunk of pureCssChunks) {
38612
- for (const key in bundle) {
38613
- const bundleChunk = bundle[key];
38614
- if (bundleChunk.type === 'chunk' &&
38615
- arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)) {
38616
- pureCssChunkNames.push(key);
38617
- break;
38618
- }
38619
- }
38620
- }
38635
+ // chunk. we check that by `preliminaryFileName` as they have different
38636
+ // `filename`s (rendered chunk has the !~{XXX}~ placeholder)
38637
+ const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle)
38638
+ .filter((chunk) => chunk.type === 'chunk')
38639
+ .map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
38640
+ const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]);
38621
38641
  const emptyChunkFiles = pureCssChunkNames
38622
38642
  .map((file) => path$o.basename(file))
38623
38643
  .join('|')
@@ -38649,6 +38669,7 @@ function cssPostPlugin(config) {
38649
38669
  pureCssChunkNames.forEach((fileName) => {
38650
38670
  removedPureCssFiles.set(fileName, bundle[fileName]);
38651
38671
  delete bundle[fileName];
38672
+ delete bundle[`${fileName}.map`];
38652
38673
  });
38653
38674
  }
38654
38675
  let extractedCss = outputToExtractedCSSMap.get(opts);
@@ -38959,8 +38980,8 @@ function createCachedImport(imp) {
38959
38980
  return cached;
38960
38981
  };
38961
38982
  }
38962
- const importPostcssImport = createCachedImport(() => import('./dep-e0331088.js').then(function (n) { return n.i; }));
38963
- const importPostcssModules = createCachedImport(() => import('./dep-73522cdf.js').then(function (n) { return n.i; }));
38983
+ const importPostcssImport = createCachedImport(() => import('./dep-c457d7ce.js').then(function (n) { return n.i; }));
38984
+ const importPostcssModules = createCachedImport(() => import('./dep-6db0c752.js').then(function (n) { return n.i; }));
38964
38985
  const importPostcss = createCachedImport(() => import('postcss'));
38965
38986
  /**
38966
38987
  * @experimental
@@ -39003,7 +39024,7 @@ async function finalizeCss(css, minify, config) {
39003
39024
  css = await hoistAtRules(css);
39004
39025
  }
39005
39026
  if (minify && config.build.cssMinify) {
39006
- css = await minifyCSS(css, config);
39027
+ css = await minifyCSS(css, config, false);
39007
39028
  }
39008
39029
  return css;
39009
39030
  }
@@ -39164,7 +39185,10 @@ async function doImportCSSReplace(rawUrl, matched, replacer) {
39164
39185
  }
39165
39186
  return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
39166
39187
  }
39167
- async function minifyCSS(css, config) {
39188
+ async function minifyCSS(css, config, inlined) {
39189
+ // We want inlined CSS to not end with a linebreak, while ensuring that
39190
+ // regular CSS assets do end with a linebreak.
39191
+ // See https://github.com/vitejs/vite/pull/13893#issuecomment-1678628198
39168
39192
  if (config.build.cssMinify === 'lightningcss') {
39169
39193
  const { code, warnings } = (await importLightningCSS()).transform({
39170
39194
  ...config.css?.lightningcss,
@@ -39179,7 +39203,8 @@ async function minifyCSS(css, config) {
39179
39203
  .map((w) => w.message)
39180
39204
  .join('\n')}`));
39181
39205
  }
39182
- return code.toString();
39206
+ // LightningCSS output does not return a linebreak at the end
39207
+ return code.toString() + (inlined ? '' : '\n');
39183
39208
  }
39184
39209
  try {
39185
39210
  const { code, warnings } = await transform$1(css, {
@@ -39191,7 +39216,8 @@ async function minifyCSS(css, config) {
39191
39216
  const msgs = await formatMessages(warnings, { kind: 'warning' });
39192
39217
  config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
39193
39218
  }
39194
- return code;
39219
+ // esbuild output does return a linebreak at the end
39220
+ return inlined ? code.trimEnd() : code;
39195
39221
  }
39196
39222
  catch (e) {
39197
39223
  if (e.errors) {
@@ -39482,6 +39508,9 @@ let ViteLessManager;
39482
39508
  function createViteLessPlugin(less, rootFile, alias, resolvers) {
39483
39509
  if (!ViteLessManager) {
39484
39510
  ViteLessManager = class ViteManager extends less.FileManager {
39511
+ resolvers;
39512
+ rootFile;
39513
+ alias;
39485
39514
  constructor(rootFile, resolvers, alias) {
39486
39515
  super();
39487
39516
  this.rootFile = rootFile;
@@ -39623,6 +39652,7 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
39623
39652
  analyzeDependencies: true,
39624
39653
  })
39625
39654
  : await (await importLightningCSS()).bundleAsync({
39655
+ ...config.css?.lightningcss,
39626
39656
  filename,
39627
39657
  resolver: {
39628
39658
  read(filePath) {
@@ -39648,14 +39678,12 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
39648
39678
  return id;
39649
39679
  },
39650
39680
  },
39651
- targets: config.css?.lightningcss?.targets,
39652
39681
  minify: config.isProduction && !!config.build.cssMinify,
39653
39682
  sourceMap: config.css?.devSourcemap,
39654
39683
  analyzeDependencies: true,
39655
39684
  cssModules: cssModuleRE.test(id)
39656
39685
  ? config.css?.lightningcss?.cssModules ?? true
39657
39686
  : undefined,
39658
- drafts: config.css?.lightningcss?.drafts,
39659
39687
  });
39660
39688
  let css = res.code.toString();
39661
39689
  for (const dep of res.dependencies) {
@@ -40274,7 +40302,8 @@ function cjsShouldExternalizeForSSR(id, externals) {
40274
40302
  }
40275
40303
  // deep imports, check ext before externalizing - only externalize
40276
40304
  // extension-less imports and explicit .js imports
40277
- if (id.startsWith(e + '/') && (!path$o.extname(id) || id.endsWith('.js'))) {
40305
+ if (id.startsWith(withTrailingSlash(e)) &&
40306
+ (!path$o.extname(id) || id.endsWith('.js'))) {
40278
40307
  return true;
40279
40308
  }
40280
40309
  });
@@ -40784,8 +40813,11 @@ function getAffectedGlobModules(file, server) {
40784
40813
  for (const [id, allGlobs] of server._importGlobMap) {
40785
40814
  // (glob1 || glob2) && !glob3 && !glob4...
40786
40815
  if (allGlobs.some(({ affirmed, negated }) => (!affirmed.length || affirmed.some((glob) => isMatch$1(file, glob))) &&
40787
- (!negated.length || negated.every((glob) => isMatch$1(file, glob)))))
40788
- modules.push(...(server.moduleGraph.getModulesByFile(id) || []));
40816
+ (!negated.length || negated.every((glob) => isMatch$1(file, glob))))) {
40817
+ const mod = server.moduleGraph.getModuleById(id);
40818
+ if (mod)
40819
+ modules.push(mod);
40820
+ }
40789
40821
  }
40790
40822
  modules.forEach((i) => {
40791
40823
  if (i?.file)
@@ -40822,7 +40854,7 @@ function importGlobPlugin(config) {
40822
40854
  },
40823
40855
  };
40824
40856
  }
40825
- const importGlobRE = /\bimport\.meta\.(glob|globEager|globEagerDefault)(?:<\w+>)?\s*\(/g;
40857
+ const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
40826
40858
  const knownOptions = {
40827
40859
  as: ['string'],
40828
40860
  eager: ['boolean'],
@@ -40887,7 +40919,6 @@ async function parseImportGlob(code, importer, root, resolveId) {
40887
40919
  }
40888
40920
  const matches = Array.from(cleanCode.matchAll(importGlobRE));
40889
40921
  const tasks = matches.map(async (match, index) => {
40890
- const type = match[1];
40891
40922
  const start = match.index;
40892
40923
  const err = (msg) => {
40893
40924
  const e = new Error(`Invalid glob import syntax: ${msg}`);
@@ -40973,13 +41004,11 @@ async function parseImportGlob(code, importer, root, resolveId) {
40973
41004
  const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId)));
40974
41005
  const isRelative = globs.every((i) => '.!'.includes(i[0]));
40975
41006
  return {
40976
- match,
40977
41007
  index,
40978
41008
  globs,
40979
41009
  globsResolved,
40980
41010
  isRelative,
40981
41011
  options,
40982
- type,
40983
41012
  start,
40984
41013
  end,
40985
41014
  };
@@ -41006,15 +41035,6 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41006
41035
  const dir = isVirtual ? undefined : dirname(id);
41007
41036
  const matches = await parseImportGlob(code, isVirtual ? undefined : id, root, resolveId);
41008
41037
  const matchedFiles = new Set();
41009
- // TODO: backwards compatibility
41010
- matches.forEach((i) => {
41011
- if (i.type === 'globEager')
41012
- i.options.eager = true;
41013
- if (i.type === 'globEagerDefault') {
41014
- i.options.eager = true;
41015
- i.options.import = 'default';
41016
- }
41017
- });
41018
41038
  if (!matches.length)
41019
41039
  return null;
41020
41040
  const s = new MagicString(code);
@@ -41073,7 +41093,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41073
41093
  }
41074
41094
  importPath = `${importPath}${importQuery}`;
41075
41095
  const isCSS = !query && isCSSRequest(file) && !isModuleCSSRequest(file);
41076
- includesCSS || (includesCSS = isCSS);
41096
+ includesCSS ||= isCSS;
41077
41097
  const importKey = options.import && options.import !== '*'
41078
41098
  ? options.import
41079
41099
  : undefined;
@@ -41216,7 +41236,9 @@ const debugHmr = createDebugger('vite:hmr');
41216
41236
  const whitespaceRE = /\s/;
41217
41237
  const normalizedClientDir = normalizePath$3(CLIENT_DIR);
41218
41238
  function getShortName(file, root) {
41219
- return file.startsWith(root + '/') ? path$o.posix.relative(root, file) : file;
41239
+ return file.startsWith(withTrailingSlash(root))
41240
+ ? path$o.posix.relative(root, file)
41241
+ : file;
41220
41242
  }
41221
41243
  async function handleHMRUpdate(file, server, configOnly) {
41222
41244
  const { ws, config, moduleGraph } = server;
@@ -41243,7 +41265,7 @@ async function handleHMRUpdate(file, server, configOnly) {
41243
41265
  }
41244
41266
  debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
41245
41267
  // (dev only) the client itself cannot be hot updated.
41246
- if (file.startsWith(normalizedClientDir)) {
41268
+ if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
41247
41269
  ws.send({
41248
41270
  type: 'full-reload',
41249
41271
  path: '*',
@@ -41804,7 +41826,7 @@ function importAnalysisPlugin(config) {
41804
41826
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
41805
41827
  // normalize all imports into resolved URLs
41806
41828
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
41807
- if (resolved.id.startsWith(root + '/')) {
41829
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
41808
41830
  // in root: infer short absolute path from root
41809
41831
  url = resolved.id.slice(root.length);
41810
41832
  }
@@ -42036,7 +42058,7 @@ function importAnalysisPlugin(config) {
42036
42058
  });
42037
42059
  }
42038
42060
  }
42039
- else if (!importer.startsWith(clientDir)) {
42061
+ else if (!importer.startsWith(withTrailingSlash(clientDir))) {
42040
42062
  if (!isInNodeModules(importer)) {
42041
42063
  // check @vite-ignore which suppresses dynamic import warning
42042
42064
  const hasViteIgnore = hasViteIgnoreRE.test(
@@ -42145,23 +42167,32 @@ function mergeAcceptedUrls(orderedUrls) {
42145
42167
  function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
42146
42168
  const source = str.original;
42147
42169
  const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
42170
+ const exp = source.slice(expStart, expEnd);
42148
42171
  if (dynamicIndex > -1) {
42149
42172
  // rewrite `import('package')` to expose the default directly
42150
- str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`, { contentOnly: true });
42173
+ str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))` +
42174
+ getLineBreaks(exp), { contentOnly: true });
42151
42175
  }
42152
42176
  else {
42153
- const exp = source.slice(expStart, expEnd);
42154
42177
  const rawUrl = source.slice(start, end);
42155
42178
  const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
42156
42179
  if (rewritten) {
42157
- str.overwrite(expStart, expEnd, rewritten, { contentOnly: true });
42180
+ str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
42181
+ contentOnly: true,
42182
+ });
42158
42183
  }
42159
42184
  else {
42160
42185
  // #1439 export * from '...'
42161
- str.overwrite(start, end, rewrittenUrl, { contentOnly: true });
42186
+ str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), {
42187
+ contentOnly: true,
42188
+ });
42162
42189
  }
42163
42190
  }
42164
42191
  }
42192
+ // get line breaks to preserve line count for not breaking source maps
42193
+ function getLineBreaks(str) {
42194
+ return str.includes('\n') ? '\n'.repeat(str.split('\n').length - 1) : '';
42195
+ }
42165
42196
  /**
42166
42197
  * Detect import statements to a known optimized CJS dependency and provide
42167
42198
  * ES named imports interop. We do this by rewriting named imports to a variable
@@ -42278,11 +42309,12 @@ function clientInjectionsPlugin(config) {
42278
42309
  const timeout = hmrConfig?.timeout || 30000;
42279
42310
  const overlay = hmrConfig?.overlay !== false;
42280
42311
  const isHmrServerSpecified = !!hmrConfig?.server;
42312
+ const hmrConfigName = path$o.basename(config.configFile || 'vite.config.js');
42281
42313
  // hmr.clientPort -> hmr.port
42282
42314
  // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
42283
42315
  let port = hmrConfig?.clientPort || hmrConfig?.port || null;
42284
42316
  if (config.server.middlewareMode && !isHmrServerSpecified) {
42285
- port || (port = 24678);
42317
+ port ||= 24678;
42286
42318
  }
42287
42319
  let directTarget = hmrConfig?.host || resolvedServerHostname;
42288
42320
  directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
@@ -42303,6 +42335,7 @@ function clientInjectionsPlugin(config) {
42303
42335
  const hmrBaseReplacement = escapeReplacement(hmrBase);
42304
42336
  const hmrTimeoutReplacement = escapeReplacement(timeout);
42305
42337
  const hmrEnableOverlayReplacement = escapeReplacement(overlay);
42338
+ const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
42306
42339
  injectConfigValues = (code) => {
42307
42340
  return code
42308
42341
  .replace(`__MODE__`, modeReplacement)
@@ -42315,7 +42348,8 @@ function clientInjectionsPlugin(config) {
42315
42348
  .replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement)
42316
42349
  .replace(`__HMR_BASE__`, hmrBaseReplacement)
42317
42350
  .replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
42318
- .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement);
42351
+ .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement)
42352
+ .replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement);
42319
42353
  };
42320
42354
  },
42321
42355
  transform(code, id, options) {
@@ -42610,9 +42644,15 @@ function webWorkerPlugin(config) {
42610
42644
  injectEnv = module?.transformResult?.code || '';
42611
42645
  }
42612
42646
  }
42613
- return {
42614
- code: injectEnv + raw,
42615
- };
42647
+ if (injectEnv) {
42648
+ const s = new MagicString(raw);
42649
+ s.prepend(injectEnv);
42650
+ return {
42651
+ code: s.toString(),
42652
+ map: s.generateMap({ hires: 'boundary' }),
42653
+ };
42654
+ }
42655
+ return;
42616
42656
  }
42617
42657
  if (query == null ||
42618
42658
  (query && (query.worker ?? query.sharedworker) == null)) {
@@ -42627,7 +42667,7 @@ function webWorkerPlugin(config) {
42627
42667
  ? 'module'
42628
42668
  : 'classic'
42629
42669
  : 'module';
42630
- const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
42670
+ const workerTypeOption = workerType === 'classic' ? undefined : 'module';
42631
42671
  if (isBuild) {
42632
42672
  getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
42633
42673
  if (query.inline != null) {
@@ -42638,21 +42678,33 @@ function webWorkerPlugin(config) {
42638
42678
  workerConstructor === 'Worker'
42639
42679
  ? `${encodedJs}
42640
42680
  const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
42641
- export default function WorkerWrapper() {
42681
+ export default function WorkerWrapper(options) {
42642
42682
  let objURL;
42643
42683
  try {
42644
42684
  objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
42645
42685
  if (!objURL) throw ''
42646
- return new ${workerConstructor}(objURL)
42686
+ return new ${workerConstructor}(objURL, { name: options?.name })
42647
42687
  } catch(e) {
42648
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
42688
+ return new ${workerConstructor}(
42689
+ "data:application/javascript;base64," + encodedJs,
42690
+ {
42691
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42692
+ name: options?.name
42693
+ }
42694
+ );
42649
42695
  } finally {
42650
42696
  objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
42651
42697
  }
42652
42698
  }`
42653
42699
  : `${encodedJs}
42654
- export default function WorkerWrapper() {
42655
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
42700
+ export default function WorkerWrapper(options) {
42701
+ return new ${workerConstructor}(
42702
+ "data:application/javascript;base64," + encodedJs,
42703
+ {
42704
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42705
+ name: options?.name
42706
+ }
42707
+ );
42656
42708
  }
42657
42709
  `;
42658
42710
  return {
@@ -42677,8 +42729,14 @@ function webWorkerPlugin(config) {
42677
42729
  };
42678
42730
  }
42679
42731
  return {
42680
- code: `export default function WorkerWrapper() {
42681
- return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
42732
+ code: `export default function WorkerWrapper(options) {
42733
+ return new ${workerConstructor}(
42734
+ ${JSON.stringify(url)},
42735
+ {
42736
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42737
+ name: options?.name
42738
+ }
42739
+ );
42682
42740
  }`,
42683
42741
  map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
42684
42742
  };
@@ -42805,7 +42863,7 @@ function matches(pattern, importee) {
42805
42863
  if (importee === pattern) {
42806
42864
  return true;
42807
42865
  }
42808
- return importee.startsWith(pattern + '/');
42866
+ return importee.startsWith(withTrailingSlash(pattern));
42809
42867
  }
42810
42868
  function getAliasPatterns(entries) {
42811
42869
  if (!entries) {
@@ -43045,7 +43103,7 @@ function workerImportMetaUrlPlugin(config) {
43045
43103
  if (rawUrl[0] === '`' && rawUrl.includes('${')) {
43046
43104
  this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
43047
43105
  }
43048
- s || (s = new MagicString(code));
43106
+ s ||= new MagicString(code);
43049
43107
  const workerType = getWorkerType(code, cleanString, index + allExp.length);
43050
43108
  const url = rawUrl.slice(1, -1);
43051
43109
  let file;
@@ -43054,15 +43112,16 @@ function workerImportMetaUrlPlugin(config) {
43054
43112
  file = tryFsResolve(file, fsResolveOptions) ?? file;
43055
43113
  }
43056
43114
  else {
43057
- workerResolver ?? (workerResolver = config.createResolver({
43115
+ workerResolver ??= config.createResolver({
43058
43116
  extensions: [],
43059
43117
  tryIndex: false,
43060
43118
  preferRelative: true,
43061
- }));
43119
+ });
43062
43120
  file = await workerResolver(url, id);
43063
- file ?? (file = url[0] === '/'
43064
- ? slash$1(path$o.join(config.publicDir, url))
43065
- : slash$1(path$o.resolve(path$o.dirname(id), url)));
43121
+ file ??=
43122
+ url[0] === '/'
43123
+ ? slash$1(path$o.join(config.publicDir, url))
43124
+ : slash$1(path$o.resolve(path$o.dirname(id), url));
43066
43125
  }
43067
43126
  let builtUrl;
43068
43127
  if (isBuild) {
@@ -43166,16 +43225,17 @@ function assetImportMetaUrlPlugin(config) {
43166
43225
  file = tryFsResolve(file, fsResolveOptions) ?? file;
43167
43226
  }
43168
43227
  else {
43169
- assetResolver ?? (assetResolver = config.createResolver({
43228
+ assetResolver ??= config.createResolver({
43170
43229
  extensions: [],
43171
43230
  mainFields: [],
43172
43231
  tryIndex: false,
43173
43232
  preferRelative: true,
43174
- }));
43233
+ });
43175
43234
  file = await assetResolver(url, id);
43176
- file ?? (file = url[0] === '/'
43177
- ? slash$1(path$o.join(config.publicDir, url))
43178
- : slash$1(path$o.resolve(path$o.dirname(id), url)));
43235
+ file ??=
43236
+ url[0] === '/'
43237
+ ? slash$1(path$o.join(config.publicDir, url))
43238
+ : slash$1(path$o.resolve(path$o.dirname(id), url));
43179
43239
  }
43180
43240
  // Get final asset URL. If the file does not exist,
43181
43241
  // we fall back to the initial URL and let it resolve in runtime
@@ -43517,7 +43577,7 @@ function dynamicImportVarsPlugin(config) {
43517
43577
  if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
43518
43578
  continue;
43519
43579
  }
43520
- s || (s = new MagicString(source));
43580
+ s ||= new MagicString(source);
43521
43581
  let result;
43522
43582
  try {
43523
43583
  // When import string is using backticks, es-module-lexer `end` captures
@@ -43895,15 +43955,15 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43895
43955
  // active plugin in that pipeline can be tracked in a concurrency-safe manner.
43896
43956
  // using a class to make creating new contexts more efficient
43897
43957
  class Context {
43958
+ meta = minimalContext.meta;
43959
+ ssr = false;
43960
+ _scan = false;
43961
+ _activePlugin;
43962
+ _activeId = null;
43963
+ _activeCode = null;
43964
+ _resolveSkips;
43965
+ _addedImports = null;
43898
43966
  constructor(initialPlugin) {
43899
- this.meta = minimalContext.meta;
43900
- this.ssr = false;
43901
- this._scan = false;
43902
- this._activeId = null;
43903
- this._activeCode = null;
43904
- this._addedImports = null;
43905
- this.debug = noop$3;
43906
- this.info = noop$3;
43907
43967
  this._activePlugin = initialPlugin || null;
43908
43968
  }
43909
43969
  parse(code, opts = {}) {
@@ -43988,6 +44048,8 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43988
44048
  // the the error middleware.
43989
44049
  throw formatError(e, position, this);
43990
44050
  }
44051
+ debug = noop$3;
44052
+ info = noop$3;
43991
44053
  }
43992
44054
  function formatError(e, position, ctx) {
43993
44055
  const err = (typeof e === 'string' ? new Error(e) : e);
@@ -44048,7 +44110,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44048
44110
  typeof err.loc?.line === 'number' &&
44049
44111
  typeof err.loc?.column === 'number') {
44050
44112
  const rawSourceMap = ctx._getCombinedSourcemap();
44051
- if (rawSourceMap) {
44113
+ if (rawSourceMap && 'version' in rawSourceMap) {
44052
44114
  const traced = new TraceMap(rawSourceMap);
44053
44115
  const { source, line, column } = originalPositionFor$1(traced, {
44054
44116
  line: Number(err.loc.line),
@@ -44085,11 +44147,13 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44085
44147
  return err;
44086
44148
  }
44087
44149
  class TransformContext extends Context {
44150
+ filename;
44151
+ originalCode;
44152
+ originalSourcemap = null;
44153
+ sourcemapChain = [];
44154
+ combinedMap = null;
44088
44155
  constructor(filename, code, inMap) {
44089
44156
  super();
44090
- this.originalSourcemap = null;
44091
- this.sourcemapChain = [];
44092
- this.combinedMap = null;
44093
44157
  this.filename = filename;
44094
44158
  this.originalCode = code;
44095
44159
  if (inMap) {
@@ -44100,7 +44164,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44100
44164
  this.sourcemapChain.push(inMap);
44101
44165
  }
44102
44166
  }
44103
- _getCombinedSourcemap(createIfNull = false) {
44167
+ _getCombinedSourcemap() {
44104
44168
  if (debugSourcemapCombine &&
44105
44169
  debugSourcemapCombineFilter &&
44106
44170
  this.filename.includes(debugSourcemapCombineFilter)) {
@@ -44110,13 +44174,24 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44110
44174
  debugSourcemapCombine('----------');
44111
44175
  }
44112
44176
  let combinedMap = this.combinedMap;
44177
+ // { mappings: '' }
44178
+ if (combinedMap &&
44179
+ !('version' in combinedMap) &&
44180
+ combinedMap.mappings === '') {
44181
+ this.sourcemapChain.length = 0;
44182
+ return combinedMap;
44183
+ }
44113
44184
  for (let m of this.sourcemapChain) {
44114
44185
  if (typeof m === 'string')
44115
44186
  m = JSON.parse(m);
44116
44187
  if (!('version' in m)) {
44188
+ // { mappings: '' }
44189
+ if (m.mappings === '') {
44190
+ combinedMap = { mappings: '' };
44191
+ break;
44192
+ }
44117
44193
  // empty, nullified source map
44118
- combinedMap = this.combinedMap = null;
44119
- this.sourcemapChain.length = 0;
44194
+ combinedMap = null;
44120
44195
  break;
44121
44196
  }
44122
44197
  if (!combinedMap) {
@@ -44129,15 +44204,6 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44129
44204
  ]);
44130
44205
  }
44131
44206
  }
44132
- if (!combinedMap) {
44133
- return createIfNull
44134
- ? new MagicString(this.originalCode).generateMap({
44135
- includeContent: true,
44136
- hires: 'boundary',
44137
- source: cleanUrl(this.filename),
44138
- })
44139
- : null;
44140
- }
44141
44207
  if (combinedMap !== this.combinedMap) {
44142
44208
  this.combinedMap = combinedMap;
44143
44209
  this.sourcemapChain.length = 0;
@@ -44145,7 +44211,15 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44145
44211
  return this.combinedMap;
44146
44212
  }
44147
44213
  getCombinedSourcemap() {
44148
- return this._getCombinedSourcemap(true);
44214
+ const map = this._getCombinedSourcemap();
44215
+ if (!map || (!('version' in map) && map.mappings === '')) {
44216
+ return new MagicString(this.originalCode).generateMap({
44217
+ includeContent: true,
44218
+ hires: 'boundary',
44219
+ source: cleanUrl(this.filename),
44220
+ });
44221
+ }
44222
+ return map;
44149
44223
  }
44150
44224
  }
44151
44225
  let closed = false;
@@ -44879,7 +44953,7 @@ function expandGlobIds(id, config) {
44879
44953
  }
44880
44954
  const possibleExportPaths = [];
44881
44955
  for (const key in exports) {
44882
- if (key.startsWith('.')) {
44956
+ if (key[0] === '.') {
44883
44957
  if (key.includes('*')) {
44884
44958
  // "./glob/*": {
44885
44959
  // "browser": "./dist/glob/*-browser/*.js", <-- get this one
@@ -45412,7 +45486,6 @@ async function createDepsOptimizer(config, server) {
45412
45486
  if (closed) {
45413
45487
  return;
45414
45488
  }
45415
- const crawlDeps = Object.keys(metadata.discovered);
45416
45489
  // Await for the scan+optimize step running in the background
45417
45490
  // It normally should be over by the time crawling of user code ended
45418
45491
  await depsOptimizer.scanProcessing;
@@ -45420,6 +45493,7 @@ async function createDepsOptimizer(config, server) {
45420
45493
  const result = await optimizationResult.result;
45421
45494
  optimizationResult = undefined;
45422
45495
  currentlyProcessing = false;
45496
+ const crawlDeps = Object.keys(metadata.discovered);
45423
45497
  const scanDeps = Object.keys(result.metadata.optimized);
45424
45498
  if (scanDeps.length === 0 && crawlDeps.length === 0) {
45425
45499
  debug$8?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
@@ -45452,6 +45526,7 @@ async function createDepsOptimizer(config, server) {
45452
45526
  }
45453
45527
  }
45454
45528
  else {
45529
+ const crawlDeps = Object.keys(metadata.discovered);
45455
45530
  currentlyProcessing = false;
45456
45531
  if (crawlDeps.length === 0) {
45457
45532
  debug$8?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
@@ -46058,7 +46133,11 @@ function newDepOptimizationProcessing() {
46058
46133
  }
46059
46134
  // Convert to { id: src }
46060
46135
  function depsFromOptimizedDepInfo(depsInfo) {
46061
- return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
46136
+ const obj = {};
46137
+ for (const key in depsInfo) {
46138
+ obj[key] = depsInfo[key].src;
46139
+ }
46140
+ return obj;
46062
46141
  }
46063
46142
  function getOptimizedDepPath(id, config, ssr) {
46064
46143
  return normalizePath$3(path$o.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
@@ -46336,7 +46415,7 @@ function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
46336
46415
  async function optimizedDepNeedsInterop(metadata, file, config, ssr) {
46337
46416
  const depInfo = optimizedDepInfoFromFile(metadata, file);
46338
46417
  if (depInfo?.src && depInfo.needsInterop === undefined) {
46339
- depInfo.exportsData ?? (depInfo.exportsData = extractExportsData(depInfo.src, config, ssr));
46418
+ depInfo.exportsData ??= extractExportsData(depInfo.src, config, ssr);
46340
46419
  depInfo.needsInterop = needsInterop(config, ssr, depInfo.id, await depInfo.exportsData);
46341
46420
  }
46342
46421
  return depInfo?.needsInterop;
@@ -46615,7 +46694,7 @@ function buildImportAnalysisPlugin(config) {
46615
46694
  }
46616
46695
  // normalize all imports into resolved URLs
46617
46696
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
46618
- if (resolved.id.startsWith(root + '/')) {
46697
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
46619
46698
  // in root: infer short absolute path from root
46620
46699
  url = resolved.id.slice(root.length);
46621
46700
  }
@@ -46946,7 +47025,7 @@ function ssrManifestPlugin(config) {
46946
47025
  if (chunk.code.includes(preloadMethod)) {
46947
47026
  // generate css deps map
46948
47027
  const code = chunk.code;
46949
- let imports;
47028
+ let imports = [];
46950
47029
  try {
46951
47030
  imports = parse$e(code)[0].filter((i) => i.n && i.d > -1);
46952
47031
  }
@@ -47214,11 +47293,18 @@ function send$2(req, res, content, type, options) {
47214
47293
  }
47215
47294
  }
47216
47295
  // inject source map reference
47217
- if (map && map.mappings) {
47296
+ if (map && 'version' in map && map.mappings) {
47218
47297
  if (type === 'js' || type === 'css') {
47219
47298
  content = getCodeWithSourcemap(type, content.toString(), map);
47220
47299
  }
47221
47300
  }
47301
+ else {
47302
+ if (type === 'js' && (!map || map.mappings !== '')) {
47303
+ const urlWithoutTimestamp = removeTimestampQuery(req.url);
47304
+ const ms = new MagicString(content.toString());
47305
+ content = getCodeWithSourcemap(type, content.toString(), ms.generateMap({ source: urlWithoutTimestamp, hires: 'boundary' }));
47306
+ }
47307
+ }
47222
47308
  res.statusCode = 200;
47223
47309
  res.end(content);
47224
47310
  return;
@@ -47614,7 +47700,7 @@ function serveStaticMiddleware(dir, server) {
47614
47700
  }
47615
47701
  if (redirectedPathname) {
47616
47702
  // dir is pre-normalized to posix style
47617
- if (redirectedPathname.startsWith(dir)) {
47703
+ if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
47618
47704
  redirectedPathname = redirectedPathname.slice(dir.length);
47619
47705
  }
47620
47706
  }
@@ -47622,7 +47708,7 @@ function serveStaticMiddleware(dir, server) {
47622
47708
  let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
47623
47709
  if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
47624
47710
  fileUrl[fileUrl.length - 1] !== '/') {
47625
- fileUrl = fileUrl + '/';
47711
+ fileUrl = withTrailingSlash(fileUrl);
47626
47712
  }
47627
47713
  if (!ensureServingAccess(fileUrl, server, res, next)) {
47628
47714
  return;
@@ -47804,7 +47890,7 @@ function resolveBuildOptions(raw, logger, root) {
47804
47890
  if (resolved.minify === 'false') {
47805
47891
  resolved.minify = false;
47806
47892
  }
47807
- if (resolved.minify === true) {
47893
+ else if (resolved.minify === true) {
47808
47894
  resolved.minify = 'esbuild';
47809
47895
  }
47810
47896
  if (resolved.cssMinify == null) {
@@ -47887,7 +47973,6 @@ async function build(inlineConfig = {}) {
47887
47973
  await initDepsOptimizer(config);
47888
47974
  }
47889
47975
  const rollupOptions = {
47890
- context: 'globalThis',
47891
47976
  preserveEntrySignatures: ssr
47892
47977
  ? 'allow-extension'
47893
47978
  : libOptions
@@ -48027,7 +48112,7 @@ function prepareOutDir(outDirs, emptyOutDir, config) {
48027
48112
  if (emptyOutDir == null) {
48028
48113
  for (const outDir of nonDuplicateDirs) {
48029
48114
  if (fs$l.existsSync(outDir) &&
48030
- !normalizePath$3(outDir).startsWith(config.root + '/')) {
48115
+ !normalizePath$3(outDir).startsWith(withTrailingSlash(config.root))) {
48031
48116
  // warn if outDir is outside of root
48032
48117
  config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} outDir ${colors$1.white(colors$1.dim(outDir))} is not inside project root and will not be emptied.\n` +
48033
48118
  `Use --emptyOutDir to override.\n`));
@@ -48084,7 +48169,7 @@ function resolveLibFilename(libOptions, format, entryName, root, extension, pack
48084
48169
  : entryName);
48085
48170
  if (!name)
48086
48171
  throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
48087
- extension ?? (extension = resolveOutputJsExtension(format, packageJson?.type));
48172
+ extension ??= resolveOutputJsExtension(format, packageJson?.type);
48088
48173
  if (format === 'cjs' || format === 'es') {
48089
48174
  return `${name}.${extension}`;
48090
48175
  }
@@ -48391,7 +48476,9 @@ const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
48391
48476
  function areSeparateFolders(a, b) {
48392
48477
  const na = normalizePath$3(a);
48393
48478
  const nb = normalizePath$3(b);
48394
- return na !== nb && !na.startsWith(nb + '/') && !nb.startsWith(na + '/');
48479
+ return (na !== nb &&
48480
+ !na.startsWith(withTrailingSlash(nb)) &&
48481
+ !nb.startsWith(withTrailingSlash(na)));
48395
48482
  }
48396
48483
 
48397
48484
  var build$1 = {
@@ -54943,7 +55030,7 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54943
55030
  if (server._restartPromise && !ssr)
54944
55031
  throwClosedServerError();
54945
55032
  // ensure module in graph after successful load
54946
- mod ?? (mod = await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved));
55033
+ mod ??= await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved);
54947
55034
  ensureWatchedFile(watcher, mod.file, root);
54948
55035
  // transform
54949
55036
  const transformStart = debugTransform ? performance.now() : 0;
@@ -54962,22 +55049,31 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54962
55049
  code = transformResult.code;
54963
55050
  map = transformResult.map;
54964
55051
  }
54965
- if (map && mod.file) {
54966
- map = (typeof map === 'string' ? JSON.parse(map) : map);
54967
- if (map.mappings) {
54968
- await injectSourcesContent(map, mod.file, logger);
55052
+ let normalizedMap;
55053
+ if (typeof map === 'string') {
55054
+ normalizedMap = JSON.parse(map);
55055
+ }
55056
+ else if (map) {
55057
+ normalizedMap = map;
55058
+ }
55059
+ else {
55060
+ normalizedMap = null;
55061
+ }
55062
+ if (normalizedMap && 'version' in normalizedMap && mod.file) {
55063
+ if (normalizedMap.mappings) {
55064
+ await injectSourcesContent(normalizedMap, mod.file, logger);
54969
55065
  }
54970
55066
  const sourcemapPath = `${mod.file}.map`;
54971
- applySourcemapIgnoreList(map, sourcemapPath, config.server.sourcemapIgnoreList, logger);
55067
+ applySourcemapIgnoreList(normalizedMap, sourcemapPath, config.server.sourcemapIgnoreList, logger);
54972
55068
  if (path$o.isAbsolute(mod.file)) {
54973
- for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
54974
- const sourcePath = map.sources[sourcesIndex];
55069
+ for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
55070
+ const sourcePath = normalizedMap.sources[sourcesIndex];
54975
55071
  if (sourcePath) {
54976
55072
  // Rewrite sources to relative paths to give debuggers the chance
54977
55073
  // to resolve and display them in a meaningful way (rather than
54978
55074
  // with absolute paths).
54979
55075
  if (path$o.isAbsolute(sourcePath)) {
54980
- map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
55076
+ normalizedMap.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
54981
55077
  }
54982
55078
  }
54983
55079
  }
@@ -54986,12 +55082,12 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54986
55082
  if (server._restartPromise && !ssr)
54987
55083
  throwClosedServerError();
54988
55084
  const result = ssr && !server.config.experimental.skipSsrTransform
54989
- ? await server.ssrTransform(code, map, url, originalCode)
54990
- : {
55085
+ ? await server.ssrTransform(code, normalizedMap, url, originalCode)
55086
+ : ({
54991
55087
  code,
54992
- map,
55088
+ map: normalizedMap,
54993
55089
  etag: getEtag(code, { weak: true }),
54994
- };
55090
+ });
54995
55091
  // Only cache the result if the module wasn't invalidated while it was
54996
55092
  // being processed, so it is re-processed next time if it is stale
54997
55093
  if (timestamp > mod.lastInvalidationTimestamp) {
@@ -55500,7 +55596,10 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
55500
55596
  },
55501
55597
  });
55502
55598
  let map = s.generateMap({ hires: 'boundary' });
55503
- if (inMap && inMap.mappings && inMap.sources.length > 0) {
55599
+ if (inMap &&
55600
+ inMap.mappings &&
55601
+ 'sources' in inMap &&
55602
+ inMap.sources.length > 0) {
55504
55603
  map = combineSourcemaps(url, [
55505
55604
  {
55506
55605
  ...map,
@@ -55958,7 +56057,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
55958
56057
  }
55959
56058
  }
55960
56059
  let sourceMapSuffix = '';
55961
- if (result.map) {
56060
+ if (result.map && 'version' in result.map) {
55962
56061
  const moduleSourceMap = Object.assign({}, result.map, {
55963
56062
  // currently we need to offset the line
55964
56063
  // https://github.com/nodejs/node/issues/43047#issuecomment-1180632750
@@ -57204,7 +57303,7 @@ function execAsync(command, options) {
57204
57303
  });
57205
57304
  }
57206
57305
 
57207
- function bindShortcuts(server, opts) {
57306
+ function bindCLIShortcuts(server, opts) {
57208
57307
  if (!server.httpServer || !process.stdin.isTTY || process.env.CI) {
57209
57308
  return;
57210
57309
  }
@@ -57309,8 +57408,13 @@ const BASE_PREVIEW_SHORTCUTS = [
57309
57408
  key: 'o',
57310
57409
  description: 'open in browser',
57311
57410
  action(server) {
57312
- const url = server.resolvedUrls.local[0] ?? server.resolvedUrls.network[0];
57313
- openBrowser(url, true, server.config.logger);
57411
+ const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
57412
+ if (url) {
57413
+ openBrowser(url, true, server.config.logger);
57414
+ }
57415
+ else {
57416
+ server.config.logger.warn('No URL available to open in browser');
57417
+ }
57314
57418
  },
57315
57419
  },
57316
57420
  {
@@ -61692,6 +61796,7 @@ function createWebSocketServer(server, config, httpsOptions) {
61692
61796
  // TODO: the main server port may not have been chosen yet as it may use the next available
61693
61797
  const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
61694
61798
  const wsServer = hmrServer || (portsAreCompatible && server);
61799
+ let hmrServerWsListener;
61695
61800
  const customListeners = new Map();
61696
61801
  const clientsMap = new WeakMap();
61697
61802
  const port = hmrPort || 24678;
@@ -61703,14 +61808,15 @@ function createWebSocketServer(server, config, httpsOptions) {
61703
61808
  hmrBase = path$o.posix.join(hmrBase, hmrPath);
61704
61809
  }
61705
61810
  wss = new WebSocketServerRaw({ noServer: true });
61706
- wsServer.on('upgrade', (req, socket, head) => {
61811
+ hmrServerWsListener = (req, socket, head) => {
61707
61812
  if (req.headers['sec-websocket-protocol'] === HMR_HEADER &&
61708
61813
  req.url === hmrBase) {
61709
61814
  wss.handleUpgrade(req, socket, head, (ws) => {
61710
61815
  wss.emit('connection', ws, req);
61711
61816
  });
61712
61817
  }
61713
- });
61818
+ };
61819
+ wsServer.on('upgrade', hmrServerWsListener);
61714
61820
  }
61715
61821
  else {
61716
61822
  // http server request handler keeps the same with
@@ -61852,6 +61958,11 @@ function createWebSocketServer(server, config, httpsOptions) {
61852
61958
  });
61853
61959
  },
61854
61960
  close() {
61961
+ // should remove listener if hmr.server is set
61962
+ // otherwise the old listener swallows all WebSocket connections
61963
+ if (hmrServerWsListener && wsServer) {
61964
+ wsServer.off('upgrade', hmrServerWsListener);
61965
+ }
61855
61966
  return new Promise((resolve, reject) => {
61856
61967
  wss.clients.forEach((client) => {
61857
61968
  client.terminate();
@@ -61909,7 +62020,7 @@ function baseMiddleware({ config, }) {
61909
62020
  }
61910
62021
  else if (req.headers.accept?.includes('text/html')) {
61911
62022
  // non-based page visit
61912
- const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
62023
+ const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
61913
62024
  res.writeHead(404, {
61914
62025
  'Content-Type': 'text/html',
61915
62026
  });
@@ -64198,9 +64309,10 @@ var history = /*@__PURE__*/getDefaultExportFromCjs(libExports);
64198
64309
 
64199
64310
  function htmlFallbackMiddleware(root, spaFallback) {
64200
64311
  const historyHtmlFallbackMiddleware = history({
64312
+ disableDotRule: true,
64201
64313
  logger: createDebugger('vite:html-fallback'),
64202
- // support /dir/ without explicit index.html
64203
64314
  rewrites: [
64315
+ // support /dir/ without explicit index.html
64204
64316
  {
64205
64317
  from: /\/$/,
64206
64318
  to({ parsedUrl, request }) {
@@ -64211,6 +64323,13 @@ function htmlFallbackMiddleware(root, spaFallback) {
64211
64323
  return spaFallback ? `/index.html` : request.url;
64212
64324
  },
64213
64325
  },
64326
+ // don't rewrite paths ending with .html
64327
+ {
64328
+ from: /\.html$/,
64329
+ to({ request }) {
64330
+ return request.url;
64331
+ },
64332
+ },
64214
64333
  ],
64215
64334
  });
64216
64335
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
@@ -64289,10 +64408,10 @@ function transformMiddleware(server) {
64289
64408
  // check if public dir is inside root dir
64290
64409
  const publicDir = normalizePath$3(server.config.publicDir);
64291
64410
  const rootDir = normalizePath$3(server.config.root);
64292
- if (publicDir.startsWith(rootDir)) {
64411
+ if (publicDir.startsWith(withTrailingSlash(rootDir))) {
64293
64412
  const publicPath = `${publicDir.slice(rootDir.length)}/`;
64294
64413
  // warn explicit public paths
64295
- if (url.startsWith(publicPath)) {
64414
+ if (url.startsWith(withTrailingSlash(publicPath))) {
64296
64415
  let warning;
64297
64416
  if (isImportRequest(url)) {
64298
64417
  const rawUrl = removeImportQuery(url);
@@ -64570,7 +64689,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
64570
64689
  const result = await server.pluginContainer.transform(code, mod.id);
64571
64690
  let content = '';
64572
64691
  if (result) {
64573
- if (result.map) {
64692
+ if (result.map && 'version' in result.map) {
64574
64693
  if (result.map.mappings) {
64575
64694
  await injectSourcesContent(result.map, proxyModulePath, config.logger);
64576
64695
  }
@@ -64654,27 +64773,35 @@ function timeMiddleware(root) {
64654
64773
  }
64655
64774
 
64656
64775
  class ModuleNode {
64776
+ /**
64777
+ * Public served url path, starts with /
64778
+ */
64779
+ url;
64780
+ /**
64781
+ * Resolved file system path + query
64782
+ */
64783
+ id = null;
64784
+ file = null;
64785
+ type;
64786
+ info;
64787
+ meta;
64788
+ importers = new Set();
64789
+ clientImportedModules = new Set();
64790
+ ssrImportedModules = new Set();
64791
+ acceptedHmrDeps = new Set();
64792
+ acceptedHmrExports = null;
64793
+ importedBindings = null;
64794
+ isSelfAccepting;
64795
+ transformResult = null;
64796
+ ssrTransformResult = null;
64797
+ ssrModule = null;
64798
+ ssrError = null;
64799
+ lastHMRTimestamp = 0;
64800
+ lastInvalidationTimestamp = 0;
64657
64801
  /**
64658
64802
  * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
64659
64803
  */
64660
64804
  constructor(url, setIsSelfAccepting = true) {
64661
- /**
64662
- * Resolved file system path + query
64663
- */
64664
- this.id = null;
64665
- this.file = null;
64666
- this.importers = new Set();
64667
- this.clientImportedModules = new Set();
64668
- this.ssrImportedModules = new Set();
64669
- this.acceptedHmrDeps = new Set();
64670
- this.acceptedHmrExports = null;
64671
- this.importedBindings = null;
64672
- this.transformResult = null;
64673
- this.ssrTransformResult = null;
64674
- this.ssrModule = null;
64675
- this.ssrError = null;
64676
- this.lastHMRTimestamp = 0;
64677
- this.lastInvalidationTimestamp = 0;
64678
64805
  this.url = url;
64679
64806
  this.type = isDirectCSSRequest(url) ? 'css' : 'js';
64680
64807
  if (setIsSelfAccepting) {
@@ -64690,21 +64817,22 @@ class ModuleNode {
64690
64817
  }
64691
64818
  }
64692
64819
  class ModuleGraph {
64820
+ resolveId;
64821
+ urlToModuleMap = new Map();
64822
+ idToModuleMap = new Map();
64823
+ // a single file may corresponds to multiple modules with different queries
64824
+ fileToModulesMap = new Map();
64825
+ safeModulesPath = new Set();
64826
+ /**
64827
+ * @internal
64828
+ */
64829
+ _unresolvedUrlToModuleMap = new Map();
64830
+ /**
64831
+ * @internal
64832
+ */
64833
+ _ssrUnresolvedUrlToModuleMap = new Map();
64693
64834
  constructor(resolveId) {
64694
64835
  this.resolveId = resolveId;
64695
- this.urlToModuleMap = new Map();
64696
- this.idToModuleMap = new Map();
64697
- // a single file may corresponds to multiple modules with different queries
64698
- this.fileToModulesMap = new Map();
64699
- this.safeModulesPath = new Set();
64700
- /**
64701
- * @internal
64702
- */
64703
- this._unresolvedUrlToModuleMap = new Map();
64704
- /**
64705
- * @internal
64706
- */
64707
- this._ssrUnresolvedUrlToModuleMap = new Map();
64708
64836
  }
64709
64837
  async getModuleByUrl(rawUrl, ssr) {
64710
64838
  // Quick path, if we already have a module for this rawUrl (even without extension)
@@ -65074,6 +65202,9 @@ async function _createServer(inlineConfig = {}, options) {
65074
65202
  throw new Error('cannot print server URLs before server.listen is called.');
65075
65203
  }
65076
65204
  },
65205
+ bindCLIShortcuts(options) {
65206
+ bindCLIShortcuts(server, options);
65207
+ },
65077
65208
  async restart(forceOptimize) {
65078
65209
  if (!server._restartPromise) {
65079
65210
  server._forceOptimizeOnRestart = !!forceOptimize;
@@ -65387,7 +65518,7 @@ async function restartServer(server) {
65387
65518
  }
65388
65519
  if (shortcutsOptions) {
65389
65520
  shortcutsOptions.print = false;
65390
- bindShortcuts(newServer, shortcutsOptions);
65521
+ bindCLIShortcuts(newServer, shortcutsOptions);
65391
65522
  }
65392
65523
  }
65393
65524
  async function updateCjsSsrExternals(server) {
@@ -65573,6 +65704,9 @@ async function preview(inlineConfig = {}) {
65573
65704
  throw new Error('cannot print server URLs before server is listening.');
65574
65705
  }
65575
65706
  },
65707
+ bindCLIShortcuts(options) {
65708
+ bindCLIShortcuts(server, options);
65709
+ },
65576
65710
  };
65577
65711
  // apply server hooks from plugins
65578
65712
  const postHooks = [];
@@ -65637,7 +65771,7 @@ var preview$1 = {
65637
65771
  };
65638
65772
 
65639
65773
  function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) {
65640
- ssr ?? (ssr = {});
65774
+ ssr ??= {};
65641
65775
  const optimizeDeps = ssr.optimizeDeps ?? {};
65642
65776
  const format = buildSsrCjsExternalHeuristics ? 'cjs' : 'esm';
65643
65777
  const target = 'node';
@@ -65721,7 +65855,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65721
65855
  optimizeDeps: { disabled: false },
65722
65856
  ssr: { optimizeDeps: { disabled: false } },
65723
65857
  });
65724
- config.build ?? (config.build = {});
65858
+ config.build ??= {};
65725
65859
  config.build.commonjsOptions = { include: [] };
65726
65860
  }
65727
65861
  // Define logger
@@ -65871,7 +66005,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65871
66005
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
65872
66006
  inlineConfig,
65873
66007
  root: resolvedRoot,
65874
- base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
66008
+ base: withTrailingSlash(resolvedBase),
65875
66009
  rawBase: resolvedBase,
65876
66010
  resolve: resolveOptions,
65877
66011
  publicDir: resolvedPublicDir,
@@ -65994,7 +66128,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
65994
66128
  if (config.legacy?.buildSsrCjsExternalHeuristics ||
65995
66129
  config.ssr?.format === 'cjs') {
65996
66130
  resolved.logger.warn(colors$1.yellow(`
65997
- (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
66131
+ (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
65998
66132
  Find more information and give feedback at https://github.com/vitejs/vite/discussions/13816.
65999
66133
  `));
66000
66134
  }
@@ -66111,7 +66245,7 @@ async function bundleConfigFile(fileName, isESM) {
66111
66245
  entryPoints: [fileName],
66112
66246
  outfile: 'out.js',
66113
66247
  write: false,
66114
- target: ['node14.18', 'node16'],
66248
+ target: ['node18'],
66115
66249
  platform: 'node',
66116
66250
  bundle: true,
66117
66251
  format: isESM ? 'esm' : 'cjs',
@@ -66288,4 +66422,4 @@ function isDepsOptimizerEnabled(config, ssr) {
66288
66422
  (command === 'serve' && disabled === 'dev'));
66289
66423
  }
66290
66424
 
66291
- export { loadEnv as A, resolveEnvPrefix as B, colors$1 as C, bindShortcuts as D, getDefaultExportFromCjs as E, commonjsGlobal as F, index$1 as G, build$1 as H, index as I, preview$1 as J, 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$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };
66425
+ export { loadEnv as A, resolveEnvPrefix as B, colors$1 as C, getDefaultExportFromCjs as D, commonjsGlobal as E, index$1 as F, build$1 as G, index as H, preview$1 as I, 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$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };