vite 3.0.0 → 3.0.3

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.
@@ -11754,7 +11754,7 @@ const dataUrlRE = /^\s*data:/i;
11754
11754
  const isDataUrl = (url) => dataUrlRE.test(url);
11755
11755
  const virtualModuleRE = /^virtual-module:.*/;
11756
11756
  const virtualModulePrefix = 'virtual-module:';
11757
- const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/;
11757
+ const knownJsSrcRE = /\.((j|t)sx?|m[jt]s|vue|marko|svelte|astro)($|\?)/;
11758
11758
  const isJSRequest = (url) => {
11759
11759
  url = cleanUrl(url);
11760
11760
  if (knownJsSrcRE.test(url)) {
@@ -12318,6 +12318,9 @@ function gracefulRemoveDir(dir, cb) {
12318
12318
  function emptyCssComments(raw) {
12319
12319
  return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length));
12320
12320
  }
12321
+ function removeComments(raw) {
12322
+ return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, '');
12323
+ }
12321
12324
  function mergeConfigRecursively(defaults, overrides, rootPath) {
12322
12325
  const merged = { ...defaults };
12323
12326
  for (const key in overrides) {
@@ -12423,7 +12426,6 @@ function stripBomTag(content) {
12423
12426
  }
12424
12427
  return content;
12425
12428
  }
12426
- const isTS = (filename) => /\.[cm]?ts$/.test(filename);
12427
12429
  const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
12428
12430
  /**
12429
12431
  * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something)
@@ -13245,12 +13247,15 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13245
13247
  if (ext === 'cjs' || ext === 'mjs') {
13246
13248
  loader = 'js';
13247
13249
  }
13250
+ else if (ext === 'cts' || ext === 'mts') {
13251
+ loader = 'ts';
13252
+ }
13248
13253
  else {
13249
13254
  loader = ext;
13250
13255
  }
13251
13256
  }
13252
13257
  let tsconfigRaw = options?.tsconfigRaw;
13253
- // if options provide tsconfigraw in string, it takes highest precedence
13258
+ // if options provide tsconfigRaw in string, it takes highest precedence
13254
13259
  if (typeof tsconfigRaw !== 'string') {
13255
13260
  // these fields would affect the compilation result
13256
13261
  // https://esbuild.github.io/content-types/#tsconfig-json
@@ -13330,7 +13335,7 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13330
13335
  }
13331
13336
  }
13332
13337
  function esbuildPlugin(options = {}) {
13333
- const filter = createFilter(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/);
13338
+ const filter = createFilter(options.include || /\.(m?ts|[jt]sx)$/, options.exclude || /\.js$/);
13334
13339
  // Remove optimization options for dev as we only need to transpile them,
13335
13340
  // and for build as the final optimization is in `buildEsbuildPlugin`
13336
13341
  const transformOptions = {
@@ -13339,7 +13344,11 @@ function esbuildPlugin(options = {}) {
13339
13344
  minifyIdentifiers: false,
13340
13345
  minifySyntax: false,
13341
13346
  minifyWhitespace: false,
13342
- treeShaking: false
13347
+ treeShaking: false,
13348
+ // keepNames is not needed when minify is disabled.
13349
+ // Also transforming multiple times with keepNames enabled breaks
13350
+ // tree-shaking. (#9164)
13351
+ keepNames: false
13343
13352
  };
13344
13353
  return {
13345
13354
  name: 'vite:esbuild',
@@ -13434,10 +13443,19 @@ function resolveEsbuildTranspileOptions(config, format) {
13434
13443
  // pure annotations and break tree-shaking
13435
13444
  // https://github.com/vuejs/core/issues/2860#issuecomment-926882793
13436
13445
  const isEsLibBuild = config.build.lib && format === 'es';
13446
+ const esbuildOptions = config.esbuild || {};
13437
13447
  const options = {
13438
- ...config.esbuild,
13448
+ ...esbuildOptions,
13439
13449
  target: target || undefined,
13440
- format: rollupToEsbuildFormatMap[format]
13450
+ format: rollupToEsbuildFormatMap[format],
13451
+ // the final build should always support dynamic import and import.meta.
13452
+ // if they need to be polyfilled, plugin-legacy should be used.
13453
+ // plugin-legacy detects these two features when checking for modern code.
13454
+ supported: {
13455
+ 'dynamic-import': true,
13456
+ 'import-meta': true,
13457
+ ...esbuildOptions.supported
13458
+ }
13441
13459
  };
13442
13460
  // If no minify, disable all minify options
13443
13461
  if (!minify) {
@@ -13551,16 +13569,19 @@ function reloadOnTsconfigChange(changedFile) {
13551
13569
  if (path$n.basename(changedFile) === 'tsconfig.json' ||
13552
13570
  (changedFile.endsWith('.json') &&
13553
13571
  tsconfckParseOptions?.cache?.has(changedFile))) {
13554
- server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure typescript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
13572
+ server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
13555
13573
  // clear module graph to remove code compiled with outdated config
13556
13574
  server.moduleGraph.invalidateAll();
13557
13575
  // reset tsconfck so that recompile works with up2date configs
13558
13576
  initTSConfck(server.config).finally(() => {
13559
- // force full reload
13560
- server.ws.send({
13561
- type: 'full-reload',
13562
- path: '*'
13563
- });
13577
+ // server may not be available if vite config is updated at the same time
13578
+ if (server) {
13579
+ // force full reload
13580
+ server.ws.send({
13581
+ type: 'full-reload',
13582
+ path: '*'
13583
+ });
13584
+ }
13564
13585
  });
13565
13586
  }
13566
13587
  }
@@ -33285,11 +33306,6 @@ function assetPlugin(config) {
33285
33306
  renderChunk(code, chunk) {
33286
33307
  let match;
33287
33308
  let s;
33288
- const toRelative = (filename, importer) => {
33289
- return {
33290
- runtime: `new URL(${JSON.stringify(path$n.posix.relative(path$n.dirname(importer), filename))},import.meta.url).href`
33291
- };
33292
- };
33293
33309
  // Urls added with JS using e.g.
33294
33310
  // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
33295
33311
  // Urls added in CSS that is imported in JS end up like
@@ -33303,7 +33319,7 @@ function assetPlugin(config) {
33303
33319
  const file = getAssetFilename(hash, config) || this.getFileName(hash);
33304
33320
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
33305
33321
  const filename = file + postfix;
33306
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, toRelative);
33322
+ const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config);
33307
33323
  const replacementString = typeof replacement === 'string'
33308
33324
  ? JSON.stringify(replacement).slice(1, -1)
33309
33325
  : `"+${replacement.runtime}+"`;
@@ -33317,7 +33333,7 @@ function assetPlugin(config) {
33317
33333
  s = s || (s = new MagicString(code));
33318
33334
  const [full, hash] = match;
33319
33335
  const publicUrl = publicAssetUrlMap.get(hash).slice(1);
33320
- const replacement = toOutputFilePathInString(publicUrl, 'public', chunk.fileName, 'js', config, toRelative);
33336
+ const replacement = toOutputFilePathInString(publicUrl, 'public', chunk.fileName, 'js', config);
33321
33337
  const replacementString = typeof replacement === 'string'
33322
33338
  ? JSON.stringify(replacement).slice(1, -1)
33323
33339
  : `"+${replacement.runtime}+"`;
@@ -33902,6 +33918,16 @@ function resolvePlugin(resolveOptions) {
33902
33918
  return res;
33903
33919
  }
33904
33920
  }
33921
+ // drive relative fs paths (only windows)
33922
+ if (isWindows$4 && id.startsWith('/')) {
33923
+ const basedir = importer ? path$n.dirname(importer) : process.cwd();
33924
+ const fsPath = path$n.resolve(basedir, id);
33925
+ if ((res = tryFsResolve(fsPath, options))) {
33926
+ isDebug$4 &&
33927
+ debug$c(`[drive-relative] ${picocolors.exports.cyan(id)} -> ${picocolors.exports.dim(res)}`);
33928
+ return res;
33929
+ }
33930
+ }
33905
33931
  // absolute fs paths
33906
33932
  if (isNonDriveRelativeAbsolutePath(id) &&
33907
33933
  (res = tryFsResolve(id, options))) {
@@ -34070,7 +34096,7 @@ function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix,
34070
34096
  }
34071
34097
  }
34072
34098
  const idToPkgMap = new Map();
34073
- function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize) {
34099
+ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize, allowLinkedExternal = true) {
34074
34100
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
34075
34101
  ssr ?? (ssr = false);
34076
34102
  // split id by last '>' for nested selected packages, for example:
@@ -34154,13 +34180,17 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
34154
34180
  if (!externalize) {
34155
34181
  return resolved;
34156
34182
  }
34183
+ // dont external symlink packages
34184
+ if (!allowLinkedExternal && !resolved.id.includes('node_modules')) {
34185
+ return resolved;
34186
+ }
34157
34187
  const resolvedExt = path$n.extname(resolved.id);
34158
34188
  let resolvedId = id;
34159
34189
  if (isDeepImport) {
34160
34190
  // check ext before externalizing - only externalize
34161
34191
  // extension-less imports and explicit .js imports
34162
34192
  if (resolvedExt && !resolved.id.match(/(.js|.mjs|.cjs)$/)) {
34163
- return;
34193
+ return resolved;
34164
34194
  }
34165
34195
  if (!pkg?.data.exports && path$n.extname(id) !== resolvedExt) {
34166
34196
  resolvedId += resolvedExt;
@@ -34512,6 +34542,8 @@ const externalTypes = [
34512
34542
  'stylus',
34513
34543
  'pcss',
34514
34544
  'postcss',
34545
+ // wasm
34546
+ 'wasm',
34515
34547
  // known SFC types
34516
34548
  'vue',
34517
34549
  'svelte',
@@ -35429,6 +35461,10 @@ async function parseImportGlob(code, importer, root, resolveId) {
35429
35461
  }
35430
35462
  if (ast.type === 'SequenceExpression')
35431
35463
  ast = ast.expressions[0];
35464
+ // immediate property access, call expression is nested
35465
+ // import.meta.glob(...)['prop']
35466
+ if (ast.type === 'MemberExpression')
35467
+ ast = ast.object;
35432
35468
  if (ast.type !== 'CallExpression')
35433
35469
  throw err(`Expect CallExpression, got ${ast.type}`);
35434
35470
  if (ast.arguments.length < 1 || ast.arguments.length > 2)
@@ -35960,14 +35996,18 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
35960
35996
  build.onResolve({
35961
35997
  // avoid matching windows volume
35962
35998
  filter: /^[\w@][^:]/
35963
- }, async ({ path: id, importer }) => {
35999
+ }, async ({ path: id, importer, pluginData }) => {
35964
36000
  if (moduleListContains(exclude, id)) {
35965
36001
  return externalUnlessEntry({ path: id });
35966
36002
  }
35967
36003
  if (depImports[id]) {
35968
36004
  return externalUnlessEntry({ path: id });
35969
36005
  }
35970
- const resolved = await resolve(id, importer);
36006
+ const resolved = await resolve(id, importer, {
36007
+ custom: {
36008
+ depScan: { loader: pluginData?.htmlType?.loader }
36009
+ }
36010
+ });
35971
36011
  if (resolved) {
35972
36012
  if (shouldExternalizeDep(resolved, id)) {
35973
36013
  return externalUnlessEntry({ path: id });
@@ -36000,9 +36040,9 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
36000
36040
  // should be faster than doing it in the catch-all via js
36001
36041
  // they are done after the bare import resolve because a package name
36002
36042
  // may end with these extensions
36003
- // css & json
36043
+ // css & json & wasm
36004
36044
  build.onResolve({
36005
- filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/
36045
+ filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json|wasm)$/
36006
36046
  }, externalUnlessEntry);
36007
36047
  // known asset types
36008
36048
  build.onResolve({
@@ -36112,7 +36152,7 @@ function getDepsOptimizer(config, ssr) {
36112
36152
  }
36113
36153
  async function initDepsOptimizer(config, server) {
36114
36154
  // Non Dev SSR Optimizer
36115
- const ssr = !!config.build.ssr;
36155
+ const ssr = config.command === 'build' && !!config.build.ssr;
36116
36156
  if (!getDepsOptimizer(config, ssr)) {
36117
36157
  await createDepsOptimizer(config, server);
36118
36158
  }
@@ -36143,7 +36183,7 @@ async function initDevSsrDepsOptimizer(config, server) {
36143
36183
  async function createDepsOptimizer(config, server) {
36144
36184
  const { logger } = config;
36145
36185
  const isBuild = config.command === 'build';
36146
- const ssr = !!config.build.ssr; // safe as Dev SSR don't use this optimizer
36186
+ const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
36147
36187
  const sessionTimestamp = Date.now().toString();
36148
36188
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr);
36149
36189
  let handle;
@@ -36246,11 +36286,11 @@ async function createDepsOptimizer(config, server) {
36246
36286
  // promises are going to be resolved once a rerun is committed
36247
36287
  depOptimizationProcessingQueue.push(depOptimizationProcessing);
36248
36288
  // Create a new promise for the next rerun, discovered missing
36249
- // dependencies will be asigned this promise from this point
36289
+ // dependencies will be assigned this promise from this point
36250
36290
  depOptimizationProcessing = newDepOptimizationProcessing();
36251
36291
  }
36252
36292
  async function optimizeNewDeps() {
36253
- // a succesful completion of the optimizeDeps rerun will end up
36293
+ // a successful completion of the optimizeDeps rerun will end up
36254
36294
  // creating new bundled version of all current and discovered deps
36255
36295
  // in the cache dir and a new metadata info object assigned
36256
36296
  // to _metadata. A fullReload is only issued if the previous bundled
@@ -36359,7 +36399,7 @@ async function createDepsOptimizer(config, server) {
36359
36399
  else {
36360
36400
  if (newDepsDiscovered) {
36361
36401
  // There are newly discovered deps, and another rerun is about to be
36362
- // excecuted. Avoid the current full reload discarding this rerun result
36402
+ // executed. Avoid the current full reload discarding this rerun result
36363
36403
  // We don't resolve the processing promise, as they will be resolved
36364
36404
  // once a rerun is committed
36365
36405
  processingResult.cancel();
@@ -36456,7 +36496,7 @@ async function createDepsOptimizer(config, server) {
36456
36496
  src: resolved,
36457
36497
  // Assing a browserHash to this missing dependency that is unique to
36458
36498
  // the current state of known + missing deps. If its optimizeDeps run
36459
- // doesn't alter the bundled files of previous known dependendencies,
36499
+ // doesn't alter the bundled files of previous known dependencies,
36460
36500
  // we don't need a full reload and this browserHash will be kept
36461
36501
  browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
36462
36502
  // loading of this pre-bundled dep needs to await for its processing
@@ -36659,7 +36699,7 @@ const jsMapExtensionRE = /\.js\.map$/i;
36659
36699
  */
36660
36700
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
36661
36701
  const log = asCommand ? config.logger.info : debug$a;
36662
- const ssr = !!config.build.ssr;
36702
+ const ssr = config.command === 'build' && !!config.build.ssr;
36663
36703
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
36664
36704
  if (cachedMetadata) {
36665
36705
  return cachedMetadata;
@@ -36794,7 +36834,8 @@ function depsLogString(qualifiedIds) {
36794
36834
  * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
36795
36835
  * the metadata and start the server without waiting for the optimizeDeps processing to be completed
36796
36836
  */
36797
- async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = !!resolvedConfig.build.ssr) {
36837
+ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command === 'build' &&
36838
+ !!resolvedConfig.build.ssr) {
36798
36839
  const isBuild = resolvedConfig.command === 'build';
36799
36840
  const config = {
36800
36841
  ...resolvedConfig,
@@ -37020,7 +37061,7 @@ function newDepOptimizationProcessing() {
37020
37061
  function depsFromOptimizedDepInfo(depsInfo) {
37021
37062
  return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
37022
37063
  }
37023
- function getOptimizedDepPath(id, config, ssr = !!config.build.ssr) {
37064
+ function getOptimizedDepPath(id, config, ssr) {
37024
37065
  return normalizePath$3(path$n.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
37025
37066
  }
37026
37067
  function getDepsCacheSuffix(config, ssr) {
@@ -37207,7 +37248,7 @@ function needsInterop(config, ssr, id, exportsData, output) {
37207
37248
  return true;
37208
37249
  }
37209
37250
  if (output) {
37210
- // if a peer dependency used require() on a ESM dependency, esbuild turns the
37251
+ // if a peer dependency used require() on an ESM dependency, esbuild turns the
37211
37252
  // ESM dependency's entry chunk into a single default export... detect
37212
37253
  // such cases by checking exports mismatch, and force interop.
37213
37254
  const generatedExports = output.exports;
@@ -37950,54 +37991,70 @@ function shouldExternalizeForSSR(id, config) {
37950
37991
  return isSsrExternal(id);
37951
37992
  }
37952
37993
  function createIsConfiguredAsSsrExternal(config) {
37953
- const { ssr } = config;
37994
+ const { ssr, root } = config;
37954
37995
  const noExternal = ssr?.noExternal;
37955
37996
  const noExternalFilter = noExternal !== 'undefined' &&
37956
37997
  typeof noExternal !== 'boolean' &&
37957
37998
  createFilter(undefined, noExternal, { resolve: false });
37999
+ const resolveOptions = {
38000
+ root,
38001
+ preserveSymlinks: config.resolve.preserveSymlinks,
38002
+ isProduction: false,
38003
+ isBuild: true
38004
+ };
38005
+ const isExternalizable = (id, configuredAsExternal) => {
38006
+ if (!bareImportRE.test(id) || id.includes('\0')) {
38007
+ return false;
38008
+ }
38009
+ return !!tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true,
38010
+ // try to externalize, will return undefined or an object without
38011
+ // a external flag if it isn't externalizable
38012
+ true,
38013
+ // Allow linked packages to be externalized if they are explicitly
38014
+ // configured as external
38015
+ !!configuredAsExternal)?.external;
38016
+ };
37958
38017
  // Returns true if it is configured as external, false if it is filtered
37959
38018
  // by noExternal and undefined if it isn't affected by the explicit config
37960
38019
  return (id) => {
37961
38020
  const { ssr } = config;
37962
38021
  if (ssr) {
37963
- if (ssr.external?.includes(id)) {
38022
+ if (
38023
+ // If this id is defined as external, force it as external
38024
+ // Note that individual package entries are allowed in ssr.external
38025
+ ssr.external?.includes(id)) {
37964
38026
  return true;
37965
38027
  }
38028
+ const pkgName = getNpmPackageName(id);
38029
+ if (!pkgName) {
38030
+ return isExternalizable(id);
38031
+ }
38032
+ if (
38033
+ // A package name in ssr.external externalizes every
38034
+ // externalizable package entry
38035
+ ssr.external?.includes(pkgName)) {
38036
+ return isExternalizable(id, true);
38037
+ }
37966
38038
  if (typeof noExternal === 'boolean') {
37967
38039
  return !noExternal;
37968
38040
  }
37969
- if (noExternalFilter && !noExternalFilter(id)) {
38041
+ if (noExternalFilter && !noExternalFilter(pkgName)) {
37970
38042
  return false;
37971
38043
  }
37972
38044
  }
37973
- return undefined;
38045
+ return isExternalizable(id);
37974
38046
  };
37975
38047
  }
37976
38048
  function createIsSsrExternal(config) {
37977
38049
  const processedIds = new Map();
37978
- const { ssr, root } = config;
37979
38050
  const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
37980
- const resolveOptions = {
37981
- root,
37982
- preserveSymlinks: config.resolve.preserveSymlinks,
37983
- isProduction: false,
37984
- isBuild: true
37985
- };
37986
- const isValidPackageEntry = (id) => {
37987
- if (!bareImportRE.test(id) || id.includes('\0')) {
37988
- return false;
37989
- }
37990
- return !!tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true, true // try to externalize, will return undefined if not possible
37991
- );
37992
- };
37993
38051
  return (id) => {
37994
38052
  if (processedIds.has(id)) {
37995
38053
  return processedIds.get(id);
37996
38054
  }
37997
38055
  let external = false;
37998
38056
  if (!id.startsWith('.') && !path$n.isAbsolute(id)) {
37999
- external =
38000
- isBuiltin(id) || (isConfiguredAsExternal(id) ?? isValidPackageEntry(id));
38057
+ external = isBuiltin(id) || isConfiguredAsExternal(id);
38001
38058
  }
38002
38059
  processedIds.set(id, external);
38003
38060
  return external;
@@ -39471,32 +39528,36 @@ function serveStaticMiddleware(dir, server) {
39471
39528
  isInternalRequest(req.url)) {
39472
39529
  return next();
39473
39530
  }
39474
- const url = decodeURIComponent(req.url);
39531
+ const url = new URL(req.url, 'http://example.com');
39532
+ const pathname = decodeURIComponent(url.pathname);
39475
39533
  // apply aliases to static requests as well
39476
- let redirected;
39534
+ let redirectedPathname;
39477
39535
  for (const { find, replacement } of server.config.resolve.alias) {
39478
- const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
39536
+ const matches = typeof find === 'string'
39537
+ ? pathname.startsWith(find)
39538
+ : find.test(pathname);
39479
39539
  if (matches) {
39480
- redirected = url.replace(find, replacement);
39540
+ redirectedPathname = pathname.replace(find, replacement);
39481
39541
  break;
39482
39542
  }
39483
39543
  }
39484
- if (redirected) {
39544
+ if (redirectedPathname) {
39485
39545
  // dir is pre-normalized to posix style
39486
- if (redirected.startsWith(dir)) {
39487
- redirected = redirected.slice(dir.length);
39546
+ if (redirectedPathname.startsWith(dir)) {
39547
+ redirectedPathname = redirectedPathname.slice(dir.length);
39488
39548
  }
39489
39549
  }
39490
- const resolvedUrl = redirected || url;
39491
- let fileUrl = path$n.resolve(dir, resolvedUrl.replace(/^\//, ''));
39492
- if (resolvedUrl.endsWith('/') && !fileUrl.endsWith('/')) {
39550
+ const resolvedPathname = redirectedPathname || pathname;
39551
+ let fileUrl = path$n.resolve(dir, resolvedPathname.replace(/^\//, ''));
39552
+ if (resolvedPathname.endsWith('/') && !fileUrl.endsWith('/')) {
39493
39553
  fileUrl = fileUrl + '/';
39494
39554
  }
39495
39555
  if (!ensureServingAccess(fileUrl, server, res, next)) {
39496
39556
  return;
39497
39557
  }
39498
- if (redirected) {
39499
- req.url = encodeURIComponent(redirected);
39558
+ if (redirectedPathname) {
39559
+ url.pathname = encodeURIComponent(redirectedPathname);
39560
+ req.url = url.href.slice(url.origin.length);
39500
39561
  }
39501
39562
  serve(req, res, next);
39502
39563
  };
@@ -39505,20 +39566,22 @@ function serveRawFsMiddleware(server) {
39505
39566
  const serveFromRoot = sirv('/', sirvOptions(server.config.server.headers));
39506
39567
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
39507
39568
  return function viteServeRawFsMiddleware(req, res, next) {
39508
- let url = decodeURIComponent(req.url);
39569
+ const url = new URL(req.url, 'http://example.com');
39509
39570
  // In some cases (e.g. linked monorepos) files outside of root will
39510
39571
  // reference assets that are also out of served root. In such cases
39511
39572
  // the paths are rewritten to `/@fs/` prefixed paths and must be served by
39512
39573
  // searching based from fs root.
39513
- if (url.startsWith(FS_PREFIX)) {
39574
+ if (url.pathname.startsWith(FS_PREFIX)) {
39575
+ const pathname = decodeURIComponent(url.pathname);
39514
39576
  // restrict files outside of `fs.allow`
39515
- if (!ensureServingAccess(slash$1(path$n.resolve(fsPathFromId(url))), server, res, next)) {
39577
+ if (!ensureServingAccess(slash$1(path$n.resolve(fsPathFromId(pathname))), server, res, next)) {
39516
39578
  return;
39517
39579
  }
39518
- url = url.slice(FS_PREFIX.length);
39580
+ let newPathname = pathname.slice(FS_PREFIX.length);
39519
39581
  if (isWindows$4)
39520
- url = url.replace(/^[A-Z]:/i, '');
39521
- req.url = encodeURIComponent(url);
39582
+ newPathname = newPathname.replace(/^[A-Z]:/i, '');
39583
+ url.pathname = encodeURIComponent(newPathname);
39584
+ req.url = url.href.slice(url.origin.length);
39522
39585
  serveFromRoot(req, res, next);
39523
39586
  }
39524
39587
  else {
@@ -39548,7 +39611,7 @@ function ensureServingAccess(url, server, res, next) {
39548
39611
  const hintMessage = `
39549
39612
  ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
39550
39613
 
39551
- Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`;
39614
+ Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
39552
39615
  server.config.logger.error(urlMessage);
39553
39616
  server.config.logger.warnOnce(hintMessage + '\n');
39554
39617
  res.statusCode = 403;
@@ -40961,7 +41024,7 @@ function polyfill() {
40961
41024
  }
40962
41025
  }
40963
41026
 
40964
- const htmlProxyRE$1 = /\?html-proxy=?[&inline\-css]*&index=(\d+)\.(js|css)$/;
41027
+ const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?&index=(\d+)\.(js|css)$/;
40965
41028
  const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
40966
41029
  // Do not allow preceding '.', but do allow preceding '...' for spread operations
40967
41030
  const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*')\)/g;
@@ -41027,7 +41090,7 @@ const assetAttrsConfig = {
41027
41090
  const isAsyncScriptMap = new WeakMap();
41028
41091
  async function traverseHtml(html, filePath, visitor) {
41029
41092
  // lazy load compiler
41030
- const { parse, transform } = await import('./dep-f2ffe191.js').then(function (n) { return n.c; });
41093
+ const { parse, transform } = await import('./dep-7f3e64a3.js').then(function (n) { return n.c; });
41031
41094
  // @vue/compiler-core doesn't like lowercase doctypes
41032
41095
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
41033
41096
  try {
@@ -42157,7 +42220,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
42157
42220
  logger: config.logger
42158
42221
  }));
42159
42222
  if (isModule) {
42160
- postcssPlugins.unshift((await import('./dep-eb5668bc.js').then(function (n) { return n.i; })).default({
42223
+ postcssPlugins.unshift((await import('./dep-676c6c22.js').then(function (n) { return n.i; })).default({
42161
42224
  ...modulesOptions,
42162
42225
  getJSON(cssFileName, _modules, outputFileName) {
42163
42226
  modules = _modules;
@@ -42468,17 +42531,23 @@ async function minifyCSS(css, config) {
42468
42531
  }
42469
42532
  }
42470
42533
  function resolveEsbuildMinifyOptions(options) {
42534
+ const base = {
42535
+ logLevel: options.logLevel,
42536
+ logLimit: options.logLimit,
42537
+ logOverride: options.logOverride
42538
+ };
42471
42539
  if (options.minifyIdentifiers != null ||
42472
42540
  options.minifySyntax != null ||
42473
42541
  options.minifyWhitespace != null) {
42474
42542
  return {
42543
+ ...base,
42475
42544
  minifyIdentifiers: options.minifyIdentifiers ?? true,
42476
42545
  minifySyntax: options.minifySyntax ?? true,
42477
42546
  minifyWhitespace: options.minifyWhitespace ?? true
42478
42547
  };
42479
42548
  }
42480
42549
  else {
42481
- return { minify: true };
42550
+ return { ...base, minify: true };
42482
42551
  }
42483
42552
  }
42484
42553
  async function hoistAtRules(css) {
@@ -43353,10 +43422,10 @@ async function doBuild(inlineConfig = {}) {
43353
43422
  ? `[name].${jsExt}`
43354
43423
  : libOptions
43355
43424
  ? resolveLibFilename(libOptions, format, config.root, jsExt)
43356
- : path$n.posix.join(options.assetsDir, `[name].[hash].js`),
43425
+ : path$n.posix.join(options.assetsDir, `[name].[hash].${jsExt}`),
43357
43426
  chunkFileNames: libOptions
43358
43427
  ? `[name].[hash].${jsExt}`
43359
- : path$n.posix.join(options.assetsDir, `[name].[hash].js`),
43428
+ : path$n.posix.join(options.assetsDir, `[name].[hash].${jsExt}`),
43360
43429
  assetFileNames: libOptions
43361
43430
  ? `[name].[ext]`
43362
43431
  : path$n.posix.join(options.assetsDir, `[name].[hash].[ext]`),
@@ -43620,7 +43689,7 @@ function wrapSsrTransform(fn) {
43620
43689
  function injectSsrFlag(options) {
43621
43690
  return { ...(options ?? {}), ssr: true };
43622
43691
  }
43623
- function toOutputFilePathInString(filename, type, hostId, hostType, config, toRelative) {
43692
+ function toOutputFilePathInString(filename, type, hostId, hostType, config, toRelative = toImportMetaURLBasedRelativePath) {
43624
43693
  const { renderBuiltUrl } = config.experimental;
43625
43694
  let relative = config.base === '' || config.base === './';
43626
43695
  if (renderBuiltUrl) {
@@ -43647,6 +43716,11 @@ function toOutputFilePathInString(filename, type, hostId, hostType, config, toRe
43647
43716
  }
43648
43717
  return config.base + filename;
43649
43718
  }
43719
+ function toImportMetaURLBasedRelativePath(filename, importer) {
43720
+ return {
43721
+ runtime: `new URL(${JSON.stringify(path$n.posix.relative(path$n.dirname(importer), filename))},import.meta.url).href`
43722
+ };
43723
+ }
43650
43724
  function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
43651
43725
  const { renderBuiltUrl } = config.experimental;
43652
43726
  let relative = config.base === '' || config.base === './';
@@ -50247,7 +50321,8 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50247
50321
  if (dep[0] !== '.' && dep[0] !== '/') {
50248
50322
  return nodeImport(dep, mod.file, resolveOptions);
50249
50323
  }
50250
- dep = unwrapId(dep);
50324
+ // convert to rollup URL because `pendingImports`, `moduleGraph.urlToModuleMap` requires that
50325
+ dep = unwrapId(dep).replace(NULL_BYTE_PLACEHOLDER, '\0');
50251
50326
  if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {
50252
50327
  pendingDeps.push(dep);
50253
50328
  if (pendingDeps.length === 1) {
@@ -50289,7 +50364,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50289
50364
  try {
50290
50365
  // eslint-disable-next-line @typescript-eslint/no-empty-function
50291
50366
  const AsyncFunction = async function () { }.constructor;
50292
- const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`);
50367
+ const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' + result.code + `\n//# sourceURL=${mod.url}`);
50293
50368
  await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
50294
50369
  }
50295
50370
  catch (e) {
@@ -50370,7 +50445,7 @@ async function nodeImport(id, importer, resolveOptions) {
50370
50445
  }
50371
50446
  // rollup-style default import interop for cjs
50372
50447
  function proxyESM(mod) {
50373
- // This is the only sensible option when the exports object is a primitve
50448
+ // This is the only sensible option when the exports object is a primitive
50374
50449
  if (isPrimitive(mod))
50375
50450
  return { default: mod };
50376
50451
  let defaultExport = 'default' in mod ? mod.default : mod;
@@ -53491,11 +53566,11 @@ function initAsClient(websocket, address, protocols, options) {
53491
53566
  ? parsedUrl.hostname.slice(1, -1)
53492
53567
  : parsedUrl.hostname;
53493
53568
  opts.headers = {
53569
+ ...opts.headers,
53494
53570
  'Sec-WebSocket-Version': opts.protocolVersion,
53495
53571
  'Sec-WebSocket-Key': key,
53496
53572
  Connection: 'Upgrade',
53497
- Upgrade: 'websocket',
53498
- ...opts.headers
53573
+ Upgrade: 'websocket'
53499
53574
  };
53500
53575
  opts.path = parsedUrl.pathname + parsedUrl.search;
53501
53576
  opts.timeout = opts.handshakeTimeout;
@@ -53549,8 +53624,11 @@ function initAsClient(websocket, address, protocols, options) {
53549
53624
 
53550
53625
  if (opts.followRedirects) {
53551
53626
  if (websocket._redirects === 0) {
53627
+ websocket._originalUnixSocket = isUnixSocket;
53552
53628
  websocket._originalSecure = isSecure;
53553
- websocket._originalHost = parsedUrl.host;
53629
+ websocket._originalHostOrSocketPath = isUnixSocket
53630
+ ? opts.socketPath
53631
+ : parsedUrl.host;
53554
53632
 
53555
53633
  const headers = options && options.headers;
53556
53634
 
@@ -53566,7 +53644,13 @@ function initAsClient(websocket, address, protocols, options) {
53566
53644
  }
53567
53645
  }
53568
53646
  } else if (websocket.listenerCount('redirect') === 0) {
53569
- const isSameHost = parsedUrl.host === websocket._originalHost;
53647
+ const isSameHost = isUnixSocket
53648
+ ? websocket._originalUnixSocket
53649
+ ? opts.socketPath === websocket._originalHostOrSocketPath
53650
+ : false
53651
+ : websocket._originalUnixSocket
53652
+ ? false
53653
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
53570
53654
 
53571
53655
  if (!isSameHost || (websocket._originalSecure && !isSecure)) {
53572
53656
  //
@@ -56933,16 +57017,29 @@ function proxyMiddleware(httpServer, options, config) {
56933
57017
  opts = { target: opts, changeOrigin: true };
56934
57018
  }
56935
57019
  const proxy = httpProxy.createProxyServer(opts);
56936
- proxy.on('error', (err, req, res) => {
56937
- config.logger.error(`${picocolors.exports.red(`http proxy error:`)}\n${err.stack}`, {
56938
- timestamp: true,
56939
- error: err
56940
- });
56941
- res
56942
- .writeHead(500, {
56943
- 'Content-Type': 'text/plain'
56944
- })
56945
- .end();
57020
+ proxy.on('error', (err, req, originalRes) => {
57021
+ // When it is ws proxy, res is net.Socket
57022
+ const res = originalRes;
57023
+ if ('req' in res) {
57024
+ config.logger.error(`${picocolors.exports.red(`http proxy error:`)}\n${err.stack}`, {
57025
+ timestamp: true,
57026
+ error: err
57027
+ });
57028
+ if (!res.headersSent && !res.writableEnded) {
57029
+ res
57030
+ .writeHead(500, {
57031
+ 'Content-Type': 'text/plain'
57032
+ })
57033
+ .end();
57034
+ }
57035
+ }
57036
+ else {
57037
+ config.logger.error(`${picocolors.exports.red(`ws proxy error:`)}\n${err.stack}`, {
57038
+ timestamp: true,
57039
+ error: err
57040
+ });
57041
+ res.end();
57042
+ }
56946
57043
  });
56947
57044
  if (opts.configure) {
56948
57045
  opts.configure(proxy, opts);
@@ -57347,9 +57444,9 @@ function transformMiddleware(server) {
57347
57444
  }
57348
57445
  // We don't need to log an error in this case, the request
57349
57446
  // is outdated because new dependencies were discovered and
57350
- // the new pre-bundle dependendencies have changed.
57447
+ // the new pre-bundle dependencies have changed.
57351
57448
  // A full-page reload has been issued, and these old requests
57352
- // can't be properly fullfilled. This isn't an unexpected
57449
+ // can't be properly fulfilled. This isn't an unexpected
57353
57450
  // error but a normal part of the missing deps discovery flow
57354
57451
  return;
57355
57452
  }
@@ -57724,10 +57821,14 @@ class ModuleGraph {
57724
57821
  url = removeImportQuery(removeTimestampQuery(url));
57725
57822
  const resolved = await this.resolveId(url, !!ssr);
57726
57823
  const resolvedId = resolved?.id || url;
57727
- const ext = extname$1(cleanUrl(resolvedId));
57728
- const { pathname, search, hash } = parse$k(url);
57729
- if (ext && !pathname.endsWith(ext)) {
57730
- url = pathname + ext + (search || '') + (hash || '');
57824
+ if (url !== resolvedId &&
57825
+ !url.includes('\0') &&
57826
+ !url.startsWith(`virtual:`)) {
57827
+ const ext = extname$1(cleanUrl(resolvedId));
57828
+ const { pathname, search, hash } = new URL(url, 'relative://');
57829
+ if (ext && !pathname.endsWith(ext)) {
57830
+ url = pathname + ext + search + hash;
57831
+ }
57731
57832
  }
57732
57833
  return [url, resolvedId, resolved?.meta];
57733
57834
  }
@@ -59768,14 +59869,6 @@ function emitSourcemapForWorkerEntry(config, query, chunk) {
59768
59869
  }
59769
59870
  return chunk;
59770
59871
  }
59771
- // TODO:base review why we aren't using import.meta.url here
59772
- function toStaticRelativePath(filename, importer) {
59773
- let outputFilepath = path$n.posix.relative(path$n.dirname(importer), filename);
59774
- if (!outputFilepath.startsWith('.')) {
59775
- outputFilepath = './' + outputFilepath;
59776
- }
59777
- return outputFilepath;
59778
- }
59779
59872
  const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
59780
59873
  function encodeWorkerAssetFileName(fileName, workerCache) {
59781
59874
  const { fileNameHash } = workerCache;
@@ -59931,7 +60024,7 @@ function webWorkerPlugin(config) {
59931
60024
  while ((match = workerAssetUrlRE.exec(code))) {
59932
60025
  const [full, hash] = match;
59933
60026
  const filename = fileNameHash.get(hash);
59934
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, toStaticRelativePath);
60027
+ const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config);
59935
60028
  const replacementString = typeof replacement === 'string'
59936
60029
  ? JSON.stringify(replacement).slice(1, -1)
59937
60030
  : `"+${replacement.runtime}+"`;
@@ -61879,7 +61972,13 @@ function dynamicImportVarsPlugin(config) {
61879
61972
  s || (s = new MagicString(source));
61880
61973
  let result;
61881
61974
  try {
61882
- result = await transformDynamicImport(source.slice(start, end), importer, resolve);
61975
+ // When import string is using backticks, es-module-lexer `end` captures
61976
+ // until the closing parenthesis, instead of the closing backtick.
61977
+ // There may be inline comments between the backtick and the closing
61978
+ // parenthesis, so we manually remove them for now.
61979
+ // See https://github.com/guybedford/es-module-lexer/issues/118
61980
+ const importSource = removeComments(source.slice(start, end)).trim();
61981
+ result = await transformDynamicImport(importSource, importer, resolve);
61883
61982
  }
61884
61983
  catch (error) {
61885
61984
  if (warnOnError) {
@@ -61956,7 +62055,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
61956
62055
  wasmFallbackPlugin(),
61957
62056
  definePlugin(config),
61958
62057
  cssPostPlugin(config),
61959
- config.build.ssr ? ssrRequireHookPlugin(config) : null,
62058
+ isBuild && config.build.ssr ? ssrRequireHookPlugin(config) : null,
61960
62059
  isBuild && buildHtmlPlugin(config),
61961
62060
  workerImportMetaUrlPlugin(config),
61962
62061
  ...buildPlugins.pre,
@@ -62293,6 +62392,23 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62293
62392
  // user config may provide an alternative mode. But --mode has a higher priority
62294
62393
  mode = inlineConfig.mode || config.mode || mode;
62295
62394
  configEnv.mode = mode;
62395
+ // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
62396
+ // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
62397
+ // So we need to separate the worker plugin from the plugin that vite needs to run.
62398
+ const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter((p) => {
62399
+ if (!p) {
62400
+ return false;
62401
+ }
62402
+ else if (!p.apply) {
62403
+ return true;
62404
+ }
62405
+ else if (typeof p.apply === 'function') {
62406
+ return p.apply({ ...config, mode }, configEnv);
62407
+ }
62408
+ else {
62409
+ return p.apply === command;
62410
+ }
62411
+ });
62296
62412
  // resolve plugins
62297
62413
  const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter((p) => {
62298
62414
  if (!p) {
@@ -62309,12 +62425,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62309
62425
  }
62310
62426
  });
62311
62427
  const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
62312
- // resolve worker
62313
- const resolvedWorkerOptions = {
62314
- format: config.worker?.format || 'iife',
62315
- plugins: [],
62316
- rollupOptions: config.worker?.rollupOptions || {}
62317
- };
62318
62428
  // run config hooks
62319
62429
  const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
62320
62430
  for (const p of userPlugins) {
@@ -62433,8 +62543,29 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62433
62543
  const middlewareMode = config?.server?.middlewareMode;
62434
62544
  const optimizeDeps = config.optimizeDeps || {};
62435
62545
  const BASE_URL = resolvedBase;
62436
- const resolved = {
62437
- ...config,
62546
+ // resolve worker
62547
+ let workerConfig = mergeConfig({}, config);
62548
+ const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
62549
+ // run config hooks
62550
+ const workerUserPlugins = [
62551
+ ...workerPrePlugins,
62552
+ ...workerNormalPlugins,
62553
+ ...workerPostPlugins
62554
+ ];
62555
+ for (const p of workerUserPlugins) {
62556
+ if (p.config) {
62557
+ const res = await p.config(workerConfig, configEnv);
62558
+ if (res) {
62559
+ workerConfig = mergeConfig(workerConfig, res);
62560
+ }
62561
+ }
62562
+ }
62563
+ const resolvedWorkerOptions = {
62564
+ format: workerConfig.worker?.format || 'iife',
62565
+ plugins: [],
62566
+ rollupOptions: workerConfig.worker?.rollupOptions || {}
62567
+ };
62568
+ const resolvedConfig = {
62438
62569
  configFile: configFile ? normalizePath$3(configFile) : undefined,
62439
62570
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$n.resolve(name))),
62440
62571
  inlineConfig,
@@ -62482,6 +62613,23 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62482
62613
  ...config.experimental
62483
62614
  }
62484
62615
  };
62616
+ const resolved = {
62617
+ ...config,
62618
+ ...resolvedConfig
62619
+ };
62620
+ resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
62621
+ const workerResolved = {
62622
+ ...workerConfig,
62623
+ ...resolvedConfig,
62624
+ isWorker: true,
62625
+ mainConfig: resolved
62626
+ };
62627
+ resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
62628
+ // call configResolved hooks
62629
+ await Promise.all(userPlugins
62630
+ .map((p) => p.configResolved?.(resolved))
62631
+ .concat(resolvedConfig.worker.plugins.map((p) => p.configResolved?.(workerResolved))));
62632
+ // validate config
62485
62633
  if (middlewareMode === 'ssr') {
62486
62634
  logger.warn(picocolors.exports.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`));
62487
62635
  }
@@ -62494,21 +62642,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62494
62642
  resolved.optimizeDeps.force = true;
62495
62643
  logger.warn(picocolors.exports.yellow(`server.force is deprecated, use optimizeDeps.force instead`));
62496
62644
  }
62497
- // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
62498
- // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
62499
- // So we need to separate the worker plugin from the plugin that vite needs to run.
62500
- const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(config.worker?.plugins);
62501
- const workerResolved = {
62502
- ...resolved,
62503
- isWorker: true,
62504
- mainConfig: resolved
62505
- };
62506
- resolved.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
62507
- // call configResolved worker plugins hooks
62508
- await Promise.all(resolved.worker.plugins.map((p) => p.configResolved?.(workerResolved)));
62509
- resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
62510
- // call configResolved hooks
62511
- await Promise.all(userPlugins.map((p) => p.configResolved?.(resolved)));
62512
62645
  if (process.env.DEBUG) {
62513
62646
  debug(`using resolved config: %O`, {
62514
62647
  ...resolved,
@@ -62590,7 +62723,6 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62590
62723
  const start = performance.now();
62591
62724
  const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
62592
62725
  let resolvedPath;
62593
- let dependencies = [];
62594
62726
  if (configFile) {
62595
62727
  // explicit config path is always resolved from cwd
62596
62728
  resolvedPath = path$n.resolve(configFile);
@@ -62626,41 +62758,9 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62626
62758
  catch (e) { }
62627
62759
  }
62628
62760
  try {
62629
- let userConfig;
62630
- if (isESM) {
62631
- const fileUrl = pathToFileURL(resolvedPath);
62632
- const bundled = await bundleConfigFile(resolvedPath, true);
62633
- dependencies = bundled.dependencies;
62634
- if (isTS(resolvedPath)) {
62635
- // before we can register loaders without requiring users to run node
62636
- // with --experimental-loader themselves, we have to do a hack here:
62637
- // bundle the config file w/ ts transforms first, write it to disk,
62638
- // load it with native Node ESM, then delete the file.
62639
- fs$l.writeFileSync(resolvedPath + '.mjs', bundled.code);
62640
- try {
62641
- userConfig = (await dynamicImport(`${fileUrl}.mjs?t=${Date.now()}`))
62642
- .default;
62643
- }
62644
- finally {
62645
- fs$l.unlinkSync(resolvedPath + '.mjs');
62646
- }
62647
- debug(`TS + native esm config loaded in ${getTime()}`, fileUrl);
62648
- }
62649
- else {
62650
- // using Function to avoid this from being compiled away by TS/Rollup
62651
- // append a query so that we force reload fresh config in case of
62652
- // server restart
62653
- userConfig = (await dynamicImport(`${fileUrl}?t=${Date.now()}`)).default;
62654
- debug(`native esm config loaded in ${getTime()}`, fileUrl);
62655
- }
62656
- }
62657
- if (!userConfig) {
62658
- // Bundle config file and transpile it to cjs using esbuild.
62659
- const bundled = await bundleConfigFile(resolvedPath);
62660
- dependencies = bundled.dependencies;
62661
- userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code);
62662
- debug(`bundled config file loaded in ${getTime()}`);
62663
- }
62761
+ const bundled = await bundleConfigFile(resolvedPath, isESM);
62762
+ const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM);
62763
+ debug(`bundled config file loaded in ${getTime()}`);
62664
62764
  const config = await (typeof userConfig === 'function'
62665
62765
  ? userConfig(configEnv)
62666
62766
  : userConfig);
@@ -62670,7 +62770,7 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62670
62770
  return {
62671
62771
  path: normalizePath$3(resolvedPath),
62672
62772
  config,
62673
- dependencies
62773
+ dependencies: bundled.dependencies
62674
62774
  };
62675
62775
  }
62676
62776
  catch (e) {
@@ -62678,7 +62778,9 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
62678
62778
  throw e;
62679
62779
  }
62680
62780
  }
62681
- async function bundleConfigFile(fileName, isESM = false) {
62781
+ async function bundleConfigFile(fileName, isESM) {
62782
+ const dirnameVarName = '__vite_injected_original_dirname';
62783
+ const filenameVarName = '__vite_injected_original_filename';
62682
62784
  const importMetaUrlVarName = '__vite_injected_original_import_meta_url';
62683
62785
  const result = await build$3({
62684
62786
  absWorkingDir: process.cwd(),
@@ -62691,19 +62793,48 @@ async function bundleConfigFile(fileName, isESM = false) {
62691
62793
  sourcemap: 'inline',
62692
62794
  metafile: true,
62693
62795
  define: {
62796
+ __dirname: dirnameVarName,
62797
+ __filename: filenameVarName,
62694
62798
  'import.meta.url': importMetaUrlVarName
62695
62799
  },
62696
62800
  plugins: [
62697
62801
  {
62698
62802
  name: 'externalize-deps',
62699
62803
  setup(build) {
62700
- build.onResolve({ filter: /.*/ }, (args) => {
62701
- const id = args.path;
62804
+ build.onResolve({ filter: /.*/ }, ({ path: id, importer }) => {
62805
+ // externalize bare imports
62702
62806
  if (id[0] !== '.' && !path$n.isAbsolute(id)) {
62703
62807
  return {
62704
62808
  external: true
62705
62809
  };
62706
62810
  }
62811
+ // bundle the rest and make sure that the we can also access
62812
+ // it's third-party dependencies. externalize if not.
62813
+ // monorepo/
62814
+ // ├─ package.json
62815
+ // ├─ utils.js -----------> bundle (share same node_modules)
62816
+ // ├─ vite-project/
62817
+ // │ ├─ vite.config.js --> entry
62818
+ // │ ├─ package.json
62819
+ // ├─ foo-project/
62820
+ // │ ├─ utils.js --------> external (has own node_modules)
62821
+ // │ ├─ package.json
62822
+ const idFsPath = path$n.resolve(path$n.dirname(importer), id);
62823
+ const idPkgPath = lookupFile(idFsPath, [`package.json`], {
62824
+ pathOnly: true
62825
+ });
62826
+ if (idPkgPath) {
62827
+ const idPkgDir = path$n.dirname(idPkgPath);
62828
+ // if this file needs to go up one or more directory to reach the vite config,
62829
+ // that means it has it's own node_modules (e.g. foo-project)
62830
+ if (path$n.relative(idPkgDir, fileName).startsWith('..')) {
62831
+ return {
62832
+ // normalize actual import after bundled as a single vite config
62833
+ path: idFsPath,
62834
+ external: true
62835
+ };
62836
+ }
62837
+ }
62707
62838
  });
62708
62839
  }
62709
62840
  },
@@ -62712,11 +62843,11 @@ async function bundleConfigFile(fileName, isESM = false) {
62712
62843
  setup(build) {
62713
62844
  build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
62714
62845
  const contents = await fs$l.promises.readFile(args.path, 'utf8');
62715
- const injectValues = `const __dirname = ${JSON.stringify(path$n.dirname(args.path))};` +
62716
- `const __filename = ${JSON.stringify(args.path)};` +
62846
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$n.dirname(args.path))};` +
62847
+ `const ${filenameVarName} = ${JSON.stringify(args.path)};` +
62717
62848
  `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`;
62718
62849
  return {
62719
- loader: isTS(args.path) ? 'ts' : 'js',
62850
+ loader: args.path.endsWith('ts') ? 'ts' : 'js',
62720
62851
  contents: injectValues + contents
62721
62852
  };
62722
62853
  });
@@ -62731,22 +62862,42 @@ async function bundleConfigFile(fileName, isESM = false) {
62731
62862
  };
62732
62863
  }
62733
62864
  const _require = createRequire$1(import.meta.url);
62734
- async function loadConfigFromBundledFile(fileName, bundledCode) {
62735
- const realFileName = fs$l.realpathSync(fileName);
62736
- const defaultLoader = _require.extensions['.js'];
62737
- _require.extensions['.js'] = (module, filename) => {
62738
- if (filename === realFileName) {
62739
- module._compile(bundledCode, filename);
62865
+ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
62866
+ // for esm, before we can register loaders without requiring users to run node
62867
+ // with --experimental-loader themselves, we have to do a hack here:
62868
+ // write it to disk, load it with native Node ESM, then delete the file.
62869
+ if (isESM) {
62870
+ const fileBase = `${fileName}.timestamp-${Date.now()}`;
62871
+ const fileNameTmp = `${fileBase}.mjs`;
62872
+ const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
62873
+ fs$l.writeFileSync(fileNameTmp, bundledCode);
62874
+ try {
62875
+ return (await dynamicImport(fileUrl)).default;
62740
62876
  }
62741
- else {
62742
- defaultLoader(module, filename);
62877
+ finally {
62878
+ fs$l.unlinkSync(fileNameTmp);
62743
62879
  }
62744
- };
62745
- // clear cache in case of server restart
62746
- delete _require.cache[_require.resolve(fileName)];
62747
- const raw = _require(fileName);
62748
- _require.extensions['.js'] = defaultLoader;
62749
- return raw.__esModule ? raw.default : raw;
62880
+ }
62881
+ // for cjs, we can register a custom loader via `_require.extensions`
62882
+ else {
62883
+ const extension = path$n.extname(fileName);
62884
+ const realFileName = fs$l.realpathSync(fileName);
62885
+ const loaderExt = extension in _require.extensions ? extension : '.js';
62886
+ const defaultLoader = _require.extensions[loaderExt];
62887
+ _require.extensions[loaderExt] = (module, filename) => {
62888
+ if (filename === realFileName) {
62889
+ module._compile(bundledCode, filename);
62890
+ }
62891
+ else {
62892
+ defaultLoader(module, filename);
62893
+ }
62894
+ };
62895
+ // clear cache in case of server restart
62896
+ delete _require.cache[_require.resolve(fileName)];
62897
+ const raw = _require(fileName);
62898
+ _require.extensions[loaderExt] = defaultLoader;
62899
+ return raw.__esModule ? raw.default : raw;
62900
+ }
62750
62901
  }
62751
62902
  function getDepOptimizationConfig(config, ssr) {
62752
62903
  return ssr ? config.ssr.optimizeDeps : config.optimizeDeps;