vite 8.1.5 → 8.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,7 +1,7 @@
1
1
  import { Module, builtinModules, createRequire } from "node:module";
2
2
  import { parseAst, parseAstAsync } from "rolldown/parseAst";
3
3
  import { esmExternalRequirePlugin, esmExternalRequirePlugin as esmExternalRequirePlugin$1 } from "rolldown/plugins";
4
- import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, transformSync } from "rolldown/utils";
4
+ import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, parseSync as parseSync$1, transformSync } from "rolldown/utils";
5
5
  import * as fs$2 from "node:fs";
6
6
  import fs, { existsSync, readFileSync } from "node:fs";
7
7
  import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
@@ -13,6 +13,7 @@ import crypto from "node:crypto";
13
13
  import pm from "picomatch";
14
14
  import { MessageChannel, Worker } from "node:worker_threads";
15
15
  import { VERSION as rolldownVersion, rolldown } from "rolldown";
16
+ import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby";
16
17
  import os from "node:os";
17
18
  import net from "node:net";
18
19
  import childProcess, { exec, execFile, execSync } from "node:child_process";
@@ -23,7 +24,6 @@ import { exactRegex, makeIdFiltersToMatchWithQuery, prefixRegex, withFilter } fr
23
24
  import { dev, oxcRuntimePlugin, resolveTsconfig, scan, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteDynamicImportVarsPlugin, viteImportGlobPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWebWorkerPostPlugin } from "rolldown/experimental";
24
25
  import readline from "node:readline";
25
26
  import isModuleSyncConditionEnabled from "#module-sync-enabled";
26
- import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby";
27
27
  import assert from "node:assert";
28
28
  import process$1 from "node:process";
29
29
  import v8 from "node:v8";
@@ -634,6 +634,7 @@ const CLIENT_PUBLIC_PATH = `/@vite/client`;
634
634
  const ENV_PUBLIC_PATH = `/@vite/env`;
635
635
  const VITE_PACKAGE_DIR = resolve(fileURLToPath(new URL("../../../src/node/constants.ts", import.meta.url)), "../../..");
636
636
  const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
637
+ const BUNDLED_DEV_CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/bundledDevClient.mjs");
637
638
  const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
638
639
  const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
639
640
  const KNOWN_ASSET_TYPES = [
@@ -1603,11 +1604,11 @@ function getDate() {
1603
1604
  function init$1(debug) {
1604
1605
  debug.inspectOpts = Object.assign({}, inspectOpts);
1605
1606
  }
1606
- var require$1, colors$39, inspectOpts, humanize$1, createDebug, node_default;
1607
+ var require$1, colors$40, inspectOpts, humanize$1, createDebug, node_default;
1607
1608
  var init_node = __esmMin((() => {
1608
1609
  init_core();
1609
1610
  require$1 = createRequire(import.meta.url);
1610
- colors$39 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
1611
+ colors$40 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
1611
1612
  20,
1612
1613
  21,
1613
1614
  26,
@@ -1709,7 +1710,7 @@ var init_node = __esmMin((() => {
1709
1710
  } catch (_unused) {
1710
1711
  humanize$1 = humanize;
1711
1712
  }
1712
- createDebug = setup(useColors(), colors$39, log, load, save, formatArgs, init$1);
1713
+ createDebug = setup(useColors(), colors$40, log, load, save, formatArgs, init$1);
1713
1714
  createDebug.inspectOpts = inspectOpts;
1714
1715
  createDebug.formatters.o = function(v) {
1715
1716
  this.inspectOpts.colors = this.useColors;
@@ -2287,6 +2288,8 @@ function lookupFile(dir, fileNames) {
2287
2288
  function isFilePathESM(filePath, packageCache) {
2288
2289
  if (/\.m[jt]s$/.test(filePath)) return true;
2289
2290
  else if (/\.c[jt]s$/.test(filePath)) return false;
2291
+ else if (filePath.startsWith("\0")) return true;
2292
+ else if (!path.isAbsolute(filePath)) return false;
2290
2293
  else try {
2291
2294
  return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
2292
2295
  } catch {
@@ -2300,6 +2303,8 @@ function isFilePathESM(filePath, packageCache) {
2300
2303
  */
2301
2304
  function isFilePathFormatExplicit(filePath, packageCache) {
2302
2305
  if (/\.[mc][jt]s$/.test(filePath)) return true;
2306
+ if (filePath.startsWith("\0")) return true;
2307
+ if (!path.isAbsolute(filePath)) return false;
2303
2308
  try {
2304
2309
  const pkg = findNearestPackageData(path.dirname(filePath), packageCache);
2305
2310
  return pkg?.data.type === "module" || pkg?.data.type === "commonjs";
@@ -2632,10 +2637,12 @@ function resolveServerUrls(server, options, hostname, httpsOptions, config) {
2632
2637
  const isAddressInfo = (x) => x?.address;
2633
2638
  if (!isAddressInfo(address)) return {
2634
2639
  local: [],
2635
- network: []
2640
+ network: [],
2641
+ networkInterfaceNames: []
2636
2642
  };
2637
2643
  const local = [];
2638
2644
  const network = [];
2645
+ const networkInterfaceNames = [];
2639
2646
  const protocol = options.https ? "https" : "http";
2640
2647
  const port = address.port;
2641
2648
  const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase;
@@ -2644,13 +2651,21 @@ function resolveServerUrls(server, options, hostname, httpsOptions, config) {
2644
2651
  if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`;
2645
2652
  const address = `${protocol}://${hostnameName}:${port}${base}`;
2646
2653
  if (loopbackHosts.has(hostname.host)) local.push(address);
2647
- else network.push(address);
2648
- } else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
2649
- let host = detail.address.replace("127.0.0.1", hostname.name);
2650
- if (host.includes(":")) host = `[${host}]`;
2651
- const url = `${protocol}://${host}:${port}${base}`;
2652
- if (detail.address.includes("127.0.0.1")) local.push(url);
2653
- else network.push(url);
2654
+ else {
2655
+ network.push(address);
2656
+ networkInterfaceNames.push(void 0);
2657
+ }
2658
+ } else Object.entries(os.networkInterfaces()).forEach(([name, nInterface]) => {
2659
+ (nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
2660
+ let host = detail.address.replace("127.0.0.1", hostname.name);
2661
+ if (host.includes(":")) host = `[${host}]`;
2662
+ const url = `${protocol}://${host}:${port}${base}`;
2663
+ if (detail.address.includes("127.0.0.1")) local.push(url);
2664
+ else {
2665
+ network.push(url);
2666
+ networkInterfaceNames.push(name);
2667
+ }
2668
+ });
2654
2669
  });
2655
2670
  const hostnamesFromCert = extractHostnamesFromCerts(httpsOptions?.cert);
2656
2671
  if (hostnamesFromCert.length > 0) {
@@ -2659,7 +2674,8 @@ function resolveServerUrls(server, options, hostname, httpsOptions, config) {
2659
2674
  }
2660
2675
  return {
2661
2676
  local,
2662
- network
2677
+ network,
2678
+ networkInterfaceNames
2663
2679
  };
2664
2680
  }
2665
2681
  function extractHostnamesFromSubjectAltName(subjectAltName) {
@@ -2851,7 +2867,10 @@ function mergeConfigRecursively(defaults, overrides, rootPath) {
2851
2867
  else merged[key] = value;
2852
2868
  continue;
2853
2869
  }
2854
- if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
2870
+ if (key === "input" && rootPath === "") {
2871
+ merged[key] = mergeInput(existing, value);
2872
+ continue;
2873
+ } else if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
2855
2874
  merged[key] = mergeAlias(existing, value);
2856
2875
  continue;
2857
2876
  } else if (key === "assetsInclude" && rootPath === "") {
@@ -2883,6 +2902,26 @@ function mergeConfig(defaults, overrides, isRoot = true) {
2883
2902
  if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`);
2884
2903
  return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
2885
2904
  }
2905
+ function mergeInput(a, b) {
2906
+ if (!a) return b;
2907
+ if (!b) return a;
2908
+ if (typeof a === "string" && typeof b === "string") return [a, b];
2909
+ if (Array.isArray(a) && (typeof b === "string" || Array.isArray(b))) return [...a, ...Array.isArray(b) ? b : [b]];
2910
+ if (Array.isArray(b) && (typeof a === "string" || Array.isArray(a))) return [...Array.isArray(a) ? a : [a], ...b];
2911
+ if (typeof a !== "string" && !Array.isArray(a)) return {
2912
+ ...a,
2913
+ ...normalizeToInputObject(b)
2914
+ };
2915
+ return {
2916
+ ...normalizeToInputObject(a),
2917
+ ...b
2918
+ };
2919
+ }
2920
+ function normalizeToInputObject(input) {
2921
+ if (typeof input === "string") return { [path.basename(input, path.extname(input))]: input };
2922
+ if (Array.isArray(input)) return Object.fromEntries(input.map((i) => [path.basename(i, path.extname(i)), i]));
2923
+ return input;
2924
+ }
2886
2925
  function mergeAlias(a, b) {
2887
2926
  if (!a) return b;
2888
2927
  if (!b) return a;
@@ -3237,10 +3276,20 @@ function createLogger(level = "info", options = {}) {
3237
3276
  };
3238
3277
  return logger;
3239
3278
  }
3279
+ const maxNetworkInterfaceNameLength = 20;
3240
3280
  function printServerUrls(urls, optionsHost, info) {
3241
3281
  const colorUrl = (url) => import_picocolors.default.cyan(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
3242
3282
  for (const url of urls.local) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Local")}: ${colorUrl(url)}`);
3243
- for (const url of urls.network) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: ${colorUrl(url)}`);
3283
+ const networkUrlMaxLength = Math.max(...urls.network.map((url) => url.length), 0);
3284
+ urls.network.forEach((url, index) => {
3285
+ const interfaceName = urls.networkInterfaceNames?.[index];
3286
+ let suffix = "";
3287
+ if (interfaceName) {
3288
+ const label = interfaceName.length > maxNetworkInterfaceNameLength ? `${interfaceName.slice(0, maxNetworkInterfaceNameLength - 1)}…` : interfaceName;
3289
+ suffix = " ".repeat(networkUrlMaxLength - url.length + 2) + import_picocolors.default.dim(label);
3290
+ }
3291
+ info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: ${colorUrl(url)}${suffix}`);
3292
+ });
3244
3293
  if (urls.network.length === 0 && optionsHost === void 0) info(import_picocolors.default.dim(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: use `) + import_picocolors.default.bold("--host") + import_picocolors.default.dim(" to expose"));
3245
3294
  }
3246
3295
  //#endregion
@@ -4148,7 +4197,7 @@ function warnDeprecatedShouldBeConvertedToPluginOptions(logger, name) {
4148
4197
  logger.warn(import_picocolors.default.yellow(`\`esbuild.${name}\` option was specified. But this option is deprecated and will be removed in future versions. This option can be achieved by using a plugin with transform hook, please use that instead.`));
4149
4198
  }
4150
4199
  //#endregion
4151
- //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
4200
+ //#region ../../node_modules/.pnpm/magic-string@1.0.0/node_modules/magic-string/dist/index.mjs
4152
4201
  var BitSet = class BitSet {
4153
4202
  constructor(arg) {
4154
4203
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -4192,14 +4241,16 @@ var Chunk = class Chunk {
4192
4241
  return this.start < index && index < this.end;
4193
4242
  }
4194
4243
  eachNext(fn) {
4195
- let chunk = this;
4244
+ fn(this);
4245
+ let chunk = this.next;
4196
4246
  while (chunk) {
4197
4247
  fn(chunk);
4198
4248
  chunk = chunk.next;
4199
4249
  }
4200
4250
  }
4201
4251
  eachPrevious(fn) {
4202
- let chunk = this;
4252
+ fn(this);
4253
+ let chunk = this.previous;
4203
4254
  while (chunk) {
4204
4255
  fn(chunk);
4205
4256
  chunk = chunk.previous;
@@ -4288,12 +4339,13 @@ var Chunk = class Chunk {
4288
4339
  };
4289
4340
  function getBtoa() {
4290
4341
  if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
4291
- else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
4292
- else return () => {
4342
+ const buffer = globalThis["Buffer"];
4343
+ if (buffer) return (str) => buffer.from(str, "utf-8").toString("base64");
4344
+ return () => {
4293
4345
  throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
4294
4346
  };
4295
4347
  }
4296
- const btoa$1 = /*#__PURE__*/ getBtoa();
4348
+ const btoa$1 = /* #__PURE__ */ getBtoa();
4297
4349
  var SourceMap = class {
4298
4350
  constructor(properties) {
4299
4351
  this.version = 3;
@@ -4305,43 +4357,20 @@ var SourceMap = class {
4305
4357
  if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
4306
4358
  if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
4307
4359
  }
4360
+ /**
4361
+ * Returns the equivalent of `JSON.stringify(map)`
4362
+ */
4308
4363
  toString() {
4309
4364
  return JSON.stringify(this);
4310
4365
  }
4366
+ /**
4367
+ * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
4368
+ * `generateMap(options?: SourceMapOptions): SourceMap;`
4369
+ */
4311
4370
  toUrl() {
4312
- return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
4371
+ return `data:application/json;charset=utf-8;base64,${btoa$1(this.toString())}`;
4313
4372
  }
4314
4373
  };
4315
- function guessIndent(code) {
4316
- const lines = code.split("\n");
4317
- const tabbed = lines.filter((line) => /^\t+/.test(line));
4318
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
4319
- if (tabbed.length === 0 && spaced.length === 0) return null;
4320
- if (tabbed.length >= spaced.length) return " ";
4321
- const min = spaced.reduce((previous, current) => {
4322
- const numSpaces = /^ +/.exec(current)[0].length;
4323
- return Math.min(numSpaces, previous);
4324
- }, Infinity);
4325
- return new Array(min + 1).join(" ");
4326
- }
4327
- function getRelativePath(from, to) {
4328
- const fromParts = from.split(/[/\\]/);
4329
- const toParts = to.split(/[/\\]/);
4330
- fromParts.pop();
4331
- while (fromParts[0] === toParts[0]) {
4332
- fromParts.shift();
4333
- toParts.shift();
4334
- }
4335
- if (fromParts.length) {
4336
- let i = fromParts.length;
4337
- while (i--) fromParts[i] = "..";
4338
- }
4339
- return fromParts.concat(toParts).join("/");
4340
- }
4341
- const toString = Object.prototype.toString;
4342
- function isObject(thing) {
4343
- return toString.call(thing) === "[object Object]";
4344
- }
4345
4374
  function getLocator(source) {
4346
4375
  const originalLines = source.split("\n");
4347
4376
  const lineOffsets = [];
@@ -4364,6 +4393,36 @@ function getLocator(source) {
4364
4393
  };
4365
4394
  };
4366
4395
  }
4396
+ function getRelativePath(from, to) {
4397
+ const fromParts = from.split(/[/\\]/);
4398
+ const toParts = to.split(/[/\\]/);
4399
+ fromParts.pop();
4400
+ while (fromParts[0] === toParts[0]) {
4401
+ fromParts.shift();
4402
+ toParts.shift();
4403
+ }
4404
+ if (fromParts.length) {
4405
+ let i = fromParts.length;
4406
+ while (i--) fromParts[i] = "..";
4407
+ }
4408
+ return fromParts.concat(toParts).join("/");
4409
+ }
4410
+ function guessIndent(code) {
4411
+ const lines = code.split("\n");
4412
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
4413
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
4414
+ if (tabbed.length === 0 && spaced.length === 0) return null;
4415
+ if (tabbed.length >= spaced.length) return " ";
4416
+ const min = spaced.reduce((previous, current) => {
4417
+ const numSpaces = /^ +/.exec(current)[0].length;
4418
+ return Math.min(numSpaces, previous);
4419
+ }, Infinity);
4420
+ return " ".repeat(min);
4421
+ }
4422
+ const toString = Object.prototype.toString;
4423
+ function isObject(thing) {
4424
+ return toString.call(thing) === "[object Object]";
4425
+ }
4367
4426
  const wordRegex = /\w/;
4368
4427
  var Mappings = class {
4369
4428
  constructor(hires) {
@@ -4463,6 +4522,8 @@ var Mappings = class {
4463
4522
  }
4464
4523
  };
4465
4524
  const n = "\n";
4525
+ const NEWLINE_CHAR = "\n".charCodeAt(0);
4526
+ const CR_CHAR = "\r".charCodeAt(0);
4466
4527
  const warned = {
4467
4528
  insertLeft: false,
4468
4529
  insertRight: false,
@@ -4536,14 +4597,25 @@ var MagicString = class MagicString {
4536
4597
  this.byStart[0] = chunk;
4537
4598
  this.byEnd[string.length] = chunk;
4538
4599
  }
4600
+ /**
4601
+ * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
4602
+ */
4539
4603
  addSourcemapLocation(char) {
4540
4604
  this.sourcemapLocations.add(char);
4541
4605
  }
4606
+ /**
4607
+ * Appends the specified content to the end of the string.
4608
+ */
4542
4609
  append(content) {
4543
4610
  if (typeof content !== "string") throw new TypeError("outro content must be a string");
4544
4611
  this.outro += content;
4545
4612
  return this;
4546
4613
  }
4614
+ /**
4615
+ * Appends the specified content at the index in the original string.
4616
+ * If a range *ending* with index is subsequently moved, the insert will be moved with it.
4617
+ * See also `s.prependLeft(...)`.
4618
+ */
4547
4619
  appendLeft(index, content) {
4548
4620
  index = index + this.offset;
4549
4621
  if (typeof content !== "string") throw new TypeError("inserted content must be a string");
@@ -4553,6 +4625,11 @@ var MagicString = class MagicString {
4553
4625
  else this.intro += content;
4554
4626
  return this;
4555
4627
  }
4628
+ /**
4629
+ * Appends the specified content at the index in the original string.
4630
+ * If a range *starting* with index is subsequently moved, the insert will be moved with it.
4631
+ * See also `s.prependRight(...)`.
4632
+ */
4556
4633
  appendRight(index, content) {
4557
4634
  index = index + this.offset;
4558
4635
  if (typeof content !== "string") throw new TypeError("inserted content must be a string");
@@ -4562,6 +4639,9 @@ var MagicString = class MagicString {
4562
4639
  else this.outro += content;
4563
4640
  return this;
4564
4641
  }
4642
+ /**
4643
+ * Does what you'd expect.
4644
+ */
4565
4645
  clone() {
4566
4646
  const cloned = new MagicString(this.original, {
4567
4647
  filename: this.filename,
@@ -4588,6 +4668,10 @@ var MagicString = class MagicString {
4588
4668
  cloned.outro = this.outro;
4589
4669
  return cloned;
4590
4670
  }
4671
+ /**
4672
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
4673
+ * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
4674
+ */
4591
4675
  generateDecodedMap(options) {
4592
4676
  options = options || {};
4593
4677
  const sourceIndex = 0;
@@ -4612,12 +4696,17 @@ var MagicString = class MagicString {
4612
4696
  x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
4613
4697
  };
4614
4698
  }
4699
+ /**
4700
+ * Generates a version 3 sourcemap.
4701
+ */
4615
4702
  generateMap(options) {
4616
4703
  return new SourceMap(this.generateDecodedMap(options));
4617
4704
  }
4705
+ /** @internal */
4618
4706
  _ensureindentStr() {
4619
4707
  if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
4620
4708
  }
4709
+ /** @internal */
4621
4710
  _getRawIndentString() {
4622
4711
  this._ensureindentStr();
4623
4712
  return this.indentStr;
@@ -4637,6 +4726,7 @@ var MagicString = class MagicString {
4637
4726
  indentStr = this.indentStr || " ";
4638
4727
  }
4639
4728
  if (indentStr === "") return this;
4729
+ const resolvedIndentStr = indentStr;
4640
4730
  options = options || {};
4641
4731
  const isExcluded = {};
4642
4732
  if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
@@ -4644,13 +4734,22 @@ var MagicString = class MagicString {
4644
4734
  });
4645
4735
  let shouldIndentNextCharacter = options.indentStart !== false;
4646
4736
  const replacer = (match) => {
4647
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
4737
+ if (shouldIndentNextCharacter) return `${resolvedIndentStr}${match}`;
4648
4738
  shouldIndentNextCharacter = true;
4649
4739
  return match;
4650
4740
  };
4651
4741
  this.intro = this.intro.replace(pattern, replacer);
4652
4742
  let charIndex = 0;
4653
4743
  let chunk = this.firstChunk;
4744
+ const indentAt = (index) => {
4745
+ shouldIndentNextCharacter = false;
4746
+ if (index === chunk.start) chunk.prependRight(resolvedIndentStr);
4747
+ else {
4748
+ this._splitChunk(chunk, index);
4749
+ chunk = chunk.next;
4750
+ chunk.prependRight(resolvedIndentStr);
4751
+ }
4752
+ };
4654
4753
  while (chunk) {
4655
4754
  const end = chunk.end;
4656
4755
  if (chunk.edited) {
@@ -4658,22 +4757,32 @@ var MagicString = class MagicString {
4658
4757
  chunk.content = chunk.content.replace(pattern, replacer);
4659
4758
  if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
4660
4759
  }
4661
- } else {
4760
+ } else if (options.exclude) {
4662
4761
  charIndex = chunk.start;
4663
4762
  while (charIndex < end) {
4664
4763
  if (!isExcluded[charIndex]) {
4665
- const char = this.original[charIndex];
4666
- if (char === "\n") shouldIndentNextCharacter = true;
4667
- else if (char !== "\r" && shouldIndentNextCharacter) {
4668
- shouldIndentNextCharacter = false;
4669
- if (charIndex === chunk.start) chunk.prependRight(indentStr);
4670
- else {
4671
- this._splitChunk(chunk, charIndex);
4672
- chunk = chunk.next;
4673
- chunk.prependRight(indentStr);
4674
- }
4675
- }
4764
+ const char = this.original.charCodeAt(charIndex);
4765
+ if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
4766
+ else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
4767
+ }
4768
+ charIndex += 1;
4769
+ }
4770
+ } else {
4771
+ charIndex = chunk.start;
4772
+ while (charIndex < end) {
4773
+ if (!shouldIndentNextCharacter) {
4774
+ const nextLine = this.original.indexOf(n, charIndex);
4775
+ if (nextLine === -1 || nextLine >= end) break;
4776
+ shouldIndentNextCharacter = true;
4777
+ charIndex = nextLine + 1;
4778
+ continue;
4779
+ }
4780
+ const char = this.original.charCodeAt(charIndex);
4781
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
4782
+ charIndex += 1;
4783
+ continue;
4676
4784
  }
4785
+ indentAt(charIndex);
4677
4786
  charIndex += 1;
4678
4787
  }
4679
4788
  }
@@ -4683,9 +4792,11 @@ var MagicString = class MagicString {
4683
4792
  this.outro = this.outro.replace(pattern, replacer);
4684
4793
  return this;
4685
4794
  }
4795
+ /** @internal */
4686
4796
  insert() {
4687
4797
  throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
4688
4798
  }
4799
+ /** @internal */
4689
4800
  insertLeft(index, content) {
4690
4801
  if (!warned.insertLeft) {
4691
4802
  console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
@@ -4693,6 +4804,7 @@ var MagicString = class MagicString {
4693
4804
  }
4694
4805
  return this.appendLeft(index, content);
4695
4806
  }
4807
+ /** @internal */
4696
4808
  insertRight(index, content) {
4697
4809
  if (!warned.insertRight) {
4698
4810
  console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
@@ -4700,10 +4812,14 @@ var MagicString = class MagicString {
4700
4812
  }
4701
4813
  return this.prependRight(index, content);
4702
4814
  }
4815
+ /**
4816
+ * Moves the characters from `start` and `end` to `index`.
4817
+ */
4703
4818
  move(start, end, index) {
4704
4819
  start = start + this.offset;
4705
4820
  end = end + this.offset;
4706
4821
  index = index + this.offset;
4822
+ if (start === end) return this;
4707
4823
  if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
4708
4824
  this._split(start);
4709
4825
  this._split(end);
@@ -4730,13 +4846,30 @@ var MagicString = class MagicString {
4730
4846
  if (!newRight) this.lastChunk = last;
4731
4847
  return this;
4732
4848
  }
4849
+ /**
4850
+ * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
4851
+ * that range. The same restrictions as `s.remove()` apply.
4852
+ *
4853
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
4854
+ * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
4855
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
4856
+ *
4857
+ * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
4858
+ */
4733
4859
  overwrite(start, end, content, options) {
4734
- options = options || {};
4860
+ const optionObject = typeof options === "object" && options ? options : {};
4735
4861
  return this.update(start, end, content, {
4736
- ...options,
4737
- overwrite: !options.contentOnly
4862
+ ...optionObject,
4863
+ overwrite: !optionObject.contentOnly
4738
4864
  });
4739
4865
  }
4866
+ /**
4867
+ * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
4868
+ *
4869
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
4870
+ * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
4871
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
4872
+ */
4740
4873
  update(start, end, content, options) {
4741
4874
  start = start + this.offset;
4742
4875
  end = end + this.offset;
@@ -4756,8 +4889,9 @@ var MagicString = class MagicString {
4756
4889
  }
4757
4890
  options = { storeName: true };
4758
4891
  }
4759
- const storeName = options !== void 0 ? options.storeName : false;
4760
- const overwrite = options !== void 0 ? options.overwrite : false;
4892
+ const optionObject = typeof options === "object" && options ? options : {};
4893
+ const storeName = optionObject.storeName || false;
4894
+ const overwrite = optionObject.overwrite || false;
4761
4895
  if (storeName) {
4762
4896
  const original = this.original.slice(start, end);
4763
4897
  Object.defineProperty(this.storedNames, original, {
@@ -4783,11 +4917,17 @@ var MagicString = class MagicString {
4783
4917
  }
4784
4918
  return this;
4785
4919
  }
4920
+ /**
4921
+ * Prepends the string with the specified content.
4922
+ */
4786
4923
  prepend(content) {
4787
4924
  if (typeof content !== "string") throw new TypeError("outro content must be a string");
4788
4925
  this.intro = content + this.intro;
4789
4926
  return this;
4790
4927
  }
4928
+ /**
4929
+ * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
4930
+ */
4791
4931
  prependLeft(index, content) {
4792
4932
  index = index + this.offset;
4793
4933
  if (typeof content !== "string") throw new TypeError("inserted content must be a string");
@@ -4797,6 +4937,9 @@ var MagicString = class MagicString {
4797
4937
  else this.intro = content + this.intro;
4798
4938
  return this;
4799
4939
  }
4940
+ /**
4941
+ * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
4942
+ */
4800
4943
  prependRight(index, content) {
4801
4944
  index = index + this.offset;
4802
4945
  if (typeof content !== "string") throw new TypeError("inserted content must be a string");
@@ -4806,6 +4949,10 @@ var MagicString = class MagicString {
4806
4949
  else this.outro = content + this.outro;
4807
4950
  return this;
4808
4951
  }
4952
+ /**
4953
+ * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
4954
+ * Removing the same content twice, or making removals that partially overlap, will cause an error.
4955
+ */
4809
4956
  remove(start, end) {
4810
4957
  start = start + this.offset;
4811
4958
  end = end + this.offset;
@@ -4827,6 +4974,9 @@ var MagicString = class MagicString {
4827
4974
  }
4828
4975
  return this;
4829
4976
  }
4977
+ /**
4978
+ * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
4979
+ */
4830
4980
  reset(start, end) {
4831
4981
  start = start + this.offset;
4832
4982
  end = end + this.offset;
@@ -4849,11 +4999,12 @@ var MagicString = class MagicString {
4849
4999
  lastChar() {
4850
5000
  if (this.outro.length) return this.outro[this.outro.length - 1];
4851
5001
  let chunk = this.lastChunk;
4852
- do {
5002
+ while (chunk) {
4853
5003
  if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
4854
5004
  if (chunk.content.length) return chunk.content[chunk.content.length - 1];
4855
5005
  if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
4856
- } while (chunk = chunk.previous);
5006
+ chunk = chunk.previous;
5007
+ }
4857
5008
  if (this.intro.length) return this.intro[this.intro.length - 1];
4858
5009
  return "";
4859
5010
  }
@@ -4862,7 +5013,7 @@ var MagicString = class MagicString {
4862
5013
  if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
4863
5014
  let lineStr = this.outro;
4864
5015
  let chunk = this.lastChunk;
4865
- do {
5016
+ while (chunk) {
4866
5017
  if (chunk.outro.length > 0) {
4867
5018
  lineIndex = chunk.outro.lastIndexOf(n);
4868
5019
  if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
@@ -4878,11 +5029,16 @@ var MagicString = class MagicString {
4878
5029
  if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
4879
5030
  lineStr = chunk.intro + lineStr;
4880
5031
  }
4881
- } while (chunk = chunk.previous);
5032
+ chunk = chunk.previous;
5033
+ }
4882
5034
  lineIndex = this.intro.lastIndexOf(n);
4883
5035
  if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
4884
5036
  return this.intro + lineStr;
4885
5037
  }
5038
+ /**
5039
+ * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string.
5040
+ * Throws error if the indices are for characters that were already removed.
5041
+ */
4886
5042
  slice(start = 0, end = this.original.length - this.offset) {
4887
5043
  start = start + this.offset;
4888
5044
  end = end + this.offset;
@@ -4911,12 +5067,16 @@ var MagicString = class MagicString {
4911
5067
  }
4912
5068
  return result;
4913
5069
  }
5070
+ /**
5071
+ * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
5072
+ */
4914
5073
  snip(start, end) {
4915
5074
  const clone = this.clone();
4916
5075
  clone.remove(0, start);
4917
5076
  clone.remove(end, clone.original.length);
4918
5077
  return clone;
4919
5078
  }
5079
+ /** @internal */
4920
5080
  _split(index) {
4921
5081
  if (this.byStart[index] || this.byEnd[index]) return;
4922
5082
  let chunk = this.lastSearchedChunk;
@@ -4929,6 +5089,7 @@ var MagicString = class MagicString {
4929
5089
  previousChunk = chunk;
4930
5090
  }
4931
5091
  }
5092
+ /** @internal */
4932
5093
  _splitChunk(chunk, index) {
4933
5094
  if (chunk.edited && chunk.content.length) {
4934
5095
  const loc = getLocator(this.original)(index);
@@ -4942,6 +5103,9 @@ var MagicString = class MagicString {
4942
5103
  this.lastSearchedChunk = chunk;
4943
5104
  return true;
4944
5105
  }
5106
+ /**
5107
+ * Returns the generated string.
5108
+ */
4945
5109
  toString() {
4946
5110
  let str = this.intro;
4947
5111
  let chunk = this.firstChunk;
@@ -4951,29 +5115,41 @@ var MagicString = class MagicString {
4951
5115
  }
4952
5116
  return str + this.outro;
4953
5117
  }
5118
+ /**
5119
+ * Returns true if the resulting source is empty (disregarding white space).
5120
+ */
4954
5121
  isEmpty() {
4955
5122
  let chunk = this.firstChunk;
4956
- do
5123
+ while (chunk) {
4957
5124
  if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
4958
- while (chunk = chunk.next);
5125
+ chunk = chunk.next;
5126
+ }
4959
5127
  return true;
4960
5128
  }
4961
5129
  length() {
4962
5130
  let chunk = this.firstChunk;
4963
5131
  let length = 0;
4964
- do
5132
+ while (chunk) {
4965
5133
  length += chunk.intro.length + chunk.content.length + chunk.outro.length;
4966
- while (chunk = chunk.next);
5134
+ chunk = chunk.next;
5135
+ }
4967
5136
  return length;
4968
5137
  }
5138
+ /**
5139
+ * Removes empty lines from the start and end.
5140
+ */
4969
5141
  trimLines() {
4970
5142
  return this.trim("[\\r\\n]");
4971
5143
  }
5144
+ /**
5145
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
5146
+ */
4972
5147
  trim(charType) {
4973
5148
  return this.trimStart(charType).trimEnd(charType);
4974
5149
  }
5150
+ /** @internal */
4975
5151
  trimEndAborted(charType) {
4976
- const rx = new RegExp((charType || "\\s") + "+$");
5152
+ const rx = new RegExp(`${charType || "\\s"}+$`);
4977
5153
  this.outro = this.outro.replace(rx, "");
4978
5154
  if (this.outro.length) return true;
4979
5155
  let chunk = this.lastChunk;
@@ -4991,12 +5167,16 @@ var MagicString = class MagicString {
4991
5167
  } while (chunk);
4992
5168
  return false;
4993
5169
  }
5170
+ /**
5171
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
5172
+ */
4994
5173
  trimEnd(charType) {
4995
5174
  this.trimEndAborted(charType);
4996
5175
  return this;
4997
5176
  }
5177
+ /** @internal */
4998
5178
  trimStartAborted(charType) {
4999
- const rx = new RegExp("^" + (charType || "\\s") + "+");
5179
+ const rx = new RegExp(`^${charType || "\\s"}+`);
5000
5180
  this.intro = this.intro.replace(rx, "");
5001
5181
  if (this.intro.length) return true;
5002
5182
  let chunk = this.firstChunk;
@@ -5014,13 +5194,20 @@ var MagicString = class MagicString {
5014
5194
  } while (chunk);
5015
5195
  return false;
5016
5196
  }
5197
+ /**
5198
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
5199
+ */
5017
5200
  trimStart(charType) {
5018
5201
  this.trimStartAborted(charType);
5019
5202
  return this;
5020
5203
  }
5204
+ /**
5205
+ * Indicates if the string has been changed.
5206
+ */
5021
5207
  hasChanged() {
5022
5208
  return this.original !== this.toString();
5023
5209
  }
5210
+ /** @internal */
5024
5211
  _replaceRegexp(searchValue, replacement) {
5025
5212
  function getReplacement(match, str) {
5026
5213
  if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
@@ -5029,12 +5216,15 @@ var MagicString = class MagicString {
5029
5216
  if (+i < match.length) return match[+i];
5030
5217
  return `$${i}`;
5031
5218
  });
5032
- else return replacement(...match, match.index, str, match.groups);
5219
+ else return replacement(match[0], ...match.slice(1), match.index, str, match.groups);
5033
5220
  }
5034
5221
  function matchAll(re, str) {
5035
- let match;
5036
5222
  const matches = [];
5037
- while (match = re.exec(str)) matches.push(match);
5223
+ while (true) {
5224
+ const match = re.exec(str);
5225
+ if (!match) break;
5226
+ matches.push(match);
5227
+ }
5038
5228
  return matches;
5039
5229
  }
5040
5230
  if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
@@ -5052,6 +5242,7 @@ var MagicString = class MagicString {
5052
5242
  }
5053
5243
  return this;
5054
5244
  }
5245
+ /** @internal */
5055
5246
  _replaceString(string, replacement) {
5056
5247
  const { original } = this;
5057
5248
  const index = original.indexOf(string);
@@ -5061,21 +5252,27 @@ var MagicString = class MagicString {
5061
5252
  }
5062
5253
  return this;
5063
5254
  }
5255
+ /**
5256
+ * String replacement with RegExp or string.
5257
+ */
5064
5258
  replace(searchValue, replacement) {
5065
5259
  if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
5066
5260
  return this._replaceRegexp(searchValue, replacement);
5067
5261
  }
5262
+ /** @internal */
5068
5263
  _replaceAllString(string, replacement) {
5069
5264
  const { original } = this;
5070
5265
  const stringLength = string.length;
5071
5266
  for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
5072
5267
  const previous = original.slice(index, index + stringLength);
5073
- let _replacement = replacement;
5074
- if (typeof replacement === "function") _replacement = replacement(previous, index, original);
5268
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : replacement;
5075
5269
  if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
5076
5270
  }
5077
5271
  return this;
5078
5272
  }
5273
+ /**
5274
+ * Same as `s.replace`, but replace all matched strings instead of just one.
5275
+ */
5079
5276
  replaceAll(searchValue, replacement) {
5080
5277
  if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
5081
5278
  if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
@@ -11628,7 +11825,276 @@ var SSRCompatModuleRunner = class extends ModuleRunner {
11628
11825
  }
11629
11826
  };
11630
11827
  //#endregion
11828
+ //#region ../../node_modules/.pnpm/zimmerframe@1.1.4/node_modules/zimmerframe/src/walk.js
11829
+ /** @import { Context, Visitor, Visitors } from './types.js' */
11830
+ /**
11831
+ * @template {{ type: string }} T
11832
+ * @template {Record<string, any> | null} U
11833
+ * @param {T} node
11834
+ * @param {U} state
11835
+ * @param {Visitors<T, U>} visitors
11836
+ */
11837
+ function walk$2(node, state, visitors) {
11838
+ const universal = visitors._;
11839
+ let stopped = false;
11840
+ /** @type {Visitor<T, U, T>} _ */
11841
+ function default_visitor(_, { next, state }) {
11842
+ next(state);
11843
+ }
11844
+ /**
11845
+ * @param {T} node
11846
+ * @param {T[]} path
11847
+ * @param {U} state
11848
+ * @returns {T | undefined}
11849
+ */
11850
+ function visit(node, path, state) {
11851
+ if (stopped) return;
11852
+ if (!node.type) return;
11853
+ /** @type {T | void} */
11854
+ let result;
11855
+ /** @type {Record<string, any>} */
11856
+ const mutations = {};
11857
+ /** @type {Context<T, U>} */
11858
+ const context = {
11859
+ path,
11860
+ state,
11861
+ next: (next_state = state) => {
11862
+ path.push(node);
11863
+ for (const key in node) {
11864
+ if (key === "type") continue;
11865
+ const child_node = node[key];
11866
+ if (child_node && typeof child_node === "object") if (Array.isArray(child_node)) {
11867
+ /** @type {Record<number, T>} */
11868
+ const array_mutations = {};
11869
+ const len = child_node.length;
11870
+ let mutated = false;
11871
+ for (let i = 0; i < len; i++) {
11872
+ const node = child_node[i];
11873
+ if (node && typeof node === "object") {
11874
+ const result = visit(node, path, next_state);
11875
+ if (result) {
11876
+ array_mutations[i] = result;
11877
+ mutated = true;
11878
+ }
11879
+ }
11880
+ }
11881
+ if (mutated) mutations[key] = child_node.map((node, i) => array_mutations[i] ?? node);
11882
+ } else {
11883
+ const result = visit(child_node, path, next_state);
11884
+ if (result) mutations[key] = result;
11885
+ }
11886
+ }
11887
+ path.pop();
11888
+ if (Object.keys(mutations).length > 0) return apply_mutations(node, mutations);
11889
+ },
11890
+ stop: () => {
11891
+ stopped = true;
11892
+ },
11893
+ visit: (next_node, next_state = state) => {
11894
+ path.push(node);
11895
+ const result = visit(next_node, path, next_state) ?? next_node;
11896
+ path.pop();
11897
+ return result;
11898
+ }
11899
+ };
11900
+ let visitor = visitors[node.type] ?? default_visitor;
11901
+ if (universal) {
11902
+ /** @type {T | void} */
11903
+ let inner_result;
11904
+ result = universal(node, {
11905
+ ...context,
11906
+ /** @param {U} next_state */
11907
+ next: (next_state = state) => {
11908
+ state = next_state;
11909
+ inner_result = visitor(node, {
11910
+ ...context,
11911
+ state: next_state
11912
+ });
11913
+ return inner_result;
11914
+ }
11915
+ });
11916
+ if (!result && inner_result) result = inner_result;
11917
+ } else result = visitor(node, context);
11918
+ if (!result) {
11919
+ if (Object.keys(mutations).length > 0) result = apply_mutations(node, mutations);
11920
+ }
11921
+ if (result) return result;
11922
+ }
11923
+ return visit(node, [], state) ?? node;
11924
+ }
11925
+ /**
11926
+ * @template {Record<string, any>} T
11927
+ * @param {T} node
11928
+ * @param {Record<string, any>} mutations
11929
+ * @returns {T}
11930
+ */
11931
+ function apply_mutations(node, mutations) {
11932
+ /** @type {Record<string, any>} */
11933
+ const obj = {};
11934
+ const descriptors = Object.getOwnPropertyDescriptors(node);
11935
+ for (const key in descriptors) Object.defineProperty(obj, key, descriptors[key]);
11936
+ for (const key in mutations) obj[key] = mutations[key];
11937
+ return obj;
11938
+ }
11939
+ //#endregion
11940
+ //#region ../../node_modules/.pnpm/is-reference@3.0.3/node_modules/is-reference/src/index.js
11941
+ /** @import { Node } from 'estree' */
11942
+ /**
11943
+ * @param {Node} node
11944
+ * @param {Node} parent
11945
+ * @returns {boolean}
11946
+ */
11947
+ function is_reference(node, parent) {
11948
+ if (node.type === "MemberExpression") return !node.computed && is_reference(node.object, node);
11949
+ if (node.type !== "Identifier") return false;
11950
+ switch (parent?.type) {
11951
+ case "MemberExpression": return parent.computed || node === parent.object;
11952
+ case "MethodDefinition": return parent.computed;
11953
+ case "MetaProperty": return parent.meta === node;
11954
+ case "PropertyDefinition": return parent.computed || node === parent.value;
11955
+ case "Property": return parent.computed || node === parent.value;
11956
+ case "ExportSpecifier":
11957
+ case "ImportSpecifier": return node === parent.local;
11958
+ case "LabeledStatement":
11959
+ case "BreakStatement":
11960
+ case "ContinueStatement": return false;
11961
+ default: return true;
11962
+ }
11963
+ }
11964
+ //#endregion
11631
11965
  //#region ../../node_modules/.pnpm/periscopic@4.0.3/node_modules/periscopic/src/index.js
11966
+ /** @param {import('estree').Node} expression */
11967
+ function analyze(expression) {
11968
+ /** @typedef {import('estree').Node} Node */
11969
+ /** @type {WeakMap<Node, Scope>} */
11970
+ const map = /* @__PURE__ */ new WeakMap();
11971
+ /** @type {Map<string, Node>} */
11972
+ const globals = /* @__PURE__ */ new Map();
11973
+ const scope = new Scope(null, false);
11974
+ /** @type {[Scope, import('estree').Identifier][]} */
11975
+ const references = [];
11976
+ /** @type {Scope} */
11977
+ let current_scope = scope;
11978
+ /**
11979
+ * @param {import('estree').Node} node
11980
+ * @param {boolean} block
11981
+ */
11982
+ function push(node, block) {
11983
+ map.set(node, current_scope = new Scope(current_scope, block));
11984
+ }
11985
+ walk$2(expression, null, { _(node, context) {
11986
+ switch (node.type) {
11987
+ case "Identifier":
11988
+ const parent = context.path.at(-1);
11989
+ if (parent && is_reference(node, parent)) references.push([current_scope, node]);
11990
+ return;
11991
+ case "ImportDefaultSpecifier":
11992
+ case "ImportSpecifier":
11993
+ current_scope.declarations.set(node.local.name, node);
11994
+ return;
11995
+ case "ExportNamedDeclaration":
11996
+ if (node.source) {
11997
+ map.set(node, current_scope = new Scope(current_scope, true));
11998
+ for (const specifier of node.specifiers) current_scope.declarations.set(specifier.local.name, specifier);
11999
+ return;
12000
+ }
12001
+ break;
12002
+ case "FunctionExpression":
12003
+ case "FunctionDeclaration":
12004
+ case "ArrowFunctionExpression":
12005
+ if (node.type === "FunctionDeclaration") {
12006
+ if (node.id) current_scope.declarations.set(node.id.name, node);
12007
+ push(node, false);
12008
+ } else {
12009
+ push(node, false);
12010
+ if (node.type === "FunctionExpression" && node.id) current_scope.declarations.set(node.id.name, node);
12011
+ }
12012
+ for (const param of node.params) for (const name of extract_names(param)) current_scope.declarations.set(name, node);
12013
+ break;
12014
+ case "ForStatement":
12015
+ case "ForInStatement":
12016
+ case "ForOfStatement":
12017
+ case "BlockStatement":
12018
+ case "SwitchStatement":
12019
+ push(node, true);
12020
+ break;
12021
+ case "ClassDeclaration":
12022
+ case "VariableDeclaration":
12023
+ current_scope.add_declaration(node);
12024
+ break;
12025
+ case "CatchClause":
12026
+ push(node, true);
12027
+ if (node.param) {
12028
+ for (const name of extract_names(node.param)) if (node.param) current_scope.declarations.set(name, node.param);
12029
+ }
12030
+ break;
12031
+ }
12032
+ context.next();
12033
+ if (map.has(node) && current_scope !== null && current_scope.parent) current_scope = current_scope.parent;
12034
+ } });
12035
+ for (let i = references.length - 1; i >= 0; --i) {
12036
+ const [scope, reference] = references[i];
12037
+ if (!scope.references.has(reference.name)) add_reference(scope, reference.name);
12038
+ if (!scope.find_owner(reference.name)) globals.set(reference.name, reference);
12039
+ }
12040
+ return {
12041
+ map,
12042
+ scope,
12043
+ globals
12044
+ };
12045
+ }
12046
+ /**
12047
+ * @param {Scope} scope
12048
+ * @param {string} name
12049
+ */
12050
+ function add_reference(scope, name) {
12051
+ scope.references.add(name);
12052
+ if (scope.parent) add_reference(scope.parent, name);
12053
+ }
12054
+ var Scope = class {
12055
+ /**
12056
+ * @param {Scope | null} parent
12057
+ * @param {boolean} block
12058
+ */
12059
+ constructor(parent, block) {
12060
+ /** @type {Scope | null} */
12061
+ this.parent = parent;
12062
+ /** @type {boolean} */
12063
+ this.block = block;
12064
+ /** @type {Map<string, import('estree').Node>} */
12065
+ this.declarations = /* @__PURE__ */ new Map();
12066
+ /** @type {Set<string>} */
12067
+ this.initialised_declarations = /* @__PURE__ */ new Set();
12068
+ /** @type {Set<string>} */
12069
+ this.references = /* @__PURE__ */ new Set();
12070
+ }
12071
+ /**
12072
+ * @param {import('estree').VariableDeclaration | import('estree').ClassDeclaration} node
12073
+ */
12074
+ add_declaration(node) {
12075
+ if (node.type === "VariableDeclaration") if (node.kind === "var" && this.block && this.parent) this.parent.add_declaration(node);
12076
+ else for (const declarator of node.declarations) for (const name of extract_names(declarator.id)) {
12077
+ this.declarations.set(name, node);
12078
+ if (declarator.init) this.initialised_declarations.add(name);
12079
+ }
12080
+ else if (node.id) this.declarations.set(node.id.name, node);
12081
+ }
12082
+ /**
12083
+ * @param {string} name
12084
+ * @returns {Scope | null}
12085
+ */
12086
+ find_owner(name) {
12087
+ if (this.declarations.has(name)) return this;
12088
+ return this.parent && this.parent.find_owner(name);
12089
+ }
12090
+ /**
12091
+ * @param {string} name
12092
+ * @returns {boolean}
12093
+ */
12094
+ has(name) {
12095
+ return this.declarations.has(name) || !!this.parent && this.parent.has(name);
12096
+ }
12097
+ };
11632
12098
  /**
11633
12099
  * @param {import('estree').Node} param
11634
12100
  * @returns {string[]}
@@ -13305,7 +13771,7 @@ function checkPublicFile(url, config) {
13305
13771
  return tryStatSync(publicFile)?.isFile() ? publicFile : void 0;
13306
13772
  }
13307
13773
  //#endregion
13308
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js
13774
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/constants.js
13309
13775
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13310
13776
  const BINARY_TYPES = [
13311
13777
  "nodebuffer",
@@ -13328,7 +13794,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13328
13794
  };
13329
13795
  }));
13330
13796
  //#endregion
13331
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js
13797
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/buffer-util.js
13332
13798
  var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13333
13799
  const { EMPTY_BUFFER } = require_constants();
13334
13800
  const FastBuffer = Buffer[Symbol.species];
@@ -13428,7 +13894,7 @@ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13428
13894
  } catch (e) {}
13429
13895
  }));
13430
13896
  //#endregion
13431
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js
13897
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/limiter.js
13432
13898
  var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13433
13899
  const kDone = Symbol("kDone");
13434
13900
  const kRun = Symbol("kRun");
@@ -13479,7 +13945,7 @@ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13479
13945
  module.exports = Limiter;
13480
13946
  }));
13481
13947
  //#endregion
13482
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js
13948
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/permessage-deflate.js
13483
13949
  var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13484
13950
  const zlib$1 = __require("zlib");
13485
13951
  const bufferUtil = require_buffer_util();
@@ -13815,7 +14281,7 @@ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module
13815
14281
  }
13816
14282
  }));
13817
14283
  //#endregion
13818
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js
14284
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/validation.js
13819
14285
  var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
13820
14286
  const { isUtf8 } = __require("buffer");
13821
14287
  const { hasBlob } = require_constants();
@@ -14011,7 +14477,7 @@ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14011
14477
  } catch (e) {}
14012
14478
  }));
14013
14479
  //#endregion
14014
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js
14480
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/receiver.js
14015
14481
  var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14016
14482
  const { Writable: Writable$1 } = __require("stream");
14017
14483
  const PerMessageDeflate = require_permessage_deflate();
@@ -14074,6 +14540,7 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14074
14540
  this._opcode = 0;
14075
14541
  this._totalPayloadLength = 0;
14076
14542
  this._messageLength = 0;
14543
+ this._numFragments = 0;
14077
14544
  this._fragments = [];
14078
14545
  this._errored = false;
14079
14546
  this._loop = false;
@@ -14314,16 +14781,16 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14314
14781
  this.controlMessage(data, cb);
14315
14782
  return;
14316
14783
  }
14784
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
14785
+ cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
14786
+ return;
14787
+ }
14317
14788
  if (this._compressed) {
14318
14789
  this._state = INFLATING;
14319
14790
  this.decompress(data, cb);
14320
14791
  return;
14321
14792
  }
14322
14793
  if (data.length) {
14323
- if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
14324
- cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
14325
- return;
14326
- }
14327
14794
  this._messageLength = this._totalPayloadLength;
14328
14795
  this._fragments.push(data);
14329
14796
  }
@@ -14345,10 +14812,6 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14345
14812
  cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
14346
14813
  return;
14347
14814
  }
14348
- if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
14349
- cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
14350
- return;
14351
- }
14352
14815
  this._fragments.push(buf);
14353
14816
  }
14354
14817
  this.dataMessage(cb);
@@ -14371,6 +14834,7 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14371
14834
  this._totalPayloadLength = 0;
14372
14835
  this._messageLength = 0;
14373
14836
  this._fragmented = 0;
14837
+ this._numFragments = 0;
14374
14838
  this._fragments = [];
14375
14839
  if (this._opcode === 2) {
14376
14840
  let data;
@@ -14476,7 +14940,7 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14476
14940
  module.exports = Receiver;
14477
14941
  }));
14478
14942
  //#endregion
14479
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js
14943
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/sender.js
14480
14944
  var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14481
14945
  const { Duplex: Duplex$3 } = __require("stream");
14482
14946
  const { randomFillSync } = __require("crypto");
@@ -14970,7 +15434,7 @@ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14970
15434
  }
14971
15435
  }));
14972
15436
  //#endregion
14973
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js
15437
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/event-target.js
14974
15438
  var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14975
15439
  const { kForOnEventAttribute, kListener } = require_constants();
14976
15440
  const kCode = Symbol("kCode");
@@ -15201,7 +15665,7 @@ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15201
15665
  }
15202
15666
  }));
15203
15667
  //#endregion
15204
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js
15668
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/extension.js
15205
15669
  var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15206
15670
  const { tokenChars } = require_validation();
15207
15671
  /**
@@ -15344,7 +15808,7 @@ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15344
15808
  };
15345
15809
  }));
15346
15810
  //#endregion
15347
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js
15811
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket.js
15348
15812
  var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15349
15813
  const EventEmitter$2 = __require("events");
15350
15814
  const https$3 = __require("https");
@@ -15849,9 +16313,9 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15849
16313
  * masking key
15850
16314
  * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
15851
16315
  * handshake request
15852
- * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
16316
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
15853
16317
  * buffered data chunks
15854
- * @param {Number} [options.maxFragments=131072] The maximum number of message
16318
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
15855
16319
  * fragments
15856
16320
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
15857
16321
  * size
@@ -15873,8 +16337,8 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15873
16337
  autoPong: true,
15874
16338
  closeTimeout: CLOSE_TIMEOUT,
15875
16339
  protocolVersion: protocolVersions[1],
15876
- maxBufferedChunks: 1024 * 1024,
15877
- maxFragments: 128 * 1024,
16340
+ maxBufferedChunks: 256 * 1024,
16341
+ maxFragments: 16 * 1024,
15878
16342
  maxPayload: 100 * 1024 * 1024,
15879
16343
  skipUTF8Validation: false,
15880
16344
  perMessageDeflate: true,
@@ -16333,7 +16797,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16333
16797
  }
16334
16798
  }));
16335
16799
  //#endregion
16336
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js
16800
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/stream.js
16337
16801
  var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16338
16802
  require_websocket();
16339
16803
  const { Duplex: Duplex$1 } = __require("stream");
@@ -16449,7 +16913,7 @@ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16449
16913
  module.exports = createWebSocketStream;
16450
16914
  }));
16451
16915
  //#endregion
16452
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js
16916
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/subprotocol.js
16453
16917
  var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16454
16918
  const { tokenChars } = require_validation();
16455
16919
  /**
@@ -16488,7 +16952,7 @@ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16488
16952
  module.exports = { parse };
16489
16953
  }));
16490
16954
  //#endregion
16491
- //#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js
16955
+ //#region ../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket-server.js
16492
16956
  var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16493
16957
  const EventEmitter$1 = __require("events");
16494
16958
  const http$4 = __require("http");
@@ -16527,9 +16991,9 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
16527
16991
  * called
16528
16992
  * @param {Function} [options.handleProtocols] A hook to handle protocols
16529
16993
  * @param {String} [options.host] The hostname where to bind the server
16530
- * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
16994
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
16531
16995
  * buffered data chunks
16532
- * @param {Number} [options.maxFragments=131072] The maximum number of message
16996
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
16533
16997
  * fragments
16534
16998
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
16535
16999
  * size
@@ -16552,8 +17016,8 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
16552
17016
  options = {
16553
17017
  allowSynchronousEvents: true,
16554
17018
  autoPong: true,
16555
- maxBufferedChunks: 1024 * 1024,
16556
- maxFragments: 128 * 1024,
17019
+ maxBufferedChunks: 256 * 1024,
17020
+ maxFragments: 16 * 1024,
16557
17021
  maxPayload: 100 * 1024 * 1024,
16558
17022
  skipUTF8Validation: false,
16559
17023
  perMessageDeflate: false,
@@ -21388,7 +21852,7 @@ var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21388
21852
  };
21389
21853
  }));
21390
21854
  //#endregion
21391
- //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17_tsx@4.23.0_yaml@2.9.0/node_modules/postcss-load-config/src/req.js
21855
+ //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.20_tsx@4.23.1_yaml@2.9.0/node_modules/postcss-load-config/src/req.js
21392
21856
  var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21393
21857
  const { createRequire: createRequire$1 } = __require("node:module");
21394
21858
  const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url");
@@ -21430,7 +21894,7 @@ var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21430
21894
  module.exports = req;
21431
21895
  }));
21432
21896
  //#endregion
21433
- //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17_tsx@4.23.0_yaml@2.9.0/node_modules/postcss-load-config/src/options.js
21897
+ //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.20_tsx@4.23.1_yaml@2.9.0/node_modules/postcss-load-config/src/options.js
21434
21898
  var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21435
21899
  const req = require_req();
21436
21900
  /**
@@ -21464,7 +21928,7 @@ var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21464
21928
  module.exports = options;
21465
21929
  }));
21466
21930
  //#endregion
21467
- //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17_tsx@4.23.0_yaml@2.9.0/node_modules/postcss-load-config/src/plugins.js
21931
+ //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.20_tsx@4.23.1_yaml@2.9.0/node_modules/postcss-load-config/src/plugins.js
21468
21932
  var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21469
21933
  const req = require_req();
21470
21934
  /**
@@ -21518,7 +21982,7 @@ var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21518
21982
  module.exports = plugins;
21519
21983
  }));
21520
21984
  //#endregion
21521
- //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17_tsx@4.23.0_yaml@2.9.0/node_modules/postcss-load-config/src/index.js
21985
+ //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.20_tsx@4.23.1_yaml@2.9.0/node_modules/postcss-load-config/src/index.js
21522
21986
  var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21523
21987
  const { resolve: resolve$3 } = __require("node:path");
21524
21988
  const config = require_src$1();
@@ -22071,6 +22535,7 @@ function cssPostPlugin(config) {
22071
22535
  let codeSplitEmitQueue = createSerialPromiseQueue();
22072
22536
  const urlEmitQueue = createSerialPromiseQueue();
22073
22537
  let pureCssChunks;
22538
+ let chunkCssReferences;
22074
22539
  let hasEmitted = false;
22075
22540
  let chunkCSSMap;
22076
22541
  const rolldownOptionsOutput = config.build.rolldownOptions.output;
@@ -22099,6 +22564,7 @@ function cssPostPlugin(config) {
22099
22564
  name: "vite:css-post",
22100
22565
  renderStart() {
22101
22566
  pureCssChunks = /* @__PURE__ */ new Set();
22567
+ chunkCssReferences = /* @__PURE__ */ new Map();
22102
22568
  hasEmitted = false;
22103
22569
  chunkCSSMap = /* @__PURE__ */ new Map();
22104
22570
  codeSplitEmitQueue = createSerialPromiseQueue();
@@ -22278,6 +22744,7 @@ function cssPostPlugin(config) {
22278
22744
  originalFileName,
22279
22745
  source: chunkCSS
22280
22746
  });
22747
+ chunkCssReferences.set(chunk.fileName, referenceId);
22281
22748
  if (isEntry) cssEntriesMap.get(this.environment).set(chunk.fileName, {
22282
22749
  referenceId,
22283
22750
  name: chunk.name
@@ -22338,6 +22805,20 @@ function cssPostPlugin(config) {
22338
22805
  });
22339
22806
  }
22340
22807
  }
22808
+ if (config.build.chunkImportMap && chunkCssReferences.size) {
22809
+ const importMap = getImportMap(bundle, config);
22810
+ const importMapReverseMapping = Object.fromEntries(Object.entries(importMap.mapping).map(([k, v]) => [v, k]));
22811
+ const chunksByPreliminaryFileName = new Map(Object.values(bundle).filter((output) => output.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk]));
22812
+ for (const [chunkFileName, referenceId] of chunkCssReferences) {
22813
+ const chunk = chunksByPreliminaryFileName.get(chunkFileName);
22814
+ if (!chunk) continue;
22815
+ const stableChunkFileName = importMapReverseMapping[chunk.fileName] ?? chunk.fileName;
22816
+ const extension = path.posix.extname(stableChunkFileName);
22817
+ const stableCssFileName = `${stableChunkFileName.slice(0, extension ? -extension.length : void 0)}.css`;
22818
+ importMap.content.imports[config.base + stableCssFileName] = config.base + this.getFileName(referenceId);
22819
+ }
22820
+ importMap.asset.source = JSON.stringify(importMap.content);
22821
+ }
22341
22822
  if (pureCssChunks.size) {
22342
22823
  const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
22343
22824
  const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
@@ -22786,7 +23267,7 @@ const UrlRewritePostcssPlugin = (opts) => {
22786
23267
  if (!opts) throw new Error("base or replace is required");
22787
23268
  return {
22788
23269
  postcssPlugin: "vite-url-rewrite",
22789
- Once(root) {
23270
+ OnceExit(root) {
22790
23271
  const promises = [];
22791
23272
  root.walkDecls((declaration) => {
22792
23273
  const importer = declaration.source?.input.file;
@@ -24490,6 +24971,7 @@ function getImportMap(bundle, config) {
24490
24971
  const content = JSON.parse(typeof asset.source === "string" ? asset.source : new TextDecoder().decode(asset.source));
24491
24972
  return {
24492
24973
  asset,
24974
+ content,
24493
24975
  mapping: Object.fromEntries(Object.entries(content.imports).map(([k, v]) => [k.slice(config.base.length), v.slice(config.base.length)]))
24494
24976
  };
24495
24977
  }
@@ -24818,6 +25300,7 @@ function handleDefineValue(value) {
24818
25300
  //#endregion
24819
25301
  //#region src/node/plugins/clientInjections.ts
24820
25302
  const normalizedClientEntry$1 = normalizePath(CLIENT_ENTRY);
25303
+ const normalizedBundledDevClientEntry = normalizePath(BUNDLED_DEV_CLIENT_ENTRY);
24821
25304
  const normalizedEnvEntry$1 = normalizePath(ENV_ENTRY);
24822
25305
  /**
24823
25306
  * some values used by the client needs to be dynamically injected by the server
@@ -24891,11 +25374,10 @@ async function createClientConfigValueReplacer(config) {
24891
25374
  const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
24892
25375
  const wsTokenReplacement = escapeReplacement(config.webSocketToken);
24893
25376
  const serverForwardConsoleReplacement = escapeReplacement(config.server.forwardConsole);
24894
- const bundleDevReplacement = escapeReplacement(config.experimental.bundledDev || false);
24895
- return (code) => code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).replace(`__SERVER_HOST__`, serverHostReplacement).replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement).replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement).replace(`__HMR_PORT__`, hmrPortReplacement).replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement).replace(`__HMR_BASE__`, hmrBaseReplacement).replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement).replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement).replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement).replace(`__WS_TOKEN__`, wsTokenReplacement).replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement).replaceAll(`__BUNDLED_DEV__`, bundleDevReplacement);
25377
+ return (code) => code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).replace(`__SERVER_HOST__`, serverHostReplacement).replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement).replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement).replace(`__HMR_PORT__`, hmrPortReplacement).replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement).replace(`__HMR_BASE__`, hmrBaseReplacement).replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement).replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement).replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement).replace(`__WS_TOKEN__`, wsTokenReplacement).replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement);
24896
25378
  }
24897
25379
  async function getHmrImplementation(config) {
24898
- const content = fs.readFileSync(normalizedClientEntry$1, "utf-8");
25380
+ const content = fs.readFileSync(normalizedBundledDevClientEntry, "utf-8");
24899
25381
  return (await createClientConfigValueReplacer(config))(content).replace(/import\s*['"]@vite\/env['"]/, "");
24900
25382
  }
24901
25383
  //#endregion
@@ -25148,6 +25630,7 @@ async function generateFallbackHtml(server) {
25148
25630
  <!DOCTYPE html>
25149
25631
  <html lang="en">
25150
25632
  <head>
25633
+ <script>globalThis.__vite_is_fallback_page__ = true<\/script>
25151
25634
  <script type="module">
25152
25635
  ${(await getHmrImplementation(server.config)).replaceAll("<\/script>", "<\\/script>")}
25153
25636
  <\/script>
@@ -25680,8 +26163,9 @@ function rejectInvalidRequestMiddleware() {
25680
26163
  //#endregion
25681
26164
  //#region src/node/server/middlewares/memoryFiles.ts
25682
26165
  function memoryFilesMiddleware(server) {
25683
- const memoryFiles = server.environments.client.bundledDev?.memoryFiles;
25684
- if (!memoryFiles) throw new Error("memoryFilesMiddleware can only be used for fullBundleMode");
26166
+ const bundledDev = server.environments.client.bundledDev;
26167
+ const memoryFiles = bundledDev?.memoryFiles;
26168
+ if (!bundledDev || !memoryFiles) throw new Error("memoryFilesMiddleware can only be used for fullBundleMode");
25685
26169
  const headers = server.config.server.headers;
25686
26170
  return function viteMemoryFilesMiddleware(req, res, next) {
25687
26171
  const cleanedUrl = cleanUrl(req.url);
@@ -25706,6 +26190,7 @@ function memoryFilesMiddleware(server) {
25706
26190
  const mime = lookup(filePath);
25707
26191
  if (mime) res.setHeader("Content-Type", mime);
25708
26192
  for (const name in headers) res.setHeader(name, headers[name]);
26193
+ res.on("finish", () => bundledDev.markPayloadDelivered(filePath));
25709
26194
  return res.end(file.source);
25710
26195
  }
25711
26196
  next();
@@ -25726,10 +26211,11 @@ function triggerLazyBundlingMiddleware(server) {
25726
26211
  }
25727
26212
  const moduleId = params.get("id");
25728
26213
  const clientId = params.get("clientId");
25729
- const code = await bundledDev.triggerLazyBundling(moduleId, clientId);
25730
- if (code == null) return next();
26214
+ const result = await bundledDev.triggerLazyBundling(moduleId, clientId);
26215
+ if (result == null) return next();
25731
26216
  res.setHeader("Content-Type", "application/javascript");
25732
- return res.end(code);
26217
+ res.on("finish", () => bundledDev.markPayloadDelivered(result.filename));
26218
+ return res.end(result.code);
25733
26219
  };
25734
26220
  }
25735
26221
  //#endregion
@@ -27718,7 +28204,14 @@ function __vite__injectQuery(url, queryToInject) {
27718
28204
  const wasmHelperId = "\0vite/wasm-helper.js";
27719
28205
  const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
27720
28206
  const wasmDirectRE = /(?<![?#].*)\.wasm$/;
28207
+ const wasmInstanceSuffix = "?vite-wasm-instance";
28208
+ const wasmInstanceRE = /[?&]vite-wasm-instance(?:&|$)/;
27721
28209
  const wasmInitUrlRE = /__VITE_WASM_INIT__([\w$]+)__/g;
28210
+ const wasmCompileOptions = {
28211
+ builtins: ["js-string"],
28212
+ importedStringConstants: "wasm:js/string-constants"
28213
+ };
28214
+ const wasmReservedModules = /* @__PURE__ */ new Set([...wasmCompileOptions.builtins.map((name) => `wasm:${name}`), wasmCompileOptions.importedStringConstants]);
27722
28215
  const wasmHelper = async (opts = {}, url) => {
27723
28216
  let result;
27724
28217
  if (url.startsWith("data:")) {
@@ -27730,7 +28223,7 @@ const wasmHelper = async (opts = {}, url) => {
27730
28223
  bytes = new Uint8Array(binaryString.length);
27731
28224
  for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
27732
28225
  } else throw new Error("Failed to decode base64-encoded data URL, Buffer and atob are not supported");
27733
- result = await WebAssembly.instantiate(bytes, opts);
28226
+ result = await WebAssembly.instantiate(bytes, opts, wasmCompileOptions);
27734
28227
  } else result = await instantiateFromUrl(url, opts);
27735
28228
  return result.instance;
27736
28229
  };
@@ -27738,10 +28231,10 @@ const wasmHelperCode = wasmHelper.toString();
27738
28231
  const instantiateFromUrl = async (url, opts) => {
27739
28232
  const response = await fetch(url);
27740
28233
  const contentType = response.headers.get("Content-Type") || "";
27741
- if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) return WebAssembly.instantiateStreaming(response, opts);
28234
+ if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) return WebAssembly.instantiateStreaming(response, opts, wasmCompileOptions);
27742
28235
  else {
27743
28236
  const buffer = await response.arrayBuffer();
27744
- return WebAssembly.instantiate(buffer, opts);
28237
+ return WebAssembly.instantiate(buffer, opts, wasmCompileOptions);
27745
28238
  }
27746
28239
  };
27747
28240
  const instantiateFromUrlCode = instantiateFromUrl.toString();
@@ -27752,7 +28245,7 @@ const instantiateFromFile = async (fileUrlString, opts) => {
27752
28245
  /** #__KEEP__ */
27753
28246
  import.meta.url
27754
28247
  ));
27755
- return WebAssembly.instantiate(buffer, opts);
28248
+ return WebAssembly.instantiate(buffer, opts, wasmCompileOptions);
27756
28249
  };
27757
28250
  const instantiateFromFileCode = instantiateFromFile.toString();
27758
28251
  const wasmHelperPlugin = () => {
@@ -27769,16 +28262,24 @@ const wasmHelperPlugin = () => {
27769
28262
  filter: { id: [
27770
28263
  exactRegex(wasmHelperId),
27771
28264
  wasmInitRE,
27772
- wasmDirectRE
28265
+ wasmDirectRE,
28266
+ wasmInstanceRE
27773
28267
  ] },
27774
28268
  async handler(id) {
27775
28269
  const ssr = this.environment.config.consumer === "server";
27776
28270
  if (id === wasmHelperId) return `
28271
+ const wasmCompileOptions = ${JSON.stringify(wasmCompileOptions)}
27777
28272
  const instantiateFromUrl = ${ssr ? instantiateFromFileCode : instantiateFromUrlCode}
27778
28273
  export default ${wasmHelperCode}
27779
28274
  `;
27780
28275
  const isInit = wasmInitRE.test(id);
27781
- const cleanedId = id.split("?")[0];
28276
+ const isInstance = wasmInstanceRE.test(id);
28277
+ const cleanedId = isInstance ? cleanUrl(id) : id.split("?")[0];
28278
+ let wasmInfo;
28279
+ if (!isInit) {
28280
+ wasmInfo = await parseWasm(cleanedId);
28281
+ if (!isInstance && wasmInfo.hasGlobalExport) return generateWrapperGlue(wasmInfo, cleanedId + wasmInstanceSuffix);
28282
+ }
27782
28283
  let url = await fileToUrl$1(this, cleanedId, ssr);
27783
28284
  assetUrlRE.lastIndex = 0;
27784
28285
  if (ssr && assetUrlRE.test(url)) url = url.replace("__VITE_ASSET__", "__VITE_WASM_INIT__");
@@ -27786,7 +28287,7 @@ export default ${wasmHelperCode}
27786
28287
  import initWasm from "${wasmHelperId}"
27787
28288
  export default opts => initWasm(opts, ${JSON.stringify(url)})
27788
28289
  `;
27789
- const glueCode = generateGlueCode(await parseWasm(cleanedId), {
28290
+ const glueCode = generateInstanceGlue(wasmInfo, {
27790
28291
  initWasm: "__vite__initWasm",
27791
28292
  wasmUrl: "__vite__wasmUrl"
27792
28293
  });
@@ -27825,43 +28326,70 @@ ${glueCode}
27825
28326
  async function parseWasm(wasmFilePath) {
27826
28327
  try {
27827
28328
  const wasmBinary = await fsp.readFile(wasmFilePath);
27828
- const wasmModule = await WebAssembly.compile(wasmBinary);
27829
- const importMap = Object.create(null);
28329
+ const wasmModule = await WebAssembly.compile(wasmBinary, wasmCompileOptions);
28330
+ const importMap = /* @__PURE__ */ new Map();
27830
28331
  for (const item of WebAssembly.Module.imports(wasmModule)) {
27831
- importMap[item.module] ??= [];
27832
- importMap[item.module].push(item.name);
28332
+ if (wasmReservedModules.has(item.module)) continue;
28333
+ let names = importMap.get(item.module);
28334
+ if (!names) importMap.set(item.module, names = []);
28335
+ names.push({
28336
+ name: item.name,
28337
+ isGlobal: item.kind === "global"
28338
+ });
27833
28339
  }
28340
+ const imports = [...importMap].map(([from, names]) => ({
28341
+ from,
28342
+ names
28343
+ }));
28344
+ let hasGlobalExport = false;
27834
28345
  return {
27835
- imports: Object.entries(importMap).map(([from, names]) => ({
27836
- from,
27837
- names
27838
- })),
27839
- exports: WebAssembly.Module.exports(wasmModule).map((item) => item.name)
28346
+ imports,
28347
+ exports: WebAssembly.Module.exports(wasmModule).map((item) => {
28348
+ const isGlobal = item.kind === "global";
28349
+ if (isGlobal) hasGlobalExport = true;
28350
+ return {
28351
+ name: item.name,
28352
+ isGlobal
28353
+ };
28354
+ }),
28355
+ hasGlobalExport
27840
28356
  };
27841
28357
  } catch (e) {
27842
28358
  throw new Error(`Failed to parse WASM file "${wasmFilePath}": ${e.message}`, { cause: e });
27843
28359
  }
27844
28360
  }
27845
- function generateGlueCode(wasmInfo, names) {
27846
- const importStatements = wasmInfo.imports.map(({ from }, i) => {
27847
- return `import * as __vite__wasmImport_${i} from ${JSON.stringify(from)};`;
27848
- });
28361
+ function generateInstanceGlue(wasmInfo, names) {
28362
+ const importStatements = [];
27849
28363
  const importObject = wasmInfo.imports.map(({ from, names: importNames }, i) => {
28364
+ const value = [];
28365
+ const globals = importNames.filter((n) => n.isGlobal);
28366
+ const others = importNames.filter((n) => !n.isGlobal);
28367
+ if (others.length > 0) {
28368
+ const ns = `__vite__wasmImport_${i}`;
28369
+ importStatements.push(`import * as ${ns} from ${JSON.stringify(from)};`);
28370
+ for (const { name } of others) value.push({
28371
+ key: JSON.stringify(name),
28372
+ value: `${ns}[${JSON.stringify(name)}]`
28373
+ });
28374
+ }
28375
+ if (globals.length > 0) {
28376
+ const ns = `__vite__wasmImportInstance_${i}`;
28377
+ importStatements.push(`import * as ${ns} from ${JSON.stringify(from + wasmInstanceSuffix)};`);
28378
+ for (const { name } of globals) value.push({
28379
+ key: JSON.stringify(name),
28380
+ value: `${ns}[${JSON.stringify(name)}]`
28381
+ });
28382
+ }
27850
28383
  return {
27851
28384
  key: JSON.stringify(from),
27852
- value: importNames.map((name) => {
27853
- return {
27854
- key: JSON.stringify(name),
27855
- value: `__vite__wasmImport_${i}[${JSON.stringify(name)}]`
27856
- };
27857
- })
28385
+ value
27858
28386
  };
27859
28387
  });
27860
28388
  const initCode = `const __vite__wasmModule = (await ${names.initWasm}(${codegenSimpleObject(importObject)}, ${names.wasmUrl})).exports;`;
27861
28389
  if (wasmInfo.exports.length === 0) return [...importStatements, initCode].join("\n");
27862
28390
  const exportStatements = [];
27863
28391
  const nameMap = /* @__PURE__ */ new Map();
27864
- for (const [index, name] of wasmInfo.exports.entries()) if (isValidJsDeclareName(name)) exportStatements.push(` ${name},`);
28392
+ for (const [index, { name }] of wasmInfo.exports.entries()) if (isValidJsDeclareName(name)) exportStatements.push(` ${name},`);
27865
28393
  else {
27866
28394
  const placeholderName = `__vite__wasmExport_${index}`;
27867
28395
  exportStatements.push(` ${JSON.stringify(name)}: ${placeholderName},`);
@@ -27871,7 +28399,7 @@ function generateGlueCode(wasmInfo, names) {
27871
28399
  exportStatements.unshift(`const {`);
27872
28400
  exportStatements.push(`} = __vite__wasmModule;`);
27873
28401
  exportStatements.push(`export {`);
27874
- for (const name of wasmInfo.exports) {
28402
+ for (const { name } of wasmInfo.exports) {
27875
28403
  const localName = nameMap.get(name);
27876
28404
  if (localName) exportStatements.push(` ${localName} as ${JSON.stringify(name)},`);
27877
28405
  else exportStatements.push(` ${name},`);
@@ -27887,6 +28415,34 @@ function generateGlueCode(wasmInfo, names) {
27887
28415
  ...exportStatements
27888
28416
  ].join("\n");
27889
28417
  }
28418
+ function generateWrapperGlue(wasmInfo, instanceId) {
28419
+ const instanceIdLiteral = JSON.stringify(instanceId);
28420
+ const lines = [`export * from ${instanceIdLiteral};`];
28421
+ if (wasmInfo.exports.some((e) => e.name === "default")) lines.push(`export { default } from ${instanceIdLiteral};`);
28422
+ const imports = [];
28423
+ const bindings = [];
28424
+ const unwraps = [];
28425
+ const reExports = [];
28426
+ for (const [index, { name, isGlobal }] of wasmInfo.exports.entries()) {
28427
+ if (!isGlobal || name === "default") continue;
28428
+ const alias = `__vite__wasmGlobal_${index}`;
28429
+ imports.push(`${codegenModuleExportName(name)} as ${alias}`);
28430
+ const binding = isValidJsDeclareName(name) ? name : `__vite__wasmGlobalValue_${index}`;
28431
+ bindings.push(binding);
28432
+ unwraps.push(`try { ${binding} = ${alias}.value; } catch {}`);
28433
+ reExports.push(binding === name ? name : `${binding} as ${JSON.stringify(name)}`);
28434
+ }
28435
+ if (bindings.length > 0) {
28436
+ lines.push(`import { ${imports.join(", ")} } from ${instanceIdLiteral};`);
28437
+ lines.push(`let ${bindings.join(", ")};`);
28438
+ lines.push(...unwraps);
28439
+ lines.push(`export { ${reExports.join(", ")} };`);
28440
+ }
28441
+ return lines.join("\n");
28442
+ }
28443
+ function codegenModuleExportName(name) {
28444
+ return isValidJsDeclareName(name) ? name : JSON.stringify(name);
28445
+ }
27890
28446
  function codegenSimpleObject(obj) {
27891
28447
  if (obj.length === 0) return "{}";
27892
28448
  return `{ ${obj.map(({ key, value }) => {
@@ -30688,7 +31244,7 @@ function scanImports(environment) {
30688
31244
  async function scan() {
30689
31245
  const entries = await computeEntries(environment);
30690
31246
  if (!entries.length) {
30691
- if (!config.optimizeDeps.entries && !config.optimizeDeps.include) environment.logger.warn(import_picocolors.default.yellow("(!) Could not auto-determine entry point from rolldownOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."));
31247
+ if (!config.optimizeDeps.entries && !config.optimizeDeps.include && !config.input) environment.logger.warn(import_picocolors.default.yellow("(!) Could not auto-determine entry point from rolldownOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."));
30692
31248
  return;
30693
31249
  }
30694
31250
  if (scanContext.cancelled) return;
@@ -30730,10 +31286,11 @@ function scanImports(environment) {
30730
31286
  async function computeEntries(environment) {
30731
31287
  let entries = [];
30732
31288
  const explicitEntryPatterns = environment.config.optimizeDeps.entries;
30733
- const buildInput = environment.config.build.rolldownOptions.input;
31289
+ const buildInput = environment.config.input ?? environment.config.build.rolldownOptions.input;
30734
31290
  if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment);
30735
31291
  else if (buildInput) {
30736
31292
  const resolvePath = async (p) => {
31293
+ if (environment.config.input) return p;
30737
31294
  const id = (await environment.pluginContainer.resolveId(p, void 0, {
30738
31295
  isEntry: true,
30739
31296
  scan: true
@@ -31881,6 +32438,11 @@ function isSingleDefaultExport(exports) {
31881
32438
  return exports.length === 1 && exports[0] === "default";
31882
32439
  }
31883
32440
  const lockfileFormats = [
32441
+ {
32442
+ path: "node_modules/.pnpm/lock.yaml",
32443
+ checkPatchesDir: false,
32444
+ manager: "pnpm"
32445
+ },
31884
32446
  {
31885
32447
  path: "node_modules/.package-lock.json",
31886
32448
  checkPatchesDir: "patches",
@@ -31891,6 +32453,26 @@ const lockfileFormats = [
31891
32453
  checkPatchesDir: false,
31892
32454
  manager: "yarn"
31893
32455
  },
32456
+ {
32457
+ path: "bun.lock",
32458
+ checkPatchesDir: "patches",
32459
+ manager: "bun"
32460
+ },
32461
+ {
32462
+ path: ".rush/temp/shrinkwrap-deps.json",
32463
+ checkPatchesDir: false,
32464
+ manager: "pnpm"
32465
+ },
32466
+ {
32467
+ path: "aube-lock.yaml",
32468
+ checkPatchesDir: false,
32469
+ manager: "aube"
32470
+ },
32471
+ {
32472
+ path: "nub.lock",
32473
+ checkPatchesDir: "patches",
32474
+ manager: "nub"
32475
+ },
31894
32476
  {
31895
32477
  path: ".pnp.cjs",
31896
32478
  checkPatchesDir: ".yarn/patches",
@@ -31906,21 +32488,6 @@ const lockfileFormats = [
31906
32488
  checkPatchesDir: "patches",
31907
32489
  manager: "yarn"
31908
32490
  },
31909
- {
31910
- path: "node_modules/.pnpm/lock.yaml",
31911
- checkPatchesDir: false,
31912
- manager: "pnpm"
31913
- },
31914
- {
31915
- path: ".rush/temp/shrinkwrap-deps.json",
31916
- checkPatchesDir: false,
31917
- manager: "pnpm"
31918
- },
31919
- {
31920
- path: "bun.lock",
31921
- checkPatchesDir: "patches",
31922
- manager: "bun"
31923
- },
31924
32491
  {
31925
32492
  path: "bun.lockb",
31926
32493
  checkPatchesDir: "patches",
@@ -32853,7 +33420,7 @@ const _buildEnvironmentOptionsDefaults = Object.freeze({
32853
33420
  watch: null
32854
33421
  });
32855
33422
  const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
32856
- function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment) {
33423
+ function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, input, isSsrTargetWebworkerEnvironment) {
32857
33424
  const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
32858
33425
  const { polyfillModulePreload, ...rest } = raw;
32859
33426
  raw = rest;
@@ -32874,6 +33441,7 @@ function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, isS
32874
33441
  platform: consumer === "client" || isSsrTargetWebworkerEnvironment ? "browser" : "node",
32875
33442
  ...merged.rolldownOptions
32876
33443
  };
33444
+ if (merged.lib && merged.lib.entry == null && input != null) merged.lib.entry = input;
32877
33445
  if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
32878
33446
  if (Array.isArray(merged.target)) merged.target = unique(merged.target);
32879
33447
  if (merged.minify === "false") merged.minify = false;
@@ -32935,7 +33503,9 @@ function resolveRolldownOptions(environment, chunkMetadataMap) {
32935
33503
  const { logger } = environment;
32936
33504
  const ssr = environment.config.consumer === "server";
32937
33505
  const resolve = (p) => path.resolve(root, p);
32938
- const input = libOptions ? options.rolldownOptions.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [alias, resolve(file)]))) : typeof options.ssr === "string" ? resolve(options.ssr) : options.rolldownOptions.input || resolve("index.html");
33506
+ const topLevelInput = environment.config.input;
33507
+ if (libOptions && libOptions.entry == null) throw new Error(`Either "build.lib.entry" or the top-level "input" option is required when "build.lib" is set.`);
33508
+ const input = libOptions ? options.rolldownOptions.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [alias, resolve(file)]))) : typeof options.ssr === "string" ? resolve(options.ssr) : options.rolldownOptions.input || (topLevelInput != null ? topLevelInput : resolve("index.html"));
32939
33509
  if (ssr && typeof input === "string" && input.endsWith(".html")) throw new Error("rolldownOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.");
32940
33510
  if (options.cssCodeSplit === false) {
32941
33511
  if ((typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input)).some((input) => input.endsWith(".css"))) throw new Error(`When "build.cssCodeSplit: false" is set, "rolldownOptions.input" should not include CSS files.`);
@@ -33117,7 +33687,7 @@ function resolveLibFilename(libOptions, format, entryName, root, extension, pack
33117
33687
  }
33118
33688
  function resolveBuildOutputs(outputs, libOptions, logger) {
33119
33689
  if (libOptions) {
33120
- const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
33690
+ const libHasMultipleEntries = typeof libOptions.entry !== "string" && libOptions.entry && Object.values(libOptions.entry).length > 1;
33121
33691
  const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
33122
33692
  if (!Array.isArray(outputs)) {
33123
33693
  if (libFormats.includes("umd") || libFormats.includes("iife")) {
@@ -34353,7 +34923,6 @@ var BundledDev = class {
34353
34923
  initialBuildCompleted = false;
34354
34924
  _closed = false;
34355
34925
  clients = new Clients();
34356
- invalidateCalledModules = /* @__PURE__ */ new Map();
34357
34926
  debouncedFullReload = debounce(20, () => {
34358
34927
  this.environment.hot.send({
34359
34928
  type: "full-reload",
@@ -34372,15 +34941,16 @@ var BundledDev = class {
34372
34941
  if (!this._devEngine) throw new Error(`dev engine was not yet initialized`);
34373
34942
  return this._devEngine;
34374
34943
  }
34944
+ pendingPayloadFilenames = /* @__PURE__ */ new Set();
34375
34945
  async listen() {
34376
34946
  this._closed = false;
34377
34947
  debug$1?.("INITIAL: setup bundle options");
34378
34948
  const rolldownOptions = await this.getRolldownOptions();
34379
34949
  if (Array.isArray(rolldownOptions.output) && rolldownOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
34380
34950
  const outputOptions = Array.isArray(rolldownOptions.output) ? rolldownOptions.output[0] : rolldownOptions.output;
34381
- this.environment.hot.on("vite:module-loaded", (payload, client) => {
34951
+ this.environment.hot.on("vite:client-connected", async (payload, client) => {
34382
34952
  this.clients.setupIfNeeded(client, payload.clientId);
34383
- this.devEngine.registerModules(payload.clientId, payload.modules);
34953
+ this.devEngine.registerClient(payload.clientId);
34384
34954
  });
34385
34955
  this.environment.hot.on("vite:client:connect", (_payload, client) => {
34386
34956
  if (this.lastBuildError) {
@@ -34412,10 +34982,7 @@ var BundledDev = class {
34412
34982
  }
34413
34983
  for (const { clientId, update } of updates) {
34414
34984
  const client = this.clients.get(clientId);
34415
- if (client) {
34416
- this.invalidateCalledModules.get(client)?.clear();
34417
- this.handleHmrOutput(client, changedFiles, update);
34418
- }
34985
+ if (client) this.handleHmrOutput(client, changedFiles, update);
34419
34986
  }
34420
34987
  },
34421
34988
  onOutput: (result) => {
@@ -34450,11 +35017,12 @@ var BundledDev = class {
34450
35017
  this.waitForInitialBuildFinish().then(() => {
34451
35018
  if (this._closed) return;
34452
35019
  debug$1?.("INITIAL: build done");
34453
- this.environment.hot.send({
35020
+ this.initialBuildCompleted = true;
35021
+ if (!this.lastBuildError) this.environment.hot.send({
34454
35022
  type: "full-reload",
34455
- path: "*"
35023
+ path: "*",
35024
+ ifFallback: true
34456
35025
  });
34457
- this.initialBuildCompleted = true;
34458
35026
  });
34459
35027
  }
34460
35028
  async waitForInitialBuildFinish() {
@@ -34470,29 +35038,6 @@ var BundledDev = class {
34470
35038
  state = await this.devEngine.getBundleState();
34471
35039
  }
34472
35040
  }
34473
- async invalidateModule(m, client) {
34474
- const invalidateCalledModules = this.invalidateCalledModules.get(client);
34475
- if (invalidateCalledModules?.has(m.path)) {
34476
- debug$1?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
34477
- return;
34478
- }
34479
- debug$1?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
34480
- if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
34481
- this.invalidateCalledModules.get(client).add(m.path);
34482
- let update;
34483
- try {
34484
- update = (await this.devEngine.invalidate(m.path, m.firstInvalidatedBy)).find((u) => this.clients.get(u.clientId) === client)?.update;
34485
- } catch (e) {
34486
- client.send({
34487
- type: "error",
34488
- err: prepareError(e)
34489
- });
34490
- return;
34491
- }
34492
- if (!update) return;
34493
- if (update.type === "Patch") this.environment.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
34494
- this.handleHmrOutput(client, [m.path], update, { firstInvalidatedBy: m.firstInvalidatedBy });
34495
- }
34496
35041
  async triggerBundleRegenerationIfStale() {
34497
35042
  const bundleState = await this.devEngine.getBundleState();
34498
35043
  if (this.initialBuildCompleted && bundleState.lastBuildErrored && bundleState.lastErrorStage === "Hmr") {
@@ -34515,7 +35060,19 @@ var BundledDev = class {
34515
35060
  async triggerLazyBundling(moduleId, clientId) {
34516
35061
  if (!moduleId || !clientId) return;
34517
35062
  debug$1?.(`TRIGGER-LAZY: trigger lazy bundling for module ${moduleId} for client ${clientId}`);
34518
- return await this.devEngine.compileEntry(moduleId, clientId);
35063
+ const result = await this.devEngine.compileEntry(moduleId, clientId);
35064
+ this.pendingPayloadFilenames.add(result.filename);
35065
+ return result;
35066
+ }
35067
+ /**
35068
+ * Called by the serving middlewares when the response for a payload completed.
35069
+ * Only delivered payloads are recorded on the server's per-client ship map, so
35070
+ * later chunks may omit a module only if the payload carrying it was delivered.
35071
+ *
35072
+ * Note: the payload filename is unique across all clients.
35073
+ */
35074
+ markPayloadDelivered(filename) {
35075
+ if (this.pendingPayloadFilenames.delete(filename)) this.devEngine.notifyPayloadDelivered(filename);
34519
35076
  }
34520
35077
  async close() {
34521
35078
  this._closed = true;
@@ -34573,46 +35130,35 @@ var BundledDev = class {
34573
35130
  }
34574
35131
  return rolldownOptions;
34575
35132
  }
34576
- handleHmrOutput(client, files, hmrOutput, invalidateInformation) {
35133
+ handleHmrOutput(client, files, hmrOutput) {
34577
35134
  if (hmrOutput.type === "Noop") return;
34578
35135
  const shortFile = files.map((file) => getShortName(file, this.environment.config.root)).join(", ");
34579
35136
  if (hmrOutput.type === "FullReload") {
34580
35137
  const reason = hmrOutput.reason ? import_picocolors.default.dim(` (${hmrOutput.reason})`) : "";
34581
35138
  this.environment.logger.info(import_picocolors.default.green(`trigger page reload `) + import_picocolors.default.dim(shortFile) + reason, {
34582
- clear: !invalidateInformation,
35139
+ clear: true,
34583
35140
  timestamp: true
34584
35141
  });
34585
- if (invalidateInformation) this.devEngine.ensureLatestBuildOutput().then(async () => {
34586
- this.debouncedFullReload();
34587
- });
34588
- else this.fullReloadPending = true;
35142
+ this.fullReloadPending = true;
34589
35143
  return;
34590
35144
  }
34591
35145
  debug$1?.(`handle hmr output for ${shortFile}`, {
34592
35146
  ...hmrOutput,
34593
35147
  code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
34594
35148
  });
35149
+ this.pendingPayloadFilenames.add(hmrOutput.filename);
34595
35150
  this.memoryFiles.set(hmrOutput.filename, { source: hmrOutput.code + "\n; export {}" });
34596
35151
  if (hmrOutput.sourcemapFilename && hmrOutput.sourcemap) this.memoryFiles.set(hmrOutput.sourcemapFilename, { source: hmrOutput.sourcemap });
34597
- const updates = hmrOutput.hmrBoundaries.map((boundary) => {
34598
- return {
34599
- type: "js-update",
34600
- url: hmrOutput.filename,
34601
- path: boundary.boundary,
34602
- acceptedPath: boundary.acceptedVia,
34603
- firstInvalidatedBy: invalidateInformation?.firstInvalidatedBy,
34604
- timestamp: Date.now()
34605
- };
34606
- });
34607
35152
  client.send({
34608
- type: "update",
34609
- updates
35153
+ type: "bundled-dev-update",
35154
+ changedIds: hmrOutput.changedIds,
35155
+ url: hmrOutput.filename,
35156
+ seq: hmrOutput.seq
34610
35157
  });
34611
- const filePaths = [...new Set(updates.map((u) => u.path))];
34612
- const { formatted, truncated } = formatAndTruncateFileList(filePaths);
34613
- if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
35158
+ const { formatted, truncated } = formatAndTruncateFileList(hmrOutput.changedIds);
35159
+ if (truncated) debugHmr?.(`hmr update ${hmrOutput.changedIds.join(", ")}`);
34614
35160
  this.environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
34615
- clear: !invalidateInformation,
35161
+ clear: true,
34616
35162
  timestamp: true
34617
35163
  });
34618
35164
  }
@@ -34786,10 +35332,7 @@ var DevEnvironment = class extends BaseEnvironment {
34786
35332
  }
34787
35333
  }
34788
35334
  invalidateModule(m, _client) {
34789
- if (this.bundledDev) {
34790
- this.bundledDev.invalidateModule(m, _client);
34791
- return;
34792
- }
35335
+ if (this.bundledDev) return;
34793
35336
  const mod = this.moduleGraph.urlToModuleMap.get(m.path);
34794
35337
  if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
34795
35338
  mod.lastHMRInvalidationReceived = true;
@@ -35101,6 +35644,177 @@ async function preview(inlineConfig = {}) {
35101
35644
  return server;
35102
35645
  }
35103
35646
  //#endregion
35647
+ //#region src/node/nativeConfigCompat.ts
35648
+ const jsTsExtRE = /\.[cm]?[jt]sx?$/;
35649
+ const indexFileRE = /^index\.[cm]?[jt]sx?$/;
35650
+ const lastSegmentOf = (specifier) => specifier.slice(specifier.lastIndexOf("/") + 1);
35651
+ /**
35652
+ * A specifier that already carries a JS/TS extension resolves as-is under the
35653
+ * native loader, so it can never be extension-less or a directory index and
35654
+ * needs no resolution to classify.
35655
+ */
35656
+ const specifierHasJsExtension = (specifier) => jsTsExtRE.test(lastSegmentOf(specifier));
35657
+ function classifyImportRef(ref, resolvedId, file) {
35658
+ const { specifier, line, column } = ref;
35659
+ const base = {
35660
+ file,
35661
+ line,
35662
+ column,
35663
+ specifier
35664
+ };
35665
+ if (specifier.endsWith(".json")) {
35666
+ if (ref.hasTypeJsonAttribute) return void 0;
35667
+ return {
35668
+ type: "json-without-attributes",
35669
+ ...base
35670
+ };
35671
+ }
35672
+ if (!resolvedId) return void 0;
35673
+ if (resolvedId.endsWith(".json") && !ref.hasTypeJsonAttribute) return {
35674
+ type: "json-without-attributes",
35675
+ ...base
35676
+ };
35677
+ const lastSegment = lastSegmentOf(specifier);
35678
+ const specifierNamesIndex = lastSegment === "index" || indexFileRE.test(lastSegment);
35679
+ if (indexFileRE.test(path.basename(resolvedId)) && !specifierNamesIndex) return {
35680
+ type: "directory-index-import",
35681
+ ...base
35682
+ };
35683
+ if (!jsTsExtRE.test(lastSegment)) return {
35684
+ type: "extensionless-import",
35685
+ ...base
35686
+ };
35687
+ }
35688
+ const isPathSpecifier = (s) => s.startsWith(".") || path.isAbsolute(s);
35689
+ const hasTypeJson = (attributes) => !!attributes?.some((attr) => {
35690
+ return (attr.key.type === "Identifier" ? attr.key.name : attr.key.value) === "type" && attr.value?.value === "json";
35691
+ });
35692
+ const DIRNAME_FILENAME = {
35693
+ __dirname: "dirname",
35694
+ __filename: "filename"
35695
+ };
35696
+ function analyzeConfigModuleReferences(code, ast, file) {
35697
+ const imports = [];
35698
+ const addImportRef = (source, hasTypeJsonAttribute) => {
35699
+ if (!isPathSpecifier(source.value)) return;
35700
+ const { line, column } = numberToPos(code, source.start);
35701
+ imports.push({
35702
+ specifier: source.value,
35703
+ line,
35704
+ column,
35705
+ hasTypeJsonAttribute
35706
+ });
35707
+ };
35708
+ walk$1(ast, { enter(_node) {
35709
+ const node = _node;
35710
+ switch (node.type) {
35711
+ case "ImportDeclaration":
35712
+ addImportRef(node.source, hasTypeJson(node.attributes));
35713
+ break;
35714
+ case "ExportNamedDeclaration":
35715
+ case "ExportAllDeclaration":
35716
+ if (node.source) addImportRef(node.source, hasTypeJson(node.attributes));
35717
+ break;
35718
+ case "ImportExpression":
35719
+ if (node.source.type === "Literal" && typeof node.source.value === "string") addImportRef(node.source, node.options != null);
35720
+ break;
35721
+ }
35722
+ } });
35723
+ const globals = [];
35724
+ if (code.includes("__dirname") || code.includes("__filename")) {
35725
+ const { globals: freeReferences } = analyze(ast);
35726
+ for (const [name, type] of Object.entries(DIRNAME_FILENAME)) {
35727
+ const node = freeReferences.get(name);
35728
+ if (!node) continue;
35729
+ const { line, column } = numberToPos(code, node.start);
35730
+ globals.push({
35731
+ type,
35732
+ file,
35733
+ line,
35734
+ column
35735
+ });
35736
+ }
35737
+ }
35738
+ return {
35739
+ globals,
35740
+ imports
35741
+ };
35742
+ }
35743
+ const esmStatementTypes = /* @__PURE__ */ new Set([
35744
+ "ImportDeclaration",
35745
+ "ExportNamedDeclaration",
35746
+ "ExportDefaultDeclaration",
35747
+ "ExportAllDeclaration"
35748
+ ]);
35749
+ function findEsmSyntaxInCjs(code, ast, file) {
35750
+ for (const node of ast.body) if (esmStatementTypes.has(node.type)) {
35751
+ const { line, column } = numberToPos(code, node.start);
35752
+ return {
35753
+ type: "esm-syntax-in-cjs",
35754
+ file,
35755
+ line,
35756
+ column
35757
+ };
35758
+ }
35759
+ }
35760
+ function describeIncompatibility(item, root) {
35761
+ const loc = `${normalizePath(path.relative(root, item.file))}:${item.line}`;
35762
+ switch (item.type) {
35763
+ case "dirname": return `\`__dirname\` (${loc}). Use \`import.meta.dirname\` instead`;
35764
+ case "filename": return `\`__filename\` (${loc}). Use \`import.meta.filename\` instead`;
35765
+ case "extensionless-import": return `import "${item.specifier}" without a file extension (${loc}). Add the file extension`;
35766
+ case "directory-index-import": return `import "${item.specifier}" resolves to a directory index (${loc}). Import the index file directly`;
35767
+ case "json-without-attributes": return item.specifier?.endsWith(".json") ? `JSON import "${item.specifier}" without import attributes (${loc}). Add \`with { type: 'json' }\`` : `import "${item.specifier}" resolves to a JSON file (${loc}). Import it with a \`.json\` extension and \`with { type: 'json' }\``;
35768
+ case "esm-syntax-in-cjs": return `ESM syntax in a file loaded as CommonJS (${loc}). Use a \`.mjs\` extension or set \`"type": "module"\` in the closest package.json`;
35769
+ }
35770
+ }
35771
+ function formatNativeConfigIncompatWarning(items, root) {
35772
+ const header = "Your Vite config uses features that are unsupported by `configLoader: 'native'`, which is planned to become the default in a future major version of Vite:";
35773
+ const lines = items.map((it) => ` - ${describeIncompatibility(it, root)}`);
35774
+ const footer = `Set \`VITE_CONFIG_NATIVE_IGNORE_WARNING=true\` to suppress this warning.`;
35775
+ return import_picocolors.default.yellow([
35776
+ `(!) ${header}`,
35777
+ ...lines,
35778
+ footer
35779
+ ].join("\n"));
35780
+ }
35781
+ function createNativeConfigCompatPlugin(collector) {
35782
+ return {
35783
+ name: "vite:native-config-compat-check",
35784
+ transform: {
35785
+ filter: { id: {
35786
+ include: /\.[cm]?[jt]sx?$/,
35787
+ exclude: /^\0/
35788
+ } },
35789
+ async handler(code, id) {
35790
+ const isESM = typeof process.versions.deno === "string" || isFilePathESM(id);
35791
+ let program;
35792
+ try {
35793
+ const result = parseSync(id, code);
35794
+ if (result.errors.length > 0) return null;
35795
+ program = result.program;
35796
+ } catch {
35797
+ return null;
35798
+ }
35799
+ if (!isESM) {
35800
+ const finding = findEsmSyntaxInCjs(code, program, id);
35801
+ if (finding) collector.push(finding);
35802
+ return null;
35803
+ }
35804
+ const { globals, imports } = analyzeConfigModuleReferences(code, program, id);
35805
+ for (const g of globals) collector.push(g);
35806
+ for (const ref of imports) {
35807
+ let resolvedId = null;
35808
+ if (!ref.specifier.endsWith(".json") && !specifierHasJsExtension(ref.specifier)) resolvedId = (await this.resolve(ref.specifier, id))?.id ?? null;
35809
+ const finding = classifyImportRef(ref, resolvedId, id);
35810
+ if (finding) collector.push(finding);
35811
+ }
35812
+ return null;
35813
+ }
35814
+ }
35815
+ };
35816
+ }
35817
+ //#endregion
35104
35818
  //#region src/node/ssr/index.ts
35105
35819
  const _ssrConfigDefaults = Object.freeze({
35106
35820
  target: "node",
@@ -35430,6 +36144,28 @@ const configDefaults = Object.freeze({
35430
36144
  environments: {},
35431
36145
  appType: "spa"
35432
36146
  });
36147
+ function resolveInput(input, root) {
36148
+ if (input === void 0) return;
36149
+ if (typeof input === "string") {
36150
+ const unescapedInput = unescapeGlobCharacters(input);
36151
+ return normalizePath(path.resolve(root, unescapedInput));
36152
+ }
36153
+ if (Array.isArray(input)) return input.map((inp) => {
36154
+ const unescapedInput = unescapeGlobCharacters(inp);
36155
+ return normalizePath(path.resolve(root, unescapedInput));
36156
+ });
36157
+ const resolved = {};
36158
+ for (const key in input) {
36159
+ const unescapedInput = unescapeGlobCharacters(input[key]);
36160
+ resolved[key] = normalizePath(path.resolve(root, unescapedInput));
36161
+ }
36162
+ return resolved;
36163
+ }
36164
+ const escapedGlobCharactersRE = /\\([*?[\]{}()!+@|])/g;
36165
+ function unescapeGlobCharacters(value) {
36166
+ if (isDynamicPattern(value)) throw new Error(`\`input\` cannot contain glob characters. They are reserved, so the ${JSON.stringify(value)} is not allowed. Please escape them with a backslash (\\)`);
36167
+ return value.replace(escapedGlobCharactersRE, "$1");
36168
+ }
35433
36169
  function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransformRequest) {
35434
36170
  const resolved = mergeWithDefaults({
35435
36171
  ...configDefaults.dev,
@@ -35444,7 +36180,7 @@ function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransfo
35444
36180
  sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
35445
36181
  };
35446
36182
  }
35447
- function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, isSsrTargetWebworkerSet, preTransformRequests) {
36183
+ function resolveEnvironmentOptions(options, alias, preserveSymlinks, root, forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, isSsrTargetWebworkerSet, preTransformRequests) {
35448
36184
  const isClientEnvironment = environmentName === "client";
35449
36185
  const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
35450
36186
  const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
@@ -35458,13 +36194,14 @@ function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimi
35458
36194
  }
35459
36195
  const resolve = resolveEnvironmentResolveOptions(options.resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment);
35460
36196
  return {
36197
+ input: resolveInput(options.input, root),
35461
36198
  define: options.define,
35462
36199
  resolve,
35463
36200
  keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
35464
36201
  consumer,
35465
36202
  optimizeDeps: resolveDepOptimizationOptions(options.optimizeDeps, resolve.preserveSymlinks, forceOptimizeDeps, consumer, logger),
35466
36203
  dev: resolveDevEnvironmentOptions(options.dev, environmentName, consumer, preTransformRequests),
35467
- build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundled && !isBuild, isSsrTargetWebworkerEnvironment),
36204
+ build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundled && !isBuild, options.input, isSsrTargetWebworkerEnvironment),
35468
36205
  isBundled,
35469
36206
  plugins: void 0,
35470
36207
  optimizeDepsPluginNames: void 0
@@ -35656,7 +36393,11 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
35656
36393
  const tsconfigPathsPlugin = userPlugins.find((p) => p.name === "vite-tsconfig-paths" || p.name === "vite-plugin-tsconfig-paths");
35657
36394
  if (tsconfigPathsPlugin) logger.warnOnce(import_picocolors.default.yellow(`The plugin ${JSON.stringify(tsconfigPathsPlugin.name)} is detected. Vite now supports tsconfig paths resolution natively via the ${import_picocolors.default.bold("resolve.tsconfigPaths")} option. You can remove the plugin and set ${import_picocolors.default.bold("resolve.tsconfigPaths: true")} in your Vite config instead.`));
35658
36395
  if (process.versions.pnp) logger.warnOnce(import_picocolors.default.yellow(`Using Yarn PnP with Vite is discouraged and PnP-specific bugs will no longer be actively worked on. Please switch to a different ${import_picocolors.default.bold("nodeLinker")} mode or to a different package manager.`));
35659
- const resolvedRoot = normalizePath(config.root ? path.resolve(config.root) : process.cwd());
36396
+ let nonNormalizedResolvedRoot = config.root ? path.resolve(config.root) : process.cwd();
36397
+ try {
36398
+ nonNormalizedResolvedRoot = safeRealpathSync(nonNormalizedResolvedRoot);
36399
+ } catch {}
36400
+ const resolvedRoot = normalizePath(nonNormalizedResolvedRoot);
35660
36401
  checkBadCharactersInPath("The project root", "directory", resolvedRoot, logger);
35661
36402
  const configEnvironmentsClient = config.environments.client;
35662
36403
  configEnvironmentsClient.dev ??= {};
@@ -35688,6 +36429,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
35688
36429
  const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
35689
36430
  const defaultClientEnvironmentOptions = {
35690
36431
  ...defaultEnvironmentOptions,
36432
+ input: config.input,
35691
36433
  resolve: config.resolve,
35692
36434
  optimizeDeps: config.optimizeDeps
35693
36435
  };
@@ -35711,10 +36453,10 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
35711
36453
  config.resolve.mainFields = config.environments.client.resolve?.mainFields;
35712
36454
  const resolvedDefaultResolve = resolveResolveOptions(config.resolve, logger);
35713
36455
  const resolvedEnvironments = {};
35714
- for (const environmentName of Object.keys(config.environments)) resolvedEnvironments[environmentName] = resolveEnvironmentOptions(config.environments[environmentName], resolvedDefaultResolve.alias, resolvedDefaultResolve.preserveSymlinks, inlineConfig.forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, config.ssr?.target === "webworker", config.server?.preTransformRequests);
36456
+ for (const environmentName of Object.keys(config.environments)) resolvedEnvironments[environmentName] = resolveEnvironmentOptions(config.environments[environmentName], resolvedDefaultResolve.alias, resolvedDefaultResolve.preserveSymlinks, resolvedRoot, inlineConfig.forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, config.ssr?.target === "webworker", config.server?.preTransformRequests);
35715
36457
  const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
35716
36458
  const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config.dev, void 0, void 0);
35717
- const resolvedBuildOptions = resolveBuildEnvironmentOptions(config.build ?? {}, logger, void 0, isBundledDev);
36459
+ const resolvedBuildOptions = resolveBuildEnvironmentOptions(config.build ?? {}, logger, void 0, isBundledDev, config.input);
35718
36460
  const ssr = resolveSSROptions({
35719
36461
  ...config.ssr,
35720
36462
  external: resolvedEnvironments.ssr?.resolve.external,
@@ -35871,6 +36613,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
35871
36613
  removeSsrLoadModule: "warn"
35872
36614
  } : config.future,
35873
36615
  ssr,
36616
+ input: resolveInput(config.input, resolvedRoot),
35874
36617
  optimizeDeps: backwardCompatibleOptimizeDeps,
35875
36618
  resolve: resolvedDefaultResolve,
35876
36619
  dev: resolvedDevEnvironmentOptions,
@@ -35998,7 +36741,7 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
35998
36741
  return null;
35999
36742
  }
36000
36743
  try {
36001
- const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile)(resolvedPath);
36744
+ const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile(resolvedPath, configRoot, logLevel, customLogger) : configLoader === "runner" ? runnerImportConfigFile(resolvedPath) : nativeImportConfigFile(resolvedPath));
36002
36745
  debug?.(`config file loaded in ${getTime()}`);
36003
36746
  const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
36004
36747
  if (!isObject$1(config)) throw new Error(`config must export or return an object.`);
@@ -36035,11 +36778,13 @@ async function runnerImportConfigFile(resolvedPath) {
36035
36778
  dependencies
36036
36779
  };
36037
36780
  }
36038
- async function bundleAndLoadConfigFile(resolvedPath) {
36781
+ async function bundleAndLoadConfigFile(resolvedPath, configRoot, logLevel, customLogger) {
36039
36782
  const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
36040
36783
  const bundled = await bundleConfigFile(resolvedPath, isESM);
36784
+ const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM);
36785
+ if (bundled.nativeIncompatibilities.length > 0) createLogger(logLevel, { customLogger }).warn(formatNativeConfigIncompatWarning(bundled.nativeIncompatibilities, configRoot));
36041
36786
  return {
36042
- configExport: await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM),
36787
+ configExport: userConfig,
36043
36788
  dependencies: bundled.dependencies
36044
36789
  };
36045
36790
  }
@@ -36051,6 +36796,7 @@ async function bundleConfigFile(fileName, isESM) {
36051
36796
  const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
36052
36797
  const importMetaResolveVarName = "__vite_injected_original_import_meta_resolve";
36053
36798
  const importMetaResolveRegex = /import\.meta\s*\.\s*resolve/;
36799
+ const nativeIncompatibilities = [];
36054
36800
  const bundle = await rolldown({
36055
36801
  input: fileName,
36056
36802
  platform: "node",
@@ -36066,68 +36812,72 @@ async function bundleConfigFile(fileName, isESM) {
36066
36812
  } },
36067
36813
  treeshake: false,
36068
36814
  tsconfig: false,
36069
- plugins: [{
36070
- name: "externalize-deps",
36071
- resolveId: {
36072
- filter: { id: /^[^.#].*/ },
36073
- handler(id, importer, { kind }) {
36074
- if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
36075
- if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return {
36076
- id,
36077
- external: true
36078
- };
36079
- const isImport = isESM || kind === "dynamic-import";
36080
- let idFsPath;
36081
- try {
36082
- idFsPath = nodeResolveWithVite(id, importer, {
36083
- root,
36084
- isRequire: !isImport
36085
- });
36086
- } catch (e) {
36087
- if (!isImport) {
36088
- let canResolveWithImport = false;
36089
- try {
36090
- canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
36091
- } catch {}
36092
- if (canResolveWithImport) throw new Error(`Failed to resolve ${JSON.stringify(id)}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
36815
+ plugins: [
36816
+ !process.env.VITE_CONFIG_NATIVE_IGNORE_WARNING && createNativeConfigCompatPlugin(nativeIncompatibilities),
36817
+ {
36818
+ name: "externalize-deps",
36819
+ resolveId: {
36820
+ filter: { id: /^[^.#].*/ },
36821
+ handler(id, importer, { kind }) {
36822
+ if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
36823
+ if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return {
36824
+ id,
36825
+ external: true
36826
+ };
36827
+ const isImport = isESM || kind === "dynamic-import";
36828
+ let idFsPath;
36829
+ try {
36830
+ idFsPath = nodeResolveWithVite(id, importer, {
36831
+ root,
36832
+ isRequire: !isImport
36833
+ });
36834
+ } catch (e) {
36835
+ if (!isImport) {
36836
+ let canResolveWithImport = false;
36837
+ try {
36838
+ canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
36839
+ } catch {}
36840
+ if (canResolveWithImport) throw new Error(`Failed to resolve ${JSON.stringify(id)}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
36841
+ }
36842
+ throw e;
36093
36843
  }
36094
- throw e;
36844
+ if (!idFsPath) return;
36845
+ if (idFsPath.endsWith(".json")) return idFsPath;
36846
+ if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
36847
+ return {
36848
+ id: idFsPath,
36849
+ external: true
36850
+ };
36095
36851
  }
36096
- if (!idFsPath) return;
36097
- if (idFsPath.endsWith(".json")) return idFsPath;
36098
- if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
36099
- return {
36100
- id: idFsPath,
36101
- external: true
36102
- };
36103
36852
  }
36104
- }
36105
- }, {
36106
- name: "inject-file-scope-variables",
36107
- transform: {
36108
- filter: { id: /\.[cm]?[jt]s$/ },
36109
- handler(code, id) {
36110
- let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
36111
- if (importMetaResolveRegex.test(code)) if (isESM) {
36112
- if (!importMetaResolverRegistered) {
36113
- importMetaResolverRegistered = true;
36114
- createImportMetaResolver();
36115
- }
36116
- injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
36117
- } else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
36118
- let injectedContents;
36119
- if (code.startsWith("#!")) {
36120
- let firstLineEndIndex = code.indexOf("\n");
36121
- if (firstLineEndIndex < 0) firstLineEndIndex = code.length;
36122
- injectedContents = code.slice(0, firstLineEndIndex + 1) + injectValues + code.slice(firstLineEndIndex + 1);
36123
- } else injectedContents = injectValues + code;
36124
- return {
36125
- code: injectedContents,
36126
- map: null
36127
- };
36853
+ },
36854
+ {
36855
+ name: "inject-file-scope-variables",
36856
+ transform: {
36857
+ filter: { id: /\.[cm]?[jt]s$/ },
36858
+ handler(code, id) {
36859
+ let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
36860
+ if (importMetaResolveRegex.test(code)) if (isESM) {
36861
+ if (!importMetaResolverRegistered) {
36862
+ importMetaResolverRegistered = true;
36863
+ createImportMetaResolver();
36864
+ }
36865
+ injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
36866
+ } else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
36867
+ let injectedContents;
36868
+ if (code.startsWith("#!")) {
36869
+ let firstLineEndIndex = code.indexOf("\n");
36870
+ if (firstLineEndIndex < 0) firstLineEndIndex = code.length;
36871
+ injectedContents = code.slice(0, firstLineEndIndex + 1) + injectValues + code.slice(firstLineEndIndex + 1);
36872
+ } else injectedContents = injectValues + code;
36873
+ return {
36874
+ code: injectedContents,
36875
+ map: null
36876
+ };
36877
+ }
36128
36878
  }
36129
36879
  }
36130
- }]
36880
+ ]
36131
36881
  });
36132
36882
  const result = await bundle.generate({
36133
36883
  format: isESM ? "esm" : "cjs",
@@ -36144,7 +36894,8 @@ async function bundleConfigFile(fileName, isESM) {
36144
36894
  collectAllModules(bundleChunks, entryChunk.fileName, allModules);
36145
36895
  return {
36146
36896
  code: entryChunk.code,
36147
- dependencies: [...allModules].filter((m) => !m.startsWith("\0"))
36897
+ dependencies: [...allModules].filter((m) => !m.startsWith("\0")),
36898
+ nativeIncompatibilities
36148
36899
  };
36149
36900
  }
36150
36901
  function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
@@ -36280,4 +37031,4 @@ const parseAst$1 = parseAst;
36280
37031
  const parseAstAsync$1 = parseAstAsync;
36281
37032
  const esbuildVersion = "0.25.0";
36282
37033
  //#endregion
36283
- export { mergeConfig as $, createServer$2 as A, ssrTransform as B, fetchModule as C, optimizeDeps as D, createBuilder as E, createIdResolver as F, resolveEnvPrefix as G, createServerModuleRunnerTransport as H, perEnvironmentState as I, createLogger as J, transformWithOxc as K, isFileLoadingAllowed as L, formatPostcssSourceMap as M, preprocessCSS as N, optimizer_exports as O, searchForWorkspaceRoot as P, mergeAlias as Q, isFileServingAllowed as R, DevEnvironment as S, build as T, buildErrorMessage as U, createServerModuleRunner as V, loadEnv as W, createFilter$1 as X, perEnvironmentPlugin as Y, isCSSRequest as Z, runnerImport as _, minifySync as a, DEFAULT_CLIENT_MAIN_FIELDS as at, createRunnableDevEnvironment as b, parseAstAsync$1 as c, DEFAULT_SERVER_MAIN_FIELDS as ct, isFetchableDevEnvironment as d, require_picocolors as dt, normalizePath as et, config_exports as f, __commonJSMin as ft, sortUserPlugins as g, resolveConfig as h, minify as i, DEFAULT_CLIENT_CONDITIONS as it, server_exports as j, createServerHotChannel as k, parseSync as l, VERSION as lt, loadConfigFromFile as m, __toESM as mt, esbuildVersion as n, rollupVersion as nt, parse as o, DEFAULT_EXTERNAL_CONDITIONS as ot, defineConfig as p, __require as pt, transformWithEsbuild as q, esmExternalRequirePlugin$1 as r, withFilter as rt, parseAst$1 as s, DEFAULT_SERVER_CONDITIONS as st, Visitor as t, rolldownVersion as tt, createFetchableDevEnvironment as u, defaultAllowedOrigins as ut, preview as v, BuildEnvironment as w, isRunnableDevEnvironment as x, preview_exports as y, send$1 as z };
37034
+ export { mergeConfig as $, createServer$2 as A, ssrTransform as B, fetchModule as C, optimizeDeps as D, createBuilder as E, createIdResolver as F, resolveEnvPrefix as G, createServerModuleRunnerTransport as H, perEnvironmentState as I, createLogger as J, transformWithOxc as K, isFileLoadingAllowed as L, formatPostcssSourceMap as M, preprocessCSS as N, optimizer_exports as O, searchForWorkspaceRoot as P, mergeAlias as Q, isFileServingAllowed as R, DevEnvironment as S, build as T, buildErrorMessage as U, createServerModuleRunner as V, loadEnv as W, createFilter$1 as X, perEnvironmentPlugin as Y, isCSSRequest as Z, runnerImport as _, minifySync as a, DEFAULT_CLIENT_MAIN_FIELDS as at, createRunnableDevEnvironment as b, parseAstAsync$1 as c, DEFAULT_SERVER_MAIN_FIELDS as ct, isFetchableDevEnvironment as d, require_picocolors as dt, normalizePath as et, config_exports as f, __commonJSMin as ft, sortUserPlugins as g, resolveConfig as h, minify as i, DEFAULT_CLIENT_CONDITIONS as it, server_exports as j, createServerHotChannel as k, parseSync$1 as l, VERSION as lt, loadConfigFromFile as m, __toESM as mt, esbuildVersion as n, rollupVersion as nt, parse as o, DEFAULT_EXTERNAL_CONDITIONS as ot, defineConfig as p, __require as pt, transformWithEsbuild as q, esmExternalRequirePlugin$1 as r, withFilter as rt, parseAst$1 as s, DEFAULT_SERVER_CONDITIONS as st, Visitor as t, rolldownVersion as tt, createFetchableDevEnvironment as u, defaultAllowedOrigins as ut, preview as v, BuildEnvironment as w, isRunnableDevEnvironment as x, preview_exports as y, send$1 as z };