vite 3.0.0-alpha.12 → 3.0.0-alpha.13

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 from 'postcss';
2
- import { x as commonjsGlobal } from './dep-7d4129cb.js';
2
+ import { x as commonjsGlobal } from './dep-5d9a8c71.js';
3
3
  import path$2 from 'path';
4
4
  import require$$1 from 'crypto';
5
5
  import fs__default from 'fs';
@@ -1,4 +1,4 @@
1
- import { x as commonjsGlobal } from './dep-7d4129cb.js';
1
+ import { x as commonjsGlobal } from './dep-5d9a8c71.js';
2
2
  import require$$1 from 'crypto';
3
3
  import 'fs';
4
4
  import 'path';
@@ -16,7 +16,6 @@ import 'http';
16
16
  import 'stream';
17
17
  import 'os';
18
18
  import 'child_process';
19
- import 'dns';
20
19
  import '../constants.js';
21
20
  import 'buffer';
22
21
  import 'querystring';
@@ -15,7 +15,6 @@ import require$$1$3, { STATUS_CODES } from 'http';
15
15
  import require$$0$5 from 'stream';
16
16
  import require$$1 from 'os';
17
17
  import require$$2, { execSync } from 'child_process';
18
- import { promises as promises$1 } from 'dns';
19
18
  import require$$1$2, { createHash as createHash$2 } from 'crypto';
20
19
  import { CLIENT_ENTRY, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, VALID_ID_PREFIX, FS_PREFIX, wildcardHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, loopbackHosts, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, OPTIMIZABLE_ENTRY_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, CLIENT_DIR, NULL_BYTE_PLACEHOLDER, VERSION, VITE_PACKAGE_DIR, ENV_ENTRY, DEFAULT_ASSETS_RE } from '../constants.js';
21
20
  import require$$0$6 from 'buffer';
@@ -11951,6 +11950,19 @@ function transformResult(s, id, config) {
11951
11950
  map: needSourceMap ? s.generateMap({ hires: true, source: id }) : null
11952
11951
  };
11953
11952
  }
11953
+ async function asyncFlatten(arr) {
11954
+ do {
11955
+ arr = (await Promise.all(arr)).flat(Infinity);
11956
+ } while (arr.some((v) => v?.then));
11957
+ return arr;
11958
+ }
11959
+ // strip UTF-8 BOM
11960
+ function stripBomTag(content) {
11961
+ if (content.charCodeAt(0) === 0xfeff) {
11962
+ return content.slice(1);
11963
+ }
11964
+ return content;
11965
+ }
11954
11966
 
11955
11967
  /* eslint no-console: 0 */
11956
11968
  const LogLevels = {
@@ -12073,9 +12085,10 @@ function printServerUrls(hostname, protocol, port, base, info) {
12073
12085
  url: colors$1.cyan(`${protocol}://${hostnameName}:${colors$1.bold(port)}${base}`)
12074
12086
  });
12075
12087
  if (hostname.name === 'localhost') {
12076
- notes.push({
12077
- label: 'Hint',
12078
- message: colors$1.dim(`Use ${colors$1.white(colors$1.bold('--host'))} to expose to network.`)
12088
+ urls.push({
12089
+ label: 'Network',
12090
+ url: `use ${colors$1.white(colors$1.bold('--host'))} to expose`,
12091
+ disabled: true
12079
12092
  });
12080
12093
  }
12081
12094
  }
@@ -12095,18 +12108,13 @@ function printServerUrls(hostname, protocol, port, base, info) {
12095
12108
  urls.push({ label, url: colors$1.cyan(url) });
12096
12109
  });
12097
12110
  }
12098
- if (!hostname.host || wildcardHosts.has(hostname.host)) {
12099
- notes.push({
12100
- label: 'Note',
12101
- message: colors$1.dim('You are using a wildcard host. Ports might be overridden.')
12102
- });
12103
- }
12104
12111
  const length = Math.max(...[...urls, ...notes].map(({ label }) => label.length));
12105
- const print = (iconWithColor, label, messageWithColor) => {
12106
- info(` ${iconWithColor} ${colors$1.bold(label)}: ${' '.repeat(length - label.length)}${messageWithColor}`);
12112
+ const print = (iconWithColor, label, messageWithColor, disabled) => {
12113
+ const message = ` ${iconWithColor} ${label ? colors$1.bold(label) + ':' : ' '} ${' '.repeat(length - label.length)}${messageWithColor}`;
12114
+ info(disabled ? colors$1.dim(message) : message);
12107
12115
  };
12108
- urls.forEach(({ label, url: text }) => {
12109
- print(colors$1.green('➜'), label, text);
12116
+ urls.forEach(({ label, url: text, disabled }) => {
12117
+ print(colors$1.green('➜'), label, text, disabled);
12110
12118
  });
12111
12119
  notes.forEach(({ label, message: text }) => {
12112
12120
  print(colors$1.white('❖'), label, text);
@@ -13290,11 +13298,20 @@ function manifestPlugin(config) {
13290
13298
  }
13291
13299
  return manifestChunk;
13292
13300
  }
13301
+ function createAsset(chunk) {
13302
+ return {
13303
+ file: chunk.fileName,
13304
+ src: chunk.name
13305
+ };
13306
+ }
13293
13307
  for (const file in bundle) {
13294
13308
  const chunk = bundle[file];
13295
13309
  if (chunk.type === 'chunk') {
13296
13310
  manifest[getChunkName(chunk)] = createChunk(chunk);
13297
13311
  }
13312
+ else if (chunk.type === 'asset' && typeof chunk.name === 'string') {
13313
+ manifest[chunk.name] = createAsset(chunk);
13314
+ }
13298
13315
  }
13299
13316
  outputCount++;
13300
13317
  const output = config.build.rollupOptions?.output;
@@ -14725,7 +14742,7 @@ const debug$c = createDebugger('vite:resolve-details', {
14725
14742
  onlyWhenFocused: true
14726
14743
  });
14727
14744
  function resolvePlugin(baseOptions) {
14728
- const { root, isBuild, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
14745
+ const { root, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
14729
14746
  const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {};
14730
14747
  return {
14731
14748
  name: 'vite:resolve',
@@ -14798,7 +14815,7 @@ function resolvePlugin(baseOptions) {
14798
14815
  // Optimized files could not yet exist in disk, resolve to the full path
14799
14816
  // Inject the current browserHash version if the path doesn't have one
14800
14817
  if (!normalizedFsPath.match(DEP_VERSION_RE)) {
14801
- const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
14818
+ const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata({ ssr }), normalizedFsPath)?.browserHash;
14802
14819
  if (browserHash) {
14803
14820
  return injectQuery(normalizedFsPath, `v=${browserHash}`);
14804
14821
  }
@@ -14856,9 +14873,8 @@ function resolvePlugin(baseOptions) {
14856
14873
  if (!external &&
14857
14874
  asSrc &&
14858
14875
  depsOptimizer &&
14859
- (isBuild || !ssr) &&
14860
14876
  !options.scan &&
14861
- (res = await tryOptimizedResolve(depsOptimizer, id, importer))) {
14877
+ (res = await tryOptimizedResolve(depsOptimizer, ssr, id, importer))) {
14862
14878
  return res;
14863
14879
  }
14864
14880
  if (targetWeb &&
@@ -15003,6 +15019,7 @@ function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix,
15003
15019
  const idToPkgMap = new Map();
15004
15020
  function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize) {
15005
15021
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
15022
+ ssr ?? (ssr = false);
15006
15023
  // split id by last '>' for nested selected packages, for example:
15007
15024
  // 'foo > bar > baz' => 'foo > bar' & 'baz'
15008
15025
  // 'foo' => '' & 'foo'
@@ -15129,7 +15146,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
15129
15146
  // otherwise we may introduce duplicated modules for externalized files
15130
15147
  // from pre-bundled deps.
15131
15148
  if (!isBuild) {
15132
- const versionHash = depsOptimizer.metadata.browserHash;
15149
+ const versionHash = depsOptimizer.metadata({ ssr }).browserHash;
15133
15150
  if (versionHash && isJsType) {
15134
15151
  resolved = injectQuery(resolved, `v=${versionHash}`);
15135
15152
  }
@@ -15138,7 +15155,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
15138
15155
  else {
15139
15156
  // this is a missing import, queue optimize-deps re-run and
15140
15157
  // get a resolved its optimized info
15141
- const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
15158
+ const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved, ssr);
15142
15159
  resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
15143
15160
  }
15144
15161
  if (isBuild) {
@@ -15153,9 +15170,13 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
15153
15170
  return { id: resolved };
15154
15171
  }
15155
15172
  }
15156
- async function tryOptimizedResolve(depsOptimizer, id, importer) {
15173
+ async function tryOptimizedResolve(depsOptimizer, ssr, id, importer) {
15157
15174
  await depsOptimizer.scanProcessing;
15158
- const depInfo = optimizedDepInfoFromId(depsOptimizer.metadata, id);
15175
+ const metadata = depsOptimizer.metadata({ ssr });
15176
+ if (!metadata) {
15177
+ return;
15178
+ }
15179
+ const depInfo = optimizedDepInfoFromId(metadata, id);
15159
15180
  if (depInfo) {
15160
15181
  return depsOptimizer.getOptimizedDepId(depInfo);
15161
15182
  }
@@ -15163,7 +15184,7 @@ async function tryOptimizedResolve(depsOptimizer, id, importer) {
15163
15184
  return;
15164
15185
  // further check if id is imported by nested dependency
15165
15186
  let resolvedSrc;
15166
- for (const optimizedData of depsOptimizer.metadata.depInfoList) {
15187
+ for (const optimizedData of metadata.depInfoList) {
15167
15188
  if (!optimizedData.src)
15168
15189
  continue; // Ignore chunks
15169
15190
  const pkgPath = optimizedData.id;
@@ -15575,24 +15596,30 @@ function esbuildDepPlugin(qualified, exportsData, config) {
15575
15596
  };
15576
15597
  });
15577
15598
  build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path }) => {
15578
- return {
15579
- // Return in CJS to intercept named imports. Use `Object.create` to
15580
- // create the Proxy in the prototype to workaround esbuild issue. Why?
15581
- //
15582
- // In short, esbuild cjs->esm flow:
15583
- // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
15584
- // 2. Assign props of `module.exports` to the object.
15585
- // 3. Return object for ESM use.
15586
- //
15587
- // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
15588
- // step 2 does nothing as there's no props for `module.exports`. The final object
15589
- // is just an empty object.
15590
- //
15591
- // Creating the Proxy in the prototype satisfies step 1 immediately, which means
15592
- // the returned object is a Proxy that we can intercept.
15593
- //
15594
- // Note: Skip keys that are accessed by esbuild and browser devtools.
15595
- contents: `\
15599
+ if (config.isProduction) {
15600
+ return {
15601
+ contents: 'module.exports = {}'
15602
+ };
15603
+ }
15604
+ else {
15605
+ return {
15606
+ // Return in CJS to intercept named imports. Use `Object.create` to
15607
+ // create the Proxy in the prototype to workaround esbuild issue. Why?
15608
+ //
15609
+ // In short, esbuild cjs->esm flow:
15610
+ // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
15611
+ // 2. Assign props of `module.exports` to the object.
15612
+ // 3. Return object for ESM use.
15613
+ //
15614
+ // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
15615
+ // step 2 does nothing as there's no props for `module.exports`. The final object
15616
+ // is just an empty object.
15617
+ //
15618
+ // Creating the Proxy in the prototype satisfies step 1 immediately, which means
15619
+ // the returned object is a Proxy that we can intercept.
15620
+ //
15621
+ // Note: Skip keys that are accessed by esbuild and browser devtools.
15622
+ contents: `\
15596
15623
  module.exports = Object.create(new Proxy({}, {
15597
15624
  get(_, key) {
15598
15625
  if (
@@ -15605,7 +15632,8 @@ module.exports = Object.create(new Proxy({}, {
15605
15632
  }
15606
15633
  }
15607
15634
  }))`
15608
- };
15635
+ };
15636
+ }
15609
15637
  });
15610
15638
  // yarn 2 pnp compat
15611
15639
  if (isRunningWithYarnPnp) {
@@ -27991,6 +28019,20 @@ function fileToDevUrl(id, config) {
27991
28019
  function getAssetFilename(hash, config) {
27992
28020
  return assetHashToFilenameMap.get(config)?.get(hash);
27993
28021
  }
28022
+ function resolveAssetFileNames(config) {
28023
+ const output = config.build?.rollupOptions?.output;
28024
+ const defaultAssetFileNames = path$p.posix.join(config.build.assetsDir, '[name].[hash][extname]');
28025
+ // Steps to determine which assetFileNames will be actually used.
28026
+ // First, if output is an object or string, use assetFileNames in it.
28027
+ // And a default assetFileNames as fallback.
28028
+ let assetFileNames = (output && !Array.isArray(output) ? output.assetFileNames : undefined) ??
28029
+ defaultAssetFileNames;
28030
+ if (output && Array.isArray(output)) {
28031
+ // Second, if output is an array, adopt assetFileNames in the first object.
28032
+ assetFileNames = output[0].assetFileNames ?? assetFileNames;
28033
+ }
28034
+ return assetFileNames;
28035
+ }
27994
28036
  /**
27995
28037
  * converts the source filepath of the asset to the output filename based on the assetFileNames option. \
27996
28038
  * this function imitates the behavior of rollup.js. \
@@ -28102,18 +28144,7 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
28102
28144
  const contentHash = getHash(content);
28103
28145
  const { search, hash } = parse$m(id);
28104
28146
  const postfix = (search || '') + (hash || '');
28105
- const output = config.build?.rollupOptions?.output;
28106
- const defaultAssetFileNames = path$p.posix.join(config.build.assetsDir, '[name].[hash][extname]');
28107
- // Steps to determine which assetFileNames will be actually used.
28108
- // First, if output is an object or string, use assetFileNames in it.
28109
- // And a default assetFileNames as fallback.
28110
- let assetFileNames = (output && !Array.isArray(output) ? output.assetFileNames : undefined) ??
28111
- defaultAssetFileNames;
28112
- if (output && Array.isArray(output)) {
28113
- // Second, if output is an array, adopt assetFileNames in the first object.
28114
- assetFileNames = output[0].assetFileNames ?? assetFileNames;
28115
- }
28116
- const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
28147
+ const fileName = assetFileNamesToFileName(resolveAssetFileNames(config), file, contentHash, content);
28117
28148
  if (!map.has(contentHash)) {
28118
28149
  map.set(contentHash, fileName);
28119
28150
  }
@@ -28426,6 +28457,7 @@ function jsonPlugin(options = {}, isBuild) {
28426
28457
  return null;
28427
28458
  if (SPECIAL_QUERY_RE.test(id))
28428
28459
  return null;
28460
+ json = stripBomTag(json);
28429
28461
  try {
28430
28462
  if (options.stringify) {
28431
28463
  if (isBuild) {
@@ -29468,12 +29500,21 @@ function getDepsOptimizer(config) {
29468
29500
  async function initDepsOptimizer(config, server) {
29469
29501
  const { logger } = config;
29470
29502
  const isBuild = config.command === 'build';
29471
- const scan = config.command !== 'build' && config.optimizeDeps.devScan;
29503
+ const scan = config.command !== 'build' && config.legacy?.devDepsScanner;
29472
29504
  const sessionTimestamp = Date.now().toString();
29473
29505
  const cachedMetadata = loadCachedDepOptimizationMetadata(config);
29474
29506
  let handle;
29507
+ let ssrServerDepsMetadata;
29508
+ let _metadata = cachedMetadata || initDepsOptimizerMetadata(config, sessionTimestamp);
29475
29509
  const depsOptimizer = {
29476
- metadata: cachedMetadata || initDepsOptimizerMetadata(config, sessionTimestamp),
29510
+ metadata: (options) => {
29511
+ if (isBuild || !options.ssr) {
29512
+ return _metadata;
29513
+ }
29514
+ else {
29515
+ return ssrServerDepsMetadata;
29516
+ }
29517
+ },
29477
29518
  registerMissingImport,
29478
29519
  run: () => debouncedProcessing(0),
29479
29520
  isOptimizedDepFile: (id) => isOptimizedDepFile(id, config),
@@ -29485,6 +29526,9 @@ async function initDepsOptimizer(config, server) {
29485
29526
  options: config.optimizeDeps
29486
29527
  };
29487
29528
  depsOptimizerMap.set(config, depsOptimizer);
29529
+ if (!isBuild && config.ssr) {
29530
+ ssrServerDepsMetadata = await optimizeServerSsrDeps(config);
29531
+ }
29488
29532
  let newDepsDiscovered = false;
29489
29533
  let newDepsToLog = [];
29490
29534
  let newDepsToLogHandle;
@@ -29515,7 +29559,7 @@ async function initDepsOptimizer(config, server) {
29515
29559
  if (!scan) {
29516
29560
  // Initialize discovered deps with manually added optimizeDeps.include info
29517
29561
  const discovered = await initialProjectDependencies(config, sessionTimestamp);
29518
- const { metadata } = depsOptimizer;
29562
+ const metadata = _metadata;
29519
29563
  for (const depInfo of Object.values(discovered)) {
29520
29564
  addOptimizedDepInfo(metadata, 'discovered', {
29521
29565
  ...depInfo,
@@ -29531,7 +29575,7 @@ async function initDepsOptimizer(config, server) {
29531
29575
  setTimeout(async () => {
29532
29576
  try {
29533
29577
  debuggerViteDeps(colors$1.green(`scanning for dependencies...`));
29534
- const { metadata } = depsOptimizer;
29578
+ const metadata = _metadata;
29535
29579
  const discovered = await discoverProjectDependencies(config, sessionTimestamp);
29536
29580
  // Respect the scan phase discover order to improve reproducibility
29537
29581
  for (const depInfo of Object.values(discovered)) {
@@ -29563,7 +29607,7 @@ async function initDepsOptimizer(config, server) {
29563
29607
  // Ensure that a rerun will not be issued for current discovered deps
29564
29608
  if (handle)
29565
29609
  clearTimeout(handle);
29566
- if (Object.keys(depsOptimizer.metadata.discovered).length === 0) {
29610
+ if (Object.keys(_metadata.discovered).length === 0) {
29567
29611
  currentlyProcessing = false;
29568
29612
  return;
29569
29613
  }
@@ -29571,11 +29615,11 @@ async function initDepsOptimizer(config, server) {
29571
29615
  // a succesful completion of the optimizeDeps rerun will end up
29572
29616
  // creating new bundled version of all current and discovered deps
29573
29617
  // in the cache dir and a new metadata info object assigned
29574
- // to optimizeDeps.metadata. A fullReload is only issued if
29575
- // the previous bundled dependencies have changed.
29576
- // if the rerun fails, optimizeDeps.metadata remains untouched,
29577
- // current discovered deps are cleaned, and a fullReload is issued
29578
- let { metadata } = depsOptimizer;
29618
+ // to _metadata. A fullReload is only issued if the previous bundled
29619
+ // dependencies have changed.
29620
+ // if the rerun fails, _metadata remains untouched, current discovered
29621
+ // deps are cleaned, and a fullReload is issued
29622
+ let metadata = _metadata;
29579
29623
  // All deps, previous known and newly discovered are rebundled,
29580
29624
  // respect insertion order to keep the metadata file stable
29581
29625
  const newDeps = {};
@@ -29655,7 +29699,7 @@ async function initDepsOptimizer(config, server) {
29655
29699
  if (isRerun) {
29656
29700
  newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
29657
29701
  }
29658
- metadata = depsOptimizer.metadata = newData;
29702
+ metadata = _metadata = newData;
29659
29703
  resolveEnqueuedProcessingPromises();
29660
29704
  };
29661
29705
  if (!needsReload) {
@@ -29727,7 +29771,7 @@ async function initDepsOptimizer(config, server) {
29727
29771
  // debounce time to wait for new missing deps finished, issue a new
29728
29772
  // optimization of deps (both old and newly found) once the previous
29729
29773
  // optimizeDeps processing is finished
29730
- const deps = Object.keys(depsOptimizer.metadata.discovered);
29774
+ const deps = Object.keys(_metadata.discovered);
29731
29775
  const depsString = depsLogString(deps);
29732
29776
  debuggerViteDeps(colors$1.green(`new dependencies found: ${depsString}`));
29733
29777
  runOptimizer();
@@ -29739,7 +29783,10 @@ async function initDepsOptimizer(config, server) {
29739
29783
  if (depsOptimizer.scanProcessing) {
29740
29784
  config.logger.error('Vite internal error: registering missing import before initial scanning is over');
29741
29785
  }
29742
- const { metadata } = depsOptimizer;
29786
+ if (!isBuild && ssr) {
29787
+ config.logger.error(`Error: ${id} is a missing dependency in SSR dev server, it needs to be added to optimizeDeps.include`);
29788
+ }
29789
+ const metadata = _metadata;
29743
29790
  const optimized = metadata.optimized[id];
29744
29791
  if (optimized) {
29745
29792
  return optimized;
@@ -29757,7 +29804,7 @@ async function initDepsOptimizer(config, server) {
29757
29804
  newDepsDiscovered = true;
29758
29805
  missing = addOptimizedDepInfo(metadata, 'discovered', {
29759
29806
  id,
29760
- file: getOptimizedDepPath(id, config),
29807
+ file: getOptimizedDepPath(id, config, ssr),
29761
29808
  src: resolved,
29762
29809
  // Assing a browserHash to this missing dependency that is unique to
29763
29810
  // the current state of known + missing deps. If its optimizeDeps run
@@ -29885,7 +29932,7 @@ const jsMapExtensionRE = /\.js\.map$/i;
29885
29932
  /**
29886
29933
  * Used by Vite CLI when running `vite optimize`
29887
29934
  */
29888
- async function optimizeDeps(config, force = config.force, asCommand = false) {
29935
+ async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
29889
29936
  const log = asCommand ? config.logger.info : debug$a;
29890
29937
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, force, asCommand);
29891
29938
  if (cachedMetadata) {
@@ -29898,6 +29945,31 @@ async function optimizeDeps(config, force = config.force, asCommand = false) {
29898
29945
  await result.commit();
29899
29946
  return result.metadata;
29900
29947
  }
29948
+ async function optimizeServerSsrDeps(config) {
29949
+ const cachedMetadata = loadCachedDepOptimizationMetadata(config, config.optimizeDeps.force, false, true // ssr
29950
+ );
29951
+ if (cachedMetadata) {
29952
+ return cachedMetadata;
29953
+ }
29954
+ let alsoInclude;
29955
+ let noExternalFilter;
29956
+ const noExternal = config.ssr?.noExternal;
29957
+ if (noExternal) {
29958
+ alsoInclude = arraify(noExternal).filter((ne) => typeof ne === 'string');
29959
+ noExternalFilter =
29960
+ noExternal === true
29961
+ ? (dep) => false
29962
+ : createFilter$1(noExternal, config.optimizeDeps?.exclude, {
29963
+ resolve: false
29964
+ });
29965
+ }
29966
+ const deps = {};
29967
+ await addManuallyIncludedOptimizeDeps(deps, config, alsoInclude, noExternalFilter);
29968
+ const depsInfo = toDiscoveredDependencies(config, deps, true);
29969
+ const result = await runOptimizeDeps(config, depsInfo, true);
29970
+ await result.commit();
29971
+ return result.metadata;
29972
+ }
29901
29973
  function initDepsOptimizerMetadata(config, timestamp) {
29902
29974
  const hash = getDepHash(config);
29903
29975
  return {
@@ -29918,14 +29990,14 @@ function addOptimizedDepInfo(metadata, type, depInfo) {
29918
29990
  * Creates the initial dep optimization metadata, loading it from the deps cache
29919
29991
  * if it exists and pre-bundling isn't forced
29920
29992
  */
29921
- function loadCachedDepOptimizationMetadata(config, force = config.force, asCommand = false) {
29993
+ function loadCachedDepOptimizationMetadata(config, force = config.optimizeDeps.force, asCommand = false, ssr = !!config.build.ssr) {
29922
29994
  const log = asCommand ? config.logger.info : debug$a;
29923
29995
  // Before Vite 2.9, dependencies were cached in the root of the cacheDir
29924
29996
  // For compat, we remove the cache if we find the old structure
29925
29997
  if (fs__default.existsSync(path$p.join(config.cacheDir, '_metadata.json'))) {
29926
29998
  emptyDir(config.cacheDir);
29927
29999
  }
29928
- const depsCacheDir = getDepsCacheDir(config);
30000
+ const depsCacheDir = getDepsCacheDir(config, ssr);
29929
30001
  if (!force) {
29930
30002
  let cachedMetadata;
29931
30003
  try {
@@ -29969,13 +30041,16 @@ async function discoverProjectDependencies(config, timestamp) {
29969
30041
  async function initialProjectDependencies(config, timestamp, knownDeps) {
29970
30042
  const deps = knownDeps ?? {};
29971
30043
  await addManuallyIncludedOptimizeDeps(deps, config);
30044
+ return toDiscoveredDependencies(config, deps, !!config.build.ssr, timestamp);
30045
+ }
30046
+ function toDiscoveredDependencies(config, deps, ssr, timestamp) {
29972
30047
  const browserHash = getOptimizedBrowserHash(getDepHash(config), deps, timestamp);
29973
30048
  const discovered = {};
29974
30049
  for (const id in deps) {
29975
30050
  const src = deps[id];
29976
30051
  discovered[id] = {
29977
30052
  id,
29978
- file: getOptimizedDepPath(id, config),
30053
+ file: getOptimizedDepPath(id, config, ssr),
29979
30054
  src,
29980
30055
  browserHash: browserHash,
29981
30056
  exportsData: extractExportsData(src, config)
@@ -30000,14 +30075,14 @@ function depsLogString(qualifiedIds) {
30000
30075
  * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
30001
30076
  * the metadata and start the server without waiting for the optimizeDeps processing to be completed
30002
30077
  */
30003
- async function runOptimizeDeps(resolvedConfig, depsInfo) {
30078
+ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = !!resolvedConfig.build.ssr) {
30004
30079
  const isBuild = resolvedConfig.command === 'build';
30005
30080
  const config = {
30006
30081
  ...resolvedConfig,
30007
30082
  command: 'build'
30008
30083
  };
30009
- const depsCacheDir = getDepsCacheDir(resolvedConfig);
30010
- const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig);
30084
+ const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr);
30085
+ const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr);
30011
30086
  // Create a temporal directory so we don't need to delete optimized deps
30012
30087
  // until they have been processed. This also avoids leaving the deps cache
30013
30088
  // directory in a corrupted state if there is an error
@@ -30114,7 +30189,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo) {
30114
30189
  const id = path$p
30115
30190
  .relative(processingCacheDirOutputPath, o)
30116
30191
  .replace(jsExtensionRE, '');
30117
- const file = getOptimizedDepPath(id, resolvedConfig);
30192
+ const file = getOptimizedDepPath(id, resolvedConfig, ssr);
30118
30193
  if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) {
30119
30194
  addOptimizedDepInfo(metadata, 'chunks', {
30120
30195
  id,
@@ -30135,15 +30210,15 @@ async function findKnownImports(config) {
30135
30210
  await addManuallyIncludedOptimizeDeps(deps, config);
30136
30211
  return Object.keys(deps);
30137
30212
  }
30138
- async function addManuallyIncludedOptimizeDeps(deps, config) {
30139
- const include = config.optimizeDeps?.include;
30213
+ async function addManuallyIncludedOptimizeDeps(deps, config, extra, filter) {
30214
+ const include = [...(config.optimizeDeps?.include ?? []), ...(extra ?? [])];
30140
30215
  if (include) {
30141
30216
  const resolve = config.createResolver({ asSrc: false, scan: true });
30142
30217
  for (const id of include) {
30143
30218
  // normalize 'foo >bar` as 'foo > bar' to prevent same id being added
30144
30219
  // and for pretty printing
30145
30220
  const normalizedId = normalizeId(id);
30146
- if (!deps[normalizedId]) {
30221
+ if (!deps[normalizedId] && filter?.(normalizedId) !== false) {
30147
30222
  const entry = await resolve(id);
30148
30223
  if (entry) {
30149
30224
  deps[normalizedId] = entry;
@@ -30166,36 +30241,37 @@ function newDepOptimizationProcessing() {
30166
30241
  function depsFromOptimizedDepInfo(depsInfo) {
30167
30242
  return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
30168
30243
  }
30169
- function getOptimizedDepPath(id, config) {
30170
- return normalizePath$3(path$p.resolve(getDepsCacheDir(config), flattenId(id) + '.js'));
30244
+ function getOptimizedDepPath(id, config, ssr = !!config.build.ssr) {
30245
+ return normalizePath$3(path$p.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
30171
30246
  }
30172
- function getDepsCacheSuffix(config) {
30247
+ function getDepsCacheSuffix(config, ssr) {
30173
30248
  let suffix = '';
30174
30249
  if (config.command === 'build') {
30175
30250
  // Differentiate build caches depending on outDir to allow parallel builds
30176
30251
  const { outDir } = config.build;
30177
30252
  const buildId = outDir.length > 8 || outDir.includes('/') ? getHash(outDir) : outDir;
30178
30253
  suffix += `_build-${buildId}`;
30179
- if (config.build.ssr) {
30180
- suffix += '_ssr';
30181
- }
30254
+ }
30255
+ if (ssr) {
30256
+ suffix += '_ssr';
30182
30257
  }
30183
30258
  return suffix;
30184
30259
  }
30185
- function getDepsCacheDir(config) {
30186
- const dirName = 'deps' + getDepsCacheSuffix(config);
30187
- return normalizePath$3(path$p.resolve(config.cacheDir, dirName));
30260
+ function getDepsCacheDir(config, ssr) {
30261
+ return getDepsCacheDirPrefix(config) + getDepsCacheSuffix(config, ssr);
30262
+ }
30263
+ function getProcessingDepsCacheDir(config, ssr) {
30264
+ return (getDepsCacheDirPrefix(config) + getDepsCacheSuffix(config, ssr) + '_temp');
30188
30265
  }
30189
- function getProcessingDepsCacheDir(config) {
30190
- const dirName = 'deps' + getDepsCacheSuffix(config) + '_temp';
30191
- return normalizePath$3(path$p.resolve(config.cacheDir, dirName));
30266
+ function getDepsCacheDirPrefix(config) {
30267
+ return normalizePath$3(path$p.resolve(config.cacheDir, 'deps'));
30192
30268
  }
30193
30269
  function isOptimizedDepFile(id, config) {
30194
- return id.startsWith(getDepsCacheDir(config));
30270
+ return id.startsWith(getDepsCacheDirPrefix(config));
30195
30271
  }
30196
30272
  function createIsOptimizedDepUrl(config) {
30197
30273
  const { root } = config;
30198
- const depsCacheDir = getDepsCacheDir(config);
30274
+ const depsCacheDir = getDepsCacheDirPrefix(config);
30199
30275
  // determine the url prefix of files inside cache directory
30200
30276
  const depsCacheDirRelative = normalizePath$3(path$p.relative(root, depsCacheDir));
30201
30277
  const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
@@ -30424,11 +30500,13 @@ var index$1 = {
30424
30500
  __proto__: null,
30425
30501
  debuggerViteDeps: debuggerViteDeps,
30426
30502
  optimizeDeps: optimizeDeps,
30503
+ optimizeServerSsrDeps: optimizeServerSsrDeps,
30427
30504
  initDepsOptimizerMetadata: initDepsOptimizerMetadata,
30428
30505
  addOptimizedDepInfo: addOptimizedDepInfo,
30429
30506
  loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
30430
30507
  discoverProjectDependencies: discoverProjectDependencies,
30431
30508
  initialProjectDependencies: initialProjectDependencies,
30509
+ toDiscoveredDependencies: toDiscoveredDependencies,
30432
30510
  depsLogString: depsLogString,
30433
30511
  runOptimizeDeps: runOptimizeDeps,
30434
30512
  findKnownImports: findKnownImports,
@@ -30436,6 +30514,7 @@ var index$1 = {
30436
30514
  depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
30437
30515
  getOptimizedDepPath: getOptimizedDepPath,
30438
30516
  getDepsCacheDir: getDepsCacheDir,
30517
+ getDepsCacheDirPrefix: getDepsCacheDirPrefix,
30439
30518
  isOptimizedDepFile: isOptimizedDepFile,
30440
30519
  createIsOptimizedDepUrl: createIsOptimizedDepUrl,
30441
30520
  extractExportsData: extractExportsData,
@@ -38383,7 +38462,7 @@ const assetAttrsConfig = {
38383
38462
  const isAsyncScriptMap = new WeakMap();
38384
38463
  async function traverseHtml(html, filePath, visitor) {
38385
38464
  // lazy load compiler
38386
- const { parse, transform } = await import('./dep-bb927dda.js').then(function (n) { return n.c; });
38465
+ const { parse, transform } = await import('./dep-dab76395.js').then(function (n) { return n.c; });
38387
38466
  // @vue/compiler-core doesn't like lowercase doctypes
38388
38467
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
38389
38468
  try {
@@ -39260,20 +39339,24 @@ function cssPostPlugin(config) {
39260
39339
  }
39261
39340
  return chunkCSS;
39262
39341
  }
39342
+ function ensureFileExt(name, ext) {
39343
+ return path$p.format({ ...path$p.parse(name), base: undefined, ext });
39344
+ }
39263
39345
  if (config.build.cssCodeSplit) {
39264
39346
  if (isPureCssChunk) {
39265
39347
  // this is a shared CSS-only chunk that is empty.
39266
39348
  pureCssChunks.add(chunk.fileName);
39267
39349
  }
39268
- if (opts.format === 'es' ||
39269
- opts.format === 'cjs' ||
39270
- opts.format === 'system') {
39271
- const cssAssetName = chunk.name + '.css';
39350
+ if (opts.format === 'es' || opts.format === 'cjs') {
39351
+ const cssAssetName = ensureFileExt(chunk.facadeModuleId
39352
+ ? normalizePath$3(path$p.relative(config.root, chunk.facadeModuleId))
39353
+ : chunk.name, '.css');
39272
39354
  chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
39273
39355
  chunkCSS = await finalizeCss(chunkCSS, true, config);
39274
39356
  // emit corresponding css file
39275
39357
  const fileHandle = this.emitFile({
39276
39358
  name: cssAssetName,
39359
+ fileName: assetFileNamesToFileName(resolveAssetFileNames(config), cssAssetName, getHash(chunkCSS), chunkCSS),
39277
39360
  type: 'asset',
39278
39361
  source: chunkCSS
39279
39362
  });
@@ -39320,7 +39403,7 @@ function cssPostPlugin(config) {
39320
39403
  .map((file) => path$p.basename(file))
39321
39404
  .join('|')
39322
39405
  .replace(/\./g, '\\.');
39323
- const emptyChunkRE = new RegExp(opts.format === 'es' || opts.format === 'system'
39406
+ const emptyChunkRE = new RegExp(opts.format === 'es'
39324
39407
  ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];\n?`
39325
39408
  : `\\brequire\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\);\n?`, 'g');
39326
39409
  for (const file in bundle) {
@@ -39483,7 +39566,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
39483
39566
  logger: config.logger
39484
39567
  }));
39485
39568
  if (isModule) {
39486
- postcssPlugins.unshift((await import('./dep-9b1a7a5b.js').then(function (n) { return n.i; })).default({
39569
+ postcssPlugins.unshift((await import('./dep-0115731f.js').then(function (n) { return n.i; })).default({
39487
39570
  ...modulesOptions,
39488
39571
  getJSON(cssFileName, _modules, outputFileName) {
39489
39572
  modules = _modules;
@@ -40594,8 +40677,8 @@ function createIsSsrExternal(config) {
40594
40677
  return external;
40595
40678
  };
40596
40679
  }
40597
- // When ssr.format is 'cjs', this function is used reverting to the Vite 2.9
40598
- // SSR externalization heuristics
40680
+ // When config.experimental.buildSsrCjsExternalHeuristics is enabled, this function
40681
+ // is used reverting to the Vite 2.9 SSR externalization heuristics
40599
40682
  function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
40600
40683
  const rootPkgContent = lookupFile(root, ['package.json']);
40601
40684
  if (!rootPkgContent) {
@@ -40726,10 +40809,11 @@ function optimizedDepsPlugin(config) {
40726
40809
  // this.load({ id }) isn't implemented in PluginContainer
40727
40810
  // The logic to register an id to wait until it is processed
40728
40811
  // is in importAnalysis, see call to delayDepsOptimizerUntil
40729
- async load(id) {
40812
+ async load(id, options) {
40813
+ const ssr = options?.ssr ?? false;
40730
40814
  const depsOptimizer = getDepsOptimizer(config);
40731
40815
  if (depsOptimizer?.isOptimizedDepFile(id)) {
40732
- const metadata = depsOptimizer?.metadata;
40816
+ const metadata = depsOptimizer?.metadata({ ssr });
40733
40817
  if (metadata) {
40734
40818
  const file = cleanUrl(id);
40735
40819
  const versionMatch = id.match(DEP_VERSION_RE);
@@ -40753,7 +40837,7 @@ function optimizedDepsPlugin(config) {
40753
40837
  throwProcessingError(id);
40754
40838
  return;
40755
40839
  }
40756
- const newMetadata = depsOptimizer.metadata;
40840
+ const newMetadata = depsOptimizer.metadata({ ssr });
40757
40841
  if (metadata !== newMetadata) {
40758
40842
  const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
40759
40843
  if (info.browserHash !== currentInfo?.browserHash) {
@@ -40795,9 +40879,10 @@ function optimizedDepsBuildPlugin(config) {
40795
40879
  await this.load({ id });
40796
40880
  });
40797
40881
  },
40798
- async load(id) {
40882
+ async load(id, options) {
40883
+ const ssr = options?.ssr ?? false;
40799
40884
  const depsOptimizer = getDepsOptimizer(config);
40800
- const metadata = depsOptimizer?.metadata;
40885
+ const metadata = depsOptimizer?.metadata({ ssr });
40801
40886
  if (!metadata || !depsOptimizer?.isOptimizedDepFile(id)) {
40802
40887
  return;
40803
40888
  }
@@ -40921,10 +41006,7 @@ function importAnalysisPlugin(config) {
40921
41006
  const start = performance.now();
40922
41007
  await init;
40923
41008
  let imports = [];
40924
- // strip UTF-8 BOM
40925
- if (source.charCodeAt(0) === 0xfeff) {
40926
- source = source.slice(1);
40927
- }
41009
+ source = stripBomTag(source);
40928
41010
  try {
40929
41011
  imports = parse$g(source)[0];
40930
41012
  }
@@ -40980,7 +41062,8 @@ function importAnalysisPlugin(config) {
40980
41062
  // the dependency needs to be resolved starting from the original source location of the optimized file
40981
41063
  // because starting from node_modules/.vite will not find the dependency if it was not hoisted
40982
41064
  // (that is, if it is under node_modules directory in the package source of the optimized file)
40983
- for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
41065
+ for (const optimizedModule of depsOptimizer.metadata({ ssr })
41066
+ .depInfoList) {
40984
41067
  if (!optimizedModule.src)
40985
41068
  continue; // Ignore chunks
40986
41069
  if (optimizedModule.file === importerModule.file) {
@@ -41005,7 +41088,7 @@ function importAnalysisPlugin(config) {
41005
41088
  // in root: infer short absolute path from root
41006
41089
  url = resolved.id.slice(root.length);
41007
41090
  }
41008
- else if (resolved.id.startsWith(getDepsCacheDir(config)) ||
41091
+ else if (resolved.id.startsWith(getDepsCacheDirPrefix(config)) ||
41009
41092
  fs__default.existsSync(cleanUrl(resolved.id))) {
41010
41093
  // an optimized deps may not yet exists in the filesystem, or
41011
41094
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
@@ -41094,7 +41177,7 @@ function importAnalysisPlugin(config) {
41094
41177
  }
41095
41178
  // skip ssr external
41096
41179
  if (ssr) {
41097
- if (config.ssr?.format === 'cjs') {
41180
+ if (config.legacy?.buildSsrCjsExternalHeuristics) {
41098
41181
  if (cjsShouldExternalizeForSSR(specifier, server._ssrExternals)) {
41099
41182
  continue;
41100
41183
  }
@@ -41132,7 +41215,7 @@ function importAnalysisPlugin(config) {
41132
41215
  // The browserHash in resolvedId could be stale in which case there will be a full
41133
41216
  // page reload. We could return a 404 in that case but it is safe to return the request
41134
41217
  const file = cleanUrl(resolvedId); // Remove ?v={hash}
41135
- const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config);
41218
+ const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata({ ssr }), file, config);
41136
41219
  if (needsInterop === undefined) {
41137
41220
  // Non-entry dynamic imports from dependencies will reach here as there isn't
41138
41221
  // optimize info for them, but they don't need es interop. If the request isn't
@@ -41270,7 +41353,7 @@ function importAnalysisPlugin(config) {
41270
41353
  // Unexpected error, log the issue but avoid an unhandled exception
41271
41354
  config.logger.error(e.message);
41272
41355
  });
41273
- if (depsOptimizer && !config.optimizeDeps.devScan) {
41356
+ if (depsOptimizer && !config.legacy?.devDepsScanner) {
41274
41357
  depsOptimizer.delayDepsOptimizerUntil(id, () => request);
41275
41358
  }
41276
41359
  });
@@ -41506,7 +41589,8 @@ function buildImportAnalysisPlugin(config) {
41506
41589
  // the dependency needs to be resolved starting from the original source location of the optimized file
41507
41590
  // because starting from node_modules/.vite will not find the dependency if it was not hoisted
41508
41591
  // (that is, if it is under node_modules directory in the package source of the optimized file)
41509
- for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
41592
+ for (const optimizedModule of depsOptimizer.metadata({ ssr })
41593
+ .depInfoList) {
41510
41594
  if (!optimizedModule.src)
41511
41595
  continue; // Ignore chunks
41512
41596
  if (optimizedModule.file === importer) {
@@ -41564,7 +41648,7 @@ function buildImportAnalysisPlugin(config) {
41564
41648
  if (depsOptimizer.isOptimizedDepFile(resolvedId) &&
41565
41649
  !resolvedId.match(optimizedDepChunkRE)) {
41566
41650
  const file = cleanUrl(resolvedId); // Remove ?v={hash}
41567
- const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config);
41651
+ const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata({ ssr }), file, config);
41568
41652
  let rewriteDone = false;
41569
41653
  if (needsInterop === undefined) {
41570
41654
  // Non-entry dynamic imports from dependencies will reach here as there isn't
@@ -42000,7 +42084,7 @@ function resolveBuildPlugins(config) {
42000
42084
  pre: [
42001
42085
  ...(options.watch ? [ensureWatchPlugin()] : []),
42002
42086
  watchPackageDataPlugin(config),
42003
- ...(!isDepsOptimizerEnabled(config)
42087
+ ...(config.legacy?.buildRollupPluginCommonjs
42004
42088
  ? [commonjs(options.commonjsOptions)]
42005
42089
  : []),
42006
42090
  dataURIPlugin(),
@@ -42069,7 +42153,7 @@ async function doBuild(inlineConfig = {}) {
42069
42153
  // In CJS, we can pass the externals to rollup as is. In ESM, we need to
42070
42154
  // do it in the resolve plugin so we can add the resolved extension for
42071
42155
  // deep node_modules imports
42072
- if (ssr && config.ssr?.format === 'cjs') {
42156
+ if (ssr && config.legacy?.buildSsrCjsExternalHeuristics) {
42073
42157
  external = await cjsSsrResolveExternal(config, userExternal);
42074
42158
  }
42075
42159
  if (isDepsOptimizerEnabled(config)) {
@@ -42321,7 +42405,7 @@ function onRollupWarning(warning, warn, config) {
42321
42405
  async function cjsSsrResolveExternal(config, user) {
42322
42406
  // see if we have cached deps data available
42323
42407
  let knownImports;
42324
- const dataPath = path$p.join(getDepsCacheDir(config), '_metadata.json');
42408
+ const dataPath = path$p.join(getDepsCacheDir(config, false), '_metadata.json');
42325
42409
  try {
42326
42410
  const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
42327
42411
  knownImports = Object.keys(data.optimized);
@@ -48725,7 +48809,7 @@ async function getCertificate(cacheDir) {
48725
48809
  return content;
48726
48810
  }
48727
48811
  catch {
48728
- const content = (await import('./dep-82a07453.js')).createCertificate();
48812
+ const content = (await import('./dep-4cea16ce.js')).createCertificate();
48729
48813
  promises
48730
48814
  .mkdir(cacheDir, { recursive: true })
48731
48815
  .then(() => promises.writeFile(cachePath, content))
@@ -48735,12 +48819,6 @@ async function getCertificate(cacheDir) {
48735
48819
  }
48736
48820
  async function httpServerStart(httpServer, serverOptions) {
48737
48821
  let { port, strictPort, host, logger } = serverOptions;
48738
- // This could be removed when Vite only supports Node 17+ because verbatim=true is default
48739
- // https://github.com/nodejs/node/pull/39987
48740
- if (host === 'localhost') {
48741
- const addr = await promises$1.lookup('localhost', { verbatim: true });
48742
- host = addr.address;
48743
- }
48744
48822
  return new Promise((resolve, reject) => {
48745
48823
  const onError = (e) => {
48746
48824
  if (e.code === 'EADDRINUSE') {
@@ -57582,10 +57660,7 @@ async function createServer(inlineConfig = {}) {
57582
57660
  const config = await resolveConfig(inlineConfig, 'serve', 'development');
57583
57661
  const { root, server: serverConfig } = config;
57584
57662
  const httpsOptions = await resolveHttpsConfig(config.server.https, config.cacheDir);
57585
- let { middlewareMode } = serverConfig;
57586
- if (middlewareMode === true) {
57587
- middlewareMode = 'ssr';
57588
- }
57663
+ const { middlewareMode } = serverConfig;
57589
57664
  const middlewares = connect();
57590
57665
  const httpServer = middlewareMode
57591
57666
  ? null
@@ -57771,20 +57846,17 @@ async function createServer(inlineConfig = {}) {
57771
57846
  // serve static files
57772
57847
  middlewares.use(serveRawFsMiddleware(server));
57773
57848
  middlewares.use(serveStaticMiddleware(root, server));
57774
- const isMiddlewareMode = middlewareMode && middlewareMode !== 'html';
57775
57849
  // spa fallback
57776
- if (config.spa && !isMiddlewareMode) {
57850
+ if (config.appType === 'spa') {
57777
57851
  middlewares.use(spaFallbackMiddleware(root));
57778
57852
  }
57779
57853
  // run post config hooks
57780
57854
  // This is applied before the html middleware so that user middleware can
57781
57855
  // serve custom content instead of index.html.
57782
57856
  postHooks.forEach((fn) => fn && fn());
57783
- if (config.spa && !isMiddlewareMode) {
57857
+ if (config.appType === 'spa' || config.appType === 'mpa') {
57784
57858
  // transform index.html
57785
57859
  middlewares.use(indexHtmlMiddleware(server));
57786
- }
57787
- if (!isMiddlewareMode) {
57788
57860
  // handle 404s
57789
57861
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
57790
57862
  middlewares.use(function vite404Middleware(_, res) {
@@ -57793,7 +57865,7 @@ async function createServer(inlineConfig = {}) {
57793
57865
  });
57794
57866
  }
57795
57867
  // error handler
57796
- middlewares.use(errorMiddleware(server, !!middlewareMode));
57868
+ middlewares.use(errorMiddleware(server, middlewareMode));
57797
57869
  const initOptimizer = async () => {
57798
57870
  if (isDepsOptimizerEnabled(config)) {
57799
57871
  await initDepsOptimizer(config, server);
@@ -57902,7 +57974,8 @@ function resolvedAllowDir(root, dir) {
57902
57974
  function resolveServerOptions(root, raw, logger) {
57903
57975
  const server = {
57904
57976
  preTransformRequests: true,
57905
- ...raw
57977
+ ...raw,
57978
+ middlewareMode: !!raw?.middlewareMode
57906
57979
  };
57907
57980
  let allowDirs = server.fs?.allow;
57908
57981
  const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}'];
@@ -57977,13 +58050,15 @@ async function restartServer(server) {
57977
58050
  }
57978
58051
  async function updateCjsSsrExternals(server) {
57979
58052
  if (!server._ssrExternals) {
58053
+ // We use the non-ssr optimized deps to find known imports
57980
58054
  let knownImports = [];
57981
58055
  const depsOptimizer = getDepsOptimizer(server.config);
57982
58056
  if (depsOptimizer) {
57983
58057
  await depsOptimizer.scanProcessing;
58058
+ const metadata = depsOptimizer.metadata({ ssr: false });
57984
58059
  knownImports = [
57985
- ...Object.keys(depsOptimizer.metadata.optimized),
57986
- ...Object.keys(depsOptimizer.metadata.discovered)
58060
+ ...Object.keys(metadata.optimized),
58061
+ ...Object.keys(metadata.discovered)
57987
58062
  ];
57988
58063
  }
57989
58064
  server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports);
@@ -58146,7 +58221,7 @@ async function preview(inlineConfig = {}) {
58146
58221
  app.use(config.base, sirv(distDir, {
58147
58222
  etag: true,
58148
58223
  dev: true,
58149
- single: config.spa
58224
+ single: config.appType === 'spa'
58150
58225
  }));
58151
58226
  // apply post server hooks from plugins
58152
58227
  postHooks.forEach((fn) => fn && fn());
@@ -58251,11 +58326,21 @@ const wasmHelperId = '/__vite-wasm-helper';
58251
58326
  const wasmHelper = async (opts = {}, url) => {
58252
58327
  let result;
58253
58328
  if (url.startsWith('data:')) {
58254
- // @ts-ignore
58255
- const binaryString = atob(url.replace(/^data:.*?base64,/, ''));
58256
- const bytes = new Uint8Array(binaryString.length);
58257
- for (let i = 0; i < binaryString.length; i++) {
58258
- bytes[i] = binaryString.charCodeAt(i);
58329
+ const urlContent = url.replace(/^data:.*?base64,/, '');
58330
+ let bytes;
58331
+ if (typeof Buffer === 'function' && typeof Buffer.from === 'function') {
58332
+ bytes = Buffer.from(urlContent, 'base64');
58333
+ }
58334
+ else if (typeof atob === 'function') {
58335
+ // @ts-ignore
58336
+ const binaryString = atob(urlContent);
58337
+ bytes = new Uint8Array(binaryString.length);
58338
+ for (let i = 0; i < binaryString.length; i++) {
58339
+ bytes[i] = binaryString.charCodeAt(i);
58340
+ }
58341
+ }
58342
+ else {
58343
+ throw new Error('Failed to decode base64-encoded data URL, Buffer and atob are not supported');
58259
58344
  }
58260
58345
  // @ts-ignore
58261
58346
  result = await WebAssembly.instantiate(bytes, opts);
@@ -58603,12 +58688,10 @@ function preAliasPlugin(config) {
58603
58688
  return {
58604
58689
  name: 'vite:pre-alias',
58605
58690
  async resolveId(id, importer, options) {
58691
+ const ssr = options?.ssr ?? false;
58606
58692
  const depsOptimizer = getDepsOptimizer(config);
58607
- if (depsOptimizer &&
58608
- !options?.ssr &&
58609
- bareImportRE.test(id) &&
58610
- !options?.scan) {
58611
- return await tryOptimizedResolve(depsOptimizer, id, importer);
58693
+ if (depsOptimizer && bareImportRE.test(id) && !options?.scan) {
58694
+ return await tryOptimizedResolve(depsOptimizer, ssr, id, importer);
58612
58695
  }
58613
58696
  }
58614
58697
  };
@@ -60842,7 +60925,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
60842
60925
  mode = inlineConfig.mode || config.mode || mode;
60843
60926
  configEnv.mode = mode;
60844
60927
  // resolve plugins
60845
- const rawUserPlugins = (config.plugins || []).flat(Infinity).filter((p) => {
60928
+ const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter((p) => {
60846
60929
  if (!p) {
60847
60930
  return false;
60848
60931
  }
@@ -60960,7 +61043,14 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
60960
61043
  ? path$p.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
60961
61044
  : '';
60962
61045
  const server = resolveServerOptions(resolvedRoot, config.server, logger);
60963
- const ssr = resolveSSROptions(config.ssr);
61046
+ let ssr = resolveSSROptions(config.ssr);
61047
+ if (config.legacy?.buildSsrCjsExternalHeuristics) {
61048
+ if (ssr)
61049
+ ssr.format = 'cjs';
61050
+ else
61051
+ ssr = { target: 'node', format: 'cjs' };
61052
+ }
61053
+ const middlewareMode = config?.server?.middlewareMode;
60964
61054
  const optimizeDeps = config.optimizeDeps || {};
60965
61055
  const resolved = {
60966
61056
  ...config,
@@ -61003,8 +61093,23 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
61003
61093
  }
61004
61094
  },
61005
61095
  worker: resolvedWorkerOptions,
61006
- spa: config.spa ?? true
61096
+ appType: config.appType ?? middlewareMode === 'ssr' ? 'custom' : 'spa'
61007
61097
  };
61098
+ if (middlewareMode === 'ssr') {
61099
+ logger.warn(colors$1.yellow(`server.middlewareMode 'ssr' is now deprecated, use server.middlewareMode true and appType 'custom'`));
61100
+ }
61101
+ if (middlewareMode === 'html') {
61102
+ logger.warn(colors$1.yellow(`server.middlewareMode 'html' is now deprecated, use server.middlewareMode true`));
61103
+ }
61104
+ if (resolved.legacy?.buildRollupPluginCommonjs) {
61105
+ const optimizerDisabled = resolved.optimizeDeps.disabled;
61106
+ if (!optimizerDisabled) {
61107
+ resolved.optimizeDeps.disabled = 'build';
61108
+ }
61109
+ else if (optimizerDisabled === 'dev') {
61110
+ resolved.optimizeDeps.disabled = true; // Also disabled during build
61111
+ }
61112
+ }
61008
61113
  // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
61009
61114
  // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
61010
61115
  // So we need to separate the worker plugin from the plugin that vite needs to run.
@@ -1,4 +1,4 @@
1
- import { y as getAugmentedNamespace, z as getDefaultExportFromCjs } from './dep-7d4129cb.js';
1
+ import { y as getAugmentedNamespace, z as getDefaultExportFromCjs } from './dep-5d9a8c71.js';
2
2
 
3
3
  import { fileURLToPath as __cjs_fileURLToPath } from 'url';
4
4
  import { dirname as __cjs_dirname } from 'path';
package/dist/node/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { performance } from 'perf_hooks';
2
2
  import { EventEmitter } from 'events';
3
- import { w as colors, k as createLogger, e as resolveConfig } from './chunks/dep-7d4129cb.js';
3
+ import { w as colors, k as createLogger, e as resolveConfig } from './chunks/dep-5d9a8c71.js';
4
4
  import { VERSION } from './constants.js';
5
5
  import 'fs';
6
6
  import 'path';
@@ -16,7 +16,6 @@ import 'http';
16
16
  import 'stream';
17
17
  import 'os';
18
18
  import 'child_process';
19
- import 'dns';
20
19
  import 'crypto';
21
20
  import 'buffer';
22
21
  import 'querystring';
@@ -683,7 +682,7 @@ cli
683
682
  .action(async (root, options) => {
684
683
  // output structure is preserved even after bundling so require()
685
684
  // is ok here
686
- const { createServer } = await import('./chunks/dep-7d4129cb.js').then(function (n) { return n.C; });
685
+ const { createServer } = await import('./chunks/dep-5d9a8c71.js').then(function (n) { return n.C; });
687
686
  try {
688
687
  const server = await createServer({
689
688
  root,
@@ -692,6 +691,7 @@ cli
692
691
  configFile: options.config,
693
692
  logLevel: options.logLevel,
694
693
  clearScreen: options.clearScreen,
694
+ optimizeDeps: { force: options.force },
695
695
  server: cleanOptions(options)
696
696
  });
697
697
  if (!server.httpServer) {
@@ -729,7 +729,7 @@ cli
729
729
  .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
730
730
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
731
731
  .action(async (root, options) => {
732
- const { build } = await import('./chunks/dep-7d4129cb.js').then(function (n) { return n.B; });
732
+ const { build } = await import('./chunks/dep-5d9a8c71.js').then(function (n) { return n.B; });
733
733
  const buildOptions = cleanOptions(options);
734
734
  try {
735
735
  await build({
@@ -739,7 +739,7 @@ cli
739
739
  configFile: options.config,
740
740
  logLevel: options.logLevel,
741
741
  clearScreen: options.clearScreen,
742
- force: options.force,
742
+ optimizeDeps: { force: options.force },
743
743
  build: buildOptions
744
744
  });
745
745
  }
@@ -753,7 +753,7 @@ cli
753
753
  .command('optimize [root]', 'pre-bundle dependencies')
754
754
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
755
755
  .action(async (root, options) => {
756
- const { optimizeDeps } = await import('./chunks/dep-7d4129cb.js').then(function (n) { return n.A; });
756
+ const { optimizeDeps } = await import('./chunks/dep-5d9a8c71.js').then(function (n) { return n.A; });
757
757
  try {
758
758
  const config = await resolveConfig({
759
759
  root,
@@ -776,7 +776,7 @@ cli
776
776
  .option('--https', `[boolean] use TLS + HTTP/2`)
777
777
  .option('--open [path]', `[boolean | string] open browser on startup`)
778
778
  .action(async (root, options) => {
779
- const { preview } = await import('./chunks/dep-7d4129cb.js').then(function (n) { return n.D; });
779
+ const { preview } = await import('./chunks/dep-5d9a8c71.js').then(function (n) { return n.D; });
780
780
  try {
781
781
  const server = await preview({
782
782
  root,
@@ -1,7 +1,7 @@
1
1
  import path, { resolve } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
3
 
4
- var version = "3.0.0-alpha.12";
4
+ var version = "3.0.0-alpha.13";
5
5
 
6
6
  const VERSION = version;
7
7
  const DEFAULT_MAIN_FIELDS = [
@@ -75,6 +75,15 @@ export declare type AnymatchFn = (testString: string) => boolean
75
75
 
76
76
  export declare type AnymatchPattern = string | RegExp | AnymatchFn
77
77
 
78
+ /**
79
+ * spa: include SPA fallback middleware and configure sirv with `single: true` in preview
80
+ *
81
+ * mpa: only include non-SPA HTML middlewares
82
+ *
83
+ * custom: don't include HTML middlewares
84
+ */
85
+ export declare type AppType = 'spa' | 'mpa' | 'custom';
86
+
78
87
  export declare interface AwaitWriteFinishOptions {
79
88
  /**
80
89
  * Amount of time in milliseconds for a file size to remain constant before emitting its event.
@@ -537,13 +546,6 @@ export declare interface DepOptimizationOptions {
537
546
  * vite project root. This will overwrite default entries inference.
538
547
  */
539
548
  entries?: string | string[];
540
- /**
541
- * Enable esbuild based scan phase, to get back to the optimized deps discovery
542
- * strategy used in Vite v2
543
- * @default false
544
- * @experimental
545
- */
546
- devScan?: boolean;
547
549
  /**
548
550
  * Force optimize listed dependencies (must be resolvable import paths,
549
551
  * cannot be globs).
@@ -590,6 +592,11 @@ export declare interface DepOptimizationOptions {
590
592
  * @experimental
591
593
  */
592
594
  disabled?: boolean | 'build' | 'dev';
595
+ /**
596
+ * Force dep pre-optimization regardless of whether deps have changed.
597
+ * @experimental
598
+ */
599
+ force?: boolean;
593
600
  }
594
601
 
595
602
  export declare interface DepOptimizationProcessing {
@@ -609,9 +616,11 @@ export declare interface DepOptimizationResult {
609
616
  }
610
617
 
611
618
  export declare interface DepsOptimizer {
612
- metadata: DepOptimizationMetadata;
619
+ metadata: (options: {
620
+ ssr: boolean;
621
+ }) => DepOptimizationMetadata;
613
622
  scanProcessing?: Promise<void>;
614
- registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
623
+ registerMissingImport: (id: string, resolved: string, ssr?: boolean) => OptimizedDepInfo;
615
624
  run: () => void;
616
625
  isOptimizedDepFile: (id: string) => boolean;
617
626
  isOptimizedDepUrl: (url: string) => boolean;
@@ -1202,6 +1211,33 @@ export declare interface KnownAsTypeMap {
1202
1211
  worker: Worker
1203
1212
  }
1204
1213
 
1214
+ export declare interface LegacyOptions {
1215
+ /**
1216
+ * Revert vite dev to the v2.9 strategy. Enable esbuild based deps scanner.
1217
+ *
1218
+ * @experimental
1219
+ * @deprecated
1220
+ * @default false
1221
+ */
1222
+ devDepsScanner?: boolean;
1223
+ /**
1224
+ * Revert vite build to the v2.9 strategy. Disable esbuild deps optimization and adds `@rollup/plugin-commonjs`
1225
+ *
1226
+ * @experimental
1227
+ * @deprecated
1228
+ * @default false
1229
+ */
1230
+ buildRollupPluginCommonjs?: boolean;
1231
+ /**
1232
+ * Revert vite build --ssr to the v2.9 strategy. Use CJS SSR build and v2.9 externalization heuristics
1233
+ *
1234
+ * @experimental
1235
+ * @deprecated
1236
+ * @default false
1237
+ */
1238
+ buildSsrCjsExternalHeuristics?: boolean;
1239
+ }
1240
+
1205
1241
  export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
1206
1242
 
1207
1243
  export declare interface LibraryOptions {
@@ -1521,7 +1557,7 @@ export declare interface PluginContainer {
1521
1557
  close(): Promise<void>;
1522
1558
  }
1523
1559
 
1524
- export declare type PluginOption = Plugin_2 | false | null | undefined | PluginOption[];
1560
+ export declare type PluginOption = Plugin_2 | false | null | undefined | PluginOption[] | Promise<Plugin_2 | false | null | undefined | PluginOption[]>;
1525
1561
 
1526
1562
  /**
1527
1563
  * Starts the Vite server in preview mode, to simulate a production deployment
@@ -1603,7 +1639,7 @@ export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'asse
1603
1639
  optimizeDeps: DepOptimizationOptions;
1604
1640
  /* Excluded from this release type: packageCache */
1605
1641
  worker: ResolveWorkerOptions;
1606
- spa: boolean;
1642
+ appType: AppType;
1607
1643
  }>;
1608
1644
 
1609
1645
  export declare interface ResolvedPreviewOptions extends PreviewOptions {
@@ -1611,6 +1647,7 @@ export declare interface ResolvedPreviewOptions extends PreviewOptions {
1611
1647
 
1612
1648
  export declare interface ResolvedServerOptions extends ServerOptions {
1613
1649
  fs: Required<FileSystemServeOptions>;
1650
+ middlewareMode: boolean;
1614
1651
  }
1615
1652
 
1616
1653
  export declare interface ResolvedSSROptions extends SSROptions {
@@ -2222,11 +2259,6 @@ export declare interface UserConfig {
2222
2259
  * Preview specific options, e.g. host, port, https...
2223
2260
  */
2224
2261
  preview?: PreviewOptions;
2225
- /**
2226
- * Force dep pre-optimization regardless of whether deps have changed.
2227
- * @experimental
2228
- */
2229
- force?: boolean;
2230
2262
  /**
2231
2263
  * Dep optimization options
2232
2264
  */
@@ -2238,11 +2270,18 @@ export declare interface UserConfig {
2238
2270
  /**
2239
2271
  * Experimental features
2240
2272
  *
2241
- * Features under this field are addressed to be changed that might NOT follow semver.
2273
+ * Features under this field could change in the future and might NOT follow semver.
2242
2274
  * Please be careful and always pin Vite's version when using them.
2243
2275
  * @experimental
2244
2276
  */
2245
2277
  experimental?: ExperimentalOptions;
2278
+ /**
2279
+ * Legacy options
2280
+ *
2281
+ * Features under this field only follow semver for patches, they could be removed in a
2282
+ * future minor version. Please always pin Vite's version to a minor when using them.
2283
+ */
2284
+ legacy?: LegacyOptions;
2246
2285
  /**
2247
2286
  * Log level.
2248
2287
  * Default: 'info'
@@ -2286,11 +2325,12 @@ export declare interface UserConfig {
2286
2325
  rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
2287
2326
  };
2288
2327
  /**
2289
- * Whether your application is a Single Page Application (SPA). Set to `false`
2290
- * for other kinds of apps like MPAs.
2291
- * @default true
2328
+ * Whether your application is a Single Page Application (SPA),
2329
+ * a Multi-Page Application (MPA), or Custom Application (SSR
2330
+ * and frameworks with custom HTML handling)
2331
+ * @default 'spa'
2292
2332
  */
2293
- spa?: boolean;
2333
+ appType?: AppType;
2294
2334
  }
2295
2335
 
2296
2336
  export declare type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn;
@@ -1,4 +1,4 @@
1
- export { b as build, h as createFilter, k as createLogger, c as createServer, d as defineConfig, f as formatPostcssSourceMap, i as isDepsOptimizerEnabled, l as loadConfigFromFile, u as loadEnv, g as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, p as preview, e as resolveConfig, v as resolveEnvPrefix, a as resolvePackageData, r as resolvePackageEntry, q as searchForWorkspaceRoot, j as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-7d4129cb.js';
1
+ export { b as build, h as createFilter, k as createLogger, c as createServer, d as defineConfig, f as formatPostcssSourceMap, i as isDepsOptimizerEnabled, l as loadConfigFromFile, u as loadEnv, g as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, p as preview, e as resolveConfig, v as resolveEnvPrefix, a as resolvePackageData, r as resolvePackageEntry, q as searchForWorkspaceRoot, j as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-5d9a8c71.js';
2
2
  export { VERSION as version } from './constants.js';
3
3
  import 'fs';
4
4
  import 'path';
@@ -16,7 +16,6 @@ import 'http';
16
16
  import 'stream';
17
17
  import 'os';
18
18
  import 'child_process';
19
- import 'dns';
20
19
  import 'crypto';
21
20
  import 'buffer';
22
21
  import 'querystring';
@@ -22,7 +22,7 @@ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
22
22
  var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
23
23
  var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
24
24
 
25
- var version = "3.0.0-alpha.12";
25
+ var version = "3.0.0-alpha.13";
26
26
 
27
27
  const VERSION = version;
28
28
  const VITE_PACKAGE_DIR = path$3.resolve(url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "3.0.0-alpha.12",
3
+ "version": "3.0.0-alpha.13",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",