vite 4.4.8 → 4.4.10

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.

package/client.d.ts CHANGED
@@ -221,7 +221,7 @@ declare module '*.txt' {
221
221
  // wasm?init
222
222
  declare module '*.wasm?init' {
223
223
  const initWasm: (
224
- options: WebAssembly.Imports,
224
+ options?: WebAssembly.Imports,
225
225
  ) => Promise<WebAssembly.Instance>
226
226
  export default initWasm
227
227
  }
@@ -11834,6 +11834,12 @@ const flattenId = (id) => id
11834
11834
  .replace(replaceNestedIdRE, '___')
11835
11835
  .replace(replaceHashRE, '____');
11836
11836
  const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > ');
11837
+ // Supported by Node, Deno, Bun
11838
+ const NODE_BUILTIN_NAMESPACE = 'node:';
11839
+ // Supported by Deno
11840
+ const NPM_BUILTIN_NAMESPACE = 'npm:';
11841
+ // Supported by Bun
11842
+ const BUN_BUILTIN_NAMESPACE = 'bun:';
11837
11843
  //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
11838
11844
  const builtins = new Set([
11839
11845
  ...builtinModules,
@@ -11851,17 +11857,26 @@ const builtins = new Set([
11851
11857
  'util/types',
11852
11858
  'wasi',
11853
11859
  ]);
11854
- const NODE_BUILTIN_NAMESPACE = 'node:';
11860
+ // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
11861
+ const nodeBuiltins = [...builtins].filter((id) => !id.includes(':'));
11862
+ // TODO: Use `isBuiltin` from `node:module`, but Deno doesn't support it
11855
11863
  function isBuiltin(id) {
11856
- return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE)
11857
- ? id.slice(NODE_BUILTIN_NAMESPACE.length)
11858
- : id);
11864
+ if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE))
11865
+ return true;
11866
+ if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE))
11867
+ return true;
11868
+ return isNodeBuiltin(id);
11869
+ }
11870
+ function isNodeBuiltin(id) {
11871
+ if (id.startsWith(NODE_BUILTIN_NAMESPACE))
11872
+ return true;
11873
+ return nodeBuiltins.includes(id);
11859
11874
  }
11860
11875
  function isInNodeModules(id) {
11861
11876
  return id.includes('node_modules');
11862
11877
  }
11863
11878
  function moduleListContains(moduleList, id) {
11864
- return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
11879
+ return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
11865
11880
  }
11866
11881
  function isOptimizable(id, optimizeDeps) {
11867
11882
  const { extensions } = optimizeDeps;
@@ -11923,6 +11938,12 @@ function fsPathFromId(id) {
11923
11938
  function fsPathFromUrl(url) {
11924
11939
  return fsPathFromId(cleanUrl(url));
11925
11940
  }
11941
+ function withTrailingSlash(path) {
11942
+ if (path[path.length - 1] !== '/') {
11943
+ return `${path}/`;
11944
+ }
11945
+ return path;
11946
+ }
11926
11947
  /**
11927
11948
  * Check if dir is a parent of file
11928
11949
  *
@@ -11933,9 +11954,7 @@ function fsPathFromUrl(url) {
11933
11954
  * @returns true if dir is a parent of file
11934
11955
  */
11935
11956
  function isParentDirectory(dir, file) {
11936
- if (dir[dir.length - 1] !== '/') {
11937
- dir = `${dir}/`;
11938
- }
11957
+ dir = withTrailingSlash(dir);
11939
11958
  return (file.startsWith(dir) ||
11940
11959
  (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
11941
11960
  }
@@ -12287,7 +12306,7 @@ function optimizeSafeRealPathSync() {
12287
12306
  function ensureWatchedFile(watcher, file, root) {
12288
12307
  if (file &&
12289
12308
  // only need to watch if out of root
12290
- !file.startsWith(root + '/') &&
12309
+ !file.startsWith(withTrailingSlash(root)) &&
12291
12310
  // some rollup plugins use null bytes for private resolved Ids
12292
12311
  !file.includes('\0') &&
12293
12312
  fs$l.existsSync(file)) {
@@ -12727,7 +12746,7 @@ function stripBase(path, base) {
12727
12746
  if (path === base) {
12728
12747
  return '/';
12729
12748
  }
12730
- const devBase = base[base.length - 1] === '/' ? base : base + '/';
12749
+ const devBase = withTrailingSlash(base);
12731
12750
  return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
12732
12751
  }
12733
12752
  function arrayEqual(a, b) {
@@ -12984,21 +13003,23 @@ function buildReporterPlugin(config) {
12984
13003
  chunkCount = 0;
12985
13004
  compressedCount = 0;
12986
13005
  },
12987
- renderChunk(code, chunk) {
12988
- for (const id of chunk.moduleIds) {
12989
- const module = this.getModuleInfo(id);
12990
- if (!module)
12991
- continue;
12992
- // When a dynamic importer shares a chunk with the imported module,
12993
- // warn that the dynamic imported module will not be moved to another chunk (#12850).
12994
- if (module.importers.length && module.dynamicImporters.length) {
12995
- // Filter out the intersection of dynamic importers and sibling modules in
12996
- // the same chunk. The intersecting dynamic importers' dynamic import is not
12997
- // expected to work. Note we're only detecting the direct ineffective
12998
- // dynamic import here.
12999
- const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
13000
- if (detectedIneffectiveDynamicImport) {
13001
- this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
13006
+ renderChunk(code, chunk, options) {
13007
+ if (!options.inlineDynamicImports) {
13008
+ for (const id of chunk.moduleIds) {
13009
+ const module = this.getModuleInfo(id);
13010
+ if (!module)
13011
+ continue;
13012
+ // When a dynamic importer shares a chunk with the imported module,
13013
+ // warn that the dynamic imported module will not be moved to another chunk (#12850).
13014
+ if (module.importers.length && module.dynamicImporters.length) {
13015
+ // Filter out the intersection of dynamic importers and sibling modules in
13016
+ // the same chunk. The intersecting dynamic importers' dynamic import is not
13017
+ // expected to work. Note we're only detecting the direct ineffective
13018
+ // dynamic import here.
13019
+ const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
13020
+ if (detectedIneffectiveDynamicImport) {
13021
+ this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
13022
+ }
13002
13023
  }
13003
13024
  }
13004
13025
  }
@@ -13082,9 +13103,10 @@ function buildReporterPlugin(config) {
13082
13103
  if (isLarge)
13083
13104
  hasLargeChunks = true;
13084
13105
  const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
13085
- let log = colors$1.dim(relativeOutDir + '/');
13106
+ let log = colors$1.dim(withTrailingSlash(relativeOutDir));
13086
13107
  log +=
13087
- !config.build.lib && entry.name.startsWith(assetsDir)
13108
+ !config.build.lib &&
13109
+ entry.name.startsWith(withTrailingSlash(assetsDir))
13088
13110
  ? colors$1.dim(assetsDir) +
13089
13111
  group.color(entry.name
13090
13112
  .slice(assetsDir.length)
@@ -13754,8 +13776,13 @@ function hasWorkspacePackageJSON(root) {
13754
13776
  if (!isFileReadable(path)) {
13755
13777
  return false;
13756
13778
  }
13757
- const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
13758
- return !!content.workspaces;
13779
+ try {
13780
+ const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
13781
+ return !!content.workspaces;
13782
+ }
13783
+ catch {
13784
+ return false;
13785
+ }
13759
13786
  }
13760
13787
  function hasRootFile(root) {
13761
13788
  return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
@@ -13792,8 +13819,8 @@ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
13792
13819
  }
13793
13820
 
13794
13821
  const debug$f = createDebugger('vite:esbuild');
13795
- const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{\s*"use strict";)/s;
13796
- const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{\s*"use strict";)/s;
13822
+ // IIFE content looks like `var MyLib = function() {`. Spaces are removed when minified
13823
+ const IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\(\)\s*\{.*"use strict";/s;
13797
13824
  const validExtensionRE = /\.\w+$/;
13798
13825
  const jsxExtensionsRE = /\.(?:j|t)sx\b/;
13799
13826
  let server;
@@ -14026,16 +14053,26 @@ const buildEsbuildPlugin = (config) => {
14026
14053
  if (config.build.lib) {
14027
14054
  // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
14028
14055
  // names are minified potentially causing collision with other globals.
14029
- // We use a regex to inject the helpers inside the wrappers.
14056
+ // We inject the helpers inside the wrappers.
14057
+ // e.g. turn:
14058
+ // <esbuild helpers> (function(){ /*actual content/* })()
14059
+ // into:
14060
+ // (function(){ <esbuild helpers> /*actual content/* })()
14061
+ // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065
14062
+ // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant
14030
14063
  // We don't need to create a MagicString here because both the helpers and
14031
14064
  // the headers don't modify the sourcemap
14032
- const injectHelpers = opts.format === 'umd'
14033
- ? INJECT_HELPERS_UMD_RE
14034
- : opts.format === 'iife'
14035
- ? INJECT_HELPERS_IIFE_RE
14036
- : undefined;
14037
- if (injectHelpers) {
14038
- res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers);
14065
+ const esbuildCode = res.code;
14066
+ const contentIndex = opts.format === 'iife'
14067
+ ? esbuildCode.match(IIFE_BEGIN_RE)?.index || 0
14068
+ : opts.format === 'umd'
14069
+ ? esbuildCode.indexOf(`(function(`) // same for minified or not
14070
+ : 0;
14071
+ if (contentIndex > 0) {
14072
+ const esbuildHelpers = esbuildCode.slice(0, contentIndex);
14073
+ res.code = esbuildCode
14074
+ .slice(contentIndex)
14075
+ .replace(`"use strict";`, `"use strict";` + esbuildHelpers);
14039
14076
  }
14040
14077
  }
14041
14078
  return res;
@@ -16174,7 +16211,7 @@ function checkPublicFile(url, { publicDir }) {
16174
16211
  return;
16175
16212
  }
16176
16213
  const publicFile = path$o.join(publicDir, cleanUrl(url));
16177
- if (!publicFile.startsWith(publicDir)) {
16214
+ if (!normalizePath$3(publicFile).startsWith(withTrailingSlash(normalizePath$3(publicDir)))) {
16178
16215
  // can happen if URL starts with '../'
16179
16216
  return;
16180
16217
  }
@@ -16199,7 +16236,7 @@ function fileToDevUrl(id, config) {
16199
16236
  // in public dir, keep the url as-is
16200
16237
  rtn = id;
16201
16238
  }
16202
- else if (id.startsWith(config.root)) {
16239
+ else if (id.startsWith(withTrailingSlash(config.root))) {
16203
16240
  // in project root, infer short public path
16204
16241
  rtn = '/' + path$o.posix.relative(config.root, id);
16205
16242
  }
@@ -21300,6 +21337,8 @@ var settings = {};
21300
21337
  if (this.stats) {
21301
21338
  this.objectMode = true;
21302
21339
  }
21340
+ // Remove the cast to the array in the next major (#404).
21341
+ this.ignore = [].concat(this.ignore);
21303
21342
  }
21304
21343
  _getValue(option, value) {
21305
21344
  return option === undefined ? value : option;
@@ -27431,7 +27470,7 @@ function encodeQueryItem(key, value) {
27431
27470
  return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
27432
27471
  }
27433
27472
  function stringifyQuery(query) {
27434
- return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&");
27473
+ return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
27435
27474
  }
27436
27475
 
27437
27476
  new Set(builtinModules);
@@ -28082,7 +28121,9 @@ function resolvePlugin(resolveOptions) {
28082
28121
  }
28083
28122
  // URL
28084
28123
  // /foo -> /fs-root/foo
28085
- if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
28124
+ if (asSrc &&
28125
+ id[0] === '/' &&
28126
+ (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
28086
28127
  const fsPath = path$o.resolve(root, id.slice(1));
28087
28128
  if ((res = tryFsResolve(fsPath, options))) {
28088
28129
  debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
@@ -28398,8 +28439,10 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28398
28439
  bareImportRE.test(id)) {
28399
28440
  const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
28400
28441
  if (mainPkg) {
28401
- if (mainPkg.peerDependencies?.[id] &&
28402
- mainPkg.peerDependenciesMeta?.[id]?.optional) {
28442
+ const pkgName = getNpmPackageName(id);
28443
+ if (pkgName != null &&
28444
+ mainPkg.peerDependencies?.[pkgName] &&
28445
+ mainPkg.peerDependenciesMeta?.[pkgName]?.optional) {
28403
28446
  return {
28404
28447
  id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
28405
28448
  };
@@ -28576,7 +28619,7 @@ async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks
28576
28619
  idPkgDir = normalizePath$3(idPkgDir);
28577
28620
  }
28578
28621
  // match by src to correctly identify if id belongs to nested dependency
28579
- if (optimizedData.src.startsWith(idPkgDir)) {
28622
+ if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
28580
28623
  return depsOptimizer.getOptimizedDepId(optimizedData);
28581
28624
  }
28582
28625
  }
@@ -36627,69 +36670,112 @@ var src$1 = rc;
36627
36670
 
36628
36671
  var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1);
36629
36672
 
36630
- function stripLiteralAcorn(code) {
36631
- const FILL = " ";
36673
+ function _stripLiteralAcorn(code, options) {
36674
+ const FILL = options?.fillChar ?? " ";
36675
+ const FILL_COMMENT = " ";
36632
36676
  let result = "";
36633
- function fulfill(index) {
36677
+ const filter = options?.filter ?? (() => true);
36678
+ function fillupTo(index) {
36634
36679
  if (index > result.length)
36635
- result += code.slice(result.length, index).replace(/[^\n]/g, FILL);
36680
+ result += code.slice(result.length, index).replace(/[^\n]/g, FILL_COMMENT);
36636
36681
  }
36637
- const tokens = tokenizer(code, {
36682
+ const tokens = [];
36683
+ const pasers = tokenizer(code, {
36638
36684
  ecmaVersion: "latest",
36639
36685
  sourceType: "module",
36640
36686
  allowHashBang: true,
36641
36687
  allowAwaitOutsideFunction: true,
36642
36688
  allowImportExportEverywhere: true
36643
36689
  });
36644
- const inter = tokens[Symbol.iterator]();
36645
- while (true) {
36646
- const { done, value: token } = inter.next();
36647
- if (done)
36648
- break;
36649
- fulfill(token.start);
36650
- if (token.type.label === "string")
36651
- result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
36652
- else if (token.type.label === "template")
36653
- result += FILL.repeat(token.end - token.start);
36654
- else
36690
+ const iter = pasers[Symbol.iterator]();
36691
+ let error;
36692
+ try {
36693
+ while (true) {
36694
+ const { done, value: token } = iter.next();
36695
+ if (done)
36696
+ break;
36697
+ tokens.push(token);
36698
+ fillupTo(token.start);
36699
+ if (token.type.label === "string") {
36700
+ const body = code.slice(token.start + 1, token.end - 1);
36701
+ if (filter(body)) {
36702
+ result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
36703
+ continue;
36704
+ }
36705
+ } else if (token.type.label === "template") {
36706
+ const body = code.slice(token.start, token.end);
36707
+ if (filter(body)) {
36708
+ result += FILL.repeat(token.end - token.start);
36709
+ continue;
36710
+ }
36711
+ } else if (token.type.label === "regexp") {
36712
+ const body = code.slice(token.start, token.end);
36713
+ if (filter(body)) {
36714
+ result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
36715
+ continue;
36716
+ }
36717
+ }
36655
36718
  result += code.slice(token.start, token.end);
36719
+ }
36720
+ fillupTo(code.length);
36721
+ } catch (e) {
36722
+ error = e;
36656
36723
  }
36657
- fulfill(code.length);
36658
- return result;
36724
+ return {
36725
+ error,
36726
+ result,
36727
+ tokens
36728
+ };
36659
36729
  }
36660
36730
 
36661
36731
  const multilineCommentsRE = /\/\*([^*\/])*?\*\//gms;
36662
36732
  const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm;
36663
- const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g;
36733
+ const templateLiteralRE$1 = /\$\{(\s*(?:|{.*}|(?!\$\{).|\n|\r)*?\s*)\}/g;
36664
36734
  const quotesRE = [
36665
36735
  /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
36666
36736
  /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm
36667
36737
  // multi-line strings (i.e. template literals only)
36668
36738
  ];
36669
- function stripLiteralRegex(code) {
36670
- code = code.replace(multilineCommentsRE, (s) => " ".repeat(s.length)).replace(singlelineCommentsRE, (s) => " ".repeat(s.length));
36739
+ function stripLiteralRegex(code, options) {
36740
+ const FILL_COMMENT = " ";
36741
+ const FILL = options?.fillChar ?? " ";
36742
+ const filter = options?.filter ?? (() => true);
36743
+ code = code.replace(multilineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s).replace(singlelineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s);
36671
36744
  let expanded = code;
36672
36745
  for (let i = 0; i < 16; i++) {
36673
36746
  const before = expanded;
36674
- expanded = expanded.replace(templateLiteralRE, "` $1`");
36747
+ expanded = expanded.replace(templateLiteralRE$1, "` $1`");
36675
36748
  if (expanded === before)
36676
36749
  break;
36677
36750
  }
36678
36751
  quotesRE.forEach((re) => {
36679
36752
  expanded = expanded.replace(re, (s, quote, body, index) => {
36680
- code = code.slice(0, index + 1) + " ".repeat(s.length - 2) + code.slice(index + s.length - 1);
36681
- return quote + " ".repeat(s.length - 2) + quote;
36753
+ if (!filter(s.slice(1, -1)))
36754
+ return s;
36755
+ code = code.slice(0, index + 1) + FILL.repeat(s.length - 2) + code.slice(index + s.length - 1);
36756
+ return quote + FILL.repeat(s.length - 2) + quote;
36682
36757
  });
36683
36758
  });
36684
36759
  return code;
36685
36760
  }
36686
36761
 
36687
- function stripLiteral(code) {
36688
- try {
36689
- return stripLiteralAcorn(code);
36690
- } catch (e) {
36691
- return stripLiteralRegex(code);
36762
+ function stripLiteral(code, options) {
36763
+ return stripLiteralDetailed(code, options).result;
36764
+ }
36765
+ function stripLiteralDetailed(code, options) {
36766
+ const acorn = _stripLiteralAcorn(code, options);
36767
+ if (!acorn.error) {
36768
+ return {
36769
+ mode: "acorn",
36770
+ result: acorn.result,
36771
+ acorn
36772
+ };
36692
36773
  }
36774
+ return {
36775
+ mode: "regex",
36776
+ result: stripLiteralRegex(acorn.result + code.slice(acorn.result.length), options),
36777
+ acorn
36778
+ };
36693
36779
  }
36694
36780
 
36695
36781
  var main$1 = {exports: {}};
@@ -38298,7 +38384,7 @@ function cssPostPlugin(config) {
38298
38384
  };
38299
38385
  return {
38300
38386
  name: 'vite:css-post',
38301
- buildStart() {
38387
+ renderStart() {
38302
38388
  // Ensure new caches for every build (i.e. rebuilding in watch mode)
38303
38389
  pureCssChunks = new Set();
38304
38390
  outputToExtractedCSSMap = new Map();
@@ -38586,9 +38672,9 @@ function cssPostPlugin(config) {
38586
38672
  // chunks instead.
38587
38673
  chunk.imports = chunk.imports.filter((file) => {
38588
38674
  if (pureCssChunkNames.includes(file)) {
38589
- const { importedCss } = bundle[file]
38590
- .viteMetadata;
38675
+ const { importedCss, importedAssets } = bundle[file].viteMetadata;
38591
38676
  importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
38677
+ importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
38592
38678
  return false;
38593
38679
  }
38594
38680
  return true;
@@ -38602,6 +38688,7 @@ function cssPostPlugin(config) {
38602
38688
  pureCssChunkNames.forEach((fileName) => {
38603
38689
  removedPureCssFiles.set(fileName, bundle[fileName]);
38604
38690
  delete bundle[fileName];
38691
+ delete bundle[`${fileName}.map`];
38605
38692
  });
38606
38693
  }
38607
38694
  let extractedCss = outputToExtractedCSSMap.get(opts);
@@ -38912,8 +38999,8 @@ function createCachedImport(imp) {
38912
38999
  return cached;
38913
39000
  };
38914
39001
  }
38915
- const importPostcssImport = createCachedImport(() => import('./dep-d502c17d.js').then(function (n) { return n.i; }));
38916
- const importPostcssModules = createCachedImport(() => import('./dep-def3b363.js').then(function (n) { return n.i; }));
39002
+ const importPostcssImport = createCachedImport(() => import('./dep-fdea5ef1.js').then(function (n) { return n.i; }));
39003
+ const importPostcssModules = createCachedImport(() => import('./dep-809640fa.js').then(function (n) { return n.i; }));
38917
39004
  const importPostcss = createCachedImport(() => import('postcss'));
38918
39005
  /**
38919
39006
  * @experimental
@@ -40227,7 +40314,8 @@ function cjsShouldExternalizeForSSR(id, externals) {
40227
40314
  }
40228
40315
  // deep imports, check ext before externalizing - only externalize
40229
40316
  // extension-less imports and explicit .js imports
40230
- if (id.startsWith(e + '/') && (!path$o.extname(id) || id.endsWith('.js'))) {
40317
+ if (id.startsWith(withTrailingSlash(e)) &&
40318
+ (!path$o.extname(id) || id.endsWith('.js'))) {
40231
40319
  return true;
40232
40320
  }
40233
40321
  });
@@ -40737,8 +40825,11 @@ function getAffectedGlobModules(file, server) {
40737
40825
  for (const [id, allGlobs] of server._importGlobMap) {
40738
40826
  // (glob1 || glob2) && !glob3 && !glob4...
40739
40827
  if (allGlobs.some(({ affirmed, negated }) => (!affirmed.length || affirmed.some((glob) => isMatch$1(file, glob))) &&
40740
- (!negated.length || negated.every((glob) => isMatch$1(file, glob)))))
40741
- modules.push(...(server.moduleGraph.getModulesByFile(id) || []));
40828
+ (!negated.length || negated.every((glob) => isMatch$1(file, glob))))) {
40829
+ const mod = server.moduleGraph.getModuleById(id);
40830
+ if (mod)
40831
+ modules.push(mod);
40832
+ }
40742
40833
  }
40743
40834
  modules.forEach((i) => {
40744
40835
  if (i?.file)
@@ -41169,7 +41260,9 @@ const debugHmr = createDebugger('vite:hmr');
41169
41260
  const whitespaceRE = /\s/;
41170
41261
  const normalizedClientDir = normalizePath$3(CLIENT_DIR);
41171
41262
  function getShortName(file, root) {
41172
- return file.startsWith(root + '/') ? path$o.posix.relative(root, file) : file;
41263
+ return file.startsWith(withTrailingSlash(root))
41264
+ ? path$o.posix.relative(root, file)
41265
+ : file;
41173
41266
  }
41174
41267
  async function handleHMRUpdate(file, server, configOnly) {
41175
41268
  const { ws, config, moduleGraph } = server;
@@ -41196,7 +41289,7 @@ async function handleHMRUpdate(file, server, configOnly) {
41196
41289
  }
41197
41290
  debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
41198
41291
  // (dev only) the client itself cannot be hot updated.
41199
- if (file.startsWith(normalizedClientDir)) {
41292
+ if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
41200
41293
  ws.send({
41201
41294
  type: 'full-reload',
41202
41295
  path: '*',
@@ -41560,6 +41653,7 @@ const hasImportInQueryParamsRE = /[?&]import=?\b/;
41560
41653
  const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
41561
41654
  const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
41562
41655
  const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
41656
+ const templateLiteralRE = /^\s*`(.*)`\s*$/;
41563
41657
  function isExplicitImportRequired(url) {
41564
41658
  return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
41565
41659
  }
@@ -41717,7 +41811,6 @@ function importAnalysisPlugin(config) {
41717
41811
  let needQueryInjectHelper = false;
41718
41812
  let s;
41719
41813
  const str = () => s || (s = new MagicString(source));
41720
- const importedUrls = new Set();
41721
41814
  let isPartiallySelfAccepting = false;
41722
41815
  const importedBindings = enablePartialAccept
41723
41816
  ? new Map()
@@ -41757,7 +41850,7 @@ function importAnalysisPlugin(config) {
41757
41850
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
41758
41851
  // normalize all imports into resolved URLs
41759
41852
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
41760
- if (resolved.id.startsWith(root + '/')) {
41853
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
41761
41854
  // in root: infer short absolute path from root
41762
41855
  url = resolved.id.slice(root.length);
41763
41856
  }
@@ -41818,13 +41911,14 @@ function importAnalysisPlugin(config) {
41818
41911
  }
41819
41912
  return [url, resolved.id];
41820
41913
  };
41914
+ const orderedImportedUrls = new Array(imports.length);
41821
41915
  const orderedAcceptedUrls = new Array(imports.length);
41822
41916
  const orderedAcceptedExports = new Array(imports.length);
41823
41917
  await Promise.all(imports.map(async (importSpecifier, index) => {
41824
- const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex,
41918
+ const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: assertIndex, } = importSpecifier;
41825
41919
  // #2083 User may use escape path,
41826
41920
  // so use imports[index].n to get the unescaped string
41827
- n: specifier, a: assertIndex, } = importSpecifier;
41921
+ let specifier = importSpecifier.n;
41828
41922
  const rawUrl = source.slice(start, end);
41829
41923
  // check import.meta usage
41830
41924
  if (rawUrl === 'import.meta') {
@@ -41854,6 +41948,15 @@ function importAnalysisPlugin(config) {
41854
41948
  }
41855
41949
  return;
41856
41950
  }
41951
+ else if (templateLiteralRE.test(rawUrl)) {
41952
+ // If the import has backticks but isn't transformed as a glob import
41953
+ // (as there's nothing to glob), check if it's simply a plain string.
41954
+ // If so, we can replace the specifier as a plain string to prevent
41955
+ // an incorrect "cannot be analyzed" warning.
41956
+ if (!(rawUrl.includes('${') && rawUrl.includes('}'))) {
41957
+ specifier = rawUrl.replace(templateLiteralRE, '$1');
41958
+ }
41959
+ }
41857
41960
  const isDynamicImport = dynamicIndex > -1;
41858
41961
  // strip import assertions as we can process them ourselves
41859
41962
  if (!isDynamicImport && assertIndex > -1) {
@@ -41966,7 +42069,7 @@ function importAnalysisPlugin(config) {
41966
42069
  const hmrUrl = unwrapId(stripBase(url, base));
41967
42070
  const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
41968
42071
  if (isLocalImport) {
41969
- importedUrls.add(hmrUrl);
42072
+ orderedImportedUrls[index] = hmrUrl;
41970
42073
  }
41971
42074
  if (enablePartialAccept && importedBindings) {
41972
42075
  extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
@@ -41989,7 +42092,7 @@ function importAnalysisPlugin(config) {
41989
42092
  });
41990
42093
  }
41991
42094
  }
41992
- else if (!importer.startsWith(clientDir)) {
42095
+ else if (!importer.startsWith(withTrailingSlash(clientDir))) {
41993
42096
  if (!isInNodeModules(importer)) {
41994
42097
  // check @vite-ignore which suppresses dynamic import warning
41995
42098
  const hasViteIgnore = hasViteIgnoreRE.test(
@@ -42017,6 +42120,7 @@ function importAnalysisPlugin(config) {
42017
42120
  }
42018
42121
  }
42019
42122
  }));
42123
+ const importedUrls = new Set(orderedImportedUrls.filter(Boolean));
42020
42124
  const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
42021
42125
  const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
42022
42126
  if (hasEnv) {
@@ -42098,23 +42202,32 @@ function mergeAcceptedUrls(orderedUrls) {
42098
42202
  function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
42099
42203
  const source = str.original;
42100
42204
  const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
42205
+ const exp = source.slice(expStart, expEnd);
42101
42206
  if (dynamicIndex > -1) {
42102
42207
  // rewrite `import('package')` to expose the default directly
42103
- str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`, { contentOnly: true });
42208
+ str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))` +
42209
+ getLineBreaks(exp), { contentOnly: true });
42104
42210
  }
42105
42211
  else {
42106
- const exp = source.slice(expStart, expEnd);
42107
42212
  const rawUrl = source.slice(start, end);
42108
42213
  const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
42109
42214
  if (rewritten) {
42110
- str.overwrite(expStart, expEnd, rewritten, { contentOnly: true });
42215
+ str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
42216
+ contentOnly: true,
42217
+ });
42111
42218
  }
42112
42219
  else {
42113
42220
  // #1439 export * from '...'
42114
- str.overwrite(start, end, rewrittenUrl, { contentOnly: true });
42221
+ str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), {
42222
+ contentOnly: true,
42223
+ });
42115
42224
  }
42116
42225
  }
42117
42226
  }
42227
+ // get line breaks to preserve line count for not breaking source maps
42228
+ function getLineBreaks(str) {
42229
+ return str.includes('\n') ? '\n'.repeat(str.split('\n').length - 1) : '';
42230
+ }
42118
42231
  /**
42119
42232
  * Detect import statements to a known optimized CJS dependency and provide
42120
42233
  * ES named imports interop. We do this by rewriting named imports to a variable
@@ -42563,9 +42676,15 @@ function webWorkerPlugin(config) {
42563
42676
  injectEnv = module?.transformResult?.code || '';
42564
42677
  }
42565
42678
  }
42566
- return {
42567
- code: injectEnv + raw,
42568
- };
42679
+ if (injectEnv) {
42680
+ const s = new MagicString(raw);
42681
+ s.prepend(injectEnv);
42682
+ return {
42683
+ code: s.toString(),
42684
+ map: s.generateMap({ hires: 'boundary' }),
42685
+ };
42686
+ }
42687
+ return;
42569
42688
  }
42570
42689
  if (query == null ||
42571
42690
  (query && (query.worker ?? query.sharedworker) == null)) {
@@ -42758,7 +42877,7 @@ function matches(pattern, importee) {
42758
42877
  if (importee === pattern) {
42759
42878
  return true;
42760
42879
  }
42761
- return importee.startsWith(pattern + '/');
42880
+ return importee.startsWith(withTrailingSlash(pattern));
42762
42881
  }
42763
42882
  function getAliasPatterns(entries) {
42764
42883
  if (!entries) {
@@ -42912,7 +43031,6 @@ function definePlugin(config) {
42912
43031
  };
42913
43032
  }
42914
43033
 
42915
- const ignoreFlagRE = /\/\*\s*@vite-ignore\s*\*\//;
42916
43034
  function err(e, pos) {
42917
43035
  const error = new Error(e);
42918
43036
  error.pos = pos;
@@ -42949,7 +43067,7 @@ function getWorkerType(raw, clean, i) {
42949
43067
  const workerOptString = raw
42950
43068
  .substring(commaIndex + 1, endIndex)
42951
43069
  .replace(/\}[\s\S]*,/g, '}'); // strip trailing comma for parsing
42952
- const hasViteIgnore = ignoreFlagRE.test(workerOptString);
43070
+ const hasViteIgnore = hasViteIgnoreRE.test(workerOptString);
42953
43071
  if (hasViteIgnore) {
42954
43072
  return 'ignore';
42955
43073
  }
@@ -43468,6 +43586,9 @@ function dynamicImportVarsPlugin(config) {
43468
43586
  if (dynamicIndex === -1 || source[start] !== '`') {
43469
43587
  continue;
43470
43588
  }
43589
+ if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
43590
+ continue;
43591
+ }
43471
43592
  s || (s = new MagicString(source));
43472
43593
  let result;
43473
43594
  try {
@@ -45363,7 +45484,6 @@ async function createDepsOptimizer(config, server) {
45363
45484
  if (closed) {
45364
45485
  return;
45365
45486
  }
45366
- const crawlDeps = Object.keys(metadata.discovered);
45367
45487
  // Await for the scan+optimize step running in the background
45368
45488
  // It normally should be over by the time crawling of user code ended
45369
45489
  await depsOptimizer.scanProcessing;
@@ -45371,6 +45491,7 @@ async function createDepsOptimizer(config, server) {
45371
45491
  const result = await optimizationResult.result;
45372
45492
  optimizationResult = undefined;
45373
45493
  currentlyProcessing = false;
45494
+ const crawlDeps = Object.keys(metadata.discovered);
45374
45495
  const scanDeps = Object.keys(result.metadata.optimized);
45375
45496
  if (scanDeps.length === 0 && crawlDeps.length === 0) {
45376
45497
  debug$8?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
@@ -45403,6 +45524,7 @@ async function createDepsOptimizer(config, server) {
45403
45524
  }
45404
45525
  }
45405
45526
  else {
45527
+ const crawlDeps = Object.keys(metadata.discovered);
45406
45528
  currentlyProcessing = false;
45407
45529
  if (crawlDeps.length === 0) {
45408
45530
  debug$8?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
@@ -46498,7 +46620,7 @@ function buildImportAnalysisPlugin(config) {
46498
46620
  ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
46499
46621
  // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
46500
46622
  // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
46501
- `function(dep, importerUrl) { return dep.startsWith('.') ? new URL(dep, importerUrl).href : dep }`
46623
+ `function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }`
46502
46624
  : optimizeModulePreloadRelativePaths
46503
46625
  ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative
46504
46626
  // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
@@ -46566,7 +46688,7 @@ function buildImportAnalysisPlugin(config) {
46566
46688
  }
46567
46689
  // normalize all imports into resolved URLs
46568
46690
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
46569
- if (resolved.id.startsWith(root + '/')) {
46691
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
46570
46692
  // in root: infer short absolute path from root
46571
46693
  url = resolved.id.slice(root.length);
46572
46694
  }
@@ -47565,7 +47687,7 @@ function serveStaticMiddleware(dir, server) {
47565
47687
  }
47566
47688
  if (redirectedPathname) {
47567
47689
  // dir is pre-normalized to posix style
47568
- if (redirectedPathname.startsWith(dir)) {
47690
+ if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
47569
47691
  redirectedPathname = redirectedPathname.slice(dir.length);
47570
47692
  }
47571
47693
  }
@@ -47573,7 +47695,7 @@ function serveStaticMiddleware(dir, server) {
47573
47695
  let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
47574
47696
  if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
47575
47697
  fileUrl[fileUrl.length - 1] !== '/') {
47576
- fileUrl = fileUrl + '/';
47698
+ fileUrl = withTrailingSlash(fileUrl);
47577
47699
  }
47578
47700
  if (!ensureServingAccess(fileUrl, server, res, next)) {
47579
47701
  return;
@@ -47978,7 +48100,7 @@ function prepareOutDir(outDirs, emptyOutDir, config) {
47978
48100
  if (emptyOutDir == null) {
47979
48101
  for (const outDir of nonDuplicateDirs) {
47980
48102
  if (fs$l.existsSync(outDir) &&
47981
- !normalizePath$3(outDir).startsWith(config.root + '/')) {
48103
+ !normalizePath$3(outDir).startsWith(withTrailingSlash(config.root))) {
47982
48104
  // warn if outDir is outside of root
47983
48105
  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` +
47984
48106
  `Use --emptyOutDir to override.\n`));
@@ -48342,7 +48464,9 @@ const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
48342
48464
  function areSeparateFolders(a, b) {
48343
48465
  const na = normalizePath$3(a);
48344
48466
  const nb = normalizePath$3(b);
48345
- return na !== nb && !na.startsWith(nb + '/') && !nb.startsWith(na + '/');
48467
+ return (na !== nb &&
48468
+ !na.startsWith(withTrailingSlash(nb)) &&
48469
+ !nb.startsWith(withTrailingSlash(na)));
48346
48470
  }
48347
48471
 
48348
48472
  var build$1 = {
@@ -55946,7 +56070,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
55946
56070
  // In node@12+ we can use dynamic import to load CJS and ESM
55947
56071
  async function nodeImport(id, importer, resolveOptions) {
55948
56072
  let url;
55949
- if (id.startsWith('node:') || id.startsWith('data:') || isBuiltin(id)) {
56073
+ if (id.startsWith('data:') || isBuiltin(id)) {
55950
56074
  url = id;
55951
56075
  }
55952
56076
  else {
@@ -61643,6 +61767,7 @@ function createWebSocketServer(server, config, httpsOptions) {
61643
61767
  // TODO: the main server port may not have been chosen yet as it may use the next available
61644
61768
  const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
61645
61769
  const wsServer = hmrServer || (portsAreCompatible && server);
61770
+ let hmrServerWsListener;
61646
61771
  const customListeners = new Map();
61647
61772
  const clientsMap = new WeakMap();
61648
61773
  const port = hmrPort || 24678;
@@ -61654,14 +61779,15 @@ function createWebSocketServer(server, config, httpsOptions) {
61654
61779
  hmrBase = path$o.posix.join(hmrBase, hmrPath);
61655
61780
  }
61656
61781
  wss = new WebSocketServerRaw({ noServer: true });
61657
- wsServer.on('upgrade', (req, socket, head) => {
61782
+ hmrServerWsListener = (req, socket, head) => {
61658
61783
  if (req.headers['sec-websocket-protocol'] === HMR_HEADER &&
61659
61784
  req.url === hmrBase) {
61660
61785
  wss.handleUpgrade(req, socket, head, (ws) => {
61661
61786
  wss.emit('connection', ws, req);
61662
61787
  });
61663
61788
  }
61664
- });
61789
+ };
61790
+ wsServer.on('upgrade', hmrServerWsListener);
61665
61791
  }
61666
61792
  else {
61667
61793
  // http server request handler keeps the same with
@@ -61803,6 +61929,11 @@ function createWebSocketServer(server, config, httpsOptions) {
61803
61929
  });
61804
61930
  },
61805
61931
  close() {
61932
+ // should remove listener if hmr.server is set
61933
+ // otherwise the old listener swallows all WebSocket connections
61934
+ if (hmrServerWsListener && wsServer) {
61935
+ wsServer.off('upgrade', hmrServerWsListener);
61936
+ }
61806
61937
  return new Promise((resolve, reject) => {
61807
61938
  wss.clients.forEach((client) => {
61808
61939
  client.terminate();
@@ -61860,7 +61991,7 @@ function baseMiddleware({ config, }) {
61860
61991
  }
61861
61992
  else if (req.headers.accept?.includes('text/html')) {
61862
61993
  // non-based page visit
61863
- const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
61994
+ const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
61864
61995
  res.writeHead(404, {
61865
61996
  'Content-Type': 'text/html',
61866
61997
  });
@@ -64240,10 +64371,10 @@ function transformMiddleware(server) {
64240
64371
  // check if public dir is inside root dir
64241
64372
  const publicDir = normalizePath$3(server.config.publicDir);
64242
64373
  const rootDir = normalizePath$3(server.config.root);
64243
- if (publicDir.startsWith(rootDir)) {
64374
+ if (publicDir.startsWith(withTrailingSlash(rootDir))) {
64244
64375
  const publicPath = `${publicDir.slice(rootDir.length)}/`;
64245
64376
  // warn explicit public paths
64246
- if (url.startsWith(publicPath)) {
64377
+ if (url.startsWith(withTrailingSlash(publicPath))) {
64247
64378
  let warning;
64248
64379
  if (isImportRequest(url)) {
64249
64380
  const rawUrl = removeImportQuery(url);
@@ -65822,7 +65953,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65822
65953
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
65823
65954
  inlineConfig,
65824
65955
  root: resolvedRoot,
65825
- base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
65956
+ base: withTrailingSlash(resolvedBase),
65826
65957
  rawBase: resolvedBase,
65827
65958
  resolve: resolveOptions,
65828
65959
  publicDir: resolvedPublicDir,
@@ -65945,7 +66076,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
65945
66076
  if (config.legacy?.buildSsrCjsExternalHeuristics ||
65946
66077
  config.ssr?.format === 'cjs') {
65947
66078
  resolved.logger.warn(colors$1.yellow(`
65948
- (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
66079
+ (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
65949
66080
  Find more information and give feedback at https://github.com/vitejs/vite/discussions/13816.
65950
66081
  `));
65951
66082
  }
@@ -66109,11 +66240,13 @@ async function bundleConfigFile(fileName, isESM) {
66109
66240
  build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => {
66110
66241
  if (kind === 'entry-point' ||
66111
66242
  path$o.isAbsolute(id) ||
66112
- isBuiltin(id)) {
66243
+ isNodeBuiltin(id)) {
66113
66244
  return;
66114
66245
  }
66115
- // partial deno support as `npm:` does not work with esbuild
66116
- if (id.startsWith('npm:')) {
66246
+ // With the `isNodeBuiltin` check above, this check captures if the builtin is a
66247
+ // non-node built-in, which esbuild doesn't know how to handle. In that case, we
66248
+ // externalize it so the non-node runtime handles it instead.
66249
+ if (isBuiltin(id)) {
66117
66250
  return { external: true };
66118
66251
  }
66119
66252
  const isImport = isESM || kind === 'dynamic-import';
@@ -1,4 +1,4 @@
1
- import { F as commonjsGlobal, E as getDefaultExportFromCjs } from './dep-75f53616.js';
1
+ import { F as commonjsGlobal, E as getDefaultExportFromCjs } from './dep-3bba9c7e.js';
2
2
  import require$$0__default from 'fs';
3
3
  import require$$0 from 'postcss';
4
4
  import require$$0$1 from 'path';
@@ -1,4 +1,4 @@
1
- import { E as getDefaultExportFromCjs } from './dep-75f53616.js';
1
+ import { E as getDefaultExportFromCjs } from './dep-3bba9c7e.js';
2
2
  import require$$0 from 'path';
3
3
  import require$$0__default from 'fs';
4
4
  import { l as lib } from './dep-c423598f.js';
package/dist/node/cli.js CHANGED
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { EventEmitter } from 'events';
5
- import { C as colors, D as bindShortcuts, x as createLogger, h as resolveConfig } from './chunks/dep-75f53616.js';
5
+ import { C as colors, D as bindShortcuts, x as createLogger, h as resolveConfig } from './chunks/dep-3bba9c7e.js';
6
6
  import { VERSION } from './constants.js';
7
7
  import 'node:fs/promises';
8
8
  import 'node:url';
@@ -714,9 +714,29 @@ function cleanOptions(options) {
714
714
  }
715
715
  return ret;
716
716
  }
717
+ /**
718
+ * host may be a number (like 0), should convert to string
719
+ */
720
+ const convertHost = (v) => {
721
+ if (typeof v === 'number') {
722
+ return String(v);
723
+ }
724
+ return v;
725
+ };
726
+ /**
727
+ * base may be a number (like 0), should convert to empty string
728
+ */
729
+ const convertBase = (v) => {
730
+ if (v === 0) {
731
+ return '';
732
+ }
733
+ return v;
734
+ };
717
735
  cli
718
736
  .option('-c, --config <file>', `[string] use specified config file`)
719
- .option('--base <path>', `[string] public base path (default: /)`)
737
+ .option('--base <path>', `[string] public base path (default: /)`, {
738
+ type: [convertBase],
739
+ })
720
740
  .option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
721
741
  .option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
722
742
  .option('-d, --debug [feat]', `[string | boolean] show debug logs`)
@@ -727,7 +747,7 @@ cli
727
747
  .command('[root]', 'start dev server') // default command
728
748
  .alias('serve') // the command is called 'serve' in Vite's API
729
749
  .alias('dev') // alias to align with the script name
730
- .option('--host [host]', `[string] specify hostname`)
750
+ .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
731
751
  .option('--port <port>', `[number] specify port`)
732
752
  .option('--https', `[boolean] use TLS + HTTP/2`)
733
753
  .option('--open [path]', `[boolean | string] open browser on startup`)
@@ -738,7 +758,7 @@ cli
738
758
  filterDuplicateOptions(options);
739
759
  // output structure is preserved even after bundling so require()
740
760
  // is ok here
741
- const { createServer } = await import('./chunks/dep-75f53616.js').then(function (n) { return n.I; });
761
+ const { createServer } = await import('./chunks/dep-3bba9c7e.js').then(function (n) { return n.I; });
742
762
  try {
743
763
  const server = await createServer({
744
764
  root,
@@ -816,7 +836,7 @@ cli
816
836
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
817
837
  .action(async (root, options) => {
818
838
  filterDuplicateOptions(options);
819
- const { build } = await import('./chunks/dep-75f53616.js').then(function (n) { return n.H; });
839
+ const { build } = await import('./chunks/dep-3bba9c7e.js').then(function (n) { return n.H; });
820
840
  const buildOptions = cleanOptions(options);
821
841
  try {
822
842
  await build({
@@ -844,7 +864,7 @@ cli
844
864
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
845
865
  .action(async (root, options) => {
846
866
  filterDuplicateOptions(options);
847
- const { optimizeDeps } = await import('./chunks/dep-75f53616.js').then(function (n) { return n.G; });
867
+ const { optimizeDeps } = await import('./chunks/dep-3bba9c7e.js').then(function (n) { return n.G; });
848
868
  try {
849
869
  const config = await resolveConfig({
850
870
  root,
@@ -863,7 +883,7 @@ cli
863
883
  // preview
864
884
  cli
865
885
  .command('preview [root]', 'locally preview production build')
866
- .option('--host [host]', `[string] specify hostname`)
886
+ .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
867
887
  .option('--port <port>', `[number] specify port`)
868
888
  .option('--strictPort', `[boolean] exit if specified port is already in use`)
869
889
  .option('--https', `[boolean] use TLS + HTTP/2`)
@@ -871,7 +891,7 @@ cli
871
891
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
872
892
  .action(async (root, options) => {
873
893
  filterDuplicateOptions(options);
874
- const { preview } = await import('./chunks/dep-75f53616.js').then(function (n) { return n.J; });
894
+ const { preview } = await import('./chunks/dep-3bba9c7e.js').then(function (n) { return n.J; });
875
895
  try {
876
896
  const server = await preview({
877
897
  root,
@@ -1,5 +1,5 @@
1
- import { i as isInNodeModules } from './chunks/dep-75f53616.js';
2
- export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, z as isFileServingAllowed, l as loadConfigFromFile, A as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, B as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-75f53616.js';
1
+ import { i as isInNodeModules } from './chunks/dep-3bba9c7e.js';
2
+ export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, z as isFileServingAllowed, l as loadConfigFromFile, A as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, B as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-3bba9c7e.js';
3
3
  export { VERSION as version } from './constants.js';
4
4
  export { version as esbuildVersion } from 'esbuild';
5
5
  export { VERSION as rollupVersion } from 'rollup';
@@ -3281,8 +3281,8 @@ const createFilter$1 = function createFilter(include, exclude, options) {
3281
3281
  };
3282
3282
 
3283
3283
  const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
3284
- const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
3285
- const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
3284
+ const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
3285
+ const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins$1}`.split(' '));
3286
3286
  forbiddenIdentifiers.add('');
3287
3287
 
3288
3288
  if (process.versions.pnp) {
@@ -3297,6 +3297,25 @@ const windowsSlashRE = /\\/g;
3297
3297
  function slash(p) {
3298
3298
  return p.replace(windowsSlashRE, '/');
3299
3299
  }
3300
+ //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
3301
+ const builtins = new Set([
3302
+ ...node_module.builtinModules,
3303
+ 'assert/strict',
3304
+ 'diagnostics_channel',
3305
+ 'dns/promises',
3306
+ 'fs/promises',
3307
+ 'path/posix',
3308
+ 'path/win32',
3309
+ 'readline/promises',
3310
+ 'stream/consumers',
3311
+ 'stream/promises',
3312
+ 'stream/web',
3313
+ 'timers/promises',
3314
+ 'util/types',
3315
+ 'wasi',
3316
+ ]);
3317
+ // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
3318
+ [...builtins].filter((id) => !id.includes(':'));
3300
3319
  function isInNodeModules(id) {
3301
3320
  return id.includes('node_modules');
3302
3321
  }
@@ -3344,6 +3363,12 @@ function fsPathFromId(id) {
3344
3363
  function fsPathFromUrl(url) {
3345
3364
  return fsPathFromId(cleanUrl(url));
3346
3365
  }
3366
+ function withTrailingSlash(path) {
3367
+ if (path[path.length - 1] !== '/') {
3368
+ return `${path}/`;
3369
+ }
3370
+ return path;
3371
+ }
3347
3372
  /**
3348
3373
  * Check if dir is a parent of file
3349
3374
  *
@@ -3354,9 +3379,7 @@ function fsPathFromUrl(url) {
3354
3379
  * @returns true if dir is a parent of file
3355
3380
  */
3356
3381
  function isParentDirectory(dir, file) {
3357
- if (dir[dir.length - 1] !== '/') {
3358
- dir = `${dir}/`;
3359
- }
3382
+ dir = withTrailingSlash(dir);
3360
3383
  return (file.startsWith(dir) ||
3361
3384
  (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
3362
3385
  }
@@ -3928,8 +3951,13 @@ function hasWorkspacePackageJSON(root) {
3928
3951
  if (!isFileReadable(path)) {
3929
3952
  return false;
3930
3953
  }
3931
- const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
3932
- return !!content.workspaces;
3954
+ try {
3955
+ const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
3956
+ return !!content.workspaces;
3957
+ }
3958
+ catch {
3959
+ return false;
3960
+ }
3933
3961
  }
3934
3962
  function hasRootFile(root) {
3935
3963
  return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "4.4.8",
3
+ "version": "4.4.10",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -28,6 +28,9 @@
28
28
  "types": "./client.d.ts"
29
29
  },
30
30
  "./dist/client/*": "./dist/client/*",
31
+ "./types/*": {
32
+ "types": "./types/*"
33
+ },
31
34
  "./package.json": "./package.json"
32
35
  },
33
36
  "files": [
@@ -68,8 +71,8 @@
68
71
  "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
69
72
  "dependencies": {
70
73
  "esbuild": "^0.18.10",
71
- "postcss": "^8.4.26",
72
- "rollup": "^3.25.2"
74
+ "postcss": "^8.4.27",
75
+ "rollup": "^3.27.1"
73
76
  },
74
77
  "optionalDependencies": {
75
78
  "fsevents": "~2.3.2"
@@ -105,7 +108,7 @@
105
108
  "escape-html": "^1.0.3",
106
109
  "estree-walker": "^3.0.3",
107
110
  "etag": "^1.8.1",
108
- "fast-glob": "^3.3.0",
111
+ "fast-glob": "^3.3.1",
109
112
  "http-proxy": "^1.18.1",
110
113
  "json-stable-stringify": "^1.0.2",
111
114
  "launch-editor-middleware": "^2.6.0",
@@ -128,11 +131,11 @@
128
131
  "sirv": "^2.0.3",
129
132
  "source-map-support": "^0.5.21",
130
133
  "strip-ansi": "^7.1.0",
131
- "strip-literal": "^1.0.1",
134
+ "strip-literal": "^1.3.0",
132
135
  "tsconfck": "^2.1.2",
133
- "tslib": "^2.6.0",
136
+ "tslib": "^2.6.1",
134
137
  "types": "link:./types",
135
- "ufo": "^1.1.2",
138
+ "ufo": "^1.2.0",
136
139
  "ws": "^8.13.0"
137
140
  },
138
141
  "peerDependencies": {
@@ -2,8 +2,6 @@
2
2
  // Thus cannot contain any top-level imports
3
3
  // <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
4
4
 
5
- /* eslint-disable @typescript-eslint/consistent-type-imports */
6
-
7
5
  interface ImportMetaEnv {
8
6
  [key: string]: any
9
7
  BASE_URL: string