vite 3.0.0-beta.8 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@ import { createHash as createHash$2 } from 'node:crypto';
22
22
  import { promisify as promisify$4 } from 'node:util';
23
23
  import { promises } from 'node:dns';
24
24
  import resolve$5 from 'resolve';
25
- import { CLIENT_ENTRY, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, OPTIMIZABLE_ENTRY_RE, VALID_ID_PREFIX, FS_PREFIX, wildcardHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, loopbackHosts, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, ESBUILD_MODULES_TARGET, CLIENT_DIR, NULL_BYTE_PLACEHOLDER, VERSION, VITE_PACKAGE_DIR, ENV_ENTRY, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
25
+ import { CLIENT_ENTRY, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, OPTIMIZABLE_ENTRY_RE, VALID_ID_PREFIX, FS_PREFIX, wildcardHosts, loopbackHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, ESBUILD_MODULES_TARGET, CLIENT_DIR, NULL_BYTE_PLACEHOLDER, VERSION, VITE_PACKAGE_DIR, ENV_ENTRY, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
26
26
  import require$$5 from 'crypto';
27
27
  import require$$0$a from 'buffer';
28
28
  import require$$0$8, { createRequire as createRequire$2 } from 'module';
@@ -12172,7 +12172,49 @@ async function resolveHostname(optionsHost) {
12172
12172
  name = localhostAddr;
12173
12173
  }
12174
12174
  }
12175
- return { host, name, implicit: optionsHost === undefined };
12175
+ return { host, name };
12176
+ }
12177
+ async function resolveServerUrls(server, options, config) {
12178
+ const address = server.address();
12179
+ const isAddressInfo = (x) => x?.address;
12180
+ if (!isAddressInfo(address)) {
12181
+ return { local: [], network: [] };
12182
+ }
12183
+ const local = [];
12184
+ const network = [];
12185
+ const hostname = await resolveHostname(options.host);
12186
+ const protocol = options.https ? 'https' : 'http';
12187
+ const port = address.port;
12188
+ const base = config.base === './' || config.base === '' ? '/' : config.base;
12189
+ if (hostname.host && loopbackHosts.has(hostname.host)) {
12190
+ let hostnameName = hostname.name;
12191
+ if (hostnameName === '::1' ||
12192
+ hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001') {
12193
+ hostnameName = `[${hostnameName}]`;
12194
+ }
12195
+ local.push(`${protocol}://${hostnameName}:${port}${base}`);
12196
+ }
12197
+ else {
12198
+ Object.values(os$3.networkInterfaces())
12199
+ .flatMap((nInterface) => nInterface ?? [])
12200
+ .filter((detail) => detail &&
12201
+ detail.address &&
12202
+ // Node < v18
12203
+ ((typeof detail.family === 'string' && detail.family === 'IPv4') ||
12204
+ // Node >= v18
12205
+ (typeof detail.family === 'number' && detail.family === 4)))
12206
+ .forEach((detail) => {
12207
+ const host = detail.address.replace('127.0.0.1', hostname.name);
12208
+ const url = `${protocol}://${host}:${port}${base}`;
12209
+ if (detail.address.includes('127.0.0.1')) {
12210
+ local.push(url);
12211
+ }
12212
+ else {
12213
+ network.push(url);
12214
+ }
12215
+ });
12216
+ }
12217
+ return { local, network };
12176
12218
  }
12177
12219
  function arraify(target) {
12178
12220
  return Array.isArray(target) ? target : [target];
@@ -12381,7 +12423,6 @@ function stripBomTag(content) {
12381
12423
  }
12382
12424
  return content;
12383
12425
  }
12384
- const isTS = (filename) => /\.[cm]?ts$/.test(filename);
12385
12426
  const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
12386
12427
  /**
12387
12428
  * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something)
@@ -12491,64 +12532,18 @@ function createLogger(level = 'info', options = {}) {
12491
12532
  };
12492
12533
  return logger;
12493
12534
  }
12494
- async function printCommonServerUrls(server, options, config) {
12495
- const address = server.address();
12496
- const isAddressInfo = (x) => x?.address;
12497
- if (isAddressInfo(address)) {
12498
- const hostname = await resolveHostname(options.host);
12499
- const protocol = options.https ? 'https' : 'http';
12500
- const base = config.base === './' || config.base === '' ? '/' : config.base;
12501
- printServerUrls(hostname, protocol, address.port, base, config.logger.info);
12535
+ function printServerUrls(urls, optionsHost, info) {
12536
+ const colorUrl = (url) => picocolors.exports.cyan(url.replace(/:(\d+)\//, (_, port) => `:${picocolors.exports.bold(port)}/`));
12537
+ for (const url of urls.local) {
12538
+ info(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Local')}: ${colorUrl(url)}`);
12502
12539
  }
12503
- }
12504
- function printServerUrls(hostname, protocol, port, base, info) {
12505
- const urls = [];
12506
- const notes = [];
12507
- if (hostname.host && loopbackHosts.has(hostname.host)) {
12508
- let hostnameName = hostname.name;
12509
- if (hostnameName === '::1' ||
12510
- hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001') {
12511
- hostnameName = `[${hostnameName}]`;
12512
- }
12513
- urls.push({
12514
- label: 'Local',
12515
- url: picocolors.exports.cyan(`${protocol}://${hostnameName}:${picocolors.exports.bold(port)}${base}`)
12516
- });
12517
- if (hostname.implicit) {
12518
- urls.push({
12519
- label: 'Network',
12520
- url: `use ${picocolors.exports.white(picocolors.exports.bold('--host'))} to expose`,
12521
- disabled: true
12522
- });
12523
- }
12540
+ for (const url of urls.network) {
12541
+ info(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Network')}: ${colorUrl(url)}`);
12524
12542
  }
12525
- else {
12526
- Object.values(os$3.networkInterfaces())
12527
- .flatMap((nInterface) => nInterface ?? [])
12528
- .filter((detail) => detail &&
12529
- detail.address &&
12530
- // Node < v18
12531
- ((typeof detail.family === 'string' && detail.family === 'IPv4') ||
12532
- // Node >= v18
12533
- (typeof detail.family === 'number' && detail.family === 4)))
12534
- .forEach((detail) => {
12535
- const host = detail.address.replace('127.0.0.1', hostname.name);
12536
- const url = `${protocol}://${host}:${picocolors.exports.bold(port)}${base}`;
12537
- const label = detail.address.includes('127.0.0.1') ? 'Local' : 'Network';
12538
- urls.push({ label, url: picocolors.exports.cyan(url) });
12539
- });
12543
+ if (urls.network.length === 0 && optionsHost === undefined) {
12544
+ const note = `use ${picocolors.exports.white(picocolors.exports.bold('--host'))} to expose`;
12545
+ info(picocolors.exports.dim(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Network')}: ${note}`));
12540
12546
  }
12541
- const length = Math.max(...[...urls, ...notes].map(({ label }) => label.length));
12542
- const print = (iconWithColor, label, messageWithColor, disabled) => {
12543
- const message = ` ${iconWithColor} ${label ? picocolors.exports.bold(label) + ':' : ' '} ${' '.repeat(length - label.length)}${messageWithColor}`;
12544
- info(disabled ? picocolors.exports.dim(message) : message);
12545
- };
12546
- urls.forEach(({ label, url: text, disabled }) => {
12547
- print(picocolors.exports.green('➜'), label, text, disabled);
12548
- });
12549
- notes.forEach(({ label, message: text }) => {
12550
- print(picocolors.exports.white('❖'), label, text);
12551
- });
12552
12547
  }
12553
12548
 
12554
12549
  const writeColors = {
@@ -13343,7 +13338,11 @@ function esbuildPlugin(options = {}) {
13343
13338
  minifyIdentifiers: false,
13344
13339
  minifySyntax: false,
13345
13340
  minifyWhitespace: false,
13346
- treeShaking: false
13341
+ treeShaking: false,
13342
+ // keepNames is not needed when minify is disabled.
13343
+ // Also transforming multiple times with keepNames enabled breaks
13344
+ // tree-shaking. (#9164)
13345
+ keepNames: false
13347
13346
  };
13348
13347
  return {
13349
13348
  name: 'vite:esbuild',
@@ -13438,10 +13437,19 @@ function resolveEsbuildTranspileOptions(config, format) {
13438
13437
  // pure annotations and break tree-shaking
13439
13438
  // https://github.com/vuejs/core/issues/2860#issuecomment-926882793
13440
13439
  const isEsLibBuild = config.build.lib && format === 'es';
13440
+ const esbuildOptions = config.esbuild || {};
13441
13441
  const options = {
13442
- ...config.esbuild,
13442
+ ...esbuildOptions,
13443
13443
  target: target || undefined,
13444
- format: rollupToEsbuildFormatMap[format]
13444
+ format: rollupToEsbuildFormatMap[format],
13445
+ // the final build should always support dynamic import and import.meta.
13446
+ // if they need to be polyfilled, plugin-legacy should be used.
13447
+ // plugin-legacy detects these two features when checking for modern code.
13448
+ supported: {
13449
+ 'dynamic-import': true,
13450
+ 'import-meta': true,
13451
+ ...esbuildOptions.supported
13452
+ }
13445
13453
  };
13446
13454
  // If no minify, disable all minify options
13447
13455
  if (!minify) {
@@ -13560,11 +13568,14 @@ function reloadOnTsconfigChange(changedFile) {
13560
13568
  server.moduleGraph.invalidateAll();
13561
13569
  // reset tsconfck so that recompile works with up2date configs
13562
13570
  initTSConfck(server.config).finally(() => {
13563
- // force full reload
13564
- server.ws.send({
13565
- type: 'full-reload',
13566
- path: '*'
13567
- });
13571
+ // server may not be available if vite config is updated at the same time
13572
+ if (server) {
13573
+ // force full reload
13574
+ server.ws.send({
13575
+ type: 'full-reload',
13576
+ path: '*'
13577
+ });
13578
+ }
13568
13579
  });
13569
13580
  }
13570
13581
  }
@@ -33906,6 +33917,16 @@ function resolvePlugin(resolveOptions) {
33906
33917
  return res;
33907
33918
  }
33908
33919
  }
33920
+ // drive relative fs paths (only windows)
33921
+ if (isWindows$4 && id.startsWith('/')) {
33922
+ const basedir = importer ? path$n.dirname(importer) : process.cwd();
33923
+ const fsPath = path$n.resolve(basedir, id);
33924
+ if ((res = tryFsResolve(fsPath, options))) {
33925
+ isDebug$4 &&
33926
+ debug$c(`[drive-relative] ${picocolors.exports.cyan(id)} -> ${picocolors.exports.dim(res)}`);
33927
+ return res;
33928
+ }
33929
+ }
33909
33930
  // absolute fs paths
33910
33931
  if (isNonDriveRelativeAbsolutePath(id) &&
33911
33932
  (res = tryFsResolve(id, options))) {
@@ -36207,41 +36228,41 @@ async function createDepsOptimizer(config, server) {
36207
36228
  }
36208
36229
  if (!isBuild) {
36209
36230
  // Important, the scanner is dev only
36210
- runScanner();
36211
- }
36212
- }
36213
- async function runScanner() {
36214
- const scanPhaseProcessing = newDepOptimizationProcessing();
36215
- depsOptimizer.scanProcessing = scanPhaseProcessing.promise;
36216
- try {
36217
- debuggerViteDeps(picocolors.exports.green(`scanning for dependencies...`));
36218
- const deps = await discoverProjectDependencies(config);
36219
- debuggerViteDeps(picocolors.exports.green(Object.keys(deps).length > 0
36220
- ? `dependencies found by scanner: ${depsLogString(Object.keys(deps))}`
36221
- : `no dependencies found by scanner`));
36222
- // Add these dependencies to the discovered list, as these are currently
36223
- // used by the preAliasPlugin to support aliased and optimized deps.
36224
- // This is also used by the CJS externalization heuristics in legacy mode
36225
- for (const id of Object.keys(deps)) {
36226
- if (!metadata.discovered[id]) {
36227
- addMissingDep(id, deps[id]);
36228
- }
36229
- }
36230
- if (!isBuild) {
36231
- const knownDeps = prepareKnownDeps();
36232
- // For dev, we run the scanner and the first optimization
36233
- // run on the background, but we wait until crawling has ended
36234
- // to decide if we send this result to the browser or we need to
36235
- // do another optimize step
36236
- postScanOptimizationResult = runOptimizeDeps(config, knownDeps);
36237
- }
36238
- }
36239
- catch (e) {
36240
- logger.error(e.message);
36241
- }
36242
- finally {
36243
- scanPhaseProcessing.resolve();
36244
- depsOptimizer.scanProcessing = undefined;
36231
+ const scanPhaseProcessing = newDepOptimizationProcessing();
36232
+ depsOptimizer.scanProcessing = scanPhaseProcessing.promise;
36233
+ // Ensure server listen is called before the scanner
36234
+ setTimeout(async () => {
36235
+ try {
36236
+ debuggerViteDeps(picocolors.exports.green(`scanning for dependencies...`));
36237
+ const deps = await discoverProjectDependencies(config);
36238
+ debuggerViteDeps(picocolors.exports.green(Object.keys(deps).length > 0
36239
+ ? `dependencies found by scanner: ${depsLogString(Object.keys(deps))}`
36240
+ : `no dependencies found by scanner`));
36241
+ // Add these dependencies to the discovered list, as these are currently
36242
+ // used by the preAliasPlugin to support aliased and optimized deps.
36243
+ // This is also used by the CJS externalization heuristics in legacy mode
36244
+ for (const id of Object.keys(deps)) {
36245
+ if (!metadata.discovered[id]) {
36246
+ addMissingDep(id, deps[id]);
36247
+ }
36248
+ }
36249
+ if (!isBuild) {
36250
+ const knownDeps = prepareKnownDeps();
36251
+ // For dev, we run the scanner and the first optimization
36252
+ // run on the background, but we wait until crawling has ended
36253
+ // to decide if we send this result to the browser or we need to
36254
+ // do another optimize step
36255
+ postScanOptimizationResult = runOptimizeDeps(config, knownDeps);
36256
+ }
36257
+ }
36258
+ catch (e) {
36259
+ logger.error(e.message);
36260
+ }
36261
+ finally {
36262
+ scanPhaseProcessing.resolve();
36263
+ depsOptimizer.scanProcessing = undefined;
36264
+ }
36265
+ }, 0);
36245
36266
  }
36246
36267
  }
36247
36268
  async function startNextDiscoveredBatch() {
@@ -36658,7 +36679,8 @@ const isDebugEnabled = _debug('vite:deps').enabled;
36658
36679
  const jsExtensionRE = /\.js$/i;
36659
36680
  const jsMapExtensionRE = /\.js\.map$/i;
36660
36681
  /**
36661
- * Used by Vite CLI when running `vite optimize`
36682
+ * Scan and optimize dependencies within a project.
36683
+ * Used by Vite CLI when running `vite optimize`.
36662
36684
  */
36663
36685
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
36664
36686
  const log = asCommand ? config.logger.info : debug$a;
@@ -37958,18 +37980,26 @@ function createIsConfiguredAsSsrExternal(config) {
37958
37980
  const noExternalFilter = noExternal !== 'undefined' &&
37959
37981
  typeof noExternal !== 'boolean' &&
37960
37982
  createFilter(undefined, noExternal, { resolve: false });
37983
+ // Returns true if it is configured as external, false if it is filtered
37984
+ // by noExternal and undefined if it isn't affected by the explicit config
37961
37985
  return (id) => {
37962
37986
  const { ssr } = config;
37963
- if (!ssr || ssr.external?.includes(id)) {
37964
- return true;
37965
- }
37966
- if (typeof noExternal === 'boolean') {
37967
- return !noExternal;
37968
- }
37969
- if (noExternalFilter) {
37970
- return noExternalFilter(id);
37987
+ if (ssr) {
37988
+ const pkgName = getNpmPackageName(id);
37989
+ if (!pkgName) {
37990
+ return undefined;
37991
+ }
37992
+ if (ssr.external?.includes(pkgName)) {
37993
+ return true;
37994
+ }
37995
+ if (typeof noExternal === 'boolean') {
37996
+ return !noExternal;
37997
+ }
37998
+ if (noExternalFilter && !noExternalFilter(pkgName)) {
37999
+ return false;
38000
+ }
37971
38001
  }
37972
- return true;
38002
+ return undefined;
37973
38003
  };
37974
38004
  }
37975
38005
  function createIsSsrExternal(config) {
@@ -37993,9 +38023,11 @@ function createIsSsrExternal(config) {
37993
38023
  if (processedIds.has(id)) {
37994
38024
  return processedIds.get(id);
37995
38025
  }
37996
- const external = !id.startsWith('.') &&
37997
- !path$n.isAbsolute(id) &&
37998
- (isBuiltin(id) || (isConfiguredAsExternal(id) && isValidPackageEntry(id)));
38026
+ let external = false;
38027
+ if (!id.startsWith('.') && !path$n.isAbsolute(id)) {
38028
+ external =
38029
+ isBuiltin(id) || (isConfiguredAsExternal(id) ?? isValidPackageEntry(id));
38030
+ }
37999
38031
  processedIds.set(id, external);
38000
38032
  return external;
38001
38033
  };
@@ -38777,11 +38809,11 @@ const ssrImportKey = `__vite_ssr_import__`;
38777
38809
  const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
38778
38810
  const ssrExportAllKey = `__vite_ssr_exportAll__`;
38779
38811
  const ssrImportMetaKey = `__vite_ssr_import_meta__`;
38780
- async function ssrTransform(code, inMap, url, options) {
38812
+ async function ssrTransform(code, inMap, url, originalCode, options) {
38781
38813
  if (options?.json?.stringify && isJSONRequest(url)) {
38782
38814
  return ssrTransformJSON(code, inMap);
38783
38815
  }
38784
- return ssrTransformScript(code, inMap, url);
38816
+ return ssrTransformScript(code, inMap, url, originalCode);
38785
38817
  }
38786
38818
  async function ssrTransformJSON(code, inMap) {
38787
38819
  return {
@@ -38791,7 +38823,7 @@ async function ssrTransformJSON(code, inMap) {
38791
38823
  dynamicDeps: []
38792
38824
  };
38793
38825
  }
38794
- async function ssrTransformScript(code, inMap, url) {
38826
+ async function ssrTransformScript(code, inMap, url, originalCode) {
38795
38827
  const s = new MagicString(code);
38796
38828
  let ast;
38797
38829
  try {
@@ -38970,11 +39002,13 @@ async function ssrTransformScript(code, inMap, url) {
38970
39002
  sourcesContent: inMap.sourcesContent
38971
39003
  },
38972
39004
  inMap
38973
- ]);
39005
+ ], false);
38974
39006
  }
38975
39007
  else {
38976
39008
  map.sources = [url];
38977
- map.sourcesContent = [code];
39009
+ // needs to use originalCode instead of code
39010
+ // because code might be already transformed even if map is null
39011
+ map.sourcesContent = [originalCode];
38978
39012
  }
38979
39013
  return {
38980
39014
  code: s.toString(),
@@ -39736,6 +39770,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
39736
39770
  inMap: map,
39737
39771
  ssr
39738
39772
  });
39773
+ const originalCode = code;
39739
39774
  if (transformResult == null ||
39740
39775
  (isObject$2(transformResult) && transformResult.code == null)) {
39741
39776
  // no transform applied, keep code as-is
@@ -39754,7 +39789,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
39754
39789
  }
39755
39790
  }
39756
39791
  const result = ssr
39757
- ? await ssrTransform(code, map, url, {
39792
+ ? await ssrTransform(code, map, url, originalCode, {
39758
39793
  json: { stringify: !!server.config.json?.stringify }
39759
39794
  })
39760
39795
  : {
@@ -40100,7 +40135,7 @@ function importAnalysisPlugin(config) {
40100
40135
  if (ssr) {
40101
40136
  return [url, url];
40102
40137
  }
40103
- this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40138
+ return this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40104
40139
  }
40105
40140
  const isRelative = url.startsWith('.');
40106
40141
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
@@ -40646,7 +40681,7 @@ function buildImportAnalysisPlugin(config) {
40646
40681
  if (ssr) {
40647
40682
  return [url, url];
40648
40683
  }
40649
- this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40684
+ return this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40650
40685
  }
40651
40686
  // normalize all imports into resolved URLs
40652
40687
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
@@ -41021,7 +41056,7 @@ const assetAttrsConfig = {
41021
41056
  const isAsyncScriptMap = new WeakMap();
41022
41057
  async function traverseHtml(html, filePath, visitor) {
41023
41058
  // lazy load compiler
41024
- const { parse, transform } = await import('./dep-001f95ce.js').then(function (n) { return n.c; });
41059
+ const { parse, transform } = await import('./dep-7d66befd.js').then(function (n) { return n.c; });
41025
41060
  // @vue/compiler-core doesn't like lowercase doctypes
41026
41061
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
41027
41062
  try {
@@ -42151,7 +42186,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
42151
42186
  logger: config.logger
42152
42187
  }));
42153
42188
  if (isModule) {
42154
- postcssPlugins.unshift((await import('./dep-0921e73a.js').then(function (n) { return n.i; })).default({
42189
+ postcssPlugins.unshift((await import('./dep-adbb28b2.js').then(function (n) { return n.i; })).default({
42155
42190
  ...modulesOptions,
42156
42191
  getJSON(cssFileName, _modules, outputFileName) {
42157
42192
  modules = _modules;
@@ -43347,10 +43382,10 @@ async function doBuild(inlineConfig = {}) {
43347
43382
  ? `[name].${jsExt}`
43348
43383
  : libOptions
43349
43384
  ? resolveLibFilename(libOptions, format, config.root, jsExt)
43350
- : path$n.posix.join(options.assetsDir, `[name].[hash].js`),
43385
+ : path$n.posix.join(options.assetsDir, `[name].[hash].${jsExt}`),
43351
43386
  chunkFileNames: libOptions
43352
43387
  ? `[name].[hash].${jsExt}`
43353
- : path$n.posix.join(options.assetsDir, `[name].[hash].js`),
43388
+ : path$n.posix.join(options.assetsDir, `[name].[hash].${jsExt}`),
43354
43389
  assetFileNames: libOptions
43355
43390
  ? `[name].[ext]`
43356
43391
  : path$n.posix.join(options.assetsDir, `[name].[hash].[ext]`),
@@ -56927,16 +56962,29 @@ function proxyMiddleware(httpServer, options, config) {
56927
56962
  opts = { target: opts, changeOrigin: true };
56928
56963
  }
56929
56964
  const proxy = httpProxy.createProxyServer(opts);
56930
- proxy.on('error', (err, req, res) => {
56931
- config.logger.error(`${picocolors.exports.red(`http proxy error:`)}\n${err.stack}`, {
56932
- timestamp: true,
56933
- error: err
56934
- });
56935
- res
56936
- .writeHead(500, {
56937
- 'Content-Type': 'text/plain'
56938
- })
56939
- .end();
56965
+ proxy.on('error', (err, req, originalRes) => {
56966
+ // When it is ws proxy, res is net.Socket
56967
+ const res = originalRes;
56968
+ if ('req' in res) {
56969
+ config.logger.error(`${picocolors.exports.red(`http proxy error:`)}\n${err.stack}`, {
56970
+ timestamp: true,
56971
+ error: err
56972
+ });
56973
+ if (!res.writableEnded) {
56974
+ res
56975
+ .writeHead(500, {
56976
+ 'Content-Type': 'text/plain'
56977
+ })
56978
+ .end();
56979
+ }
56980
+ }
56981
+ else {
56982
+ config.logger.error(`${picocolors.exports.red(`ws proxy error:`)}\n${err.stack}`, {
56983
+ timestamp: true,
56984
+ error: err
56985
+ });
56986
+ res.end();
56987
+ }
56940
56988
  });
56941
56989
  if (opts.configure) {
56942
56990
  opts.configure(proxy, opts);
@@ -58924,8 +58972,9 @@ async function createServer(inlineConfig = {}) {
58924
58972
  pluginContainer: container,
58925
58973
  ws,
58926
58974
  moduleGraph,
58975
+ resolvedUrls: null,
58927
58976
  ssrTransform(code, inMap, url) {
58928
- return ssrTransform(code, inMap, url, {
58977
+ return ssrTransform(code, inMap, url, code, {
58929
58978
  json: { stringify: server.config.json?.stringify }
58930
58979
  });
58931
58980
  },
@@ -58949,8 +58998,12 @@ async function createServer(inlineConfig = {}) {
58949
58998
  ssrRewriteStacktrace(stack) {
58950
58999
  return ssrRewriteStacktrace(stack, moduleGraph);
58951
59000
  },
58952
- listen(port, isRestart) {
58953
- return startServer(server, port, isRestart);
59001
+ async listen(port, isRestart) {
59002
+ await startServer(server, port, isRestart);
59003
+ if (httpServer) {
59004
+ server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config);
59005
+ }
59006
+ return server;
58954
59007
  },
58955
59008
  async close() {
58956
59009
  if (!middlewareMode) {
@@ -58965,14 +59018,18 @@ async function createServer(inlineConfig = {}) {
58965
59018
  container.close(),
58966
59019
  closeHttpServer()
58967
59020
  ]);
59021
+ server.resolvedUrls = null;
58968
59022
  },
58969
- async printUrls() {
58970
- if (httpServer) {
58971
- await printCommonServerUrls(httpServer, config.server, config);
59023
+ printUrls() {
59024
+ if (server.resolvedUrls) {
59025
+ printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
58972
59026
  }
58973
- else {
59027
+ else if (middlewareMode) {
58974
59028
  throw new Error('cannot print server URLs in middleware mode.');
58975
59029
  }
59030
+ else {
59031
+ throw new Error('cannot print server URLs before server.listen is called.');
59032
+ }
58976
59033
  },
58977
59034
  async restart(forceOptimize) {
58978
59035
  if (!server._restartPromise) {
@@ -59181,7 +59238,6 @@ async function startServer(server, inlinePort, isRestart = false) {
59181
59238
  ? path
59182
59239
  : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger);
59183
59240
  }
59184
- return server;
59185
59241
  }
59186
59242
  function createServerCloseFn(server) {
59187
59243
  if (!server) {
@@ -59488,6 +59544,7 @@ async function preview(inlineConfig = {}) {
59488
59544
  host: hostname.host,
59489
59545
  logger
59490
59546
  });
59547
+ const resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
59491
59548
  if (options.open) {
59492
59549
  const path = typeof options.open === 'string' ? options.open : previewBase;
59493
59550
  openBrowser(path.startsWith('http')
@@ -59497,8 +59554,9 @@ async function preview(inlineConfig = {}) {
59497
59554
  return {
59498
59555
  config,
59499
59556
  httpServer,
59500
- async printUrls() {
59501
- await printCommonServerUrls(httpServer, config.preview, config);
59557
+ resolvedUrls,
59558
+ printUrls() {
59559
+ printServerUrls(resolvedUrls, options.host, logger.info);
59502
59560
  }
59503
59561
  };
59504
59562
  }
@@ -59521,6 +59579,10 @@ function clientInjectionsPlugin(config) {
59521
59579
  name: 'vite:client-inject',
59522
59580
  async transform(code, id, options) {
59523
59581
  if (id === normalizedClientEntry || id === normalizedEnvEntry) {
59582
+ const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
59583
+ const resolvedServerPort = config.server.port;
59584
+ const devBase = config.base;
59585
+ const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
59524
59586
  let hmrConfig = config.server.hmr;
59525
59587
  hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
59526
59588
  const host = hmrConfig?.host || null;
@@ -59533,9 +59595,8 @@ function clientInjectionsPlugin(config) {
59533
59595
  if (config.server.middlewareMode) {
59534
59596
  port || (port = 24678);
59535
59597
  }
59536
- const devBase = config.base;
59537
- let directTarget = hmrConfig?.host || (await resolveHostname(config.server.host)).name;
59538
- directTarget += `:${hmrConfig?.port || config.server.port}`;
59598
+ let directTarget = hmrConfig?.host || resolvedServerHostname;
59599
+ directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
59539
59600
  directTarget += devBase;
59540
59601
  let hmrBase = devBase;
59541
59602
  if (hmrConfig?.path) {
@@ -59545,6 +59606,7 @@ function clientInjectionsPlugin(config) {
59545
59606
  .replace(`__MODE__`, JSON.stringify(config.mode))
59546
59607
  .replace(`__BASE__`, JSON.stringify(devBase))
59547
59608
  .replace(`__DEFINES__`, serializeDefine(config.define || {}))
59609
+ .replace(`__SERVER_HOST__`, JSON.stringify(serverHost))
59548
59610
  .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
59549
59611
  .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
59550
59612
  .replace(`__HMR_PORT__`, JSON.stringify(port))
@@ -62238,7 +62300,6 @@ function defineConfig(config) {
62238
62300
  return config;
62239
62301
  }
62240
62302
  async function resolveConfig(inlineConfig, command, defaultMode = 'development') {
62241
- var _a;
62242
62303
  let config = inlineConfig;
62243
62304
  let configFileDependencies = [];
62244
62305
  let mode = inlineConfig.mode || defaultMode;
@@ -62248,6 +62309,10 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62248
62309
  if (mode === 'production') {
62249
62310
  process.env.NODE_ENV = 'production';
62250
62311
  }
62312
+ // production env would not work in serve, fallback to development
62313
+ if (command === 'serve' && process.env.NODE_ENV === 'production') {
62314
+ process.env.NODE_ENV = 'development';
62315
+ }
62251
62316
  const configEnv = {
62252
62317
  mode,
62253
62318
  command,
@@ -62302,6 +62367,14 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62302
62367
  }
62303
62368
  }
62304
62369
  }
62370
+ if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) {
62371
+ config = mergeConfig(config, {
62372
+ optimizeDeps: { disabled: false },
62373
+ ssr: { optimizeDeps: { disabled: false } }
62374
+ });
62375
+ config.build ?? (config.build = {});
62376
+ config.build.commonjsOptions = { include: [] };
62377
+ }
62305
62378
  // resolve root
62306
62379
  const resolvedRoot = normalizePath$3(config.root ? path$n.resolve(config.root) : process.cwd());
62307
62380
  const clientAlias = [
@@ -62401,15 +62474,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62401
62474
  const ssr = resolveSSROptions(config.ssr, config.legacy?.buildSsrCjsExternalHeuristics, config.resolve?.preserveSymlinks);
62402
62475
  const middlewareMode = config?.server?.middlewareMode;
62403
62476
  const optimizeDeps = config.optimizeDeps || {};
62404
- if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) {
62405
- config.build ?? (config.build = {});
62406
- config.build.commonjsOptions = { include: [] };
62407
- config.optimizeDeps ?? (config.optimizeDeps = {});
62408
- config.optimizeDeps.disabled = false;
62409
- config.ssr ?? (config.ssr = {});
62410
- (_a = config.ssr).optimizeDeps ?? (_a.optimizeDeps = {});
62411
- config.ssr.optimizeDeps.disabled = false;
62412
- }
62413
62477
  const BASE_URL = resolvedBase;
62414
62478
  const resolved = {
62415
62479
  ...config,
@@ -62568,7 +62632,6 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62568
62632
  const start = performance.now();
62569
62633
  const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
62570
62634
  let resolvedPath;
62571
- let dependencies = [];
62572
62635
  if (configFile) {
62573
62636
  // explicit config path is always resolved from cwd
62574
62637
  resolvedPath = path$n.resolve(configFile);
@@ -62604,41 +62667,9 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62604
62667
  catch (e) { }
62605
62668
  }
62606
62669
  try {
62607
- let userConfig;
62608
- if (isESM) {
62609
- const fileUrl = pathToFileURL(resolvedPath);
62610
- const bundled = await bundleConfigFile(resolvedPath, true);
62611
- dependencies = bundled.dependencies;
62612
- if (isTS(resolvedPath)) {
62613
- // before we can register loaders without requiring users to run node
62614
- // with --experimental-loader themselves, we have to do a hack here:
62615
- // bundle the config file w/ ts transforms first, write it to disk,
62616
- // load it with native Node ESM, then delete the file.
62617
- fs$l.writeFileSync(resolvedPath + '.mjs', bundled.code);
62618
- try {
62619
- userConfig = (await dynamicImport(`${fileUrl}.mjs?t=${Date.now()}`))
62620
- .default;
62621
- }
62622
- finally {
62623
- fs$l.unlinkSync(resolvedPath + '.mjs');
62624
- }
62625
- debug(`TS + native esm config loaded in ${getTime()}`, fileUrl);
62626
- }
62627
- else {
62628
- // using Function to avoid this from being compiled away by TS/Rollup
62629
- // append a query so that we force reload fresh config in case of
62630
- // server restart
62631
- userConfig = (await dynamicImport(`${fileUrl}?t=${Date.now()}`)).default;
62632
- debug(`native esm config loaded in ${getTime()}`, fileUrl);
62633
- }
62634
- }
62635
- if (!userConfig) {
62636
- // Bundle config file and transpile it to cjs using esbuild.
62637
- const bundled = await bundleConfigFile(resolvedPath);
62638
- dependencies = bundled.dependencies;
62639
- userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code);
62640
- debug(`bundled config file loaded in ${getTime()}`);
62641
- }
62670
+ const bundled = await bundleConfigFile(resolvedPath, isESM);
62671
+ const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM);
62672
+ debug(`bundled config file loaded in ${getTime()}`);
62642
62673
  const config = await (typeof userConfig === 'function'
62643
62674
  ? userConfig(configEnv)
62644
62675
  : userConfig);
@@ -62648,7 +62679,7 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62648
62679
  return {
62649
62680
  path: normalizePath$3(resolvedPath),
62650
62681
  config,
62651
- dependencies
62682
+ dependencies: bundled.dependencies
62652
62683
  };
62653
62684
  }
62654
62685
  catch (e) {
@@ -62656,7 +62687,9 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62656
62687
  throw e;
62657
62688
  }
62658
62689
  }
62659
- async function bundleConfigFile(fileName, isESM = false) {
62690
+ async function bundleConfigFile(fileName, isESM) {
62691
+ const dirnameVarName = '__vite_injected_original_dirname';
62692
+ const filenameVarName = '__vite_injected_original_filename';
62660
62693
  const importMetaUrlVarName = '__vite_injected_original_import_meta_url';
62661
62694
  const result = await build$3({
62662
62695
  absWorkingDir: process.cwd(),
@@ -62669,19 +62702,48 @@ async function bundleConfigFile(fileName, isESM = false) {
62669
62702
  sourcemap: 'inline',
62670
62703
  metafile: true,
62671
62704
  define: {
62705
+ __dirname: dirnameVarName,
62706
+ __filename: filenameVarName,
62672
62707
  'import.meta.url': importMetaUrlVarName
62673
62708
  },
62674
62709
  plugins: [
62675
62710
  {
62676
62711
  name: 'externalize-deps',
62677
62712
  setup(build) {
62678
- build.onResolve({ filter: /.*/ }, (args) => {
62679
- const id = args.path;
62713
+ build.onResolve({ filter: /.*/ }, ({ path: id, importer }) => {
62714
+ // externalize bare imports
62680
62715
  if (id[0] !== '.' && !path$n.isAbsolute(id)) {
62681
62716
  return {
62682
62717
  external: true
62683
62718
  };
62684
62719
  }
62720
+ // bundle the rest and make sure that the we can also access
62721
+ // it's third-party dependencies. externalize if not.
62722
+ // monorepo/
62723
+ // ├─ package.json
62724
+ // ├─ utils.js -----------> bundle (share same node_modules)
62725
+ // ├─ vite-project/
62726
+ // │ ├─ vite.config.js --> entry
62727
+ // │ ├─ package.json
62728
+ // ├─ foo-project/
62729
+ // │ ├─ utils.js --------> external (has own node_modules)
62730
+ // │ ├─ package.json
62731
+ const idFsPath = path$n.resolve(path$n.dirname(importer), id);
62732
+ const idPkgPath = lookupFile(idFsPath, [`package.json`], {
62733
+ pathOnly: true
62734
+ });
62735
+ if (idPkgPath) {
62736
+ const idPkgDir = path$n.dirname(idPkgPath);
62737
+ // if this file needs to go up one or more directory to reach the vite config,
62738
+ // that means it has it's own node_modules (e.g. foo-project)
62739
+ if (path$n.relative(idPkgDir, fileName).startsWith('..')) {
62740
+ return {
62741
+ // normalize actual import after bundled as a single vite config
62742
+ path: idFsPath,
62743
+ external: true
62744
+ };
62745
+ }
62746
+ }
62685
62747
  });
62686
62748
  }
62687
62749
  },
@@ -62690,11 +62752,11 @@ async function bundleConfigFile(fileName, isESM = false) {
62690
62752
  setup(build) {
62691
62753
  build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
62692
62754
  const contents = await fs$l.promises.readFile(args.path, 'utf8');
62693
- const injectValues = `const __dirname = ${JSON.stringify(path$n.dirname(args.path))};` +
62694
- `const __filename = ${JSON.stringify(args.path)};` +
62755
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$n.dirname(args.path))};` +
62756
+ `const ${filenameVarName} = ${JSON.stringify(args.path)};` +
62695
62757
  `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`;
62696
62758
  return {
62697
- loader: isTS(args.path) ? 'ts' : 'js',
62759
+ loader: args.path.endsWith('ts') ? 'ts' : 'js',
62698
62760
  contents: injectValues + contents
62699
62761
  };
62700
62762
  });
@@ -62709,22 +62771,40 @@ async function bundleConfigFile(fileName, isESM = false) {
62709
62771
  };
62710
62772
  }
62711
62773
  const _require = createRequire$1(import.meta.url);
62712
- async function loadConfigFromBundledFile(fileName, bundledCode) {
62713
- const realFileName = fs$l.realpathSync(fileName);
62714
- const defaultLoader = _require.extensions['.js'];
62715
- _require.extensions['.js'] = (module, filename) => {
62716
- if (filename === realFileName) {
62717
- module._compile(bundledCode, filename);
62774
+ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
62775
+ // for esm, before we can register loaders without requiring users to run node
62776
+ // with --experimental-loader themselves, we have to do a hack here:
62777
+ // write it to disk, load it with native Node ESM, then delete the file.
62778
+ if (isESM) {
62779
+ const fileUrl = pathToFileURL(fileName);
62780
+ fs$l.writeFileSync(fileName + '.mjs', bundledCode);
62781
+ try {
62782
+ return (await dynamicImport(`${fileUrl}.mjs?t=${Date.now()}`)).default;
62718
62783
  }
62719
- else {
62720
- defaultLoader(module, filename);
62784
+ finally {
62785
+ fs$l.unlinkSync(fileName + '.mjs');
62721
62786
  }
62722
- };
62723
- // clear cache in case of server restart
62724
- delete _require.cache[_require.resolve(fileName)];
62725
- const raw = _require(fileName);
62726
- _require.extensions['.js'] = defaultLoader;
62727
- return raw.__esModule ? raw.default : raw;
62787
+ }
62788
+ // for cjs, we can register a custom loader via `_require.extensions`
62789
+ else {
62790
+ const extension = path$n.extname(fileName);
62791
+ const realFileName = fs$l.realpathSync(fileName);
62792
+ const loaderExt = extension in _require.extensions ? extension : '.js';
62793
+ const defaultLoader = _require.extensions[loaderExt];
62794
+ _require.extensions[loaderExt] = (module, filename) => {
62795
+ if (filename === realFileName) {
62796
+ module._compile(bundledCode, filename);
62797
+ }
62798
+ else {
62799
+ defaultLoader(module, filename);
62800
+ }
62801
+ };
62802
+ // clear cache in case of server restart
62803
+ delete _require.cache[_require.resolve(fileName)];
62804
+ const raw = _require(fileName);
62805
+ _require.extensions[loaderExt] = defaultLoader;
62806
+ return raw.__esModule ? raw.default : raw;
62807
+ }
62728
62808
  }
62729
62809
  function getDepOptimizationConfig(config, ssr) {
62730
62810
  return ssr ? config.ssr.optimizeDeps : config.optimizeDeps;