vite 4.0.0-alpha.0 → 4.0.0-alpha.2

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.
@@ -1,5 +1,5 @@
1
1
  import require$$0$1 from 'postcss';
2
- import { A as commonjsGlobal } from './dep-f991744a.js';
2
+ import { A as commonjsGlobal } from './dep-b8ca7cde.js';
3
3
  import require$$0 from 'path';
4
4
  import require$$5 from 'crypto';
5
5
  import require$$0__default from 'fs';
@@ -11974,16 +11974,10 @@ function writeFile(filename, content) {
11974
11974
  }
11975
11975
  fs$l.writeFileSync(filename, content);
11976
11976
  }
11977
- /**
11978
- * Use fs.statSync(filename) instead of fs.existsSync(filename)
11979
- * #2051 if we don't have read permission on a directory, existsSync() still
11980
- * works and will result in massively slow subsequent checks (which are
11981
- * unnecessary in the first place)
11982
- */
11983
11977
  function isFileReadable(filename) {
11984
11978
  try {
11985
- const stat = fs$l.statSync(filename, { throwIfNoEntry: false });
11986
- return !!stat;
11979
+ fs$l.accessSync(filename, fs$l.constants.R_OK);
11980
+ return true;
11987
11981
  }
11988
11982
  catch {
11989
11983
  return false;
@@ -12232,7 +12226,7 @@ async function resolveServerUrls(server, options, config) {
12232
12226
  const hostname = await resolveHostname(options.host);
12233
12227
  const protocol = options.https ? 'https' : 'http';
12234
12228
  const port = address.port;
12235
- const base = config.base === './' || config.base === '' ? '/' : config.base;
12229
+ const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase;
12236
12230
  if (hostname.host && loopbackHosts.has(hostname.host)) {
12237
12231
  let hostnameName = hostname.name;
12238
12232
  if (hostnameName === '::1' ||
@@ -12299,12 +12293,15 @@ function getHash(text) {
12299
12293
  return createHash$2('sha256').update(text).digest('hex').substring(0, 8);
12300
12294
  }
12301
12295
  const requireResolveFromRootWithFallback = (root, id) => {
12296
+ const paths = _require$4.resolve.paths?.(id) || [];
12302
12297
  // Search in the root directory first, and fallback to the default require paths.
12303
- const fallbackPaths = _require$4.resolve.paths?.(id) || [];
12304
- const path = _require$4.resolve(id, {
12305
- paths: [root, ...fallbackPaths]
12306
- });
12307
- return path;
12298
+ paths.unshift(root);
12299
+ // Use `resolve` package to check existence first, so if the package is not found,
12300
+ // it won't be cached by nodejs, since there isn't a way to invalidate them:
12301
+ // https://github.com/nodejs/node/issues/44663
12302
+ resolve$5.sync(id, { basedir: root, paths });
12303
+ // Use `require.resolve` again as the `resolve` package doesn't support the `exports` field
12304
+ return _require$4.resolve(id, { paths });
12308
12305
  };
12309
12306
  // Based on node-graceful-fs
12310
12307
  // The ISC License
@@ -12484,6 +12481,41 @@ const isNonDriveRelativeAbsolutePath = (p) => {
12484
12481
  return p.startsWith('/');
12485
12482
  return windowsDrivePathPrefixRE.test(p);
12486
12483
  };
12484
+ /**
12485
+ * Determine if a file is being requested with the correct case, to ensure
12486
+ * consistent behaviour between dev and prod and across operating systems.
12487
+ */
12488
+ function shouldServe(url, assetsDir) {
12489
+ try {
12490
+ // viteTestUrl is set to something like http://localhost:4173/ and then many tests make calls
12491
+ // like `await page.goto(viteTestUrl + '/example')` giving us URLs beginning with a double slash
12492
+ const pathname = decodeURI(new URL$3(url.startsWith('//') ? url.substring(1) : url, 'http://example.com').pathname);
12493
+ const file = path$o.join(assetsDir, pathname);
12494
+ if (!fs$l.existsSync(file) ||
12495
+ (isCaseInsensitiveFS && // can skip case check on Linux
12496
+ !fs$l.statSync(file).isDirectory() &&
12497
+ !hasCorrectCase(file, assetsDir))) {
12498
+ return false;
12499
+ }
12500
+ return true;
12501
+ }
12502
+ catch (err) {
12503
+ return false;
12504
+ }
12505
+ }
12506
+ /**
12507
+ * Note that we can't use realpath here, because we don't want to follow
12508
+ * symlinks.
12509
+ */
12510
+ function hasCorrectCase(file, assets) {
12511
+ if (file === assets)
12512
+ return true;
12513
+ const parent = path$o.dirname(file);
12514
+ if (fs$l.readdirSync(parent).includes(path$o.basename(file))) {
12515
+ return hasCorrectCase(parent, assets);
12516
+ }
12517
+ return false;
12518
+ }
12487
12519
  function joinUrlSegments(a, b) {
12488
12520
  if (!a || !b) {
12489
12521
  return a || b || '';
@@ -12496,6 +12528,13 @@ function joinUrlSegments(a, b) {
12496
12528
  }
12497
12529
  return a + b;
12498
12530
  }
12531
+ function stripBase(path, base) {
12532
+ if (path === base) {
12533
+ return '/';
12534
+ }
12535
+ const devBase = base.endsWith('/') ? base : base + '/';
12536
+ return path.replace(RegExp('^' + devBase), '/');
12537
+ }
12499
12538
  function arrayEqual(a, b) {
12500
12539
  if (a === b)
12501
12540
  return true;
@@ -13412,6 +13451,7 @@ function esbuildPlugin(options = {}) {
13412
13451
  // and for build as the final optimization is in `buildEsbuildPlugin`
13413
13452
  const transformOptions = {
13414
13453
  target: 'esnext',
13454
+ charset: 'utf8',
13415
13455
  ...options,
13416
13456
  minify: false,
13417
13457
  minifyIdentifiers: false,
@@ -13518,6 +13558,7 @@ function resolveEsbuildTranspileOptions(config, format) {
13518
13558
  const isEsLibBuild = config.build.lib && format === 'es';
13519
13559
  const esbuildOptions = config.esbuild || {};
13520
13560
  const options = {
13561
+ charset: 'utf8',
13521
13562
  ...esbuildOptions,
13522
13563
  target: target || undefined,
13523
13564
  format: rollupToEsbuildFormatMap[format],
@@ -32282,14 +32323,13 @@ function lookup(extn) {
32282
32323
  return mimes$1[!~idx ? tmp : tmp.substring(++idx)];
32283
32324
  }
32284
32325
 
32285
- const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
32286
- const duplicateAssets = new WeakMap();
32326
+ const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g;
32287
32327
  const rawRE = /(\?|&)raw(?:&|$)/;
32288
32328
  const urlRE = /(\?|&)url(?:&|$)/;
32289
32329
  const assetCache = new WeakMap();
32290
- const assetHashToFilenameMap = new WeakMap();
32291
- // save hashes of the files that has been emitted in build watch
32292
- const emittedHashMap = new WeakMap();
32330
+ // chunk.name is the basename for the asset ignoring the directory structure
32331
+ // For the manifest, we need to preserve the original file path
32332
+ const generatedAssets = new WeakMap();
32293
32333
  // add own dictionary entry by directly assigning mrmime
32294
32334
  function registerCustomMime() {
32295
32335
  // https://github.com/lukeed/mrmime/issues/3
@@ -32312,10 +32352,8 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
32312
32352
  // In both cases, the wrapping should already be fine
32313
32353
  while ((match = assetUrlRE.exec(code))) {
32314
32354
  s || (s = new MagicString(code));
32315
- const [full, hash, postfix = ''] = match;
32316
- // some internal plugins may still need to emit chunks (e.g. worker) so
32317
- // fallback to this.getFileName for that. TODO: remove, not needed
32318
- const file = getAssetFilename(hash, config) || ctx.getFileName(hash);
32355
+ const [full, referenceId, postfix = ''] = match;
32356
+ const file = ctx.getFileName(referenceId);
32319
32357
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
32320
32358
  const filename = file + postfix;
32321
32359
  const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
@@ -32342,15 +32380,12 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
32342
32380
  * Also supports loading plain strings with import text from './foo.txt?raw'
32343
32381
  */
32344
32382
  function assetPlugin(config) {
32345
- // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
32346
- assetHashToFilenameMap.set(config, new Map());
32347
32383
  registerCustomMime();
32348
32384
  return {
32349
32385
  name: 'vite:asset',
32350
32386
  buildStart() {
32351
32387
  assetCache.set(config, new Map());
32352
- emittedHashMap.set(config, new Set());
32353
- duplicateAssets.set(config, new Map());
32388
+ generatedAssets.set(config, new Map());
32354
32389
  },
32355
32390
  resolveId(id) {
32356
32391
  if (!config.assetsInclude(cleanUrl(id))) {
@@ -32442,14 +32477,11 @@ function fileToDevUrl(id, config) {
32442
32477
  else {
32443
32478
  // outside of project root, use absolute fs path
32444
32479
  // (this is special handled by the serve static middleware
32445
- rtn = path$o.posix.join(FS_PREFIX + id);
32480
+ rtn = path$o.posix.join(FS_PREFIX, id);
32446
32481
  }
32447
32482
  const base = joinUrlSegments(config.server?.origin ?? '', config.base);
32448
32483
  return joinUrlSegments(base, rtn.replace(/^\//, ''));
32449
32484
  }
32450
- function getAssetFilename(hash, config) {
32451
- return assetHashToFilenameMap.get(config)?.get(hash);
32452
- }
32453
32485
  function getPublicAssetFilename(hash, config) {
32454
32486
  return publicAssetUrlCache.get(config)?.get(hash);
32455
32487
  }
@@ -32594,41 +32626,17 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
32594
32626
  }
32595
32627
  else {
32596
32628
  // emit as asset
32597
- // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
32598
- // that uses runtime url sniffing and it can be verbose when targeting
32599
- // non-module format. It also fails to cascade the asset content change
32600
- // into the chunk's hash, so we have to do our own content hashing here.
32601
- // https://bundlers.tooling.report/hashing/asset-cascade/
32602
- // https://github.com/rollup/rollup/issues/3415
32603
- const map = assetHashToFilenameMap.get(config);
32604
- const contentHash = getHash(content);
32605
32629
  const { search, hash } = parse$j(id);
32606
32630
  const postfix = (search || '') + (hash || '');
32607
- const fileName = assetFileNamesToFileName(resolveAssetFileNames(config), file, contentHash, content);
32608
- if (!map.has(contentHash)) {
32609
- map.set(contentHash, fileName);
32610
- }
32611
- const emittedSet = emittedHashMap.get(config);
32612
- const duplicates = duplicateAssets.get(config);
32613
- const name = normalizePath$3(path$o.relative(config.root, file));
32614
- if (!emittedSet.has(contentHash)) {
32615
- pluginContext.emitFile({
32616
- name,
32617
- fileName,
32618
- type: 'asset',
32619
- source: content
32620
- });
32621
- emittedSet.add(contentHash);
32622
- }
32623
- else {
32624
- duplicates.set(name, {
32625
- name,
32626
- fileName: map.get(contentHash),
32627
- type: 'asset',
32628
- source: content
32629
- });
32630
- }
32631
- url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE
32631
+ const referenceId = pluginContext.emitFile({
32632
+ // Ignore directory structure for asset file names
32633
+ name: path$o.basename(file),
32634
+ type: 'asset',
32635
+ source: content
32636
+ });
32637
+ const originalName = normalizePath$3(path$o.relative(config.root, file));
32638
+ generatedAssets.get(config).set(referenceId, { originalName });
32639
+ url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE
32632
32640
  }
32633
32641
  cache.set(id, url);
32634
32642
  return url;
@@ -33704,9 +33712,6 @@ function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
33704
33712
  }
33705
33713
  }
33706
33714
  function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson) {
33707
- // #2051 if we don't have read permission on a directory, existsSync() still
33708
- // works and will result in massively slow subsequent checks (which are
33709
- // unnecessary in the first place)
33710
33715
  if (isFileReadable(file)) {
33711
33716
  if (!fs$l.statSync(file).isDirectory()) {
33712
33717
  return getRealPath(file, options.preserveSymlinks) + postfix;
@@ -34298,7 +34303,7 @@ const externalTypes = [
34298
34303
  'tsx',
34299
34304
  ...KNOWN_ASSET_TYPES
34300
34305
  ];
34301
- function esbuildDepPlugin(qualified, exportsData, external, config, ssr) {
34306
+ function esbuildDepPlugin(qualified, external, config, ssr) {
34302
34307
  const { extensions } = getDepOptimizationConfig(config, ssr);
34303
34308
  // remove optimizable extensions from `externalTypes` list
34304
34309
  const allExternalTypes = extensions
@@ -35458,9 +35463,8 @@ function updateModules(file, modules, timestamp, { config, ws }) {
35458
35463
  debugHmr(picocolors.exports.yellow(`no update happened `) + picocolors.exports.dim(file));
35459
35464
  return;
35460
35465
  }
35461
- config.logger.info(updates
35462
- .map(({ path }) => picocolors.exports.green(`hmr update `) + picocolors.exports.dim(path))
35463
- .join('\n'), { clear: true, timestamp: true });
35466
+ config.logger.info(picocolors.exports.green(`hmr update `) +
35467
+ picocolors.exports.dim([...new Set(updates.map((u) => u.path))].join(', ')), { clear: true, timestamp: true });
35464
35468
  ws.send({
35465
35469
  type: 'update',
35466
35470
  updates
@@ -36329,7 +36333,10 @@ function servePublicMiddleware(dir, headers) {
36329
36333
  if (isImportRequest(req.url) || isInternalRequest(req.url)) {
36330
36334
  return next();
36331
36335
  }
36332
- serve(req, res, next);
36336
+ if (shouldServe(req.url, dir)) {
36337
+ return serve(req, res, next);
36338
+ }
36339
+ next();
36333
36340
  };
36334
36341
  }
36335
36342
  function serveStaticMiddleware(dir, server) {
@@ -36458,6 +36465,8 @@ function renderRestrictedErrorHTML(msg) {
36458
36465
  `;
36459
36466
  }
36460
36467
 
36468
+ const ERR_LOAD_URL = 'ERR_LOAD_URL';
36469
+ const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
36461
36470
  const debugLoad = createDebugger('vite:load');
36462
36471
  const debugTransform = createDebugger('vite:transform');
36463
36472
  const debugCache$1 = createDebugger('vite:cache');
@@ -36603,15 +36612,15 @@ async function loadAndTransform(id, url, server, options, timestamp) {
36603
36612
  }
36604
36613
  }
36605
36614
  if (code == null) {
36606
- if (checkPublicFile(url, config)) {
36607
- throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` +
36608
- `This file is in /public and will be copied as-is during build without ` +
36615
+ const isPublicFile = checkPublicFile(url, config);
36616
+ const msg = isPublicFile
36617
+ ? `This file is in /public and will be copied as-is during build without ` +
36609
36618
  `going through the plugin transforms, and therefore should not be ` +
36610
- `imported from source code. It can only be referenced via HTML tags.`);
36611
- }
36612
- else {
36613
- return null;
36614
- }
36619
+ `imported from source code. It can only be referenced via HTML tags.`
36620
+ : `Does the file exist?`;
36621
+ const err = new Error(`Failed to load url ${url} (resolved id: ${id}). ${msg}`);
36622
+ err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
36623
+ throw err;
36615
36624
  }
36616
36625
  // ensure module in graph after successful load
36617
36626
  const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
@@ -36813,9 +36822,7 @@ function importAnalysisPlugin(config) {
36813
36822
  : null;
36814
36823
  const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url);
36815
36824
  const normalizeUrl = async (url, pos) => {
36816
- if (base !== '/' && url.startsWith(base)) {
36817
- url = url.replace(base, '/');
36818
- }
36825
+ url = stripBase(url, base);
36819
36826
  let importerFile = importer;
36820
36827
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
36821
36828
  if (moduleListContains(optimizeDeps?.exclude, url)) {
@@ -36856,7 +36863,7 @@ function importAnalysisPlugin(config) {
36856
36863
  fs$l.existsSync(cleanUrl(resolved.id))) {
36857
36864
  // an optimized deps may not yet exists in the filesystem, or
36858
36865
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
36859
- url = path$o.posix.join(FS_PREFIX + resolved.id);
36866
+ url = path$o.posix.join(FS_PREFIX, resolved.id);
36860
36867
  }
36861
36868
  else {
36862
36869
  url = resolved.id;
@@ -36903,8 +36910,8 @@ function importAnalysisPlugin(config) {
36903
36910
  e.pos = pos;
36904
36911
  throw e;
36905
36912
  }
36906
- // prepend base (dev base is guaranteed to have ending slash)
36907
- url = base + url.replace(/^\//, '');
36913
+ // prepend base
36914
+ url = joinUrlSegments(base, url);
36908
36915
  }
36909
36916
  return [url, resolved.id];
36910
36917
  };
@@ -37021,7 +37028,7 @@ function importAnalysisPlugin(config) {
37021
37028
  }
37022
37029
  // record for HMR import chain analysis
37023
37030
  // make sure to unwrap and normalize away base
37024
- const hmrUrl = unwrapId(url.replace(base, '/'));
37031
+ const hmrUrl = unwrapId(stripBase(url, base));
37025
37032
  importedUrls.add(hmrUrl);
37026
37033
  if (enablePartialAccept && importedBindings) {
37027
37034
  extractImportedBindings(resolvedId, source, imports[index], importedBindings);
@@ -37134,7 +37141,7 @@ function importAnalysisPlugin(config) {
37134
37141
  // These requests will also be registered in transformRequest to be awaited
37135
37142
  // by the deps optimizer
37136
37143
  if (config.server.preTransformRequests && staticImportedUrls.size) {
37137
- staticImportedUrls.forEach(({ url, id }) => {
37144
+ staticImportedUrls.forEach(({ url }) => {
37138
37145
  url = removeImportQuery(url);
37139
37146
  transformRequest(url, server, { ssr }).catch((e) => {
37140
37147
  if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
@@ -41463,7 +41470,6 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41463
41470
  // path.
41464
41471
  const flatIdDeps = {};
41465
41472
  const idToExports = {};
41466
- const flatIdToExports = {};
41467
41473
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
41468
41474
  const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
41469
41475
  for (const id in depsInfo) {
@@ -41481,7 +41487,6 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41481
41487
  const flatId = flattenId(id);
41482
41488
  flatIdDeps[flatId] = src;
41483
41489
  idToExports[id] = exportsData;
41484
- flatIdToExports[flatId] = exportsData;
41485
41490
  }
41486
41491
  // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
41487
41492
  // In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
@@ -41513,7 +41518,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41513
41518
  if (external.length) {
41514
41519
  plugins.push(esbuildCjsExternalPlugin(external));
41515
41520
  }
41516
- plugins.push(esbuildDepPlugin(flatIdDeps, flatIdToExports, external, config, ssr));
41521
+ plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr));
41517
41522
  const start = performance.now();
41518
41523
  const result = await build$3({
41519
41524
  absWorkingDir: process.cwd(),
@@ -41540,6 +41545,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41540
41545
  ignoreAnnotations: !isBuild,
41541
41546
  metafile: true,
41542
41547
  plugins,
41548
+ charset: 'utf8',
41543
41549
  ...esbuildOptions,
41544
41550
  supported: {
41545
41551
  'dynamic-import': true,
@@ -43014,7 +43020,7 @@ function buildHtmlPlugin(config) {
43014
43020
  });
43015
43021
  // resolve asset url references
43016
43022
  result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
43017
- return (toOutputAssetFilePath(getAssetFilename(fileHash, config)) + postfix);
43023
+ return toOutputAssetFilePath(this.getFileName(fileHash)) + postfix;
43018
43024
  });
43019
43025
  result = result.replace(publicAssetUrlRE, (_, fileHash) => {
43020
43026
  return normalizePath$3(toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config)));
@@ -43341,7 +43347,7 @@ function cssPlugin(config) {
43341
43347
  for (const file of deps) {
43342
43348
  depModules.add(isCSSRequest(file)
43343
43349
  ? moduleGraph.createFileOnlyEntry(file)
43344
- : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace((config.server?.origin ?? '') + devBase, '/'), ssr));
43350
+ : await moduleGraph.ensureEntryFromUrl(stripBase(await fileToUrl(file, config, this), (config.server?.origin ?? '') + devBase), ssr));
43345
43351
  }
43346
43352
  moduleGraph.updateModuleInfo(thisModule, depModules, null,
43347
43353
  // The root CSS proxy module is self-accepting and should not
@@ -43510,7 +43516,7 @@ function cssPostPlugin(config) {
43510
43516
  const cssEntryFiles = cssEntryFilesCache.get(config);
43511
43517
  const publicAssetUrlMap = publicAssetUrlCache.get(config);
43512
43518
  // resolve asset URL placeholders to their built file URLs
43513
- function resolveAssetUrlsInCss(chunkCSS, cssAssetName) {
43519
+ const resolveAssetUrlsInCss = (chunkCSS, cssAssetName) => {
43514
43520
  const encodedPublicUrls = encodePublicUrlsInCSS(config);
43515
43521
  const relative = config.base === './' || config.base === '';
43516
43522
  const cssAssetDirname = encodedPublicUrls || relative
@@ -43525,7 +43531,7 @@ function cssPostPlugin(config) {
43525
43531
  };
43526
43532
  // replace asset url references with resolved url.
43527
43533
  chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
43528
- const filename = getAssetFilename(fileHash, config) + postfix;
43534
+ const filename = this.getFileName(fileHash) + postfix;
43529
43535
  chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
43530
43536
  return toOutputFilePathInCss(filename, 'asset', cssAssetName, 'css', config, toRelative);
43531
43537
  });
@@ -43538,7 +43544,7 @@ function cssPostPlugin(config) {
43538
43544
  });
43539
43545
  }
43540
43546
  return chunkCSS;
43541
- }
43547
+ };
43542
43548
  function ensureFileExt(name, ext) {
43543
43549
  return normalizePath$3(path$o.format({ ...path$o.parse(name), base: undefined, ext }));
43544
43550
  }
@@ -43808,10 +43814,9 @@ async function compileCSS(id, code, config, urlReplacer) {
43808
43814
  }));
43809
43815
  }
43810
43816
  if (isModule) {
43811
- postcssPlugins.unshift((await import('./dep-cb778398.js').then(function (n) { return n.i; })).default({
43817
+ postcssPlugins.unshift((await import('./dep-2a67faac.js').then(function (n) { return n.i; })).default({
43812
43818
  ...modulesOptions,
43813
- // TODO: convert null to undefined (`null` should be removed from `CSSModulesOptions.localsConvention`)
43814
- localsConvention: modulesOptions?.localsConvention ?? undefined,
43819
+ localsConvention: modulesOptions?.localsConvention,
43815
43820
  getJSON(cssFileName, _modules, outputFileName) {
43816
43821
  modules = _modules;
43817
43822
  if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
@@ -44575,28 +44580,43 @@ function manifestPlugin(config) {
44575
44580
  }
44576
44581
  return manifestChunk;
44577
44582
  }
44578
- function createAsset(chunk) {
44583
+ function createAsset(chunk, src) {
44579
44584
  const manifestChunk = {
44580
44585
  file: chunk.fileName,
44581
- src: chunk.name
44586
+ src
44582
44587
  };
44583
44588
  if (cssEntryFiles.has(chunk.name))
44584
44589
  manifestChunk.isEntry = true;
44585
44590
  return manifestChunk;
44586
44591
  }
44587
44592
  const cssEntryFiles = cssEntryFilesCache.get(config);
44593
+ const fileNameToAssetMeta = new Map();
44594
+ generatedAssets.get(config).forEach((asset, referenceId) => {
44595
+ const fileName = this.getFileName(referenceId);
44596
+ fileNameToAssetMeta.set(fileName, asset);
44597
+ });
44598
+ const fileNameToAsset = new Map();
44588
44599
  for (const file in bundle) {
44589
44600
  const chunk = bundle[file];
44590
44601
  if (chunk.type === 'chunk') {
44591
44602
  manifest[getChunkName(chunk)] = createChunk(chunk);
44592
44603
  }
44593
44604
  else if (chunk.type === 'asset' && typeof chunk.name === 'string') {
44594
- manifest[chunk.name] = createAsset(chunk);
44605
+ // Add every unique asset to the manifest, keyed by its original name
44606
+ const src = fileNameToAssetMeta.get(chunk.fileName)?.originalName ?? chunk.name;
44607
+ const asset = createAsset(chunk, src);
44608
+ manifest[src] = asset;
44609
+ fileNameToAsset.set(chunk.fileName, asset);
44610
+ }
44611
+ }
44612
+ // Add duplicate assets to the manifest
44613
+ fileNameToAssetMeta.forEach(({ originalName }, fileName) => {
44614
+ if (!manifest[originalName]) {
44615
+ const asset = fileNameToAsset.get(fileName);
44616
+ if (asset) {
44617
+ manifest[originalName] = asset;
44618
+ }
44595
44619
  }
44596
- }
44597
- duplicateAssets.get(config).forEach((asset) => {
44598
- const chunk = createAsset(asset);
44599
- manifest[asset.name] = chunk;
44600
44620
  });
44601
44621
  outputCount++;
44602
44622
  const output = config.build.rollupOptions?.output;
@@ -45096,10 +45116,16 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
45096
45116
  }));
45097
45117
  }));
45098
45118
  // let environment variables use each other
45099
- main({
45100
- parsed,
45119
+ const expandParsed = main({
45120
+ parsed: {
45121
+ ...process.env,
45122
+ ...parsed
45123
+ },
45101
45124
  // prevent process.env mutation
45102
45125
  ignoreProcessEnv: true
45126
+ }).parsed;
45127
+ Object.keys(parsed).forEach((key) => {
45128
+ parsed[key] = expandParsed[key];
45103
45129
  });
45104
45130
  // only keys that start with prefix are exposed to client
45105
45131
  for (const [key, value] of Object.entries(parsed)) {
@@ -45509,29 +45535,30 @@ function resolveLibFilename(libOptions, format, entryName, root, extension) {
45509
45535
  }
45510
45536
  function resolveBuildOutputs(outputs, libOptions, logger) {
45511
45537
  if (libOptions) {
45512
- const hasMultipleEntries = typeof libOptions.entry !== 'string' &&
45538
+ const libHasMultipleEntries = typeof libOptions.entry !== 'string' &&
45513
45539
  Object.values(libOptions.entry).length > 1;
45514
- const formats = libOptions.formats || (hasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
45515
- if (formats.includes('umd') || formats.includes('iife')) {
45516
- if (hasMultipleEntries) {
45517
- throw new Error(`Multiple entry points are not supported when output formats include "umd" or "iife".`);
45518
- }
45519
- if (!libOptions.name) {
45520
- throw new Error(`Option "build.lib.name" is required when output formats ` +
45521
- `include "umd" or "iife".`);
45540
+ const libFormats = libOptions.formats ||
45541
+ (libHasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
45542
+ if (!Array.isArray(outputs)) {
45543
+ if (libFormats.includes('umd') || libFormats.includes('iife')) {
45544
+ if (libHasMultipleEntries) {
45545
+ throw new Error('Multiple entry points are not supported when output formats include "umd" or "iife".');
45546
+ }
45547
+ if (!libOptions.name) {
45548
+ throw new Error('Option "build.lib.name" is required when output formats include "umd" or "iife".');
45549
+ }
45522
45550
  }
45551
+ return libFormats.map((format) => ({ ...outputs, format }));
45523
45552
  }
45524
- if (!outputs) {
45525
- return formats.map((format) => ({ format }));
45526
- }
45527
- else if (!Array.isArray(outputs)) {
45528
- return formats.map((format) => ({ ...outputs, format }));
45529
- }
45530
- else if (libOptions.formats) {
45531
- // user explicitly specifying own output array
45532
- logger.warn(picocolors.exports.yellow(`"build.lib.formats" will be ignored because ` +
45533
- `"build.rollupOptions.output" is already an array format`));
45553
+ // By this point, we know "outputs" is an Array.
45554
+ if (libOptions.formats) {
45555
+ logger.warn(picocolors.exports.yellow('"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'));
45534
45556
  }
45557
+ outputs.forEach((output) => {
45558
+ if (['umd', 'iife'].includes(output.format) && !output.name) {
45559
+ throw new Error('Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".');
45560
+ }
45561
+ });
45535
45562
  }
45536
45563
  return outputs;
45537
45564
  }
@@ -45762,7 +45789,7 @@ function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config
45762
45789
  return toRelative(filename, hostId);
45763
45790
  }
45764
45791
  else {
45765
- return config.base + filename;
45792
+ return joinUrlSegments(config.base, filename);
45766
45793
  }
45767
45794
  }
45768
45795
  const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
@@ -55288,7 +55315,7 @@ const EventTarget = {
55288
55315
  * Register an event listener.
55289
55316
  *
55290
55317
  * @param {String} type A string representing the event type to listen for
55291
- * @param {Function} listener The listener to add
55318
+ * @param {(Function|Object)} handler The listener to add
55292
55319
  * @param {Object} [options] An options object specifies characteristics about
55293
55320
  * the event listener
55294
55321
  * @param {Boolean} [options.once=false] A `Boolean` indicating that the
@@ -55296,7 +55323,17 @@ const EventTarget = {
55296
55323
  * the listener would be automatically removed when invoked.
55297
55324
  * @public
55298
55325
  */
55299
- addEventListener(type, listener, options = {}) {
55326
+ addEventListener(type, handler, options = {}) {
55327
+ for (const listener of this.listeners(type)) {
55328
+ if (
55329
+ !options[kForOnEventAttribute$1] &&
55330
+ listener[kListener$1] === handler &&
55331
+ !listener[kForOnEventAttribute$1]
55332
+ ) {
55333
+ return;
55334
+ }
55335
+ }
55336
+
55300
55337
  let wrapper;
55301
55338
 
55302
55339
  if (type === 'message') {
@@ -55306,7 +55343,7 @@ const EventTarget = {
55306
55343
  });
55307
55344
 
55308
55345
  event[kTarget] = this;
55309
- listener.call(this, event);
55346
+ callListener(handler, this, event);
55310
55347
  };
55311
55348
  } else if (type === 'close') {
55312
55349
  wrapper = function onClose(code, message) {
@@ -55317,7 +55354,7 @@ const EventTarget = {
55317
55354
  });
55318
55355
 
55319
55356
  event[kTarget] = this;
55320
- listener.call(this, event);
55357
+ callListener(handler, this, event);
55321
55358
  };
55322
55359
  } else if (type === 'error') {
55323
55360
  wrapper = function onError(error) {
@@ -55327,21 +55364,21 @@ const EventTarget = {
55327
55364
  });
55328
55365
 
55329
55366
  event[kTarget] = this;
55330
- listener.call(this, event);
55367
+ callListener(handler, this, event);
55331
55368
  };
55332
55369
  } else if (type === 'open') {
55333
55370
  wrapper = function onOpen() {
55334
55371
  const event = new Event('open');
55335
55372
 
55336
55373
  event[kTarget] = this;
55337
- listener.call(this, event);
55374
+ callListener(handler, this, event);
55338
55375
  };
55339
55376
  } else {
55340
55377
  return;
55341
55378
  }
55342
55379
 
55343
55380
  wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
55344
- wrapper[kListener$1] = listener;
55381
+ wrapper[kListener$1] = handler;
55345
55382
 
55346
55383
  if (options.once) {
55347
55384
  this.once(type, wrapper);
@@ -55354,7 +55391,7 @@ const EventTarget = {
55354
55391
  * Remove an event listener.
55355
55392
  *
55356
55393
  * @param {String} type A string representing the event type to remove
55357
- * @param {Function} handler The listener to remove
55394
+ * @param {(Function|Object)} handler The listener to remove
55358
55395
  * @public
55359
55396
  */
55360
55397
  removeEventListener(type, handler) {
@@ -55375,6 +55412,22 @@ var eventTarget = {
55375
55412
  MessageEvent
55376
55413
  };
55377
55414
 
55415
+ /**
55416
+ * Call an event listener
55417
+ *
55418
+ * @param {(Function|Object)} listener The listener to call
55419
+ * @param {*} thisArg The value to use as `this`` when calling the listener
55420
+ * @param {Event} event The event to pass to the listener
55421
+ * @private
55422
+ */
55423
+ function callListener(listener, thisArg, event) {
55424
+ if (typeof listener === 'object' && listener.handleEvent) {
55425
+ listener.handleEvent.call(listener, event);
55426
+ } else {
55427
+ listener.call(thisArg, event);
55428
+ }
55429
+ }
55430
+
55378
55431
  const { tokenChars: tokenChars$1 } = validation.exports;
55379
55432
 
55380
55433
  /**
@@ -57668,18 +57721,18 @@ function createWebSocketServer(server, config, httpsOptions) {
57668
57721
  };
57669
57722
  }
57670
57723
 
57671
- // this middleware is only active when (config.base !== '/')
57724
+ // this middleware is only active when (base !== '/')
57672
57725
  function baseMiddleware({ config }) {
57673
- const devBase = config.base.endsWith('/') ? config.base : config.base + '/';
57674
57726
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
57675
57727
  return function viteBaseMiddleware(req, res, next) {
57676
57728
  const url = req.url;
57677
57729
  const parsed = new URL(url, 'http://vitejs.dev');
57678
57730
  const path = parsed.pathname || '/';
57679
- if (path.startsWith(devBase)) {
57731
+ const base = config.rawBase;
57732
+ if (path.startsWith(base)) {
57680
57733
  // rewrite url to remove base. this ensures that other middleware does
57681
57734
  // not need to consider base being prepended or not
57682
- req.url = url.replace(devBase, '/');
57735
+ req.url = stripBase(url, base);
57683
57736
  return next();
57684
57737
  }
57685
57738
  // skip redirect and error fallback on middleware mode, #4057
@@ -57689,18 +57742,18 @@ function baseMiddleware({ config }) {
57689
57742
  if (path === '/' || path === '/index.html') {
57690
57743
  // redirect root visit to based url with search and hash
57691
57744
  res.writeHead(302, {
57692
- Location: config.base + (parsed.search || '') + (parsed.hash || '')
57745
+ Location: base + (parsed.search || '') + (parsed.hash || '')
57693
57746
  });
57694
57747
  res.end();
57695
57748
  return;
57696
57749
  }
57697
57750
  else if (req.headers.accept?.includes('text/html')) {
57698
57751
  // non-based page visit
57699
- const redirectPath = joinUrlSegments(config.base, url);
57752
+ const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
57700
57753
  res.writeHead(404, {
57701
57754
  'Content-Type': 'text/html'
57702
57755
  });
57703
- res.end(`The server is configured with a public base URL of ${config.base} - ` +
57756
+ res.end(`The server is configured with a public base URL of ${base} - ` +
57704
57757
  `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
57705
57758
  return;
57706
57759
  }
@@ -60145,6 +60198,10 @@ function transformMiddleware(server) {
60145
60198
  // error but a normal part of the missing deps discovery flow
60146
60199
  return;
60147
60200
  }
60201
+ if (e?.code === ERR_LOAD_URL) {
60202
+ // Let other middleware handle if we can't load the url via transformRequest
60203
+ return next();
60204
+ }
60148
60205
  return next(e);
60149
60206
  }
60150
60207
  next();
@@ -61936,28 +61993,12 @@ async function startServer(server, inlinePort, isRestart = false) {
61936
61993
  const port = inlinePort ?? options.port ?? 5173;
61937
61994
  const hostname = await resolveHostname(options.host);
61938
61995
  const protocol = options.https ? 'https' : 'http';
61939
- const info = server.config.logger.info;
61940
61996
  const serverPort = await httpServerStart(httpServer, {
61941
61997
  port,
61942
61998
  strictPort: options.strictPort,
61943
61999
  host: hostname.host,
61944
62000
  logger: server.config.logger
61945
62001
  });
61946
- // @ts-ignore
61947
- const profileSession = global.__vite_profile_session;
61948
- if (profileSession) {
61949
- profileSession.post('Profiler.stop', (err, { profile }) => {
61950
- // Write profile to disk, upload, etc.
61951
- if (!err) {
61952
- const outPath = path$o.resolve('./vite-profile.cpuprofile');
61953
- fs$l.writeFileSync(outPath, JSON.stringify(profile));
61954
- info(picocolors.exports.yellow(` CPU profile written to ${picocolors.exports.white(picocolors.exports.dim(outPath))}\n`));
61955
- }
61956
- else {
61957
- throw err;
61958
- }
61959
- });
61960
- }
61961
62002
  if (options.open && !isRestart) {
61962
62003
  const path = typeof options.open === 'string' ? options.open : server.config.base;
61963
62004
  openBrowser(path.startsWith('http')
@@ -62252,7 +62293,7 @@ async function preview(inlineConfig = {}) {
62252
62293
  // static assets
62253
62294
  const distDir = path$o.resolve(config.root, config.build.outDir);
62254
62295
  const headers = config.preview.headers;
62255
- app.use(previewBase, sirv(distDir, {
62296
+ const assetServer = sirv(distDir, {
62256
62297
  etag: true,
62257
62298
  dev: true,
62258
62299
  single: config.appType === 'spa',
@@ -62263,7 +62304,13 @@ async function preview(inlineConfig = {}) {
62263
62304
  }
62264
62305
  }
62265
62306
  }
62266
- }));
62307
+ });
62308
+ app.use(previewBase, async (req, res, next) => {
62309
+ if (shouldServe(req.url, distDir)) {
62310
+ return assetServer(req, res, next);
62311
+ }
62312
+ next();
62313
+ });
62267
62314
  // apply post server hooks from plugins
62268
62315
  postHooks.forEach((fn) => fn && fn());
62269
62316
  const options = config.preview;
@@ -62367,11 +62414,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62367
62414
  configFileDependencies = loadResult.dependencies;
62368
62415
  }
62369
62416
  }
62370
- // Define logger
62371
- const logger = createLogger(config.logLevel, {
62372
- allowClearScreen: config.clearScreen,
62373
- customLogger: config.customLogger
62374
- });
62375
62417
  // user config may provide an alternative mode. But --mode has a higher priority
62376
62418
  mode = inlineConfig.mode || config.mode || mode;
62377
62419
  configEnv.mode = mode;
@@ -62407,6 +62449,11 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62407
62449
  config.build ?? (config.build = {});
62408
62450
  config.build.commonjsOptions = { include: [] };
62409
62451
  }
62452
+ // Define logger
62453
+ const logger = createLogger(config.logLevel, {
62454
+ allowClearScreen: config.clearScreen,
62455
+ customLogger: config.customLogger
62456
+ });
62410
62457
  // resolve root
62411
62458
  const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd());
62412
62459
  const clientAlias = [
@@ -62537,7 +62584,8 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62537
62584
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
62538
62585
  inlineConfig,
62539
62586
  root: resolvedRoot,
62540
- base: resolvedBase,
62587
+ base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
62588
+ rawBase: resolvedBase,
62541
62589
  resolve: resolveOptions,
62542
62590
  publicDir: resolvedPublicDir,
62543
62591
  cacheDir,
@@ -62659,28 +62707,22 @@ function resolveBaseUrl(base = '/', isBuild, logger) {
62659
62707
  if (base.startsWith('.')) {
62660
62708
  logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
62661
62709
  `URL, ./, or an empty string.`)));
62662
- base = '/';
62710
+ return '/';
62663
62711
  }
62664
- // external URL
62665
- if (isExternalUrl(base)) {
62666
- if (!isBuild) {
62667
- // get base from full url during dev
62668
- const parsed = parse$j(base);
62669
- base = parsed.pathname || '/';
62670
- }
62712
+ // external URL flag
62713
+ const isExternal = isExternalUrl(base);
62714
+ // no leading slash warn
62715
+ if (!isExternal && !base.startsWith('/')) {
62716
+ logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should start with a slash.`)));
62671
62717
  }
62672
- else {
62718
+ // parse base when command is serve or base is not External URL
62719
+ if (!isBuild || !isExternal) {
62720
+ base = new URL(base, 'http://vitejs.dev').pathname;
62673
62721
  // ensure leading slash
62674
62722
  if (!base.startsWith('/')) {
62675
- logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should start with a slash.`)));
62676
62723
  base = '/' + base;
62677
62724
  }
62678
62725
  }
62679
- // ensure ending slash
62680
- if (!base.endsWith('/')) {
62681
- logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should end with a slash.`)));
62682
- base += '/';
62683
- }
62684
62726
  return base;
62685
62727
  }
62686
62728
  function sortUserPlugins(plugins) {
package/dist/node/cli.js CHANGED
@@ -1,9 +1,9 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
1
3
  import { performance } from 'node:perf_hooks';
2
4
  import { EventEmitter } from 'events';
3
- import { z as picocolors, v as createLogger, g as resolveConfig } from './chunks/dep-f991744a.js';
5
+ import { z as picocolors, v as createLogger, g as resolveConfig } from './chunks/dep-b8ca7cde.js';
4
6
  import { VERSION } from './constants.js';
5
- import 'node:fs';
6
- import 'node:path';
7
7
  import 'node:url';
8
8
  import 'node:module';
9
9
  import 'tty';
@@ -651,6 +651,23 @@ class CAC extends EventEmitter {
651
651
  const cac = (name = "") => new CAC(name);
652
652
 
653
653
  const cli = cac('vite');
654
+ const stopProfiler = (log) => {
655
+ // @ts-ignore
656
+ const profileSession = global.__vite_profile_session;
657
+ if (profileSession) {
658
+ profileSession.post('Profiler.stop', (err, { profile }) => {
659
+ // Write profile to disk, upload, etc.
660
+ if (!err) {
661
+ const outPath = path.resolve('./vite-profile.cpuprofile');
662
+ fs.writeFileSync(outPath, JSON.stringify(profile));
663
+ log(picocolors.exports.yellow(`CPU profile written to ${picocolors.exports.white(picocolors.exports.dim(outPath))}`));
664
+ }
665
+ else {
666
+ throw err;
667
+ }
668
+ });
669
+ }
670
+ };
654
671
  const filterDuplicateOptions = (options) => {
655
672
  for (const [key, value] of Object.entries(options)) {
656
673
  if (Array.isArray(value)) {
@@ -702,7 +719,7 @@ cli
702
719
  filterDuplicateOptions(options);
703
720
  // output structure is preserved even after bundling so require()
704
721
  // is ok here
705
- const { createServer } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.D; });
722
+ const { createServer } = await import('./chunks/dep-b8ca7cde.js').then(function (n) { return n.D; });
706
723
  try {
707
724
  const server = await createServer({
708
725
  root,
@@ -726,9 +743,14 @@ cli
726
743
  : '';
727
744
  info(`\n ${picocolors.exports.green(`${picocolors.exports.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, { clear: !server.config.logger.hasWarned });
728
745
  server.printUrls();
746
+ stopProfiler((message) => server.config.logger.info(` ${message}`));
729
747
  }
730
748
  catch (e) {
731
- createLogger(options.logLevel).error(picocolors.exports.red(`error when starting dev server:\n${e.stack}`), { error: e });
749
+ const logger = createLogger(options.logLevel);
750
+ logger.error(picocolors.exports.red(`error when starting dev server:\n${e.stack}`), {
751
+ error: e
752
+ });
753
+ stopProfiler(logger.info);
732
754
  process.exit(1);
733
755
  }
734
756
  });
@@ -750,7 +772,7 @@ cli
750
772
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
751
773
  .action(async (root, options) => {
752
774
  filterDuplicateOptions(options);
753
- const { build } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.C; });
775
+ const { build } = await import('./chunks/dep-b8ca7cde.js').then(function (n) { return n.C; });
754
776
  const buildOptions = cleanOptions(options);
755
777
  try {
756
778
  await build({
@@ -768,6 +790,9 @@ cli
768
790
  createLogger(options.logLevel).error(picocolors.exports.red(`error during build:\n${e.stack}`), { error: e });
769
791
  process.exit(1);
770
792
  }
793
+ finally {
794
+ stopProfiler((message) => createLogger(options.logLevel).info(message));
795
+ }
771
796
  });
772
797
  // optimize
773
798
  cli
@@ -775,7 +800,7 @@ cli
775
800
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
776
801
  .action(async (root, options) => {
777
802
  filterDuplicateOptions(options);
778
- const { optimizeDeps } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.B; });
803
+ const { optimizeDeps } = await import('./chunks/dep-b8ca7cde.js').then(function (n) { return n.B; });
779
804
  try {
780
805
  const config = await resolveConfig({
781
806
  root,
@@ -800,7 +825,7 @@ cli
800
825
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
801
826
  .action(async (root, options) => {
802
827
  filterDuplicateOptions(options);
803
- const { preview } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.E; });
828
+ const { preview } = await import('./chunks/dep-b8ca7cde.js').then(function (n) { return n.E; });
804
829
  try {
805
830
  const server = await preview({
806
831
  root,
@@ -825,7 +850,12 @@ cli
825
850
  createLogger(options.logLevel).error(picocolors.exports.red(`error when starting preview server:\n${e.stack}`), { error: e });
826
851
  process.exit(1);
827
852
  }
853
+ finally {
854
+ stopProfiler((message) => createLogger(options.logLevel).info(message));
855
+ }
828
856
  });
829
857
  cli.help();
830
858
  cli.version(VERSION);
831
859
  cli.parse();
860
+
861
+ export { stopProfiler };
@@ -498,9 +498,9 @@ export declare interface CSSModulesOptions {
498
498
  generateScopedName?: string | ((name: string, filename: string, css: string) => string);
499
499
  hashPrefix?: string;
500
500
  /**
501
- * default: null
501
+ * default: undefined
502
502
  */
503
- localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null;
503
+ localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
504
504
  }
505
505
 
506
506
  export declare interface CSSOptions {
@@ -1626,6 +1626,7 @@ export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'asse
1626
1626
  inlineConfig: InlineConfig;
1627
1627
  root: string;
1628
1628
  base: string;
1629
+ /* Excluded from this release type: rawBase */
1629
1630
  publicDir: string;
1630
1631
  cacheDir: string;
1631
1632
  command: 'build' | 'serve';
@@ -1,4 +1,4 @@
1
- export { b as build, q as createFilter, v as createLogger, c as createServer, e as defineConfig, f as formatPostcssSourceMap, i as getDepOptimizationConfig, j as isDepsOptimizerEnabled, l as loadConfigFromFile, x as loadEnv, k as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, h as resolveBaseUrl, g as resolveConfig, y as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-f991744a.js';
1
+ export { b as build, q as createFilter, v as createLogger, c as createServer, e as defineConfig, f as formatPostcssSourceMap, i as getDepOptimizationConfig, j as isDepsOptimizerEnabled, l as loadConfigFromFile, x as loadEnv, k as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, h as resolveBaseUrl, g as resolveConfig, y as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-b8ca7cde.js';
2
2
  export { VERSION as version } from './constants.js';
3
3
  export { version as esbuildVersion } from 'esbuild';
4
4
  export { VERSION as rollupVersion } from 'rollup';
@@ -3444,16 +3444,10 @@ function lookupFile(dir, formats, options) {
3444
3444
  return lookupFile(parentDir, formats, options);
3445
3445
  }
3446
3446
  }
3447
- /**
3448
- * Use fs.statSync(filename) instead of fs.existsSync(filename)
3449
- * #2051 if we don't have read permission on a directory, existsSync() still
3450
- * works and will result in massively slow subsequent checks (which are
3451
- * unnecessary in the first place)
3452
- */
3453
3447
  function isFileReadable(filename) {
3454
3448
  try {
3455
- const stat = fs$1.statSync(filename, { throwIfNoEntry: false });
3456
- return !!stat;
3449
+ fs$1.accessSync(filename, fs$1.constants.R_OK);
3450
+ return true;
3457
3451
  }
3458
3452
  catch {
3459
3453
  return false;
@@ -4179,10 +4173,16 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
4179
4173
  }));
4180
4174
  }));
4181
4175
  // let environment variables use each other
4182
- main({
4183
- parsed,
4176
+ const expandParsed = main({
4177
+ parsed: {
4178
+ ...process.env,
4179
+ ...parsed
4180
+ },
4184
4181
  // prevent process.env mutation
4185
4182
  ignoreProcessEnv: true
4183
+ }).parsed;
4184
+ Object.keys(parsed).forEach((key) => {
4185
+ parsed[key] = expandParsed[key];
4186
4186
  });
4187
4187
  // only keys that start with prefix are exposed to client
4188
4188
  for (const [key, value] of Object.entries(parsed)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "4.0.0-alpha.0",
3
+ "version": "4.0.0-alpha.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -61,20 +61,20 @@
61
61
  "esbuild": "^0.15.9",
62
62
  "postcss": "^8.4.18",
63
63
  "resolve": "^1.22.1",
64
- "rollup": "~3.2.3"
64
+ "rollup": "~3.3.0"
65
65
  },
66
66
  "optionalDependencies": {
67
67
  "fsevents": "~2.3.2"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@ampproject/remapping": "^2.2.0",
71
- "@babel/parser": "^7.20.0",
72
- "@babel/types": "^7.20.0",
71
+ "@babel/parser": "^7.20.2",
72
+ "@babel/types": "^7.20.2",
73
73
  "@jridgewell/trace-mapping": "^0.3.17",
74
74
  "@rollup/plugin-alias": "^4.0.2",
75
75
  "@rollup/plugin-commonjs": "^23.0.2",
76
76
  "@rollup/plugin-dynamic-import-vars": "^2.0.1",
77
- "@rollup/plugin-json": "^4.1.0",
77
+ "@rollup/plugin-json": "^5.0.1",
78
78
  "@rollup/plugin-node-resolve": "14.1.0",
79
79
  "@rollup/plugin-typescript": "^8.5.0",
80
80
  "@rollup/pluginutils": "^4.2.1",
@@ -117,10 +117,10 @@
117
117
  "strip-ansi": "^7.0.1",
118
118
  "strip-literal": "^0.4.2",
119
119
  "tsconfck": "^2.0.1",
120
- "tslib": "^2.4.0",
120
+ "tslib": "^2.4.1",
121
121
  "types": "link:./types",
122
122
  "ufo": "^0.8.6",
123
- "ws": "^8.10.0"
123
+ "ws": "^8.11.0"
124
124
  },
125
125
  "peerDependencies": {
126
126
  "@types/node": ">= 14",
package/types/alias.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export type {
2
- Alias,
3
- ResolverFunction,
4
- ResolverObject,
5
- AliasOptions
6
- } from '../dist/node'
@@ -1 +0,0 @@
1
- export type { AnymatchFn, AnymatchPattern, Matcher } from '../dist/node'
@@ -1,11 +0,0 @@
1
- export type {
2
- FSWatcher,
3
- WatchOptions,
4
- AwaitWriteFinishOptions
5
- } from '../dist/node'
6
-
7
- import type { FSWatcher, WatchOptions } from '../dist/node'
8
- export function watch(
9
- paths: string | ReadonlyArray<string>,
10
- options?: WatchOptions
11
- ): FSWatcher
@@ -1 +0,0 @@
1
- export type { RollupCommonJSOptions } from '../dist/node'
@@ -1 +0,0 @@
1
- export type { Connect } from '../dist/node'
@@ -1 +0,0 @@
1
- export type { RollupDynamicImportVarsOptions } from '../dist/node'
@@ -1 +0,0 @@
1
- export type { HttpProxy } from '../dist/node'
package/types/terser.d.ts DELETED
@@ -1 +0,0 @@
1
- export type { Terser } from '../dist/node'
package/types/ws.d.ts DELETED
@@ -1 +0,0 @@
1
- export type { WebSocket, WebSocketAlias } from '../dist/node'