vite 3.1.4 → 3.2.0-beta.0

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,11 +1,11 @@
1
1
  import fs$l, { promises as promises$2 } from 'node:fs';
2
- import path$n, { posix as posix$2, isAbsolute as isAbsolute$2, resolve as resolve$6, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
2
+ import path$n, { posix as posix$2, isAbsolute as isAbsolute$3, resolve as resolve$6, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
3
3
  import { URL as URL$3, pathToFileURL, URLSearchParams, parse as parse$k } from 'node:url';
4
4
  import { performance } from 'node:perf_hooks';
5
5
  import { createRequire as createRequire$1, builtinModules } from 'node:module';
6
6
  import require$$0$3 from 'tty';
7
7
  import { transform as transform$2, build as build$3, formatMessages } from 'esbuild';
8
- import require$$0$4, { sep, resolve as resolve$4, posix as posix$1, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, win32 as win32$1, isAbsolute as isAbsolute$1, normalize } from 'path';
8
+ import require$$0$4, { sep, resolve as resolve$4, posix as posix$1, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, win32 as win32$1, isAbsolute as isAbsolute$2, normalize } from 'path';
9
9
  import * as require$$0$2 from 'fs';
10
10
  import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdirSync } from 'fs';
11
11
  import require$$0$5 from 'events';
@@ -22,7 +22,7 @@ import { createHash as createHash$2 } from 'node:crypto';
22
22
  import { promisify as promisify$4 } from 'node:util';
23
23
  import { promises } from 'node:dns';
24
24
  import resolve$5 from 'resolve';
25
- import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION, VITE_PACKAGE_DIR, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
25
+ import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, SPECIAL_QUERY_RE, DEP_VERSION_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION, VITE_PACKAGE_DIR, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
26
26
  import require$$5 from 'crypto';
27
27
  import require$$0$a from 'buffer';
28
28
  import { Buffer as Buffer$1 } from 'node:buffer';
@@ -210,7 +210,7 @@ function alias$1(options = {}) {
210
210
  };
211
211
  }
212
212
 
213
- var picomatch$4 = {exports: {}};
213
+ var picomatch$5 = {exports: {}};
214
214
 
215
215
  var utils$k = {};
216
216
 
@@ -1960,9 +1960,9 @@ const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val);
1960
1960
  * @api public
1961
1961
  */
1962
1962
 
1963
- const picomatch$3 = (glob, options, returnState = false) => {
1963
+ const picomatch$4 = (glob, options, returnState = false) => {
1964
1964
  if (Array.isArray(glob)) {
1965
- const fns = glob.map(input => picomatch$3(input, options, returnState));
1965
+ const fns = glob.map(input => picomatch$4(input, options, returnState));
1966
1966
  const arrayMatcher = str => {
1967
1967
  for (const isMatch of fns) {
1968
1968
  const state = isMatch(str);
@@ -1982,8 +1982,8 @@ const picomatch$3 = (glob, options, returnState = false) => {
1982
1982
  const opts = options || {};
1983
1983
  const posix = utils$h.isWindows(options);
1984
1984
  const regex = isState
1985
- ? picomatch$3.compileRe(glob, options)
1986
- : picomatch$3.makeRe(glob, options, false, true);
1985
+ ? picomatch$4.compileRe(glob, options)
1986
+ : picomatch$4.makeRe(glob, options, false, true);
1987
1987
 
1988
1988
  const state = regex.state;
1989
1989
  delete regex.state;
@@ -1991,11 +1991,11 @@ const picomatch$3 = (glob, options, returnState = false) => {
1991
1991
  let isIgnored = () => false;
1992
1992
  if (opts.ignore) {
1993
1993
  const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
1994
- isIgnored = picomatch$3(opts.ignore, ignoreOpts, returnState);
1994
+ isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState);
1995
1995
  }
1996
1996
 
1997
1997
  const matcher = (input, returnObject = false) => {
1998
- const { isMatch, match, output } = picomatch$3.test(input, regex, options, { glob, posix });
1998
+ const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix });
1999
1999
  const result = { glob, state, regex, posix, input, output, match, isMatch };
2000
2000
 
2001
2001
  if (typeof opts.onResult === 'function') {
@@ -2045,7 +2045,7 @@ const picomatch$3 = (glob, options, returnState = false) => {
2045
2045
  * @api public
2046
2046
  */
2047
2047
 
2048
- picomatch$3.test = (input, regex, options, { glob, posix } = {}) => {
2048
+ picomatch$4.test = (input, regex, options, { glob, posix } = {}) => {
2049
2049
  if (typeof input !== 'string') {
2050
2050
  throw new TypeError('Expected input to be a string');
2051
2051
  }
@@ -2066,7 +2066,7 @@ picomatch$3.test = (input, regex, options, { glob, posix } = {}) => {
2066
2066
 
2067
2067
  if (match === false || opts.capture === true) {
2068
2068
  if (opts.matchBase === true || opts.basename === true) {
2069
- match = picomatch$3.matchBase(input, regex, options, posix);
2069
+ match = picomatch$4.matchBase(input, regex, options, posix);
2070
2070
  } else {
2071
2071
  match = regex.exec(output);
2072
2072
  }
@@ -2089,8 +2089,8 @@ picomatch$3.test = (input, regex, options, { glob, posix } = {}) => {
2089
2089
  * @api public
2090
2090
  */
2091
2091
 
2092
- picomatch$3.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => {
2093
- const regex = glob instanceof RegExp ? glob : picomatch$3.makeRe(glob, options);
2092
+ picomatch$4.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => {
2093
+ const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options);
2094
2094
  return regex.test(path$l.basename(input));
2095
2095
  };
2096
2096
 
@@ -2111,7 +2111,7 @@ picomatch$3.matchBase = (input, glob, options, posix = utils$h.isWindows(options
2111
2111
  * @api public
2112
2112
  */
2113
2113
 
2114
- picomatch$3.isMatch = (str, patterns, options) => picomatch$3(patterns, options)(str);
2114
+ picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str);
2115
2115
 
2116
2116
  /**
2117
2117
  * Parse a glob pattern to create the source string for a regular
@@ -2127,8 +2127,8 @@ picomatch$3.isMatch = (str, patterns, options) => picomatch$3(patterns, options)
2127
2127
  * @api public
2128
2128
  */
2129
2129
 
2130
- picomatch$3.parse = (pattern, options) => {
2131
- if (Array.isArray(pattern)) return pattern.map(p => picomatch$3.parse(p, options));
2130
+ picomatch$4.parse = (pattern, options) => {
2131
+ if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options));
2132
2132
  return parse$i(pattern, { ...options, fastpaths: false });
2133
2133
  };
2134
2134
 
@@ -2159,7 +2159,7 @@ picomatch$3.parse = (pattern, options) => {
2159
2159
  * @api public
2160
2160
  */
2161
2161
 
2162
- picomatch$3.scan = (input, options) => scan$1(input, options);
2162
+ picomatch$4.scan = (input, options) => scan$1(input, options);
2163
2163
 
2164
2164
  /**
2165
2165
  * Compile a regular expression from the `state` object returned by the
@@ -2173,7 +2173,7 @@ picomatch$3.scan = (input, options) => scan$1(input, options);
2173
2173
  * @api public
2174
2174
  */
2175
2175
 
2176
- picomatch$3.compileRe = (state, options, returnOutput = false, returnState = false) => {
2176
+ picomatch$4.compileRe = (state, options, returnOutput = false, returnState = false) => {
2177
2177
  if (returnOutput === true) {
2178
2178
  return state.output;
2179
2179
  }
@@ -2187,7 +2187,7 @@ picomatch$3.compileRe = (state, options, returnOutput = false, returnState = fal
2187
2187
  source = `^(?!${source}).*$`;
2188
2188
  }
2189
2189
 
2190
- const regex = picomatch$3.toRegex(source, options);
2190
+ const regex = picomatch$4.toRegex(source, options);
2191
2191
  if (returnState === true) {
2192
2192
  regex.state = state;
2193
2193
  }
@@ -2214,7 +2214,7 @@ picomatch$3.compileRe = (state, options, returnOutput = false, returnState = fal
2214
2214
  * @api public
2215
2215
  */
2216
2216
 
2217
- picomatch$3.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
2217
+ picomatch$4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
2218
2218
  if (!input || typeof input !== 'string') {
2219
2219
  throw new TypeError('Expected a non-empty string');
2220
2220
  }
@@ -2229,7 +2229,7 @@ picomatch$3.makeRe = (input, options = {}, returnOutput = false, returnState = f
2229
2229
  parsed = parse$i(input, options);
2230
2230
  }
2231
2231
 
2232
- return picomatch$3.compileRe(parsed, options, returnOutput, returnState);
2232
+ return picomatch$4.compileRe(parsed, options, returnOutput, returnState);
2233
2233
  };
2234
2234
 
2235
2235
  /**
@@ -2249,7 +2249,7 @@ picomatch$3.makeRe = (input, options = {}, returnOutput = false, returnState = f
2249
2249
  * @api public
2250
2250
  */
2251
2251
 
2252
- picomatch$3.toRegex = (source, options) => {
2252
+ picomatch$4.toRegex = (source, options) => {
2253
2253
  try {
2254
2254
  const opts = options || {};
2255
2255
  return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
@@ -2264,20 +2264,20 @@ picomatch$3.toRegex = (source, options) => {
2264
2264
  * @return {Object}
2265
2265
  */
2266
2266
 
2267
- picomatch$3.constants = constants$4;
2267
+ picomatch$4.constants = constants$4;
2268
2268
 
2269
2269
  /**
2270
2270
  * Expose "picomatch"
2271
2271
  */
2272
2272
 
2273
- var picomatch_1 = picomatch$3;
2273
+ var picomatch_1 = picomatch$4;
2274
2274
 
2275
2275
  (function (module) {
2276
2276
 
2277
2277
  module.exports = picomatch_1;
2278
- } (picomatch$4));
2278
+ } (picomatch$5));
2279
2279
 
2280
- var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$4.exports);
2280
+ var picomatch$3 = /*@__PURE__*/getDefaultExportFromCjs(picomatch$5.exports);
2281
2281
 
2282
2282
  function walk$4(ast, { enter, leave }) {
2283
2283
  return visit$2(ast, null, enter, leave);
@@ -2576,7 +2576,7 @@ const createFilter$2 = function createFilter(include, exclude, options) {
2576
2576
  test: (what) => {
2577
2577
  // this refactor is a tad overly verbose but makes for easy debugging
2578
2578
  const pattern = getMatcherString$1(id, resolutionBase);
2579
- const fn = pm(pattern, { dot: true });
2579
+ const fn = picomatch$3(pattern, { dot: true });
2580
2580
  const result = fn(what);
2581
2581
  return result;
2582
2582
  }
@@ -4327,7 +4327,7 @@ function ownProp (obj, field) {
4327
4327
  var fs$i = require$$0__default;
4328
4328
  var path$i = require$$0$4;
4329
4329
  var minimatch = minimatch_1;
4330
- var isAbsolute = pathIsAbsolute.exports;
4330
+ var isAbsolute$1 = pathIsAbsolute.exports;
4331
4331
  var Minimatch = minimatch.Minimatch;
4332
4332
 
4333
4333
  function alphasort (a, b) {
@@ -4415,7 +4415,7 @@ function setopts (self, pattern, options) {
4415
4415
 
4416
4416
  // TODO: is an absolute `cwd` supposed to be resolved against `root`?
4417
4417
  // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
4418
- self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
4418
+ self.cwdAbs = isAbsolute$1(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
4419
4419
  if (process.platform === "win32")
4420
4420
  self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
4421
4421
  self.nomount = !!options.nomount;
@@ -4514,7 +4514,7 @@ function makeAbs (self, f) {
4514
4514
  var abs = f;
4515
4515
  if (f.charAt(0) === '/') {
4516
4516
  abs = path$i.join(self.root, f);
4517
- } else if (isAbsolute(f) || f === '') {
4517
+ } else if (isAbsolute$1(f) || f === '') {
4518
4518
  abs = f;
4519
4519
  } else if (self.changedCwd) {
4520
4520
  abs = path$i.resolve(self.cwd, f);
@@ -11473,7 +11473,7 @@ const normalizePath$4 = function normalizePath(filename) {
11473
11473
  };
11474
11474
 
11475
11475
  function getMatcherString(id, resolutionBase) {
11476
- if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
11476
+ if (resolutionBase === false || isAbsolute$2(id) || id.startsWith('*')) {
11477
11477
  return normalizePath$4(id);
11478
11478
  }
11479
11479
  // resolve('') is valid and will default to process.cwd()
@@ -11494,7 +11494,7 @@ const createFilter$1 = function createFilter(include, exclude, options) {
11494
11494
  test: (what) => {
11495
11495
  // this refactor is a tad overly verbose but makes for easy debugging
11496
11496
  const pattern = getMatcherString(id, resolutionBase);
11497
- const fn = pm(pattern, { dot: true });
11497
+ const fn = picomatch$3(pattern, { dot: true });
11498
11498
  const result = fn(what);
11499
11499
  return result;
11500
11500
  }
@@ -11995,16 +11995,46 @@ function isFileReadable(filename) {
11995
11995
  return false;
11996
11996
  }
11997
11997
  }
11998
+ const splitFirstDirRE = /(.+?)[\\/](.+)/;
11998
11999
  /**
11999
12000
  * Delete every file and subdirectory. **The given directory must exist.**
12000
- * Pass an optional `skip` array to preserve files in the root directory.
12001
+ * Pass an optional `skip` array to preserve files under the root directory.
12001
12002
  */
12002
12003
  function emptyDir(dir, skip) {
12004
+ const skipInDir = [];
12005
+ let nested = null;
12006
+ if (skip?.length) {
12007
+ for (const file of skip) {
12008
+ if (path$n.dirname(file) !== '.') {
12009
+ const matched = file.match(splitFirstDirRE);
12010
+ if (matched) {
12011
+ nested ?? (nested = new Map());
12012
+ const [, nestedDir, skipPath] = matched;
12013
+ let nestedSkip = nested.get(nestedDir);
12014
+ if (!nestedSkip) {
12015
+ nestedSkip = [];
12016
+ nested.set(nestedDir, nestedSkip);
12017
+ }
12018
+ if (!nestedSkip.includes(skipPath)) {
12019
+ nestedSkip.push(skipPath);
12020
+ }
12021
+ }
12022
+ }
12023
+ else {
12024
+ skipInDir.push(file);
12025
+ }
12026
+ }
12027
+ }
12003
12028
  for (const file of fs$l.readdirSync(dir)) {
12004
- if (skip?.includes(file)) {
12029
+ if (skipInDir.includes(file)) {
12005
12030
  continue;
12006
12031
  }
12007
- fs$l.rmSync(path$n.resolve(dir, file), { recursive: true, force: true });
12032
+ if (nested?.has(file)) {
12033
+ emptyDir(path$n.resolve(dir, file), nested.get(file));
12034
+ }
12035
+ else {
12036
+ fs$l.rmSync(path$n.resolve(dir, file), { recursive: true, force: true });
12037
+ }
12008
12038
  }
12009
12039
  }
12010
12040
  function copyDir(srcDir, destDir) {
@@ -15503,7 +15533,7 @@ var braces_1 = braces$2;
15503
15533
 
15504
15534
  const util$1 = require$$0$6;
15505
15535
  const braces$1 = braces_1;
15506
- const picomatch$2 = picomatch$4.exports;
15536
+ const picomatch$2 = picomatch$5.exports;
15507
15537
  const utils$b = utils$k;
15508
15538
  const isEmptyString = val => val === '' || val === './';
15509
15539
 
@@ -26127,11 +26157,10 @@ class Chunk {
26127
26157
  this.storeName = false;
26128
26158
  this.edited = false;
26129
26159
 
26130
- // we make these non-enumerable, for sanity while debugging
26131
- Object.defineProperties(this, {
26132
- previous: { writable: true, value: null },
26133
- next: { writable: true, value: null },
26134
- });
26160
+ {
26161
+ this.previous = null;
26162
+ this.next = null;
26163
+ }
26135
26164
  }
26136
26165
 
26137
26166
  appendLeft(content) {
@@ -27142,7 +27171,7 @@ class MagicString {
27142
27171
  return this.original !== this.toString();
27143
27172
  }
27144
27173
 
27145
- replace(searchValue, replacement) {
27174
+ _replaceRegexp(searchValue, replacement) {
27146
27175
  function getReplacement(match, str) {
27147
27176
  if (typeof replacement === 'string') {
27148
27177
  return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
@@ -27165,7 +27194,7 @@ class MagicString {
27165
27194
  }
27166
27195
  return matches;
27167
27196
  }
27168
- if (typeof searchValue !== 'string' && searchValue.global) {
27197
+ if (searchValue.global) {
27169
27198
  const matches = matchAll(searchValue, this.original);
27170
27199
  matches.forEach((match) => {
27171
27200
  if (match.index != null)
@@ -27186,6 +27215,53 @@ class MagicString {
27186
27215
  }
27187
27216
  return this;
27188
27217
  }
27218
+
27219
+ _replaceString(string, replacement) {
27220
+ const { original } = this;
27221
+ const index = original.indexOf(string);
27222
+
27223
+ if (index !== -1) {
27224
+ this.overwrite(index, index + string.length, replacement);
27225
+ }
27226
+
27227
+ return this;
27228
+ }
27229
+
27230
+ replace(searchValue, replacement) {
27231
+ if (typeof searchValue === 'string') {
27232
+ return this._replaceString(searchValue, replacement);
27233
+ }
27234
+
27235
+ return this._replaceRegexp(searchValue, replacement);
27236
+ }
27237
+
27238
+ _replaceAllString(string, replacement) {
27239
+ const { original } = this;
27240
+ const stringLength = string.length;
27241
+ for (
27242
+ let index = original.indexOf(string);
27243
+ index !== -1;
27244
+ index = original.indexOf(string, index + stringLength)
27245
+ ) {
27246
+ this.overwrite(index, index + stringLength, replacement);
27247
+ }
27248
+
27249
+ return this;
27250
+ }
27251
+
27252
+ replaceAll(searchValue, replacement) {
27253
+ if (typeof searchValue === 'string') {
27254
+ return this._replaceAllString(searchValue, replacement);
27255
+ }
27256
+
27257
+ if (!searchValue.global) {
27258
+ throw new TypeError(
27259
+ 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
27260
+ );
27261
+ }
27262
+
27263
+ return this._replaceRegexp(searchValue, replacement);
27264
+ }
27189
27265
  }
27190
27266
 
27191
27267
  const isDebug$6 = !!process.env.DEBUG;
@@ -32875,7 +32951,7 @@ function stripLiteralAcorn(code) {
32875
32951
  }
32876
32952
 
32877
32953
  const multilineCommentsRE = /\/\*.*?\*\//gms;
32878
- const singlelineCommentsRE = /\/\/.*$/gm;
32954
+ const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm;
32879
32955
  const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g;
32880
32956
  const quotesRE = [
32881
32957
  /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
@@ -33323,6 +33399,7 @@ function lookup(extn) {
33323
33399
  }
33324
33400
 
33325
33401
  const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
33402
+ const duplicateAssets = new WeakMap();
33326
33403
  const rawRE = /(\?|&)raw(?:&|$)/;
33327
33404
  const urlRE = /(\?|&)url(?:&|$)/;
33328
33405
  const assetCache = new WeakMap();
@@ -33341,6 +33418,7 @@ function registerCustomMime() {
33341
33418
  mimes$1['eot'] = 'application/vnd.ms-fontobject';
33342
33419
  }
33343
33420
  function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
33421
+ const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format);
33344
33422
  let match;
33345
33423
  let s;
33346
33424
  // Urls added with JS using e.g.
@@ -33356,7 +33434,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
33356
33434
  const file = getAssetFilename(hash, config) || ctx.getFileName(hash);
33357
33435
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
33358
33436
  const filename = file + postfix;
33359
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, opts.format);
33437
+ const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
33360
33438
  const replacementString = typeof replacement === 'string'
33361
33439
  ? JSON.stringify(replacement).slice(1, -1)
33362
33440
  : `"+${replacement.runtime}+"`;
@@ -33370,7 +33448,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
33370
33448
  s || (s = new MagicString(code));
33371
33449
  const [full, hash] = match;
33372
33450
  const publicUrl = publicAssetUrlMap.get(hash).slice(1);
33373
- const replacement = toOutputFilePathInString(publicUrl, 'public', chunk.fileName, 'js', config, opts.format);
33451
+ const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime);
33374
33452
  const replacementString = typeof replacement === 'string'
33375
33453
  ? JSON.stringify(replacement).slice(1, -1)
33376
33454
  : `"+${replacement.runtime}+"`;
@@ -33392,6 +33470,7 @@ function assetPlugin(config) {
33392
33470
  buildStart() {
33393
33471
  assetCache.set(config, new Map());
33394
33472
  emittedHashMap.set(config, new Set());
33473
+ duplicateAssets.set(config, new Map());
33395
33474
  },
33396
33475
  resolveId(id) {
33397
33476
  if (!config.assetsInclude(cleanUrl(id))) {
@@ -33651,8 +33730,9 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
33651
33730
  map.set(contentHash, fileName);
33652
33731
  }
33653
33732
  const emittedSet = emittedHashMap.get(config);
33733
+ const duplicates = duplicateAssets.get(config);
33734
+ const name = normalizePath$3(path$n.relative(config.root, file));
33654
33735
  if (!emittedSet.has(contentHash)) {
33655
- const name = normalizePath$3(path$n.relative(config.root, file));
33656
33736
  pluginContext.emitFile({
33657
33737
  name,
33658
33738
  fileName,
@@ -33661,6 +33741,15 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
33661
33741
  });
33662
33742
  emittedSet.add(contentHash);
33663
33743
  }
33744
+ else {
33745
+ duplicates.set(name, {
33746
+ name,
33747
+ fileName: map.get(contentHash),
33748
+ type: 'asset',
33749
+ source: content,
33750
+ isAsset: true
33751
+ });
33752
+ }
33664
33753
  url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE
33665
33754
  }
33666
33755
  cache.set(id, url);
@@ -34184,6 +34273,284 @@ function watchPackageDataPlugin(config) {
34184
34273
  };
34185
34274
  }
34186
34275
 
34276
+ const WORKER_FILE_ID = 'worker_file';
34277
+ const workerCache = new WeakMap();
34278
+ function isWorkerRequest(id) {
34279
+ const query = parseRequest(id);
34280
+ if (query && query[WORKER_FILE_ID] != null) {
34281
+ return true;
34282
+ }
34283
+ return false;
34284
+ }
34285
+ function saveEmitWorkerAsset(config, asset) {
34286
+ const fileName = asset.fileName;
34287
+ const workerMap = workerCache.get(config.mainConfig || config);
34288
+ workerMap.assets.set(fileName, asset);
34289
+ }
34290
+ async function bundleWorkerEntry(config, id, query) {
34291
+ // bundle the file as entry to support imports
34292
+ const { rollup } = await import('rollup');
34293
+ const { plugins, rollupOptions, format } = config.worker;
34294
+ const bundle = await rollup({
34295
+ ...rollupOptions,
34296
+ input: cleanUrl(id),
34297
+ plugins,
34298
+ onwarn(warning, warn) {
34299
+ onRollupWarning(warning, warn, config);
34300
+ },
34301
+ preserveEntrySignatures: false
34302
+ });
34303
+ let chunk;
34304
+ try {
34305
+ const workerOutputConfig = config.worker.rollupOptions.output;
34306
+ const workerConfig = workerOutputConfig
34307
+ ? Array.isArray(workerOutputConfig)
34308
+ ? workerOutputConfig[0] || {}
34309
+ : workerOutputConfig
34310
+ : {};
34311
+ const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
34312
+ entryFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].js'),
34313
+ chunkFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].js'),
34314
+ assetFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].[ext]'),
34315
+ ...workerConfig,
34316
+ format,
34317
+ sourcemap: config.build.sourcemap
34318
+ });
34319
+ chunk = outputChunk;
34320
+ outputChunks.forEach((outputChunk) => {
34321
+ if (outputChunk.type === 'asset') {
34322
+ saveEmitWorkerAsset(config, outputChunk);
34323
+ }
34324
+ else if (outputChunk.type === 'chunk') {
34325
+ saveEmitWorkerAsset(config, {
34326
+ fileName: outputChunk.fileName,
34327
+ source: outputChunk.code,
34328
+ type: 'asset'
34329
+ });
34330
+ }
34331
+ });
34332
+ }
34333
+ finally {
34334
+ await bundle.close();
34335
+ }
34336
+ return emitSourcemapForWorkerEntry(config, query, chunk);
34337
+ }
34338
+ function emitSourcemapForWorkerEntry(config, query, chunk) {
34339
+ const { map: sourcemap } = chunk;
34340
+ if (sourcemap) {
34341
+ if (config.build.sourcemap === 'inline') {
34342
+ // Manually add the sourcemap to the code if configured for inline sourcemaps.
34343
+ // TODO: Remove when https://github.com/rollup/rollup/issues/3913 is resolved
34344
+ // Currently seems that it won't be resolved until Rollup 3
34345
+ const dataUrl = sourcemap.toUrl();
34346
+ chunk.code += `//# sourceMappingURL=${dataUrl}`;
34347
+ }
34348
+ else if (config.build.sourcemap === 'hidden' ||
34349
+ config.build.sourcemap === true) {
34350
+ const data = sourcemap.toString();
34351
+ const mapFileName = chunk.fileName + '.map';
34352
+ saveEmitWorkerAsset(config, {
34353
+ fileName: mapFileName,
34354
+ type: 'asset',
34355
+ source: data
34356
+ });
34357
+ // Emit the comment that tells the JS debugger where it can find the
34358
+ // sourcemap file.
34359
+ // 'hidden' causes the sourcemap file to be created but
34360
+ // the comment in the file to be omitted.
34361
+ if (config.build.sourcemap === true) {
34362
+ // inline web workers need to use the full sourcemap path
34363
+ // non-inline web workers can use a relative path
34364
+ const sourceMapUrl = query?.inline != null
34365
+ ? mapFileName
34366
+ : path$n.relative(config.build.assetsDir, mapFileName);
34367
+ chunk.code += `//# sourceMappingURL=${sourceMapUrl}`;
34368
+ }
34369
+ }
34370
+ }
34371
+ return chunk;
34372
+ }
34373
+ const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
34374
+ function encodeWorkerAssetFileName(fileName, workerCache) {
34375
+ const { fileNameHash } = workerCache;
34376
+ const hash = getHash(fileName);
34377
+ if (!fileNameHash.get(hash)) {
34378
+ fileNameHash.set(hash, fileName);
34379
+ }
34380
+ return `__VITE_WORKER_ASSET__${hash}__`;
34381
+ }
34382
+ async function workerFileToUrl(config, id, query) {
34383
+ const workerMap = workerCache.get(config.mainConfig || config);
34384
+ let fileName = workerMap.bundle.get(id);
34385
+ if (!fileName) {
34386
+ const outputChunk = await bundleWorkerEntry(config, id, query);
34387
+ fileName = outputChunk.fileName;
34388
+ saveEmitWorkerAsset(config, {
34389
+ fileName,
34390
+ source: outputChunk.code,
34391
+ type: 'asset'
34392
+ });
34393
+ workerMap.bundle.set(id, fileName);
34394
+ }
34395
+ return encodeWorkerAssetFileName(fileName, workerMap);
34396
+ }
34397
+ function webWorkerPlugin(config) {
34398
+ const isBuild = config.command === 'build';
34399
+ let server;
34400
+ const isWorker = config.isWorker;
34401
+ return {
34402
+ name: 'vite:worker',
34403
+ configureServer(_server) {
34404
+ server = _server;
34405
+ },
34406
+ buildStart() {
34407
+ if (isWorker) {
34408
+ return;
34409
+ }
34410
+ workerCache.set(config, {
34411
+ assets: new Map(),
34412
+ bundle: new Map(),
34413
+ fileNameHash: new Map()
34414
+ });
34415
+ },
34416
+ load(id) {
34417
+ if (isBuild) {
34418
+ const parsedQuery = parseRequest(id);
34419
+ if (parsedQuery &&
34420
+ (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
34421
+ return '';
34422
+ }
34423
+ }
34424
+ },
34425
+ async transform(raw, id, options) {
34426
+ const ssr = options?.ssr === true;
34427
+ const query = parseRequest(id);
34428
+ if (query && query[WORKER_FILE_ID] != null) {
34429
+ // if import worker by worker constructor will have query.type
34430
+ // other type will be import worker by esm
34431
+ const workerType = query['type'];
34432
+ let injectEnv = '';
34433
+ if (workerType === 'classic') {
34434
+ injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
34435
+ }
34436
+ else if (workerType === 'module') {
34437
+ injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
34438
+ }
34439
+ else if (workerType === 'ignore') {
34440
+ if (isBuild) {
34441
+ injectEnv = '';
34442
+ }
34443
+ else if (server) {
34444
+ // dynamic worker type we can't know how import the env
34445
+ // so we copy /@vite/env code of server transform result into file header
34446
+ const { moduleGraph } = server;
34447
+ const module = moduleGraph.getModuleById(ENV_ENTRY);
34448
+ injectEnv = module?.transformResult?.code || '';
34449
+ }
34450
+ }
34451
+ return {
34452
+ code: injectEnv + raw
34453
+ };
34454
+ }
34455
+ if (query == null ||
34456
+ (query && (query.worker ?? query.sharedworker) == null)) {
34457
+ return;
34458
+ }
34459
+ // stringified url or `new URL(...)`
34460
+ let url;
34461
+ const { format } = config.worker;
34462
+ const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
34463
+ const workerType = isBuild
34464
+ ? format === 'es'
34465
+ ? 'module'
34466
+ : 'classic'
34467
+ : 'module';
34468
+ const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
34469
+ if (isBuild) {
34470
+ getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
34471
+ if (query.inline != null) {
34472
+ const chunk = await bundleWorkerEntry(config, id, query);
34473
+ // inline as blob data url
34474
+ return {
34475
+ code: `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";
34476
+ const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
34477
+ export default function WorkerWrapper() {
34478
+ const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
34479
+ try {
34480
+ return objURL ? new ${workerConstructor}(objURL) : new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
34481
+ } finally {
34482
+ objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
34483
+ }
34484
+ }`,
34485
+ // Empty sourcemap to suppress Rollup warning
34486
+ map: { mappings: '' }
34487
+ };
34488
+ }
34489
+ else {
34490
+ url = await workerFileToUrl(config, id, query);
34491
+ }
34492
+ }
34493
+ else {
34494
+ url = await fileToUrl(cleanUrl(id), config, this);
34495
+ url = injectQuery(url, WORKER_FILE_ID);
34496
+ url = injectQuery(url, `type=${workerType}`);
34497
+ }
34498
+ if (query.url != null) {
34499
+ return {
34500
+ code: `export default ${JSON.stringify(url)}`,
34501
+ map: { mappings: '' } // Empty sourcemap to suppress Rollup warning
34502
+ };
34503
+ }
34504
+ return {
34505
+ code: `export default function WorkerWrapper() {
34506
+ return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
34507
+ }`,
34508
+ map: { mappings: '' } // Empty sourcemap to suppress Rollup warning
34509
+ };
34510
+ },
34511
+ renderChunk(code, chunk, outputOptions) {
34512
+ let s;
34513
+ const result = () => {
34514
+ return (s && {
34515
+ code: s.toString(),
34516
+ map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
34517
+ });
34518
+ };
34519
+ if (code.match(workerAssetUrlRE) || code.includes('import.meta.url')) {
34520
+ const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format);
34521
+ let match;
34522
+ s = new MagicString(code);
34523
+ // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
34524
+ const workerMap = workerCache.get(config.mainConfig || config);
34525
+ const { fileNameHash } = workerMap;
34526
+ while ((match = workerAssetUrlRE.exec(code))) {
34527
+ const [full, hash] = match;
34528
+ const filename = fileNameHash.get(hash);
34529
+ const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
34530
+ const replacementString = typeof replacement === 'string'
34531
+ ? JSON.stringify(replacement).slice(1, -1)
34532
+ : `"+${replacement.runtime}+"`;
34533
+ s.overwrite(match.index, match.index + full.length, replacementString, {
34534
+ contentOnly: true
34535
+ });
34536
+ }
34537
+ }
34538
+ return result();
34539
+ },
34540
+ generateBundle(opts) {
34541
+ // @ts-ignore asset emits are skipped in legacy bundle
34542
+ if (opts.__vite_skip_asset_emit__ || isWorker) {
34543
+ return;
34544
+ }
34545
+ const workerMap = workerCache.get(config);
34546
+ workerMap.assets.forEach((asset) => {
34547
+ this.emitFile(asset);
34548
+ workerMap.assets.delete(asset.fileName);
34549
+ });
34550
+ }
34551
+ };
34552
+ }
34553
+
34187
34554
  const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
34188
34555
  const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
34189
34556
  // special id for paths marked with browser: false
@@ -34218,12 +34585,15 @@ function resolvePlugin(resolveOptions) {
34218
34585
  scan: resolveOpts?.scan ?? resolveOptions.scan
34219
34586
  };
34220
34587
  if (importer) {
34221
- if (isTsRequest(importer) ||
34588
+ const _importer = isWorkerRequest(importer)
34589
+ ? splitFileAndPostfix(importer).file
34590
+ : importer;
34591
+ if (isTsRequest(_importer) ||
34222
34592
  resolveOpts.custom?.depScan?.loader?.startsWith('ts')) {
34223
34593
  options.isFromTsImporter = true;
34224
34594
  }
34225
34595
  else {
34226
- const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang;
34596
+ const moduleLang = this.getModuleInfo(_importer)?.meta?.vite?.lang;
34227
34597
  options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
34228
34598
  }
34229
34599
  }
@@ -34294,6 +34664,7 @@ function resolvePlugin(resolveOptions) {
34294
34664
  return normalizedFsPath;
34295
34665
  }
34296
34666
  if (targetWeb &&
34667
+ options.browserField &&
34297
34668
  (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
34298
34669
  return res;
34299
34670
  }
@@ -34351,6 +34722,7 @@ function resolvePlugin(resolveOptions) {
34351
34722
  return res;
34352
34723
  }
34353
34724
  if (targetWeb &&
34725
+ options.browserField &&
34354
34726
  (res = tryResolveBrowserMapping(id, importer, options, false, external))) {
34355
34727
  return res;
34356
34728
  }
@@ -34438,7 +34810,7 @@ function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
34438
34810
  if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
34439
34811
  return res;
34440
34812
  }
34441
- for (const ext of options.extensions || DEFAULT_EXTENSIONS$1) {
34813
+ for (const ext of options.extensions) {
34442
34814
  if (postfix &&
34443
34815
  (res = tryResolveFile(fsPath + ext, '', options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
34444
34816
  return res;
@@ -34618,7 +34990,9 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
34618
34990
  let resolvedId = id;
34619
34991
  if (isDeepImport) {
34620
34992
  if (!pkg?.data.exports && path$n.extname(id) !== resolvedExt) {
34621
- resolvedId += resolvedExt;
34993
+ resolvedId = resolved.id.slice(resolved.id.indexOf(id));
34994
+ isDebug$4 &&
34995
+ debug$c(`[processResult] ${picocolors.exports.cyan(id)} -> ${picocolors.exports.dim(resolvedId)}`);
34622
34996
  }
34623
34997
  }
34624
34998
  return { ...resolved, id: resolvedId, external: true };
@@ -34759,7 +35133,9 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
34759
35133
  // This is because .mjs files can technically import .cjs files which would
34760
35134
  // make them invalid for pure ESM environments - so if other module/browser
34761
35135
  // fields are present, prioritize those instead.
34762
- if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) {
35136
+ if (targetWeb &&
35137
+ options.browserField &&
35138
+ (!entryPoint || entryPoint.endsWith('.mjs'))) {
34763
35139
  // check browser field
34764
35140
  // https://github.com/defunctzombie/package-browser-field-spec
34765
35141
  const browserEntry = typeof data.browser === 'string'
@@ -34768,6 +35144,7 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
34768
35144
  if (browserEntry) {
34769
35145
  // check if the package also has a "module" field.
34770
35146
  if (!options.isRequire &&
35147
+ options.mainFields.includes('module') &&
34771
35148
  typeof data.module === 'string' &&
34772
35149
  data.module !== browserEntry) {
34773
35150
  // if both are present, we may have a problem: some package points both
@@ -34795,7 +35172,9 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
34795
35172
  }
34796
35173
  }
34797
35174
  if (!entryPoint || entryPoint.endsWith('.mjs')) {
34798
- for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) {
35175
+ for (const field of options.mainFields) {
35176
+ if (field === 'browser')
35177
+ continue; // already checked above
34799
35178
  if (typeof data[field] === 'string') {
34800
35179
  entryPoint = data[field];
34801
35180
  break;
@@ -34810,14 +35189,14 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
34810
35189
  : ['index.js', 'index.json', 'index.node'];
34811
35190
  for (let entry of entryPoints) {
34812
35191
  // make sure we don't get scripts when looking for sass
34813
- if (options.mainFields?.[0] === 'sass' &&
34814
- !options.extensions?.includes(path$n.extname(entry))) {
35192
+ if (options.mainFields[0] === 'sass' &&
35193
+ !options.extensions.includes(path$n.extname(entry))) {
34815
35194
  entry = '';
34816
35195
  options.skipPackageJson = true;
34817
35196
  }
34818
35197
  // resolve object browser field in package.json
34819
35198
  const { browser: browserField } = data;
34820
- if (targetWeb && isObject$2(browserField)) {
35199
+ if (targetWeb && options.browserField && isObject$2(browserField)) {
34821
35200
  entry = mapWithBrowserField(entry, browserField) || entry;
34822
35201
  }
34823
35202
  const entryPointPath = path$n.join(dir, entry);
@@ -34845,12 +35224,12 @@ function resolveExports(pkg, key, options, targetWeb) {
34845
35224
  if (!options.isRequire) {
34846
35225
  conditions.push('module');
34847
35226
  }
34848
- if (options.conditions) {
35227
+ if (options.conditions.length > 0) {
34849
35228
  conditions.push(...options.conditions);
34850
35229
  }
34851
35230
  return resolve(pkg, key, {
34852
- browser: targetWeb,
34853
- require: options.isRequire,
35231
+ browser: targetWeb && !conditions.includes('node'),
35232
+ require: options.isRequire && !conditions.includes('import'),
34854
35233
  conditions
34855
35234
  });
34856
35235
  }
@@ -34883,7 +35262,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
34883
35262
  `${path$n.join(dir, 'package.json')}.`);
34884
35263
  }
34885
35264
  }
34886
- else if (targetWeb && isObject$2(browserField)) {
35265
+ else if (targetWeb && options.browserField && isObject$2(browserField)) {
34887
35266
  // resolve without postfix (see #7098)
34888
35267
  const { file, postfix } = splitFileAndPostfix(relativeId);
34889
35268
  const mapped = mapWithBrowserField(file, browserField);
@@ -34907,7 +35286,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
34907
35286
  }
34908
35287
  function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
34909
35288
  let res;
34910
- const pkg = importer && idToPkgMap.get(importer);
35289
+ const pkg = importer && (idToPkgMap.get(importer) || resolvePkg(importer, options));
34911
35290
  if (pkg && isObject$2(pkg.data.browser)) {
34912
35291
  const mapId = isFilePath ? './' + slash$1(path$n.relative(pkg.dir, id)) : id;
34913
35292
  const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
@@ -34958,6 +35337,36 @@ function getRealPath(resolved, preserveSymlinks) {
34958
35337
  }
34959
35338
  return normalizePath$3(resolved);
34960
35339
  }
35340
+ /**
35341
+ * if importer was not resolved by vite's resolver previously
35342
+ * (when esbuild resolved it)
35343
+ * resolve importer's pkg and add to idToPkgMap
35344
+ */
35345
+ function resolvePkg(importer, options) {
35346
+ const { root, preserveSymlinks, packageCache } = options;
35347
+ if (importer.includes('\x00')) {
35348
+ return null;
35349
+ }
35350
+ const possiblePkgIds = [];
35351
+ for (let prevSlashIndex = -1;;) {
35352
+ const slashIndex = importer.indexOf(isWindows$4 ? '\\' : '/', prevSlashIndex);
35353
+ if (slashIndex < 0) {
35354
+ break;
35355
+ }
35356
+ prevSlashIndex = slashIndex + 1;
35357
+ const possiblePkgId = importer.slice(0, slashIndex);
35358
+ possiblePkgIds.push(possiblePkgId);
35359
+ }
35360
+ let pkg;
35361
+ possiblePkgIds.reverse().find((pkgId) => {
35362
+ pkg = resolvePackageData(pkgId, root, preserveSymlinks, packageCache);
35363
+ return pkg;
35364
+ });
35365
+ if (pkg) {
35366
+ idToPkgMap.set(importer, pkg);
35367
+ }
35368
+ return pkg;
35369
+ }
34961
35370
 
34962
35371
  const externalWithConversionNamespace = 'vite:dep-pre-bundle:external-conversion';
34963
35372
  const convertedExternalPrefix = 'vite-dep-pre-bundle-external:';
@@ -35254,7 +35663,7 @@ function cjsSsrResolveExternals(config, knownImports) {
35254
35663
  ssrExternals.add(id);
35255
35664
  seen.add(id);
35256
35665
  });
35257
- cjsSsrCollectExternals(config.root, config.resolve.preserveSymlinks, ssrExternals, seen, config.logger);
35666
+ cjsSsrCollectExternals(config.root, config.resolve, ssrExternals, seen, config.logger);
35258
35667
  const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
35259
35668
  for (const dep of importedDeps) {
35260
35669
  // Assume external if not yet seen
@@ -35292,8 +35701,8 @@ function createIsConfiguredAsSsrExternal(config) {
35292
35701
  typeof noExternal !== 'boolean' &&
35293
35702
  createFilter(undefined, noExternal, { resolve: false });
35294
35703
  const resolveOptions = {
35704
+ ...config.resolve,
35295
35705
  root,
35296
- preserveSymlinks: config.resolve.preserveSymlinks,
35297
35706
  isProduction: false,
35298
35707
  isBuild: true
35299
35708
  };
@@ -35364,7 +35773,7 @@ function createIsSsrExternal(config) {
35364
35773
  }
35365
35774
  // When config.experimental.buildSsrCjsExternalHeuristics is enabled, this function
35366
35775
  // is used reverting to the Vite 2.9 SSR externalization heuristics
35367
- function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
35776
+ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger) {
35368
35777
  const rootPkgContent = lookupFile(root, ['package.json']);
35369
35778
  if (!rootPkgContent) {
35370
35779
  return;
@@ -35374,9 +35783,9 @@ function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logg
35374
35783
  ...rootPkg.devDependencies,
35375
35784
  ...rootPkg.dependencies
35376
35785
  };
35377
- const resolveOptions = {
35786
+ const internalResolveOptions = {
35787
+ ...resolveOptions,
35378
35788
  root,
35379
- preserveSymlinks,
35380
35789
  isProduction: false,
35381
35790
  isBuild: true
35382
35791
  };
@@ -35388,7 +35797,7 @@ function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logg
35388
35797
  let esmEntry;
35389
35798
  let requireEntry;
35390
35799
  try {
35391
- esmEntry = tryNodeResolve(id, undefined, resolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry
35800
+ esmEntry = tryNodeResolve(id, undefined, internalResolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry
35392
35801
  undefined, true)?.id;
35393
35802
  // normalizePath required for windows. tryNodeResolve uses normalizePath
35394
35803
  // which returns with '/', require.resolve returns with '\\'
@@ -35448,7 +35857,7 @@ function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logg
35448
35857
  }
35449
35858
  }
35450
35859
  for (const depRoot of depsToTrace) {
35451
- cjsSsrCollectExternals(depRoot, preserveSymlinks, ssrExternals, seen, logger);
35860
+ cjsSsrCollectExternals(depRoot, resolveOptions, ssrExternals, seen, logger);
35452
35861
  }
35453
35862
  }
35454
35863
  function cjsShouldExternalizeForSSR(id, externals) {
@@ -35680,11 +36089,11 @@ function throwOutdatedRequest(id) {
35680
36089
  throw err;
35681
36090
  }
35682
36091
 
35683
- const { isMatch: isMatch$2, scan } = micromatch_1;
36092
+ const { isMatch: isMatch$1, scan } = micromatch_1;
35684
36093
  function getAffectedGlobModules(file, server) {
35685
36094
  const modules = [];
35686
36095
  for (const [id, allGlobs] of server._importGlobMap) {
35687
- if (allGlobs.some((glob) => isMatch$2(file, glob)))
36096
+ if (allGlobs.some((glob) => isMatch$1(file, glob)))
35688
36097
  modules.push(...(server.moduleGraph.getModulesByFile(id) || []));
35689
36098
  }
35690
36099
  modules.forEach((i) => {
@@ -36036,7 +36445,7 @@ async function toAbsoluteGlob(glob, root, importer, resolveId) {
36036
36445
  if (glob.startsWith('**'))
36037
36446
  return pre + glob;
36038
36447
  const resolved = normalizePath$3((await resolveId(glob, importer)) || glob);
36039
- if (isAbsolute$2(resolved)) {
36448
+ if (isAbsolute$3(resolved)) {
36040
36449
  return pre + globSafeResolvedPath(resolved, glob);
36041
36450
  }
36042
36451
  throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
@@ -36161,11 +36570,11 @@ function updateModules(file, modules, timestamp, { config, ws }) {
36161
36570
  updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({
36162
36571
  type: `${boundary.type}-update`,
36163
36572
  timestamp,
36164
- path: boundary.url,
36573
+ path: normalizeHmrUrl(boundary.url),
36165
36574
  explicitImportRequired: boundary.type === 'js'
36166
36575
  ? isExplicitImportRequired(acceptedVia.url)
36167
36576
  : undefined,
36168
- acceptedPath: acceptedVia.url
36577
+ acceptedPath: normalizeHmrUrl(acceptedVia.url)
36169
36578
  })));
36170
36579
  }
36171
36580
  if (needFullReload) {
@@ -36433,6 +36842,12 @@ function lexAcceptedHmrExports(code, start, exportNames) {
36433
36842
  }
36434
36843
  return urls.size > 0;
36435
36844
  }
36845
+ function normalizeHmrUrl(url) {
36846
+ if (!url.startsWith('.') && !url.startsWith('/')) {
36847
+ url = wrapId(url);
36848
+ }
36849
+ return url;
36850
+ }
36436
36851
  function error$1(pos) {
36437
36852
  const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` +
36438
36853
  `Array of string literals.`);
@@ -36859,7 +37274,7 @@ function parse$a(req) {
36859
37274
 
36860
37275
  const noop$2 = () => {};
36861
37276
 
36862
- function isMatch$1(uri, arr) {
37277
+ function isMatch(uri, arr) {
36863
37278
  for (let i=0; i < arr.length; i++) {
36864
37279
  if (arr[i].test(uri)) return true;
36865
37280
  }
@@ -37025,7 +37440,7 @@ function sirv (dir, opts={}) {
37025
37440
  catch (err) { /* malform uri */ }
37026
37441
  }
37027
37442
 
37028
- let data = lookup(pathname, extns) || isSPA && !isMatch$1(pathname, ignores) && lookup(fallback, extns);
37443
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
37029
37444
  if (!data) return next ? next() : isNotFound(req, res);
37030
37445
 
37031
37446
  if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
@@ -37042,7 +37457,6 @@ function sirv (dir, opts={}) {
37042
37457
  };
37043
37458
  }
37044
37459
 
37045
- const { isMatch } = micromatch_1;
37046
37460
  const sirvOptions = (headers) => {
37047
37461
  return {
37048
37462
  dev: true,
@@ -37151,12 +37565,11 @@ function serveRawFsMiddleware(server) {
37151
37565
  }
37152
37566
  };
37153
37567
  }
37154
- const _matchOptions = { matchBase: true };
37155
37568
  function isFileServingAllowed(url, server) {
37156
37569
  if (!server.config.server.fs.strict)
37157
37570
  return true;
37158
37571
  const file = fsPathFromUrl(url);
37159
- if (server.config.server.fs.deny.some((i) => isMatch(file, i, _matchOptions)))
37572
+ if (server._fsDenyGlob(file))
37160
37573
  return false;
37161
37574
  if (server.moduleGraph.safeModulesPath.has(file))
37162
37575
  return true;
@@ -37471,7 +37884,7 @@ function extractImportedBindings(id, source, importSpec, importedBindings) {
37471
37884
  * ```
37472
37885
  *
37473
37886
  * - CSS imports are appended with `.js` since both the js module and the actual
37474
- * css (referenced via <link>) may go through the transform pipeline:
37887
+ * css (referenced via `<link>`) may go through the transform pipeline:
37475
37888
  *
37476
37889
  * ```js
37477
37890
  * import './style.css'
@@ -37505,8 +37918,8 @@ function importAnalysisPlugin(config) {
37505
37918
  }
37506
37919
  const start = performance.now();
37507
37920
  await init;
37508
- let imports = [];
37509
- let exports = [];
37921
+ let imports;
37922
+ let exports;
37510
37923
  source = stripBomTag(source);
37511
37924
  try {
37512
37925
  [imports, exports] = parse$b(source);
@@ -37828,7 +38241,7 @@ function importAnalysisPlugin(config) {
37828
38241
  : `[detected api usage]`} ${prettyImporter}`);
37829
38242
  // inject hot context
37830
38243
  str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
37831
- `import.meta.hot = __vite__createHotContext(${JSON.stringify(importerModule.url)});`);
38244
+ `import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
37832
38245
  }
37833
38246
  if (needQueryInjectHelper) {
37834
38247
  str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
@@ -38155,276 +38568,6 @@ const wasmFallbackPlugin = () => {
38155
38568
  };
38156
38569
  };
38157
38570
 
38158
- const WORKER_FILE_ID = 'worker_file';
38159
- const workerCache = new WeakMap();
38160
- function saveEmitWorkerAsset(config, asset) {
38161
- const fileName = asset.fileName;
38162
- const workerMap = workerCache.get(config.mainConfig || config);
38163
- workerMap.assets.set(fileName, asset);
38164
- }
38165
- async function bundleWorkerEntry(config, id, query) {
38166
- // bundle the file as entry to support imports
38167
- const { rollup } = await import('rollup');
38168
- const { plugins, rollupOptions, format } = config.worker;
38169
- const bundle = await rollup({
38170
- ...rollupOptions,
38171
- input: cleanUrl(id),
38172
- plugins,
38173
- onwarn(warning, warn) {
38174
- onRollupWarning(warning, warn, config);
38175
- },
38176
- preserveEntrySignatures: false
38177
- });
38178
- let chunk;
38179
- try {
38180
- const workerOutputConfig = config.worker.rollupOptions.output;
38181
- const workerConfig = workerOutputConfig
38182
- ? Array.isArray(workerOutputConfig)
38183
- ? workerOutputConfig[0] || {}
38184
- : workerOutputConfig
38185
- : {};
38186
- const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
38187
- entryFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].js'),
38188
- chunkFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].js'),
38189
- assetFileNames: path$n.posix.join(config.build.assetsDir, '[name].[hash].[ext]'),
38190
- ...workerConfig,
38191
- format,
38192
- sourcemap: config.build.sourcemap
38193
- });
38194
- chunk = outputChunk;
38195
- outputChunks.forEach((outputChunk) => {
38196
- if (outputChunk.type === 'asset') {
38197
- saveEmitWorkerAsset(config, outputChunk);
38198
- }
38199
- else if (outputChunk.type === 'chunk') {
38200
- saveEmitWorkerAsset(config, {
38201
- fileName: outputChunk.fileName,
38202
- source: outputChunk.code,
38203
- type: 'asset'
38204
- });
38205
- }
38206
- });
38207
- }
38208
- finally {
38209
- await bundle.close();
38210
- }
38211
- return emitSourcemapForWorkerEntry(config, query, chunk);
38212
- }
38213
- function emitSourcemapForWorkerEntry(config, query, chunk) {
38214
- const { map: sourcemap } = chunk;
38215
- if (sourcemap) {
38216
- if (config.build.sourcemap === 'inline') {
38217
- // Manually add the sourcemap to the code if configured for inline sourcemaps.
38218
- // TODO: Remove when https://github.com/rollup/rollup/issues/3913 is resolved
38219
- // Currently seems that it won't be resolved until Rollup 3
38220
- const dataUrl = sourcemap.toUrl();
38221
- chunk.code += `//# sourceMappingURL=${dataUrl}`;
38222
- }
38223
- else if (config.build.sourcemap === 'hidden' ||
38224
- config.build.sourcemap === true) {
38225
- const data = sourcemap.toString();
38226
- const mapFileName = chunk.fileName + '.map';
38227
- saveEmitWorkerAsset(config, {
38228
- fileName: mapFileName,
38229
- type: 'asset',
38230
- source: data
38231
- });
38232
- // Emit the comment that tells the JS debugger where it can find the
38233
- // sourcemap file.
38234
- // 'hidden' causes the sourcemap file to be created but
38235
- // the comment in the file to be omitted.
38236
- if (config.build.sourcemap === true) {
38237
- // inline web workers need to use the full sourcemap path
38238
- // non-inline web workers can use a relative path
38239
- const sourceMapUrl = query?.inline != null
38240
- ? mapFileName
38241
- : path$n.relative(config.build.assetsDir, mapFileName);
38242
- chunk.code += `//# sourceMappingURL=${sourceMapUrl}`;
38243
- }
38244
- }
38245
- }
38246
- return chunk;
38247
- }
38248
- const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
38249
- function encodeWorkerAssetFileName(fileName, workerCache) {
38250
- const { fileNameHash } = workerCache;
38251
- const hash = getHash(fileName);
38252
- if (!fileNameHash.get(hash)) {
38253
- fileNameHash.set(hash, fileName);
38254
- }
38255
- return `__VITE_WORKER_ASSET__${hash}__`;
38256
- }
38257
- async function workerFileToUrl(config, id, query) {
38258
- const workerMap = workerCache.get(config.mainConfig || config);
38259
- let fileName = workerMap.bundle.get(id);
38260
- if (!fileName) {
38261
- const outputChunk = await bundleWorkerEntry(config, id, query);
38262
- fileName = outputChunk.fileName;
38263
- saveEmitWorkerAsset(config, {
38264
- fileName,
38265
- source: outputChunk.code,
38266
- type: 'asset'
38267
- });
38268
- workerMap.bundle.set(id, fileName);
38269
- }
38270
- return encodeWorkerAssetFileName(fileName, workerMap);
38271
- }
38272
- function webWorkerPlugin(config) {
38273
- const isBuild = config.command === 'build';
38274
- let server;
38275
- const isWorker = config.isWorker;
38276
- return {
38277
- name: 'vite:worker',
38278
- configureServer(_server) {
38279
- server = _server;
38280
- },
38281
- buildStart() {
38282
- if (isWorker) {
38283
- return;
38284
- }
38285
- workerCache.set(config, {
38286
- assets: new Map(),
38287
- bundle: new Map(),
38288
- fileNameHash: new Map()
38289
- });
38290
- },
38291
- load(id) {
38292
- if (isBuild) {
38293
- const parsedQuery = parseRequest(id);
38294
- if (parsedQuery &&
38295
- (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
38296
- return '';
38297
- }
38298
- }
38299
- },
38300
- async transform(raw, id, options) {
38301
- const ssr = options?.ssr === true;
38302
- const query = parseRequest(id);
38303
- if (query && query[WORKER_FILE_ID] != null) {
38304
- // if import worker by worker constructor will have query.type
38305
- // other type will be import worker by esm
38306
- const workerType = query['type'];
38307
- let injectEnv = '';
38308
- if (workerType === 'classic') {
38309
- injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
38310
- }
38311
- else if (workerType === 'module') {
38312
- injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
38313
- }
38314
- else if (workerType === 'ignore') {
38315
- if (isBuild) {
38316
- injectEnv = '';
38317
- }
38318
- else if (server) {
38319
- // dynamic worker type we can't know how import the env
38320
- // so we copy /@vite/env code of server transform result into file header
38321
- const { moduleGraph } = server;
38322
- const module = moduleGraph.getModuleById(ENV_ENTRY);
38323
- injectEnv = module?.transformResult?.code || '';
38324
- }
38325
- }
38326
- return {
38327
- code: injectEnv + raw
38328
- };
38329
- }
38330
- if (query == null ||
38331
- (query && (query.worker ?? query.sharedworker) == null)) {
38332
- return;
38333
- }
38334
- // stringified url or `new URL(...)`
38335
- let url;
38336
- const { format } = config.worker;
38337
- const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
38338
- const workerType = isBuild
38339
- ? format === 'es'
38340
- ? 'module'
38341
- : 'classic'
38342
- : 'module';
38343
- const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
38344
- if (isBuild) {
38345
- getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
38346
- if (query.inline != null) {
38347
- const chunk = await bundleWorkerEntry(config, id, query);
38348
- // inline as blob data url
38349
- return {
38350
- code: `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";
38351
- const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
38352
- export default function WorkerWrapper() {
38353
- const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
38354
- try {
38355
- return objURL ? new ${workerConstructor}(objURL) : new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
38356
- } finally {
38357
- objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
38358
- }
38359
- }`,
38360
- // Empty sourcemap to suppress Rollup warning
38361
- map: { mappings: '' }
38362
- };
38363
- }
38364
- else {
38365
- url = await workerFileToUrl(config, id, query);
38366
- }
38367
- }
38368
- else {
38369
- url = await fileToUrl(cleanUrl(id), config, this);
38370
- url = injectQuery(url, WORKER_FILE_ID);
38371
- url = injectQuery(url, `type=${workerType}`);
38372
- }
38373
- if (query.url != null) {
38374
- return {
38375
- code: `export default ${JSON.stringify(url)}`,
38376
- map: { mappings: '' } // Empty sourcemap to suppress Rollup warning
38377
- };
38378
- }
38379
- return {
38380
- code: `export default function WorkerWrapper() {
38381
- return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
38382
- }`,
38383
- map: { mappings: '' } // Empty sourcemap to suppress Rollup warning
38384
- };
38385
- },
38386
- renderChunk(code, chunk, outputOptions) {
38387
- let s;
38388
- const result = () => {
38389
- return (s && {
38390
- code: s.toString(),
38391
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
38392
- });
38393
- };
38394
- if (code.match(workerAssetUrlRE) || code.includes('import.meta.url')) {
38395
- let match;
38396
- s = new MagicString(code);
38397
- // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
38398
- const workerMap = workerCache.get(config.mainConfig || config);
38399
- const { fileNameHash } = workerMap;
38400
- while ((match = workerAssetUrlRE.exec(code))) {
38401
- const [full, hash] = match;
38402
- const filename = fileNameHash.get(hash);
38403
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, outputOptions.format);
38404
- const replacementString = typeof replacement === 'string'
38405
- ? JSON.stringify(replacement).slice(1, -1)
38406
- : `"+${replacement.runtime}+"`;
38407
- s.overwrite(match.index, match.index + full.length, replacementString, {
38408
- contentOnly: true
38409
- });
38410
- }
38411
- }
38412
- return result();
38413
- },
38414
- generateBundle(opts) {
38415
- // @ts-ignore asset emits are skipped in legacy bundle
38416
- if (opts.__vite_skip_asset_emit__ || isWorker) {
38417
- return;
38418
- }
38419
- const workerMap = workerCache.get(config);
38420
- workerMap.assets.forEach((asset) => {
38421
- this.emitFile(asset);
38422
- workerMap.assets.delete(asset.fileName);
38423
- });
38424
- }
38425
- };
38426
- }
38427
-
38428
38571
  /**
38429
38572
  * A plugin to avoid an aliased AND optimized dep from being aliased in src
38430
38573
  */
@@ -38640,7 +38783,7 @@ function definePlugin(config) {
38640
38783
  function ssrRequireHookPlugin(config) {
38641
38784
  if (config.command !== 'build' ||
38642
38785
  !config.build.ssr ||
38643
- !config.resolve.dedupe?.length ||
38786
+ !config.resolve.dedupe.length ||
38644
38787
  config.ssr?.noExternal === true ||
38645
38788
  config.ssr?.format !== 'cjs' ||
38646
38789
  isBuildOutputEsm(config)) {
@@ -40110,14 +40253,16 @@ function getWorkerType(raw, clean, i) {
40110
40253
  return 'classic';
40111
40254
  }
40112
40255
  // need to find in comment code
40113
- const workerOptString = raw.substring(commaIndex + 1, endIndex);
40256
+ const workerOptString = raw
40257
+ .substring(commaIndex + 1, endIndex)
40258
+ .replace(/}[^]*,/g, '}'); // strip trailing comma for parsing
40114
40259
  const hasViteIgnore = ignoreFlagRE.test(workerOptString);
40115
40260
  if (hasViteIgnore) {
40116
40261
  return 'ignore';
40117
40262
  }
40118
40263
  // need to find in no comment code
40119
- const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
40120
- if (!cleanWorkerOptString.trim().length) {
40264
+ const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex).trim();
40265
+ if (!cleanWorkerOptString.length) {
40121
40266
  return 'classic';
40122
40267
  }
40123
40268
  let workerOpts = { type: 'classic' };
@@ -40136,6 +40281,7 @@ function getWorkerType(raw, clean, i) {
40136
40281
  }
40137
40282
  function workerImportMetaUrlPlugin(config) {
40138
40283
  const isBuild = config.command === 'build';
40284
+ let workerResolver;
40139
40285
  return {
40140
40286
  name: 'vite:worker-import-meta-url',
40141
40287
  async transform(code, id, options) {
@@ -40161,20 +40307,33 @@ function workerImportMetaUrlPlugin(config) {
40161
40307
  }
40162
40308
  s || (s = new MagicString(code));
40163
40309
  const workerType = getWorkerType(code, cleanString, index + allExp.length);
40164
- const file = normalizePath$3(path$n.resolve(path$n.dirname(id), rawUrl.slice(1, -1)));
40165
- let url;
40310
+ const url = rawUrl.slice(1, -1);
40311
+ let file;
40312
+ if (url.startsWith('.')) {
40313
+ file = path$n.resolve(path$n.dirname(id), url);
40314
+ }
40315
+ else {
40316
+ workerResolver ?? (workerResolver = config.createResolver({
40317
+ extensions: [],
40318
+ tryIndex: false,
40319
+ preferRelative: true
40320
+ }));
40321
+ file = await workerResolver(url, id);
40322
+ file ?? (file = url.startsWith('/')
40323
+ ? slash$1(path$n.join(config.publicDir, url))
40324
+ : slash$1(path$n.resolve(path$n.dirname(id), url)));
40325
+ }
40326
+ let builtUrl;
40166
40327
  if (isBuild) {
40167
40328
  getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
40168
- url = await workerFileToUrl(config, file, query);
40329
+ builtUrl = await workerFileToUrl(config, file, query);
40169
40330
  }
40170
40331
  else {
40171
- url = await fileToUrl(cleanUrl(file), config, this);
40172
- url = injectQuery(url, WORKER_FILE_ID);
40173
- url = injectQuery(url, `type=${workerType}`);
40332
+ builtUrl = await fileToUrl(cleanUrl(file), config, this);
40333
+ builtUrl = injectQuery(builtUrl, WORKER_FILE_ID);
40334
+ builtUrl = injectQuery(builtUrl, `type=${workerType}`);
40174
40335
  }
40175
- s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url), {
40176
- contentOnly: true
40177
- });
40336
+ s.overwrite(urlIndex, urlIndex + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, { contentOnly: true });
40178
40337
  }
40179
40338
  if (s) {
40180
40339
  return transformStableResult(s, id, config);
@@ -40185,6 +40344,119 @@ function workerImportMetaUrlPlugin(config) {
40185
40344
  };
40186
40345
  }
40187
40346
 
40347
+ /**
40348
+ * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
40349
+ *
40350
+ * Supports template string with dynamic segments:
40351
+ * ```
40352
+ * new URL(`./dir/${name}.png`, import.meta.url)
40353
+ * // transformed to
40354
+ * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
40355
+ * ```
40356
+ */
40357
+ function assetImportMetaUrlPlugin(config) {
40358
+ const normalizedPublicDir = normalizePath$3(config.publicDir);
40359
+ let assetResolver;
40360
+ return {
40361
+ name: 'vite:asset-import-meta-url',
40362
+ async transform(code, id, options) {
40363
+ if (!options?.ssr &&
40364
+ id !== preloadHelperId &&
40365
+ code.includes('new URL') &&
40366
+ code.includes(`import.meta.url`)) {
40367
+ let s;
40368
+ const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*,?\s*\)/g;
40369
+ const cleanString = stripLiteral(code);
40370
+ let match;
40371
+ while ((match = assetImportMetaUrlRE.exec(cleanString))) {
40372
+ const { 0: exp, 1: emptyUrl, index } = match;
40373
+ const urlStart = cleanString.indexOf(emptyUrl, index);
40374
+ const urlEnd = urlStart + emptyUrl.length;
40375
+ const rawUrl = code.slice(urlStart, urlEnd);
40376
+ if (!s)
40377
+ s = new MagicString(code);
40378
+ // potential dynamic template string
40379
+ if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
40380
+ const ast = this.parse(rawUrl);
40381
+ const templateLiteral = ast.body[0].expression;
40382
+ if (templateLiteral.expressions.length) {
40383
+ const pattern = JSON.stringify(buildGlobPattern(templateLiteral));
40384
+ // Note: native import.meta.url is not supported in the baseline
40385
+ // target so we use the global location here. It can be
40386
+ // window.location or self.location in case it is used in a Web Worker.
40387
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
40388
+ s.overwrite(index, index + exp.length, `new URL((import.meta.glob(${pattern}, { eager: true, import: 'default', as: 'url' }))[${rawUrl}], self.location)`, { contentOnly: true });
40389
+ continue;
40390
+ }
40391
+ }
40392
+ const url = rawUrl.slice(1, -1);
40393
+ let file;
40394
+ if (url.startsWith('.')) {
40395
+ file = slash$1(path$n.resolve(path$n.dirname(id), url));
40396
+ }
40397
+ else {
40398
+ assetResolver ?? (assetResolver = config.createResolver({
40399
+ extensions: [],
40400
+ mainFields: [],
40401
+ tryIndex: false,
40402
+ preferRelative: true
40403
+ }));
40404
+ file = await assetResolver(url, id);
40405
+ file ?? (file = url.startsWith('/')
40406
+ ? slash$1(path$n.join(config.publicDir, url))
40407
+ : slash$1(path$n.resolve(path$n.dirname(id), url)));
40408
+ }
40409
+ // Get final asset URL. If the file does not exist,
40410
+ // we fall back to the initial URL and let it resolve in runtime
40411
+ let builtUrl;
40412
+ if (file) {
40413
+ try {
40414
+ if (isParentDirectory(normalizedPublicDir, file)) {
40415
+ const publicPath = '/' + path$n.posix.relative(normalizedPublicDir, file);
40416
+ builtUrl = await fileToUrl(publicPath, config, this);
40417
+ }
40418
+ else {
40419
+ builtUrl = await fileToUrl(file, config, this);
40420
+ }
40421
+ }
40422
+ catch {
40423
+ // do nothing, we'll log a warning after this
40424
+ }
40425
+ }
40426
+ if (!builtUrl) {
40427
+ const rawExp = code.slice(index, index + exp.length);
40428
+ config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
40429
+ builtUrl = url;
40430
+ }
40431
+ s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, { contentOnly: true });
40432
+ }
40433
+ if (s) {
40434
+ return transformStableResult(s, id, config);
40435
+ }
40436
+ }
40437
+ return null;
40438
+ }
40439
+ };
40440
+ }
40441
+ function buildGlobPattern(ast) {
40442
+ let pattern = '';
40443
+ let lastElementIndex = -1;
40444
+ for (const exp of ast.expressions) {
40445
+ for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
40446
+ const el = ast.quasis[i];
40447
+ if (el.end < exp.start) {
40448
+ pattern += el.value.raw;
40449
+ lastElementIndex = i;
40450
+ }
40451
+ }
40452
+ pattern += '**';
40453
+ }
40454
+ for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
40455
+ pattern += ast.quasis[i].value.raw;
40456
+ }
40457
+ return pattern;
40458
+ }
40459
+
40188
40460
  /**
40189
40461
  * plugin to ensure rollup can watch correctly.
40190
40462
  */
@@ -40366,6 +40638,12 @@ function parseDynamicImportPattern(strings) {
40366
40638
  if (rawQuery?.raw !== undefined) {
40367
40639
  globParams = { as: 'raw' };
40368
40640
  }
40641
+ if (rawQuery?.url !== undefined) {
40642
+ globParams = { as: 'url' };
40643
+ }
40644
+ if (rawQuery?.worker !== undefined) {
40645
+ globParams = { as: 'worker' };
40646
+ }
40369
40647
  return {
40370
40648
  globParams,
40371
40649
  userPattern,
@@ -40485,13 +40763,15 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
40485
40763
  const buildPlugins = isBuild
40486
40764
  ? (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
40487
40765
  : { pre: [], post: [] };
40766
+ const { modulePreload } = config.build;
40488
40767
  return [
40489
40768
  isWatch ? ensureWatchPlugin() : null,
40490
40769
  isBuild ? metadataPlugin() : null,
40491
40770
  preAliasPlugin(config),
40492
40771
  alias$1({ entries: config.resolve.alias }),
40493
40772
  ...prePlugins,
40494
- config.build.polyfillModulePreload
40773
+ modulePreload === true ||
40774
+ (typeof modulePreload === 'object' && modulePreload.polyfill)
40495
40775
  ? modulePreloadPolyfillPlugin(config)
40496
40776
  : null,
40497
40777
  ...(isDepsOptimizerEnabled(config, false) ||
@@ -40532,6 +40812,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
40532
40812
  isBuild && config.build.ssr ? ssrRequireHookPlugin(config) : null,
40533
40813
  isBuild && buildHtmlPlugin(config),
40534
40814
  workerImportMetaUrlPlugin(config),
40815
+ assetImportMetaUrlPlugin(config),
40535
40816
  ...buildPlugins.pre,
40536
40817
  dynamicImportVarsPlugin(config),
40537
40818
  importGlobPlugin(config),
@@ -41462,7 +41743,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
41462
41743
  // may end with these extensions
41463
41744
  // css & json & wasm
41464
41745
  build.onResolve({
41465
- filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json|wasm)$/
41746
+ filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss|json|wasm)$/
41466
41747
  }, externalUnlessEntry);
41467
41748
  // known asset types
41468
41749
  build.onResolve({
@@ -41607,6 +41888,7 @@ async function createDepsOptimizer(config, server) {
41607
41888
  const sessionTimestamp = Date.now().toString();
41608
41889
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr);
41609
41890
  let handle;
41891
+ let closed = false;
41610
41892
  let metadata = cachedMetadata || initDepsOptimizerMetadata(config, ssr, sessionTimestamp);
41611
41893
  const depsOptimizer = {
41612
41894
  metadata,
@@ -41619,6 +41901,7 @@ async function createDepsOptimizer(config, server) {
41619
41901
  delayDepsOptimizerUntil,
41620
41902
  resetRegisteredIds,
41621
41903
  ensureFirstRun,
41904
+ close,
41622
41905
  options: getDepOptimizationConfig(config, ssr)
41623
41906
  };
41624
41907
  depsOptimizerMap.set(config, depsOptimizer);
@@ -41647,6 +41930,12 @@ async function createDepsOptimizer(config, server) {
41647
41930
  // If there wasn't a cache or it is outdated, we need to prepare a first run
41648
41931
  let firstRunCalled = !!cachedMetadata;
41649
41932
  let postScanOptimizationResult;
41933
+ let optimizingNewDeps;
41934
+ async function close() {
41935
+ closed = true;
41936
+ await postScanOptimizationResult;
41937
+ await optimizingNewDeps;
41938
+ }
41650
41939
  if (!cachedMetadata) {
41651
41940
  // Enter processing state until crawl of static imports ends
41652
41941
  currentlyProcessing = true;
@@ -41744,13 +42033,20 @@ async function createDepsOptimizer(config, server) {
41744
42033
  // Ensure that a rerun will not be issued for current discovered deps
41745
42034
  if (handle)
41746
42035
  clearTimeout(handle);
41747
- if (Object.keys(metadata.discovered).length === 0) {
42036
+ if (closed || Object.keys(metadata.discovered).length === 0) {
41748
42037
  currentlyProcessing = false;
41749
42038
  return;
41750
42039
  }
41751
42040
  currentlyProcessing = true;
41752
42041
  try {
41753
- const processingResult = preRunResult ?? (await optimizeNewDeps());
42042
+ const processingResult = preRunResult ?? (await (optimizingNewDeps = optimizeNewDeps()));
42043
+ optimizingNewDeps = undefined;
42044
+ if (closed) {
42045
+ currentlyProcessing = false;
42046
+ processingResult.cancel();
42047
+ resolveEnqueuedProcessingPromises();
42048
+ return;
42049
+ }
41754
42050
  const newData = processingResult.metadata;
41755
42051
  const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
41756
42052
  // After a re-optimization, if the internal bundled chunks change a full page reload
@@ -42019,7 +42315,7 @@ async function createDepsOptimizer(config, server) {
42019
42315
  function ensureFirstRun() {
42020
42316
  if (!firstRunEnsured && !firstRunCalled && registeredIds.length === 0) {
42021
42317
  setTimeout(() => {
42022
- if (registeredIds.length === 0) {
42318
+ if (!closed && registeredIds.length === 0) {
42023
42319
  onCrawlEnd();
42024
42320
  }
42025
42321
  }, runOptimizerIfIdleAfterMs);
@@ -42050,7 +42346,7 @@ async function createDepsOptimizer(config, server) {
42050
42346
  waitingOn = next.id;
42051
42347
  const afterLoad = () => {
42052
42348
  waitingOn = undefined;
42053
- if (!workersSources.has(next.id)) {
42349
+ if (!closed && !workersSources.has(next.id)) {
42054
42350
  if (registeredIds.length > 0) {
42055
42351
  runOptimizerWhenIdle();
42056
42352
  }
@@ -42086,6 +42382,7 @@ async function createDevSsrDepsOptimizer(config) {
42086
42382
  delayDepsOptimizerUntil: (id, done) => { },
42087
42383
  resetRegisteredIds: () => { },
42088
42384
  ensureFirstRun: () => { },
42385
+ close: async () => { },
42089
42386
  options: config.ssr.optimizeDeps
42090
42387
  };
42091
42388
  devSsrDepsOptimizerMap.set(config, depsOptimizer);
@@ -42695,7 +42992,12 @@ function needsInterop(config, ssr, id, exportsData, output) {
42695
42992
  function isSingleDefaultExport(exports) {
42696
42993
  return exports.length === 1 && exports[0] === 'default';
42697
42994
  }
42698
- const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
42995
+ const lockfileFormats = [
42996
+ 'package-lock.json',
42997
+ 'yarn.lock',
42998
+ 'pnpm-lock.yaml',
42999
+ 'bun.lockb'
43000
+ ];
42699
43001
  function getDepHash(config, ssr) {
42700
43002
  let content = lookupFile(config.root, lockfileFormats) || '';
42701
43003
  // also take config into account
@@ -42795,6 +43097,10 @@ const dynamicImportPrefixRE = /import\s*\(/;
42795
43097
  // TODO: abstract
42796
43098
  const optimizedDepChunkRE = /\/chunk-[A-Z0-9]{8}\.js/;
42797
43099
  const optimizedDepDynamicRE = /-[A-Z0-9]{8}\.js/;
43100
+ function toRelativePath(filename, importer) {
43101
+ const relPath = path$n.relative(path$n.dirname(importer), filename);
43102
+ return relPath.startsWith('.') ? relPath : `./${relPath}`;
43103
+ }
42798
43104
  /**
42799
43105
  * Helper for preloading CSS and direct imports of async chunks in parallel to
42800
43106
  * the async chunk itself.
@@ -42812,6 +43118,7 @@ function preload(baseModule, deps, importerUrl) {
42812
43118
  if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
42813
43119
  return baseModule();
42814
43120
  }
43121
+ const links = document.getElementsByTagName('link');
42815
43122
  return Promise.all(deps.map((dep) => {
42816
43123
  // @ts-ignore
42817
43124
  dep = assetsURL(dep, importerUrl);
@@ -42822,8 +43129,21 @@ function preload(baseModule, deps, importerUrl) {
42822
43129
  seen[dep] = true;
42823
43130
  const isCss = dep.endsWith('.css');
42824
43131
  const cssSelector = isCss ? '[rel="stylesheet"]' : '';
42825
- // @ts-ignore check if the file is already preloaded by SSR markup
42826
- if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
43132
+ const isBaseRelative = !!importerUrl;
43133
+ // check if the file is already preloaded by SSR markup
43134
+ if (isBaseRelative) {
43135
+ // When isBaseRelative is true then we have `importerUrl` and `dep` is
43136
+ // already converted to an absolute URL by the `assetsURL` function
43137
+ for (let i = links.length - 1; i >= 0; i--) {
43138
+ const link = links[i];
43139
+ // The `links[i].href` is an absolute URL thanks to browser doing the work
43140
+ // for us. See https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:idl-domstring-5
43141
+ if (link.href === dep && (!isCss || link.rel === 'stylesheet')) {
43142
+ return;
43143
+ }
43144
+ }
43145
+ }
43146
+ else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
42827
43147
  return;
42828
43148
  }
42829
43149
  // @ts-ignore
@@ -42851,14 +43171,39 @@ function preload(baseModule, deps, importerUrl) {
42851
43171
  function buildImportAnalysisPlugin(config) {
42852
43172
  const ssr = !!config.build.ssr;
42853
43173
  const isWorker = config.isWorker;
42854
- const insertPreload = !(ssr || !!config.build.lib || isWorker);
42855
- const relativePreloadUrls = config.base === './' || config.base === '';
42856
- const scriptRel = config.build.polyfillModulePreload
43174
+ const insertPreload = !(ssr ||
43175
+ !!config.build.lib ||
43176
+ isWorker ||
43177
+ config.build.modulePreload === false);
43178
+ const resolveModulePreloadDependencies = config.build.modulePreload && config.build.modulePreload.resolveDependencies;
43179
+ const renderBuiltUrl = config.experimental.renderBuiltUrl;
43180
+ const customModulePreloadPaths = !!(resolveModulePreloadDependencies || renderBuiltUrl);
43181
+ const isRelativeBase = config.base === './' || config.base === '';
43182
+ const optimizeModulePreloadRelativePaths = isRelativeBase && !customModulePreloadPaths;
43183
+ const { modulePreload } = config.build;
43184
+ const scriptRel = modulePreload && modulePreload.polyfill
42857
43185
  ? `'modulepreload'`
42858
43186
  : `(${detectScriptRel.toString()})()`;
42859
- const assetsURL = relativePreloadUrls
42860
- ? `function(dep,importerUrl) { return new URL(dep, importerUrl).href }`
42861
- : `function(dep) { return ${JSON.stringify(config.base)}+dep }`;
43187
+ // There are three different cases for the preload list format in __vitePreload
43188
+ //
43189
+ // __vitePreload(() => import(asyncChunk), [ ...deps... ])
43190
+ //
43191
+ // This is maintained to keep backwards compatibility as some users developed plugins
43192
+ // using regex over this list to workaround the fact that module preload wasn't
43193
+ // configurable.
43194
+ const assetsURL = customModulePreloadPaths
43195
+ ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
43196
+ // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
43197
+ // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
43198
+ `function(dep, importerUrl) { return dep.startsWith('.') ? new URL(dep, importerUrl).href : dep }`
43199
+ : optimizeModulePreloadRelativePaths
43200
+ ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative
43201
+ // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
43202
+ // The importerUrl is passed as third parameter to __vitePreload in this case
43203
+ `function(dep, importerUrl) { return new URL(dep, importerUrl).href }`
43204
+ : // If the base isn't relative, then the deps are relative to the projects `outDir` and the base
43205
+ // is appendended inside __vitePreload too.
43206
+ `function(dep) { return ${JSON.stringify(config.base)}+dep }`;
42862
43207
  const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
42863
43208
  return {
42864
43209
  name: 'vite:build-import-analysis',
@@ -42944,7 +43289,9 @@ function buildImportAnalysisPlugin(config) {
42944
43289
  if (isDynamicImport && insertPreload) {
42945
43290
  needPreloadHelper = true;
42946
43291
  str().prependLeft(expStart, `${preloadMethod}(() => `);
42947
- str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0${relativePreloadUrls ? ',import.meta.url' : ''})`);
43292
+ str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0${optimizeModulePreloadRelativePaths || customModulePreloadPaths
43293
+ ? ',import.meta.url'
43294
+ : ''})`);
42948
43295
  }
42949
43296
  // static import or valid string in dynamic import
42950
43297
  // If resolvable, let's resolve it
@@ -43039,7 +43386,10 @@ function buildImportAnalysisPlugin(config) {
43039
43386
  return null;
43040
43387
  },
43041
43388
  generateBundle({ format }, bundle) {
43042
- if (format !== 'es' || ssr || isWorker) {
43389
+ if (format !== 'es' ||
43390
+ ssr ||
43391
+ isWorker ||
43392
+ config.build.modulePreload === false) {
43043
43393
  return;
43044
43394
  }
43045
43395
  for (const file in bundle) {
@@ -43048,7 +43398,7 @@ function buildImportAnalysisPlugin(config) {
43048
43398
  // dynamic import to constant json may get inlined.
43049
43399
  if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
43050
43400
  const code = chunk.code;
43051
- let imports = [];
43401
+ let imports;
43052
43402
  try {
43053
43403
  imports = parse$b(code)[0].filter((i) => i.d > -1);
43054
43404
  }
@@ -43070,7 +43420,9 @@ function buildImportAnalysisPlugin(config) {
43070
43420
  }
43071
43421
  const deps = new Set();
43072
43422
  let hasRemovedPureCssChunk = false;
43423
+ let normalizedFile = undefined;
43073
43424
  if (url) {
43425
+ normalizedFile = path$n.posix.join(path$n.posix.dirname(chunk.fileName), url);
43074
43426
  const ownerFilename = chunk.fileName;
43075
43427
  // literal import - trace direct imports and add to deps
43076
43428
  const analyzed = new Set();
@@ -43083,10 +43435,12 @@ function buildImportAnalysisPlugin(config) {
43083
43435
  const chunk = bundle[filename];
43084
43436
  if (chunk) {
43085
43437
  deps.add(chunk.fileName);
43438
+ chunk.imports.forEach(addDeps);
43439
+ // Ensure that the css imported by current chunk is loaded after the dependencies.
43440
+ // So the style of current chunk won't be overwritten unexpectedly.
43086
43441
  chunk.viteMetadata.importedCss.forEach((file) => {
43087
43442
  deps.add(file);
43088
43443
  });
43089
- chunk.imports.forEach(addDeps);
43090
43444
  }
43091
43445
  else {
43092
43446
  const removedPureCssFiles = removedPureCssFilesCache.get(config);
@@ -43104,7 +43458,6 @@ function buildImportAnalysisPlugin(config) {
43104
43458
  }
43105
43459
  }
43106
43460
  };
43107
- const normalizedFile = path$n.posix.join(path$n.posix.dirname(chunk.fileName), url);
43108
43461
  addDeps(normalizedFile);
43109
43462
  }
43110
43463
  let markerStartPos = code.indexOf(preloadMarkerWithQuote, end);
@@ -43113,19 +43466,53 @@ function buildImportAnalysisPlugin(config) {
43113
43466
  markerStartPos = code.indexOf(preloadMarkerWithQuote);
43114
43467
  }
43115
43468
  if (markerStartPos > 0) {
43116
- s.overwrite(markerStartPos, markerStartPos + preloadMarkerWithQuote.length,
43117
- // the dep list includes the main chunk, so only need to reload when there are
43118
- // actual other deps. Don't include the assets dir if the default asset file names
43119
- // are used, the path will be reconstructed by the import preload helper
43120
- deps.size > 1 ||
43469
+ // the dep list includes the main chunk, so only need to reload when there are actual other deps.
43470
+ const depsArray = deps.size > 1 ||
43121
43471
  // main chunk is removed
43122
43472
  (hasRemovedPureCssChunk && deps.size > 0)
43123
- ? `[${[...deps]
43124
- .map((d) => JSON.stringify(relativePreloadUrls
43125
- ? path$n.relative(path$n.dirname(file), d)
43126
- : d))
43127
- .join(',')}]`
43128
- : `[]`, { contentOnly: true });
43473
+ ? [...deps]
43474
+ : [];
43475
+ let renderedDeps;
43476
+ if (normalizedFile && customModulePreloadPaths) {
43477
+ const { modulePreload } = config.build;
43478
+ const resolveDependencies = modulePreload && modulePreload.resolveDependencies;
43479
+ let resolvedDeps;
43480
+ if (resolveDependencies) {
43481
+ // We can't let the user remove css deps as these aren't really preloads, they are just using
43482
+ // the same mechanism as module preloads for this chunk
43483
+ const cssDeps = [];
43484
+ const otherDeps = [];
43485
+ for (const dep of depsArray) {
43486
+ (dep.endsWith('.css') ? cssDeps : otherDeps).push(dep);
43487
+ }
43488
+ resolvedDeps = [
43489
+ ...resolveDependencies(normalizedFile, otherDeps, {
43490
+ hostId: file,
43491
+ hostType: 'js'
43492
+ }),
43493
+ ...cssDeps
43494
+ ];
43495
+ }
43496
+ else {
43497
+ resolvedDeps = depsArray;
43498
+ }
43499
+ renderedDeps = resolvedDeps.map((dep) => {
43500
+ const replacement = toOutputFilePathInJS(dep, 'asset', chunk.fileName, 'js', config, toRelativePath);
43501
+ const replacementString = typeof replacement === 'string'
43502
+ ? JSON.stringify(replacement)
43503
+ : replacement.runtime;
43504
+ return replacementString;
43505
+ });
43506
+ }
43507
+ else {
43508
+ renderedDeps = depsArray.map((d) =>
43509
+ // Don't include the assets dir if the default asset file names
43510
+ // are used, the path will be reconstructed by the import preload helper
43511
+ JSON.stringify(optimizeModulePreloadRelativePaths
43512
+ ? toRelativePath(d, file)
43513
+ : d));
43514
+ }
43515
+ s.overwrite(markerStartPos, markerStartPos + preloadMarkerWithQuote.length, `[${renderedDeps.join(',')}]`, { contentOnly: true });
43129
43516
  rewroteMarkerStartPos.add(markerStartPos);
43130
43517
  }
43131
43518
  }
@@ -43610,7 +43997,9 @@ function buildHtmlPlugin(config) {
43610
43997
  }
43611
43998
  processedHtml.set(id, s.toString());
43612
43999
  // inject module preload polyfill only when configured and needed
43613
- if (config.build.polyfillModulePreload &&
44000
+ const { modulePreload } = config.build;
44001
+ if ((modulePreload === true ||
44002
+ (typeof modulePreload === 'object' && modulePreload.polyfill)) &&
43614
44003
  (someScriptsAreAsync || someScriptsAreDefer)) {
43615
44004
  js = `import "${modulePreloadPolyfillId}";\n${js}`;
43616
44005
  }
@@ -43641,12 +44030,12 @@ function buildHtmlPlugin(config) {
43641
44030
  src: toOutputPath(chunk.fileName)
43642
44031
  }
43643
44032
  });
43644
- const toPreloadTag = (chunk, toOutputPath) => ({
44033
+ const toPreloadTag = (filename, toOutputPath) => ({
43645
44034
  tag: 'link',
43646
44035
  attrs: {
43647
44036
  rel: 'modulepreload',
43648
44037
  crossorigin: true,
43649
- href: toOutputPath(chunk.fileName)
44038
+ href: toOutputPath(filename)
43650
44039
  }
43651
44040
  });
43652
44041
  const getCssTagsForChunk = (chunk, toOutputPath, seen = new Set()) => {
@@ -43705,12 +44094,26 @@ function buildHtmlPlugin(config) {
43705
44094
  // when not inlined, inject <script> for entry and modulepreload its dependencies
43706
44095
  // when inlined, discard entry chunk and inject <script> for everything in post-order
43707
44096
  const imports = getImportedChunks(chunk);
43708
- const assetTags = canInlineEntry
43709
- ? imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync))
43710
- : [
44097
+ let assetTags;
44098
+ if (canInlineEntry) {
44099
+ assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
44100
+ }
44101
+ else {
44102
+ const { modulePreload } = config.build;
44103
+ const resolveDependencies = typeof modulePreload === 'object' &&
44104
+ modulePreload.resolveDependencies;
44105
+ const importsFileNames = imports.map((chunk) => chunk.fileName);
44106
+ const resolvedDeps = resolveDependencies
44107
+ ? resolveDependencies(chunk.fileName, importsFileNames, {
44108
+ hostId: relativeUrlPath,
44109
+ hostType: 'html'
44110
+ })
44111
+ : importsFileNames;
44112
+ assetTags = [
43711
44113
  toScriptTag(chunk, toOutputAssetFilePath, isAsync),
43712
- ...imports.map((i) => toPreloadTag(i, toOutputAssetFilePath))
44114
+ ...resolvedDeps.map((i) => toPreloadTag(i, toOutputAssetFilePath))
43713
44115
  ];
44116
+ }
43714
44117
  assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
43715
44118
  result = injectToHead(result, assetTags);
43716
44119
  }
@@ -43977,7 +44380,7 @@ function incrementIndent(indent = '') {
43977
44380
  return `${indent}${indent[0] === '\t' ? '\t' : ' '}`;
43978
44381
  }
43979
44382
 
43980
- const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
44383
+ const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)($|\\?)`;
43981
44384
  const cssLangRE = new RegExp(cssLangs);
43982
44385
  const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
43983
44386
  const directRequestRE = /(\?|&)direct\b/;
@@ -43994,7 +44397,7 @@ const isDirectRequest = (request) => directRequestRE.test(request);
43994
44397
  const cssModulesCache = new WeakMap();
43995
44398
  const removedPureCssFilesCache = new WeakMap();
43996
44399
  const cssEntryFilesCache = new WeakMap();
43997
- const postcssConfigCache = new WeakMap();
44400
+ const postcssConfigCache = {};
43998
44401
  function encodePublicUrlsInCSS(config) {
43999
44402
  return config.command === 'build';
44000
44403
  }
@@ -44300,7 +44703,7 @@ function cssPostPlugin(config) {
44300
44703
  // the legacy build should avoid inserting entry CSS modules here, they
44301
44704
  // will be collected into `chunk.viteMetadata.importedCss` and injected
44302
44705
  // later by the `'vite:build-html'` plugin into the `index.html`
44303
- if (chunk.isEntry) {
44706
+ if (chunk.isEntry && !config.build.lib) {
44304
44707
  return null;
44305
44708
  }
44306
44709
  chunkCSS = await finalizeCss(chunkCSS, true, config);
@@ -44432,8 +44835,8 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
44432
44835
  // crawl them in order to register watch dependencies.
44433
44836
  const needInlineImport = code.includes('@import');
44434
44837
  const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
44435
- const postcssConfig = await resolvePostcssConfig(config);
44436
44838
  const lang = id.match(cssLangRE)?.[1];
44839
+ const postcssConfig = await resolvePostcssConfig(config, getCssDialect(lang));
44437
44840
  // 1. plain css that needs no processing
44438
44841
  if (lang === 'css' &&
44439
44842
  !postcssConfig &&
@@ -44488,9 +44891,13 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
44488
44891
  }
44489
44892
  // 3. postcss
44490
44893
  const postcssOptions = (postcssConfig && postcssConfig.options) || {};
44894
+ // for sugarss change parser
44895
+ if (lang === 'sss') {
44896
+ postcssOptions.parser = loadPreprocessor("sugarss" /* sss */, config.root);
44897
+ }
44491
44898
  const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
44492
44899
  if (needInlineImport) {
44493
- postcssPlugins.unshift((await import('./dep-42c2c4e4.js').then(function (n) { return n.i; })).default({
44900
+ postcssPlugins.unshift((await import('./dep-39e6741e.js').then(function (n) { return n.i; })).default({
44494
44901
  async resolve(id, basedir) {
44495
44902
  const publicFile = checkPublicFile(id, config);
44496
44903
  if (publicFile) {
@@ -44512,7 +44919,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
44512
44919
  logger: config.logger
44513
44920
  }));
44514
44921
  if (isModule) {
44515
- postcssPlugins.unshift((await import('./dep-55b95cd5.js').then(function (n) { return n.i; })).default({
44922
+ postcssPlugins.unshift((await import('./dep-553f6a62.js').then(function (n) { return n.i; })).default({
44516
44923
  ...modulesOptions,
44517
44924
  getJSON(cssFileName, _modules, outputFileName) {
44518
44925
  modules = _modules;
@@ -44660,8 +45067,9 @@ async function finalizeCss(css, minify, config) {
44660
45067
  }
44661
45068
  return css;
44662
45069
  }
44663
- async function resolvePostcssConfig(config) {
44664
- let result = postcssConfigCache.get(config);
45070
+ async function resolvePostcssConfig(config, dialect = 'css') {
45071
+ postcssConfigCache[dialect] ?? (postcssConfigCache[dialect] = new WeakMap());
45072
+ let result = postcssConfigCache[dialect].get(config);
44665
45073
  if (result !== undefined) {
44666
45074
  return result;
44667
45075
  }
@@ -44697,7 +45105,7 @@ async function resolvePostcssConfig(config) {
44697
45105
  result = null;
44698
45106
  }
44699
45107
  }
44700
- postcssConfigCache.set(config, result);
45108
+ postcssConfigCache[dialect].set(config, result);
44701
45109
  return result;
44702
45110
  }
44703
45111
  // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
@@ -44922,8 +45330,8 @@ const scss = async (source, root, options, resolvers) => {
44922
45330
  const importer = [internalImporter];
44923
45331
  if (options.importer) {
44924
45332
  Array.isArray(options.importer)
44925
- ? importer.push(...options.importer)
44926
- : importer.push(options.importer);
45333
+ ? importer.unshift(...options.importer)
45334
+ : importer.unshift(options.importer);
44927
45335
  }
44928
45336
  const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
44929
45337
  const finalOptions = {
@@ -45196,6 +45604,9 @@ const preProcessors = Object.freeze({
45196
45604
  function isPreProcessor(lang) {
45197
45605
  return lang && lang in preProcessors;
45198
45606
  }
45607
+ function getCssDialect(lang) {
45608
+ return lang === 'sss' ? 'sss' : 'css';
45609
+ }
45199
45610
 
45200
45611
  function manifestPlugin(config) {
45201
45612
  const manifest = {};
@@ -45282,6 +45693,10 @@ function manifestPlugin(config) {
45282
45693
  manifest[chunk.name] = createAsset(chunk);
45283
45694
  }
45284
45695
  }
45696
+ duplicateAssets.get(config).forEach((asset) => {
45697
+ const chunk = createAsset(asset);
45698
+ manifest[asset.name] = chunk;
45699
+ });
45285
45700
  outputCount++;
45286
45701
  const output = config.build.rollupOptions?.output;
45287
45702
  const outputLength = Array.isArray(output) ? output.length : 1;
@@ -45421,87 +45836,6 @@ function ssrManifestPlugin(config) {
45421
45836
  };
45422
45837
  }
45423
45838
 
45424
- /**
45425
- * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
45426
- *
45427
- * Supports template string with dynamic segments:
45428
- * ```
45429
- * new URL(`./dir/${name}.png`, import.meta.url)
45430
- * // transformed to
45431
- * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
45432
- * ```
45433
- */
45434
- function assetImportMetaUrlPlugin(config) {
45435
- return {
45436
- name: 'vite:asset-import-meta-url',
45437
- async transform(code, id, options) {
45438
- if (!options?.ssr &&
45439
- id !== preloadHelperId &&
45440
- code.includes('new URL') &&
45441
- code.includes(`import.meta.url`)) {
45442
- let s;
45443
- const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*,?\s*\)/g;
45444
- const cleanString = stripLiteral(code);
45445
- let match;
45446
- while ((match = assetImportMetaUrlRE.exec(cleanString))) {
45447
- const { 0: exp, 1: emptyUrl, index } = match;
45448
- const urlStart = cleanString.indexOf(emptyUrl, index);
45449
- const urlEnd = urlStart + emptyUrl.length;
45450
- const rawUrl = code.slice(urlStart, urlEnd);
45451
- if (!s)
45452
- s = new MagicString(code);
45453
- // potential dynamic template string
45454
- if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
45455
- const ast = this.parse(rawUrl);
45456
- const templateLiteral = ast.body[0].expression;
45457
- if (templateLiteral.expressions.length) {
45458
- const pattern = JSON.stringify(buildGlobPattern(templateLiteral));
45459
- // Note: native import.meta.url is not supported in the baseline
45460
- // target so we use the global location here. It can be
45461
- // window.location or self.location in case it is used in a Web Worker.
45462
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
45463
- s.overwrite(index, index + exp.length, `new URL((import.meta.glob(${pattern}, { eager: true, import: 'default', as: 'url' }))[${rawUrl}], self.location)`, { contentOnly: true });
45464
- continue;
45465
- }
45466
- }
45467
- const url = rawUrl.slice(1, -1);
45468
- const file = path$n.resolve(path$n.dirname(id), url);
45469
- // Get final asset URL. Catch error if the file does not exist,
45470
- // in which we can resort to the initial URL and let it resolve in runtime
45471
- const builtUrl = await fileToUrl(file, config, this).catch(() => {
45472
- const rawExp = code.slice(index, index + exp.length);
45473
- config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
45474
- return url;
45475
- });
45476
- s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, { contentOnly: true });
45477
- }
45478
- if (s) {
45479
- return transformStableResult(s, id, config);
45480
- }
45481
- }
45482
- return null;
45483
- }
45484
- };
45485
- }
45486
- function buildGlobPattern(ast) {
45487
- let pattern = '';
45488
- let lastElementIndex = -1;
45489
- for (const exp of ast.expressions) {
45490
- for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
45491
- const el = ast.quasis[i];
45492
- if (el.end < exp.start) {
45493
- pattern += el.value.raw;
45494
- lastElementIndex = i;
45495
- }
45496
- }
45497
- pattern += '**';
45498
- }
45499
- for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
45500
- pattern += ast.quasis[i].value.raw;
45501
- }
45502
- return pattern;
45503
- }
45504
-
45505
45839
  /**
45506
45840
  * A plugin to provide build load fallback for arbitrary request with queries.
45507
45841
  */
@@ -45555,9 +45889,24 @@ function completeSystemWrapPlugin() {
45555
45889
  }
45556
45890
 
45557
45891
  function resolveBuildOptions(raw, isBuild, logger) {
45892
+ const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload;
45893
+ if (raw) {
45894
+ const { polyfillModulePreload, ...rest } = raw;
45895
+ raw = rest;
45896
+ if (deprecatedPolyfillModulePreload !== undefined) {
45897
+ logger.warn('polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.');
45898
+ }
45899
+ if (deprecatedPolyfillModulePreload === false &&
45900
+ raw.modulePreload === undefined) {
45901
+ raw.modulePreload = { polyfill: false };
45902
+ }
45903
+ }
45904
+ const modulePreload = raw?.modulePreload;
45905
+ const defaultModulePreload = {
45906
+ polyfill: true
45907
+ };
45558
45908
  const resolved = {
45559
45909
  target: 'modules',
45560
- polyfillModulePreload: true,
45561
45910
  outDir: 'dist',
45562
45911
  assetsDir: 'assets',
45563
45912
  assetsInlineLimit: 4096,
@@ -45586,7 +45935,16 @@ function resolveBuildOptions(raw, isBuild, logger) {
45586
45935
  warnOnError: true,
45587
45936
  exclude: [/node_modules/],
45588
45937
  ...raw?.dynamicImportVarsOptions
45589
- }
45938
+ },
45939
+ // Resolve to false | object
45940
+ modulePreload: modulePreload === false
45941
+ ? false
45942
+ : typeof modulePreload === 'object'
45943
+ ? {
45944
+ ...defaultModulePreload,
45945
+ ...modulePreload
45946
+ }
45947
+ : defaultModulePreload
45590
45948
  };
45591
45949
  // handle special build targets
45592
45950
  if (resolved.target === 'modules') {
@@ -45620,7 +45978,6 @@ function resolveBuildPlugins(config) {
45620
45978
  watchPackageDataPlugin(config),
45621
45979
  ...(usePluginCommonjs ? [commonjs(options.commonjsOptions)] : []),
45622
45980
  dataURIPlugin(),
45623
- assetImportMetaUrlPlugin(config),
45624
45981
  ...(options.rollupOptions.plugins
45625
45982
  ? options.rollupOptions.plugins.filter(Boolean)
45626
45983
  : [])
@@ -45669,7 +46026,15 @@ async function doBuild(inlineConfig = {}) {
45669
46026
  config.logger.info(picocolors.exports.cyan(`vite v${VERSION} ${picocolors.exports.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
45670
46027
  const resolve = (p) => path$n.resolve(config.root, p);
45671
46028
  const input = libOptions
45672
- ? options.rollupOptions?.input || resolve(libOptions.entry)
46029
+ ? options.rollupOptions?.input ||
46030
+ (typeof libOptions.entry === 'string'
46031
+ ? resolve(libOptions.entry)
46032
+ : Array.isArray(libOptions.entry)
46033
+ ? libOptions.entry.map(resolve)
46034
+ : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [
46035
+ alias,
46036
+ resolve(file)
46037
+ ])))
45673
46038
  : typeof options.ssr === 'string'
45674
46039
  ? resolve(options.ssr)
45675
46040
  : options.rollupOptions?.input || resolve('index.html');
@@ -45746,7 +46111,7 @@ async function doBuild(inlineConfig = {}) {
45746
46111
  entryFileNames: ssr
45747
46112
  ? `[name].${jsExt}`
45748
46113
  : libOptions
45749
- ? resolveLibFilename(libOptions, format, config.root, jsExt)
46114
+ ? ({ name }) => resolveLibFilename(libOptions, format, name, config.root, jsExt)
45750
46115
  : path$n.posix.join(options.assetsDir, `[name].[hash].${jsExt}`),
45751
46116
  chunkFileNames: libOptions
45752
46117
  ? `[name].[hash].${jsExt}`
@@ -45763,23 +46128,24 @@ async function doBuild(inlineConfig = {}) {
45763
46128
  };
45764
46129
  // resolve lib mode outputs
45765
46130
  const outputs = resolveBuildOutputs(options.rollupOptions?.output, libOptions, config.logger);
46131
+ const normalizedOutputs = [];
46132
+ if (Array.isArray(outputs)) {
46133
+ for (const resolvedOutput of outputs) {
46134
+ normalizedOutputs.push(buildOutputOptions(resolvedOutput));
46135
+ }
46136
+ }
46137
+ else {
46138
+ normalizedOutputs.push(buildOutputOptions(outputs));
46139
+ }
46140
+ const outDirs = normalizedOutputs.map(({ dir }) => resolve(dir));
45766
46141
  // watch file changes with rollup
45767
46142
  if (config.build.watch) {
45768
46143
  config.logger.info(picocolors.exports.cyan(`\nwatching for file changes...`));
45769
- const output = [];
45770
- if (Array.isArray(outputs)) {
45771
- for (const resolvedOutput of outputs) {
45772
- output.push(buildOutputOptions(resolvedOutput));
45773
- }
45774
- }
45775
- else {
45776
- output.push(buildOutputOptions(outputs));
45777
- }
45778
46144
  const resolvedChokidarOptions = resolveChokidarOptions(config.build.watch.chokidar);
45779
46145
  const { watch } = await import('rollup');
45780
46146
  const watcher = watch({
45781
46147
  ...rollupOptions,
45782
- output,
46148
+ output: normalizedOutputs,
45783
46149
  watch: {
45784
46150
  ...config.build.watch,
45785
46151
  chokidar: resolvedChokidarOptions
@@ -45789,7 +46155,7 @@ async function doBuild(inlineConfig = {}) {
45789
46155
  if (event.code === 'BUNDLE_START') {
45790
46156
  config.logger.info(picocolors.exports.cyan(`\nbuild started...`));
45791
46157
  if (options.write) {
45792
- prepareOutDir(outDir, options.emptyOutDir, config);
46158
+ prepareOutDir(outDirs, options.emptyOutDir, config);
45793
46159
  }
45794
46160
  }
45795
46161
  else if (event.code === 'BUNDLE_END') {
@@ -45807,41 +46173,56 @@ async function doBuild(inlineConfig = {}) {
45807
46173
  const bundle = await rollup(rollupOptions);
45808
46174
  parallelBuilds.push(bundle);
45809
46175
  const generate = (output = {}) => {
45810
- return bundle[options.write ? 'write' : 'generate'](buildOutputOptions(output));
46176
+ return bundle[options.write ? 'write' : 'generate'](output);
45811
46177
  };
45812
46178
  if (options.write) {
45813
- prepareOutDir(outDir, options.emptyOutDir, config);
46179
+ prepareOutDir(outDirs, options.emptyOutDir, config);
45814
46180
  }
45815
- if (Array.isArray(outputs)) {
45816
- const res = [];
45817
- for (const output of outputs) {
45818
- res.push(await generate(output));
45819
- }
45820
- return res;
45821
- }
45822
- else {
45823
- return await generate(outputs);
46181
+ const res = [];
46182
+ for (const output of normalizedOutputs) {
46183
+ res.push(await generate(output));
45824
46184
  }
46185
+ return Array.isArray(outputs) ? res : res[0];
45825
46186
  }
45826
46187
  catch (e) {
45827
46188
  outputBuildError(e);
45828
46189
  throw e;
45829
46190
  }
45830
46191
  }
45831
- function prepareOutDir(outDir, emptyOutDir, config) {
45832
- if (fs$l.existsSync(outDir)) {
45833
- if (emptyOutDir == null &&
45834
- !normalizePath$3(outDir).startsWith(config.root + '/')) {
45835
- // warn if outDir is outside of root
45836
- config.logger.warn(picocolors.exports.yellow(`\n${picocolors.exports.bold(`(!)`)} outDir ${picocolors.exports.white(picocolors.exports.dim(outDir))} is not inside project root and will not be emptied.\n` +
45837
- `Use --emptyOutDir to override.\n`));
45838
- }
45839
- else if (emptyOutDir !== false) {
45840
- emptyDir(outDir, ['.git']);
46192
+ function prepareOutDir(outDirs, emptyOutDir, config) {
46193
+ const nonDuplicateDirs = new Set(outDirs);
46194
+ let outside = false;
46195
+ if (emptyOutDir == null) {
46196
+ for (const outDir of nonDuplicateDirs) {
46197
+ if (fs$l.existsSync(outDir) &&
46198
+ !normalizePath$3(outDir).startsWith(config.root + '/')) {
46199
+ // warn if outDir is outside of root
46200
+ config.logger.warn(picocolors.exports.yellow(`\n${picocolors.exports.bold(`(!)`)} outDir ${picocolors.exports.white(picocolors.exports.dim(outDir))} is not inside project root and will not be emptied.\n` +
46201
+ `Use --emptyOutDir to override.\n`));
46202
+ outside = true;
46203
+ break;
46204
+ }
45841
46205
  }
45842
46206
  }
45843
- if (config.publicDir && fs$l.existsSync(config.publicDir)) {
45844
- copyDir(config.publicDir, outDir);
46207
+ for (const outDir of nonDuplicateDirs) {
46208
+ if (!outside && emptyOutDir !== false && fs$l.existsSync(outDir)) {
46209
+ // skip those other outDirs which are nested in current outDir
46210
+ const skipDirs = outDirs
46211
+ .map((dir) => {
46212
+ const relative = path$n.relative(outDir, dir);
46213
+ if (relative &&
46214
+ !relative.startsWith('..') &&
46215
+ !path$n.isAbsolute(relative)) {
46216
+ return relative;
46217
+ }
46218
+ return '';
46219
+ })
46220
+ .filter(Boolean);
46221
+ emptyDir(outDir, [...skipDirs, '.git']);
46222
+ }
46223
+ if (config.publicDir && fs$l.existsSync(config.publicDir)) {
46224
+ copyDir(config.publicDir, outDir);
46225
+ }
45845
46226
  }
45846
46227
  }
45847
46228
  function getPkgJson(root) {
@@ -45858,12 +46239,15 @@ function resolveOutputJsExtension(format, type = 'commonjs') {
45858
46239
  return format === 'es' ? 'mjs' : 'js';
45859
46240
  }
45860
46241
  }
45861
- function resolveLibFilename(libOptions, format, root, extension) {
46242
+ function resolveLibFilename(libOptions, format, entryName, root, extension) {
45862
46243
  if (typeof libOptions.fileName === 'function') {
45863
- return libOptions.fileName(format);
46244
+ return libOptions.fileName(format, entryName);
45864
46245
  }
45865
46246
  const packageJson = getPkgJson(root);
45866
- const name = libOptions.fileName || getPkgName(packageJson.name);
46247
+ const name = libOptions.fileName ||
46248
+ (typeof libOptions.entry === 'string'
46249
+ ? getPkgName(packageJson.name)
46250
+ : entryName);
45867
46251
  if (!name)
45868
46252
  throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
45869
46253
  extension ?? (extension = resolveOutputJsExtension(format, packageJson.type));
@@ -45875,10 +46259,15 @@ function resolveLibFilename(libOptions, format, root, extension) {
45875
46259
  function resolveBuildOutputs(outputs, libOptions, logger) {
45876
46260
  if (libOptions) {
45877
46261
  const formats = libOptions.formats || ['es', 'umd'];
45878
- if ((formats.includes('umd') || formats.includes('iife')) &&
45879
- !libOptions.name) {
45880
- throw new Error(`Option "build.lib.name" is required when output formats ` +
45881
- `include "umd" or "iife".`);
46262
+ if (formats.includes('umd') || formats.includes('iife')) {
46263
+ if (typeof libOptions.entry !== 'string' &&
46264
+ Object.values(libOptions.entry).length > 1) {
46265
+ throw new Error(`Multiple entry points are not supported when output formats include "umd" or "iife".`);
46266
+ }
46267
+ if (!libOptions.name) {
46268
+ throw new Error(`Option "build.lib.name" is required when output formats ` +
46269
+ `include "umd" or "iife".`);
46270
+ }
45882
46271
  }
45883
46272
  if (!outputs) {
45884
46273
  return formats.map((format) => ({ format }));
@@ -46062,7 +46451,7 @@ const relativeUrlMechanisms = {
46062
46451
  system: (relativePath) => getResolveUrl(`'${relativePath}', module.meta.url`),
46063
46452
  umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
46064
46453
  };
46065
- function toOutputFilePathInString(filename, type, hostId, hostType, config, format, toRelative = getToImportMetaURLBasedRelativePath(format)) {
46454
+ function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
46066
46455
  const { renderBuiltUrl } = config.experimental;
46067
46456
  let relative = config.base === '' || config.base === './';
46068
46457
  if (renderBuiltUrl) {
@@ -46089,7 +46478,7 @@ function toOutputFilePathInString(filename, type, hostId, hostType, config, form
46089
46478
  }
46090
46479
  return config.base + filename;
46091
46480
  }
46092
- function getToImportMetaURLBasedRelativePath(format) {
46481
+ function createToImportMetaURLBasedRelativeRuntime(format) {
46093
46482
  const toRelativePath = relativeUrlMechanisms[format];
46094
46483
  return (filename, importer) => ({
46095
46484
  runtime: toRelativePath(path$n.posix.relative(path$n.dirname(importer), filename))
@@ -46134,7 +46523,8 @@ var build$1 = {
46134
46523
  build: build,
46135
46524
  resolveLibFilename: resolveLibFilename,
46136
46525
  onRollupWarning: onRollupWarning,
46137
- toOutputFilePathInString: toOutputFilePathInString,
46526
+ toOutputFilePathInJS: toOutputFilePathInJS,
46527
+ createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
46138
46528
  toOutputFilePathWithoutRuntime: toOutputFilePathWithoutRuntime,
46139
46529
  toOutputFilePathInCss: toOutputFilePathInCss,
46140
46530
  toOutputFilePathInHtml: toOutputFilePathInHtml
@@ -48937,7 +49327,7 @@ const fs$9 = require$$0__default;
48937
49327
  const { Readable } = require$$0$7;
48938
49328
  const sysPath$3 = require$$0$4;
48939
49329
  const { promisify: promisify$3 } = require$$0$6;
48940
- const picomatch$1 = picomatch$4.exports;
49330
+ const picomatch$1 = picomatch$5.exports;
48941
49331
 
48942
49332
  const readdir$1 = promisify$3(fs$9.readdir);
48943
49333
  const stat$3 = promisify$3(fs$9.stat);
@@ -49259,7 +49649,7 @@ var normalizePath$2 = function(path, stripTrailing) {
49259
49649
 
49260
49650
  Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
49261
49651
 
49262
- const picomatch = picomatch$4.exports;
49652
+ const picomatch = picomatch$5.exports;
49263
49653
  const normalizePath$1 = normalizePath$2;
49264
49654
 
49265
49655
  /**
@@ -52501,7 +52891,7 @@ async function resolveHttpServer({ proxy }, app, httpsOptions) {
52501
52891
  app);
52502
52892
  }
52503
52893
  }
52504
- async function resolveHttpsConfig(https, cacheDir) {
52894
+ async function resolveHttpsConfig(https) {
52505
52895
  if (!https)
52506
52896
  return undefined;
52507
52897
  const httpsOption = isObject$2(https) ? { ...https } : {};
@@ -53063,35 +53453,35 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
53063
53453
  function isInScope(name, parents) {
53064
53454
  return parents.some((node) => node && scopeMap.get(node)?.has(name));
53065
53455
  }
53066
- function handlePattern(p, parentFunction) {
53456
+ function handlePattern(p, parentScope) {
53067
53457
  if (p.type === 'Identifier') {
53068
- setScope(parentFunction, p.name);
53458
+ setScope(parentScope, p.name);
53069
53459
  }
53070
53460
  else if (p.type === 'RestElement') {
53071
- handlePattern(p.argument, parentFunction);
53461
+ handlePattern(p.argument, parentScope);
53072
53462
  }
53073
53463
  else if (p.type === 'ObjectPattern') {
53074
53464
  p.properties.forEach((property) => {
53075
53465
  if (property.type === 'RestElement') {
53076
- setScope(parentFunction, property.argument.name);
53466
+ setScope(parentScope, property.argument.name);
53077
53467
  }
53078
53468
  else {
53079
- handlePattern(property.value, parentFunction);
53469
+ handlePattern(property.value, parentScope);
53080
53470
  }
53081
53471
  });
53082
53472
  }
53083
53473
  else if (p.type === 'ArrayPattern') {
53084
53474
  p.elements.forEach((element) => {
53085
53475
  if (element) {
53086
- handlePattern(element, parentFunction);
53476
+ handlePattern(element, parentScope);
53087
53477
  }
53088
53478
  });
53089
53479
  }
53090
53480
  else if (p.type === 'AssignmentPattern') {
53091
- handlePattern(p.left, parentFunction);
53481
+ handlePattern(p.left, parentScope);
53092
53482
  }
53093
53483
  else {
53094
- setScope(parentFunction, p.name);
53484
+ setScope(parentScope, p.name);
53095
53485
  }
53096
53486
  }
53097
53487
  walk$1(root, {
@@ -53099,7 +53489,12 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
53099
53489
  if (node.type === 'ImportDeclaration') {
53100
53490
  return this.skip();
53101
53491
  }
53102
- parent && parentStack.unshift(parent);
53492
+ // track parent stack, skip for "else-if"/"else" branches as acorn nests
53493
+ // the ast within "if" nodes instead of flattening them
53494
+ if (parent &&
53495
+ !(parent.type === 'IfStatement' && node === parent.alternate)) {
53496
+ parentStack.unshift(parent);
53497
+ }
53103
53498
  if (node.type === 'MetaProperty' && node.meta.name === 'import') {
53104
53499
  onImportMeta(node);
53105
53500
  }
@@ -53117,9 +53512,9 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
53117
53512
  // If it is a function declaration, it could be shadowing an import
53118
53513
  // Add its name to the scope so it won't get replaced
53119
53514
  if (node.type === 'FunctionDeclaration') {
53120
- const parentFunction = findParentFunction(parentStack);
53121
- if (parentFunction) {
53122
- setScope(parentFunction, node.id.name);
53515
+ const parentScope = findParentScope(parentStack);
53516
+ if (parentScope) {
53517
+ setScope(parentScope, node.id.name);
53123
53518
  }
53124
53519
  }
53125
53520
  // walk function expressions and add its arguments to known identifiers
@@ -53158,14 +53553,18 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
53158
53553
  setIsNodeInPattern(node);
53159
53554
  }
53160
53555
  else if (node.type === 'VariableDeclarator') {
53161
- const parentFunction = findParentFunction(parentStack);
53556
+ const parentFunction = findParentScope(parentStack);
53162
53557
  if (parentFunction) {
53163
53558
  handlePattern(node.id, parentFunction);
53164
53559
  }
53165
53560
  }
53166
53561
  },
53167
53562
  leave(node, parent) {
53168
- parent && parentStack.shift();
53563
+ // untrack parent stack from above
53564
+ if (parent &&
53565
+ !(parent.type === 'IfStatement' && node === parent.alternate)) {
53566
+ parentStack.shift();
53567
+ }
53169
53568
  }
53170
53569
  });
53171
53570
  // emit the identifier events in BFS so the hoisted declarations
@@ -53227,11 +53626,13 @@ function isRefIdentifier(id, parent, parentStack) {
53227
53626
  }
53228
53627
  const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
53229
53628
  const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
53629
+ const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
53230
53630
  function isFunction(node) {
53231
- return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
53631
+ return functionNodeTypeRE.test(node.type);
53232
53632
  }
53233
- function findParentFunction(parentStack) {
53234
- return parentStack.find((i) => isFunction(i));
53633
+ const scopeNodeTypeRE = /(?:Function|Class)(?:Expression|Declaration)$|Method$|^IfStatement$/;
53634
+ function findParentScope(parentStack) {
53635
+ return parentStack.find((i) => scopeNodeTypeRE.test(i.type));
53235
53636
  }
53236
53637
  function isInDestructuringAssignment(parent, parentStack) {
53237
53638
  if (parent &&
@@ -53354,13 +53755,15 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
53354
53755
  // CommonJS modules are preferred. We want to avoid ESM->ESM imports
53355
53756
  // whenever possible, because `hookNodeResolve` can't intercept them.
53356
53757
  const resolveOptions = {
53357
- dedupe,
53758
+ mainFields: ['main'],
53759
+ browserField: true,
53760
+ conditions: [],
53358
53761
  extensions: ['.js', '.cjs', '.json'],
53762
+ dedupe,
53763
+ preserveSymlinks,
53359
53764
  isBuild: true,
53360
53765
  isProduction,
53361
53766
  isRequire: true,
53362
- mainFields: ['main'],
53363
- preserveSymlinks,
53364
53767
  root
53365
53768
  };
53366
53769
  // Since dynamic imports can happen in parallel, we need to
@@ -56579,20 +56982,20 @@ function initAsClient(websocket, address, protocols, options) {
56579
56982
  }
56580
56983
 
56581
56984
  const isSecure = parsedUrl.protocol === 'wss:';
56582
- const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
56583
- let invalidURLMessage;
56985
+ const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
56986
+ let invalidUrlMessage;
56584
56987
 
56585
- if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
56586
- invalidURLMessage =
56988
+ if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
56989
+ invalidUrlMessage =
56587
56990
  'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
56588
- } else if (isUnixSocket && !parsedUrl.pathname) {
56589
- invalidURLMessage = "The URL's pathname is empty";
56991
+ } else if (isIpcUrl && !parsedUrl.pathname) {
56992
+ invalidUrlMessage = "The URL's pathname is empty";
56590
56993
  } else if (parsedUrl.hash) {
56591
- invalidURLMessage = 'The URL contains a fragment identifier';
56994
+ invalidUrlMessage = 'The URL contains a fragment identifier';
56592
56995
  }
56593
56996
 
56594
- if (invalidURLMessage) {
56595
- const err = new SyntaxError(invalidURLMessage);
56997
+ if (invalidUrlMessage) {
56998
+ const err = new SyntaxError(invalidUrlMessage);
56596
56999
 
56597
57000
  if (websocket._redirects === 0) {
56598
57001
  throw err;
@@ -56662,7 +57065,7 @@ function initAsClient(websocket, address, protocols, options) {
56662
57065
  opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
56663
57066
  }
56664
57067
 
56665
- if (isUnixSocket) {
57068
+ if (isIpcUrl) {
56666
57069
  const parts = opts.path.split(':');
56667
57070
 
56668
57071
  opts.socketPath = parts[0];
@@ -56673,9 +57076,9 @@ function initAsClient(websocket, address, protocols, options) {
56673
57076
 
56674
57077
  if (opts.followRedirects) {
56675
57078
  if (websocket._redirects === 0) {
56676
- websocket._originalUnixSocket = isUnixSocket;
57079
+ websocket._originalIpc = isIpcUrl;
56677
57080
  websocket._originalSecure = isSecure;
56678
- websocket._originalHostOrSocketPath = isUnixSocket
57081
+ websocket._originalHostOrSocketPath = isIpcUrl
56679
57082
  ? opts.socketPath
56680
57083
  : parsedUrl.host;
56681
57084
 
@@ -56693,11 +57096,11 @@ function initAsClient(websocket, address, protocols, options) {
56693
57096
  }
56694
57097
  }
56695
57098
  } else if (websocket.listenerCount('redirect') === 0) {
56696
- const isSameHost = isUnixSocket
56697
- ? websocket._originalUnixSocket
57099
+ const isSameHost = isIpcUrl
57100
+ ? websocket._originalIpc
56698
57101
  ? opts.socketPath === websocket._originalHostOrSocketPath
56699
57102
  : false
56700
- : websocket._originalUnixSocket
57103
+ : websocket._originalIpc
56701
57104
  ? false
56702
57105
  : parsedUrl.host === websocket._originalHostOrSocketPath;
56703
57106
 
@@ -60287,9 +60690,9 @@ var lib = {exports: {}};
60287
60690
 
60288
60691
  var history = lib.exports;
60289
60692
 
60290
- function spaFallbackMiddleware(root) {
60291
- const historySpaFallbackMiddleware = history({
60292
- logger: createDebugger('vite:spa-fallback'),
60693
+ function htmlFallbackMiddleware(root, spaFallback) {
60694
+ const historyHtmlFallbackMiddleware = history({
60695
+ logger: createDebugger('vite:html-fallback'),
60293
60696
  // support /dir/ without explicit index.html
60294
60697
  rewrites: [
60295
60698
  {
@@ -60300,15 +60703,17 @@ function spaFallbackMiddleware(root) {
60300
60703
  return rewritten;
60301
60704
  }
60302
60705
  else {
60303
- return `/index.html`;
60706
+ if (spaFallback) {
60707
+ return `/index.html`;
60708
+ }
60304
60709
  }
60305
60710
  }
60306
60711
  }
60307
60712
  ]
60308
60713
  });
60309
60714
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
60310
- return function viteSpaFallbackMiddleware(req, res, next) {
60311
- return historySpaFallbackMiddleware(req, res, next);
60715
+ return function viteHtmlFallbackMiddleware(req, res, next) {
60716
+ return historyHtmlFallbackMiddleware(req, res, next);
60312
60717
  };
60313
60718
  }
60314
60719
 
@@ -60673,7 +61078,7 @@ function indexHtmlMiddleware(server) {
60673
61078
  return next();
60674
61079
  }
60675
61080
  const url = req.url && cleanUrl(req.url);
60676
- // spa-fallback always redirects to /index.html
61081
+ // htmlFallbackMiddleware appends '.html' to URLs
60677
61082
  if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {
60678
61083
  const filename = getHtmlFilename(url, server);
60679
61084
  if (fs$l.existsSync(filename)) {
@@ -62132,6 +62537,8 @@ async function createServer(inlineConfig = {}) {
62132
62537
  watcher.close(),
62133
62538
  ws.close(),
62134
62539
  container.close(),
62540
+ getDepsOptimizer(server.config)?.close(),
62541
+ getDepsOptimizer(server.config, true)?.close(),
62135
62542
  closeHttpServer()
62136
62543
  ]);
62137
62544
  server.resolvedUrls = null;
@@ -62161,7 +62568,8 @@ async function createServer(inlineConfig = {}) {
62161
62568
  _restartPromise: null,
62162
62569
  _importGlobMap: new Map(),
62163
62570
  _forceOptimizeOnRestart: false,
62164
- _pendingRequests: new Map()
62571
+ _pendingRequests: new Map(),
62572
+ _fsDenyGlob: picomatch$3(config.server.fs.deny, { matchBase: true })
62165
62573
  };
62166
62574
  server.transformIndexHtml = createDevHtmlTransformFn(server);
62167
62575
  if (!middlewareMode) {
@@ -62211,6 +62619,13 @@ async function createServer(inlineConfig = {}) {
62211
62619
  watcher.on('unlink', (file) => {
62212
62620
  handleFileAddUnlink(normalizePath$3(file), server);
62213
62621
  });
62622
+ ws.on('vite:invalidate', async ({ path }) => {
62623
+ const mod = moduleGraph.urlToModuleMap.get(path);
62624
+ if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
62625
+ const file = getShortName(mod.file, config.root);
62626
+ updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server);
62627
+ }
62628
+ });
62214
62629
  if (!middlewareMode && httpServer) {
62215
62630
  httpServer.once('listening', () => {
62216
62631
  // update actual port since this may be different from initial value
@@ -62255,9 +62670,9 @@ async function createServer(inlineConfig = {}) {
62255
62670
  // serve static files
62256
62671
  middlewares.use(serveRawFsMiddleware(server));
62257
62672
  middlewares.use(serveStaticMiddleware(root, server));
62258
- // spa fallback
62259
- if (config.appType === 'spa') {
62260
- middlewares.use(spaFallbackMiddleware(root));
62673
+ // html fallback
62674
+ if (config.appType === 'spa' || config.appType === 'mpa') {
62675
+ middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'));
62261
62676
  }
62262
62677
  // run post config hooks
62263
62678
  // This is applied before the html middleware so that user middleware can
@@ -62886,10 +63301,10 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
62886
63301
  prefixes = arraify(prefixes);
62887
63302
  const env = {};
62888
63303
  const envFiles = [
62889
- /** mode local file */ `.env.${mode}.local`,
62890
- /** mode file */ `.env.${mode}`,
63304
+ /** default file */ `.env`,
62891
63305
  /** local file */ `.env.local`,
62892
- /** default file */ `.env`
63306
+ /** mode file */ `.env.${mode}`,
63307
+ /** mode local file */ `.env.${mode}.local`
62893
63308
  ];
62894
63309
  // check if there are actual env variables starting with VITE_*
62895
63310
  // these are typically provided inline and should be prioritized
@@ -62899,30 +63314,32 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
62899
63314
  env[key] = process.env[key];
62900
63315
  }
62901
63316
  }
62902
- for (const file of envFiles) {
62903
- const path = lookupFile(envDir, [file], { pathOnly: true, rootDir: envDir });
62904
- if (path) {
62905
- const parsed = main$1.exports.parse(fs$l.readFileSync(path), {
62906
- debug: process.env.DEBUG?.includes('vite:dotenv') || undefined
62907
- });
62908
- // let environment variables use each other
62909
- main({
62910
- parsed,
62911
- // prevent process.env mutation
62912
- ignoreProcessEnv: true
62913
- });
62914
- // only keys that start with prefix are exposed to client
62915
- for (const [key, value] of Object.entries(parsed)) {
62916
- if (prefixes.some((prefix) => key.startsWith(prefix)) &&
62917
- env[key] === undefined) {
62918
- env[key] = value;
62919
- }
62920
- else if (key === 'NODE_ENV' &&
62921
- process.env.VITE_USER_NODE_ENV === undefined) {
62922
- // NODE_ENV override in .env file
62923
- process.env.VITE_USER_NODE_ENV = value;
62924
- }
62925
- }
63317
+ const parsed = Object.fromEntries(envFiles.flatMap((file) => {
63318
+ const path = lookupFile(envDir, [file], {
63319
+ pathOnly: true,
63320
+ rootDir: envDir
63321
+ });
63322
+ if (!path)
63323
+ return [];
63324
+ return Object.entries(main$1.exports.parse(fs$l.readFileSync(path), {
63325
+ debug: process.env.DEBUG?.includes('vite:dotenv')
63326
+ }));
63327
+ }));
63328
+ // let environment variables use each other
63329
+ main({
63330
+ parsed,
63331
+ // prevent process.env mutation
63332
+ ignoreProcessEnv: true
63333
+ });
63334
+ // only keys that start with prefix are exposed to client
63335
+ for (const [key, value] of Object.entries(parsed)) {
63336
+ if (prefixes.some((prefix) => key.startsWith(prefix))) {
63337
+ env[key] = value;
63338
+ }
63339
+ else if (key === 'NODE_ENV' &&
63340
+ process.env.VITE_USER_NODE_ENV === undefined) {
63341
+ // NODE_ENV override in .env file
63342
+ process.env.VITE_USER_NODE_ENV = value;
62926
63343
  }
62927
63344
  }
62928
63345
  return env;
@@ -62935,7 +63352,7 @@ function resolveEnvPrefix({ envPrefix = 'VITE_' }) {
62935
63352
  return envPrefix;
62936
63353
  }
62937
63354
 
62938
- function resolveSSROptions(ssr, buildSsrCjsExternalHeuristics, preserveSymlinks) {
63355
+ function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) {
62939
63356
  ssr ?? (ssr = {});
62940
63357
  const optimizeDeps = ssr.optimizeDeps ?? {};
62941
63358
  let format = 'esm';
@@ -63066,7 +63483,12 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
63066
63483
  // replacement, but its implementation does work with function values.
63067
63484
  clientAlias, config.resolve?.alias || []));
63068
63485
  const resolveOptions = {
63069
- ...config.resolve,
63486
+ mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS,
63487
+ browserField: config.resolve?.browserField ?? true,
63488
+ conditions: config.resolve?.conditions ?? [],
63489
+ extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$1,
63490
+ dedupe: config.resolve?.dedupe ?? [],
63491
+ preserveSymlinks: config.resolve?.preserveSymlinks ?? false,
63070
63492
  alias: resolvedAlias
63071
63493
  };
63072
63494
  // load .env files
@@ -63095,7 +63517,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
63095
63517
  ? '/'
63096
63518
  : './'
63097
63519
  : resolveBaseUrl(config.base, isBuild, logger) ?? '/';
63098
- const resolvedBuildOptions = resolveBuildOptions(config.build);
63520
+ const resolvedBuildOptions = resolveBuildOptions(config.build, isBuild, logger);
63099
63521
  // resolve cache directory
63100
63522
  const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true });
63101
63523
  const cacheDir = config.cacheDir
@@ -63150,7 +63572,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
63150
63572
  ? path$n.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
63151
63573
  : '';
63152
63574
  const server = resolveServerOptions(resolvedRoot, config.server, logger);
63153
- const ssr = resolveSSROptions(config.ssr, config.legacy?.buildSsrCjsExternalHeuristics, config.resolve?.preserveSymlinks);
63575
+ const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics);
63154
63576
  const middlewareMode = config?.server?.middlewareMode;
63155
63577
  const optimizeDeps = config.optimizeDeps || {};
63156
63578
  const BASE_URL = resolvedBase;
@@ -63207,7 +63629,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
63207
63629
  disabled: 'build',
63208
63630
  ...optimizeDeps,
63209
63631
  esbuildOptions: {
63210
- preserveSymlinks: config.resolve?.preserveSymlinks,
63632
+ preserveSymlinks: resolveOptions.preserveSymlinks,
63211
63633
  ...optimizeDeps.esbuildOptions
63212
63634
  }
63213
63635
  },
@@ -63421,40 +63843,32 @@ async function bundleConfigFile(fileName, isESM) {
63421
63843
  {
63422
63844
  name: 'externalize-deps',
63423
63845
  setup(build) {
63424
- build.onResolve({ filter: /.*/ }, ({ path: id, importer }) => {
63846
+ const options = {
63847
+ root: path$n.dirname(fileName),
63848
+ isBuild: true,
63849
+ isProduction: true,
63850
+ isRequire: !isESM,
63851
+ preferRelative: false,
63852
+ tryIndex: true,
63853
+ mainFields: DEFAULT_MAIN_FIELDS,
63854
+ browserField: false,
63855
+ conditions: [],
63856
+ dedupe: [],
63857
+ extensions: DEFAULT_EXTENSIONS$1,
63858
+ preserveSymlinks: false
63859
+ };
63860
+ build.onResolve({ filter: /.*/ }, ({ path: id, importer, kind }) => {
63425
63861
  // externalize bare imports
63426
- if (id[0] !== '.' && !path$n.isAbsolute(id)) {
63862
+ if (id[0] !== '.' && !isAbsolute(id)) {
63863
+ let idFsPath = tryNodeResolve(id, importer, options, false)?.id;
63864
+ if (idFsPath && (isESM || kind === 'dynamic-import')) {
63865
+ idFsPath = pathToFileURL(idFsPath).href;
63866
+ }
63427
63867
  return {
63868
+ path: idFsPath,
63428
63869
  external: true
63429
63870
  };
63430
63871
  }
63431
- // bundle the rest and make sure that the we can also access
63432
- // it's third-party dependencies. externalize if not.
63433
- // monorepo/
63434
- // ├─ package.json
63435
- // ├─ utils.js -----------> bundle (share same node_modules)
63436
- // ├─ vite-project/
63437
- // │ ├─ vite.config.js --> entry
63438
- // │ ├─ package.json
63439
- // ├─ foo-project/
63440
- // │ ├─ utils.js --------> external (has own node_modules)
63441
- // │ ├─ package.json
63442
- const idFsPath = path$n.resolve(path$n.dirname(importer), id);
63443
- const idPkgPath = lookupFile(idFsPath, [`package.json`], {
63444
- pathOnly: true
63445
- });
63446
- if (idPkgPath) {
63447
- const idPkgDir = path$n.dirname(idPkgPath);
63448
- // if this file needs to go up one or more directory to reach the vite config,
63449
- // that means it has it's own node_modules (e.g. foo-project)
63450
- if (path$n.relative(idPkgDir, fileName).startsWith('..')) {
63451
- return {
63452
- // normalize actual import after bundled as a single vite config
63453
- path: isESM ? pathToFileURL(idFsPath).href : idFsPath,
63454
- external: true
63455
- };
63456
- }
63457
- }
63458
63872
  });
63459
63873
  }
63460
63874
  },
@@ -63548,5 +63962,8 @@ function isDepsOptimizerEnabled(config, ssr) {
63548
63962
  (command === 'build' && disabled === 'build') ||
63549
63963
  (command === 'serve' && disabled === 'dev'));
63550
63964
  }
63965
+ function isAbsolute(id) {
63966
+ return path$n.isAbsolute(id) || path$n.posix.isAbsolute(id);
63967
+ }
63551
63968
 
63552
63969
  export { index$1 as A, build$1 as B, index as C, preview$1 as D, resolvePackageData as a, build as b, createServer as c, defineConfig as d, resolveConfig as e, formatPostcssSourceMap as f, resolveBaseUrl as g, getDepOptimizationConfig as h, isDepsOptimizerEnabled as i, mergeAlias as j, createFilter as k, loadConfigFromFile as l, mergeConfig as m, normalizePath$3 as n, optimizeDeps as o, preview as p, send as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, createLogger as u, searchForWorkspaceRoot as v, loadEnv as w, resolveEnvPrefix as x, picocolors as y, commonjsGlobal as z };