@sveltejs/vite-plugin-svelte 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -36,8 +36,8 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" +
36
36
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
37
37
 
38
38
  // src/index.ts
39
- var import_fs6 = __toESM(require("fs"), 1);
40
- var import_vitefu3 = require("vitefu");
39
+ var import_fs7 = __toESM(require("fs"), 1);
40
+ var import_vitefu4 = require("vitefu");
41
41
 
42
42
  // src/utils/log.ts
43
43
  var import_colors = require("kleur/colors");
@@ -318,81 +318,105 @@ function toSafe(base64) {
318
318
 
319
319
  // src/utils/compile.ts
320
320
  var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
321
- var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
322
- const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
323
- const { emitCss = true } = options;
324
- const dependencies = [];
325
- const compileOptions = {
326
- ...options.compilerOptions,
327
- filename,
328
- generate: ssr ? "ssr" : "dom",
329
- format: "esm"
330
- };
331
- if (options.hot && options.emitCss) {
332
- const hash = `s-${safeBase64Hash(normalizedFilename)}`;
333
- log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
334
- compileOptions.cssHash = () => hash;
335
- }
336
- if (ssr && compileOptions.enableSourcemap !== false) {
337
- if (typeof compileOptions.enableSourcemap === "object") {
338
- compileOptions.enableSourcemap.css = false;
339
- } else {
340
- compileOptions.enableSourcemap = { js: true, css: false };
321
+ var _createCompileSvelte = (makeHot) => {
322
+ let stats;
323
+ return async function compileSvelte2(svelteRequest, code, options) {
324
+ const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
325
+ const { emitCss = true } = options;
326
+ const dependencies = [];
327
+ if (options.stats) {
328
+ if (options.isBuild) {
329
+ if (!stats) {
330
+ stats = options.stats.startCollection(`${ssr ? "ssr" : "dom"} compile`, {
331
+ logInProgress: () => false
332
+ });
333
+ }
334
+ } else {
335
+ if (ssr && !stats) {
336
+ stats = options.stats.startCollection("ssr compile");
337
+ }
338
+ if (!ssr && stats) {
339
+ stats.finish();
340
+ stats = void 0;
341
+ }
342
+ }
341
343
  }
342
- }
343
- let preprocessed;
344
- if (options.preprocess) {
345
- try {
346
- preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
347
- } catch (e) {
348
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
349
- throw e;
344
+ const compileOptions = {
345
+ ...options.compilerOptions,
346
+ filename,
347
+ generate: ssr ? "ssr" : "dom",
348
+ format: "esm"
349
+ };
350
+ if (options.hot && options.emitCss) {
351
+ const hash = `s-${safeBase64Hash(normalizedFilename)}`;
352
+ log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
353
+ compileOptions.cssHash = () => hash;
350
354
  }
351
- if (preprocessed.dependencies)
352
- dependencies.push(...preprocessed.dependencies);
353
- if (preprocessed.map)
354
- compileOptions.sourcemap = preprocessed.map;
355
- }
356
- const finalCode = preprocessed ? preprocessed.code : code;
357
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
358
- filename,
359
- code: finalCode,
360
- compileOptions
361
- });
362
- if (dynamicCompileOptions && log.debug.enabled) {
363
- log.debug(
364
- `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
365
- );
366
- }
367
- const finalCompileOptions = dynamicCompileOptions ? {
368
- ...compileOptions,
369
- ...dynamicCompileOptions
370
- } : compileOptions;
371
- const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
372
- const hasCss = compiled.css?.code?.trim().length > 0;
373
- if (emitCss && hasCss) {
374
- compiled.js.code += `
355
+ if (ssr && compileOptions.enableSourcemap !== false) {
356
+ if (typeof compileOptions.enableSourcemap === "object") {
357
+ compileOptions.enableSourcemap.css = false;
358
+ } else {
359
+ compileOptions.enableSourcemap = { js: true, css: false };
360
+ }
361
+ }
362
+ let preprocessed;
363
+ if (options.preprocess) {
364
+ try {
365
+ preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
366
+ } catch (e) {
367
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
368
+ throw e;
369
+ }
370
+ if (preprocessed.dependencies)
371
+ dependencies.push(...preprocessed.dependencies);
372
+ if (preprocessed.map)
373
+ compileOptions.sourcemap = preprocessed.map;
374
+ }
375
+ const finalCode = preprocessed ? preprocessed.code : code;
376
+ const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
377
+ filename,
378
+ code: finalCode,
379
+ compileOptions
380
+ });
381
+ if (dynamicCompileOptions && log.debug.enabled) {
382
+ log.debug(
383
+ `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
384
+ );
385
+ }
386
+ const finalCompileOptions = dynamicCompileOptions ? {
387
+ ...compileOptions,
388
+ ...dynamicCompileOptions
389
+ } : compileOptions;
390
+ const endStat = stats?.start(filename);
391
+ const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
392
+ if (endStat) {
393
+ endStat();
394
+ }
395
+ const hasCss = compiled.css?.code?.trim().length > 0;
396
+ if (emitCss && hasCss) {
397
+ compiled.js.code += `
375
398
  import ${JSON.stringify(cssId)};
376
399
  `;
377
- }
378
- if (!ssr && makeHot) {
379
- compiled.js.code = makeHot({
380
- id: filename,
381
- compiledCode: compiled.js.code,
382
- hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
400
+ }
401
+ if (!ssr && makeHot) {
402
+ compiled.js.code = makeHot({
403
+ id: filename,
404
+ compiledCode: compiled.js.code,
405
+ hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
406
+ compiled,
407
+ originalCode: code,
408
+ compileOptions: finalCompileOptions
409
+ });
410
+ }
411
+ compiled.js.dependencies = dependencies;
412
+ return {
413
+ filename,
414
+ normalizedFilename,
415
+ lang: code.match(scriptLangRE)?.[1] || "js",
383
416
  compiled,
384
- originalCode: code,
385
- compileOptions: finalCompileOptions
386
- });
387
- }
388
- compiled.js.dependencies = dependencies;
389
- return {
390
- filename,
391
- normalizedFilename,
392
- lang: code.match(scriptLangRE)?.[1] || "js",
393
- compiled,
394
- ssr,
395
- dependencies
417
+ ssr,
418
+ dependencies
419
+ };
396
420
  };
397
421
  };
398
422
  function buildMakeHot(options) {
@@ -492,7 +516,7 @@ function buildIdParser(options) {
492
516
  }
493
517
 
494
518
  // src/utils/options.ts
495
- var import_vite3 = require("vite");
519
+ var import_vite4 = require("vite");
496
520
 
497
521
  // src/utils/load-svelte-config.ts
498
522
  var import_module = require("module");
@@ -600,9 +624,10 @@ var SVELTE_HMR_IMPORTS = [
600
624
  "svelte-hmr/runtime/proxy-adapter-dom.js",
601
625
  "svelte-hmr"
602
626
  ];
627
+ var SVELTE_EXPORT_CONDITIONS = ["svelte"];
603
628
 
604
629
  // src/utils/options.ts
605
- var import_path4 = __toESM(require("path"), 1);
630
+ var import_path5 = __toESM(require("path"), 1);
606
631
 
607
632
  // src/utils/esbuild.ts
608
633
  var import_fs2 = require("fs");
@@ -702,19 +727,28 @@ function esbuildSveltePlugin(options) {
702
727
  return;
703
728
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
704
729
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
730
+ let statsCollection;
731
+ build.onStart(() => {
732
+ statsCollection = options.stats?.startCollection("prebundle libraries", {
733
+ logResult: (c) => c.stats.length > 1
734
+ });
735
+ });
705
736
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
706
- const code = await import_fs2.promises.readFile(filename, "utf8");
737
+ const code = (0, import_fs2.readFileSync)(filename, "utf8");
707
738
  try {
708
- const contents = await compileSvelte(options, { filename, code });
739
+ const contents = await compileSvelte(options, { filename, code }, statsCollection);
709
740
  return { contents };
710
741
  } catch (e) {
711
742
  return { errors: [toESBuildError(e, options)] };
712
743
  }
713
744
  });
745
+ build.onEnd(() => {
746
+ statsCollection?.finish();
747
+ });
714
748
  }
715
749
  };
716
750
  }
717
- async function compileSvelte(options, { filename, code }) {
751
+ async function compileSvelte(options, { filename, code }, statsCollection) {
718
752
  let css = options.compilerOptions.css;
719
753
  if (css !== "none") {
720
754
  css = isCssString ? "injected" : true;
@@ -750,7 +784,11 @@ async function compileSvelte(options, { filename, code }) {
750
784
  ...compileOptions,
751
785
  ...dynamicCompileOptions
752
786
  } : compileOptions;
787
+ const endStat = statsCollection?.start(filename);
753
788
  const compiled = (0, import_compiler3.compile)(finalCode, finalCompileOptions);
789
+ if (endStat) {
790
+ endStat();
791
+ }
754
792
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
755
793
  }
756
794
 
@@ -1012,7 +1050,7 @@ function validateSourceMapOutputWrapper(group, i) {
1012
1050
 
1013
1051
  // src/utils/options.ts
1014
1052
  var import_deepmerge = __toESM(require("deepmerge"), 1);
1015
- var import_vitefu2 = require("vitefu");
1053
+ var import_vitefu3 = require("vitefu");
1016
1054
 
1017
1055
  // src/utils/dependencies.ts
1018
1056
  var import_path3 = __toESM(require("path"), 1);
@@ -1076,6 +1114,165 @@ function isCommonDepWithoutSvelteField(dependency) {
1076
1114
  );
1077
1115
  }
1078
1116
 
1117
+ // src/utils/vite-plugin-svelte-stats.ts
1118
+ var import_vitefu2 = require("vitefu");
1119
+ var import_fs3 = require("fs");
1120
+ var import_path4 = require("path");
1121
+ var import_perf_hooks = require("perf_hooks");
1122
+ var import_vite3 = require("vite");
1123
+ var defaultCollectionOptions = {
1124
+ logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
1125
+ logResult: () => true
1126
+ };
1127
+ function humanDuration(n) {
1128
+ return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1e3).toFixed(2)}s`;
1129
+ }
1130
+ function formatPackageStats(pkgStats) {
1131
+ const statLines = pkgStats.map((pkgStat) => {
1132
+ const duration = pkgStat.duration;
1133
+ const avg = duration / pkgStat.files;
1134
+ return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
1135
+ });
1136
+ statLines.unshift(["package", "files", "time", "avg"]);
1137
+ const columnWidths = statLines.reduce(
1138
+ (widths, row) => {
1139
+ for (let i = 0; i < row.length; i++) {
1140
+ const cell = row[i];
1141
+ if (widths[i] < cell.length) {
1142
+ widths[i] = cell.length;
1143
+ }
1144
+ }
1145
+ return widths;
1146
+ },
1147
+ statLines[0].map(() => 0)
1148
+ );
1149
+ const table = statLines.map(
1150
+ (row) => row.map((cell, i) => {
1151
+ if (i === 0) {
1152
+ return cell.padEnd(columnWidths[i], " ");
1153
+ } else {
1154
+ return cell.padStart(columnWidths[i], " ");
1155
+ }
1156
+ }).join(" ")
1157
+ ).join("\n");
1158
+ return table;
1159
+ }
1160
+ async function getClosestNamedPackage(file) {
1161
+ let name = "$unknown";
1162
+ let path9 = await (0, import_vitefu2.findClosestPkgJsonPath)(file, (pkgPath) => {
1163
+ const pkg = JSON.parse((0, import_fs3.readFileSync)(pkgPath, "utf-8"));
1164
+ if (pkg.name != null) {
1165
+ name = pkg.name;
1166
+ return true;
1167
+ }
1168
+ return false;
1169
+ });
1170
+ path9 = (0, import_vite3.normalizePath)((0, import_path4.dirname)(path9 ?? file)) + "/";
1171
+ return { name, path: path9 };
1172
+ }
1173
+ var VitePluginSvelteStats = class {
1174
+ constructor() {
1175
+ this._packages = [];
1176
+ this._collections = [];
1177
+ }
1178
+ startCollection(name, opts) {
1179
+ const options = {
1180
+ ...defaultCollectionOptions,
1181
+ ...opts
1182
+ };
1183
+ const stats = [];
1184
+ const collectionStart = import_perf_hooks.performance.now();
1185
+ const _this = this;
1186
+ let hasLoggedProgress = false;
1187
+ const collection = {
1188
+ name,
1189
+ options,
1190
+ stats,
1191
+ collectionStart,
1192
+ finished: false,
1193
+ start(file) {
1194
+ if (collection.finished) {
1195
+ throw new Error("called after finish() has been used");
1196
+ }
1197
+ file = (0, import_vite3.normalizePath)(file);
1198
+ const start = import_perf_hooks.performance.now();
1199
+ const stat = { file, start, end: start };
1200
+ return () => {
1201
+ const now = import_perf_hooks.performance.now();
1202
+ stat.end = now;
1203
+ stats.push(stat);
1204
+ if (!hasLoggedProgress && options.logInProgress(collection, now)) {
1205
+ hasLoggedProgress = true;
1206
+ log.info(`${name} in progress ...`);
1207
+ }
1208
+ };
1209
+ },
1210
+ async finish() {
1211
+ await _this._finish(collection);
1212
+ }
1213
+ };
1214
+ _this._collections.push(collection);
1215
+ return collection;
1216
+ }
1217
+ async finishAll() {
1218
+ await Promise.all(this._collections.map((c) => c.finish()));
1219
+ }
1220
+ async _finish(collection) {
1221
+ try {
1222
+ collection.finished = true;
1223
+ const now = import_perf_hooks.performance.now();
1224
+ collection.duration = now - collection.collectionStart;
1225
+ const logResult = collection.options.logResult(collection);
1226
+ if (logResult) {
1227
+ await this._aggregateStatsResult(collection);
1228
+ log.info(`${collection.name} done.`, formatPackageStats(collection.packageStats));
1229
+ }
1230
+ const index = this._collections.indexOf(collection);
1231
+ this._collections.splice(index, 1);
1232
+ collection.stats.length = 0;
1233
+ collection.stats = [];
1234
+ if (collection.packageStats) {
1235
+ collection.packageStats.length = 0;
1236
+ collection.packageStats = [];
1237
+ }
1238
+ collection.start = () => () => {
1239
+ };
1240
+ collection.finish = () => {
1241
+ };
1242
+ } catch (e) {
1243
+ log.debug.once(`failed to finish stats for ${collection.name}`, e);
1244
+ }
1245
+ }
1246
+ async _aggregateStatsResult(collection) {
1247
+ const stats = collection.stats;
1248
+ for (const stat of stats) {
1249
+ let pkg = this._packages.find((p) => stat.file.startsWith(p.path));
1250
+ if (!pkg) {
1251
+ pkg = await getClosestNamedPackage(stat.file);
1252
+ this._packages.push(pkg);
1253
+ }
1254
+ stat.pkg = pkg.name;
1255
+ }
1256
+ const grouped = {};
1257
+ stats.forEach((stat) => {
1258
+ const pkg = stat.pkg;
1259
+ let group = grouped[pkg];
1260
+ if (!group) {
1261
+ group = grouped[pkg] = {
1262
+ files: 0,
1263
+ duration: 0,
1264
+ pkg
1265
+ };
1266
+ }
1267
+ group.files += 1;
1268
+ group.duration += stat.end - stat.start;
1269
+ });
1270
+ const groups = Object.values(grouped);
1271
+ groups.sort((a, b) => b.duration - a.duration);
1272
+ collection.packageStats = groups;
1273
+ }
1274
+ };
1275
+
1079
1276
  // src/utils/options.ts
1080
1277
  var cssAsString = atLeastSvelte("3.53.0");
1081
1278
  var allowedPluginOptions = /* @__PURE__ */ new Set([
@@ -1161,16 +1358,18 @@ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1161
1358
  ...viteUserConfig,
1162
1359
  root: resolveViteRoot(viteUserConfig)
1163
1360
  };
1361
+ const isBuild = viteEnv.command === "build";
1164
1362
  const defaultOptions = {
1165
1363
  extensions: [".svelte"],
1166
- emitCss: true
1364
+ emitCss: true,
1365
+ prebundleSvelteLibraries: !isBuild
1167
1366
  };
1168
1367
  const svelteConfig = convertPluginOptions(
1169
1368
  await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
1170
1369
  );
1171
1370
  const extraOptions = {
1172
1371
  root: viteConfigWithResolvedRoot.root,
1173
- isBuild: viteEnv.command === "build",
1372
+ isBuild,
1174
1373
  isServe: viteEnv.command === "serve",
1175
1374
  isDebug: process.env.DEBUG != null
1176
1375
  };
@@ -1217,6 +1416,12 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1217
1416
  addExtraPreprocessors(merged, viteConfig);
1218
1417
  enforceOptionsForHmr(merged);
1219
1418
  enforceOptionsForProduction(merged);
1419
+ const isLogLevelInfo = [void 0, "info"].includes(viteConfig.logLevel);
1420
+ const disableCompileStats = merged.experimental?.disableCompileStats;
1421
+ const statsEnabled = disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? "build" : "dev");
1422
+ if (statsEnabled && isLogLevelInfo) {
1423
+ merged.stats = new VitePluginSvelteStats();
1424
+ }
1220
1425
  return merged;
1221
1426
  }
1222
1427
  function enforceOptionsForHmr(options) {
@@ -1307,13 +1512,14 @@ function handleDeprecatedOptions(options) {
1307
1512
  }
1308
1513
  }
1309
1514
  function resolveViteRoot(viteConfig) {
1310
- return (0, import_vite3.normalizePath)(viteConfig.root ? import_path4.default.resolve(viteConfig.root) : process.cwd());
1515
+ return (0, import_vite4.normalizePath)(viteConfig.root ? import_path5.default.resolve(viteConfig.root) : process.cwd());
1311
1516
  }
1312
1517
  async function buildExtraViteConfig(options, config) {
1313
1518
  const extraViteConfig = {
1314
1519
  resolve: {
1315
1520
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1316
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1521
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1522
+ conditions: [...SVELTE_EXPORT_CONDITIONS]
1317
1523
  }
1318
1524
  };
1319
1525
  const extraSvelteConfig = buildExtraConfigForSvelte(config);
@@ -1322,13 +1528,13 @@ async function buildExtraViteConfig(options, config) {
1322
1528
  include: [
1323
1529
  ...extraSvelteConfig.optimizeDeps.include,
1324
1530
  ...extraDepsConfig.optimizeDeps.include.filter(
1325
- (dep) => !(0, import_vitefu2.isDepExcluded)(dep, extraSvelteConfig.optimizeDeps.exclude)
1531
+ (dep) => !(0, import_vitefu3.isDepExcluded)(dep, extraSvelteConfig.optimizeDeps.exclude)
1326
1532
  )
1327
1533
  ],
1328
1534
  exclude: [
1329
1535
  ...extraSvelteConfig.optimizeDeps.exclude,
1330
1536
  ...extraDepsConfig.optimizeDeps.exclude.filter(
1331
- (dep) => !(0, import_vitefu2.isDepIncluded)(dep, extraSvelteConfig.optimizeDeps.include)
1537
+ (dep) => !(0, import_vitefu3.isDepIncluded)(dep, extraSvelteConfig.optimizeDeps.include)
1332
1538
  )
1333
1539
  ]
1334
1540
  };
@@ -1336,36 +1542,76 @@ async function buildExtraViteConfig(options, config) {
1336
1542
  external: [
1337
1543
  ...extraSvelteConfig.ssr.external,
1338
1544
  ...extraDepsConfig.ssr.external.filter(
1339
- (dep) => !(0, import_vitefu2.isDepNoExternaled)(dep, extraSvelteConfig.ssr.noExternal)
1545
+ (dep) => !(0, import_vitefu3.isDepNoExternaled)(dep, extraSvelteConfig.ssr.noExternal)
1340
1546
  )
1341
1547
  ],
1342
1548
  noExternal: [
1343
1549
  ...extraSvelteConfig.ssr.noExternal,
1344
1550
  ...extraDepsConfig.ssr.noExternal.filter(
1345
- (dep) => !(0, import_vitefu2.isDepExternaled)(dep, extraSvelteConfig.ssr.external)
1551
+ (dep) => !(0, import_vitefu3.isDepExternaled)(dep, extraSvelteConfig.ssr.external)
1346
1552
  )
1347
1553
  ]
1348
1554
  };
1349
1555
  if (options.prebundleSvelteLibraries) {
1350
- extraViteConfig.optimizeDeps.extensions = options.extensions ?? [".svelte"];
1351
- extraViteConfig.optimizeDeps.esbuildOptions = {
1352
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1353
- } }]
1556
+ extraViteConfig.optimizeDeps = {
1557
+ ...extraViteConfig.optimizeDeps,
1558
+ extensions: options.extensions ?? [".svelte"],
1559
+ esbuildOptions: {
1560
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1561
+ } }]
1562
+ }
1354
1563
  };
1355
1564
  }
1356
1565
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1357
1566
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1358
1567
  extraViteConfig.experimental = { hmrPartialAccept: true };
1359
1568
  }
1569
+ validateViteConfig(extraViteConfig, config, options);
1360
1570
  return extraViteConfig;
1361
1571
  }
1572
+ function validateViteConfig(extraViteConfig, config, options) {
1573
+ const { prebundleSvelteLibraries, isBuild } = options;
1574
+ if (prebundleSvelteLibraries) {
1575
+ const isEnabled = (option) => option !== true && option !== (isBuild ? "build" : "dev");
1576
+ const logWarning = (name, value, recommendation) => log.warn.once(
1577
+ `Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
1578
+ value
1579
+ )}\` ${isBuild ? "during build." : "."} ${recommendation}`
1580
+ );
1581
+ const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? "build";
1582
+ const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
1583
+ if (!isBuild && !isOptimizeDepsEnabled) {
1584
+ logWarning(
1585
+ "optimizeDeps.disabled",
1586
+ viteOptimizeDepsDisabled,
1587
+ 'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
1588
+ );
1589
+ extraViteConfig.optimizeDeps.disabled = "build";
1590
+ } else if (isBuild && isOptimizeDepsEnabled) {
1591
+ logWarning(
1592
+ "optimizeDeps.disabled",
1593
+ viteOptimizeDepsDisabled,
1594
+ "Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors."
1595
+ );
1596
+ }
1597
+ }
1598
+ }
1362
1599
  async function buildExtraConfigForDependencies(options, config) {
1363
- const depsConfig = await (0, import_vitefu2.crawlFrameworkPkgs)({
1600
+ const depsConfig = await (0, import_vitefu3.crawlFrameworkPkgs)({
1364
1601
  root: options.root,
1365
1602
  isBuild: options.isBuild,
1366
1603
  viteUserConfig: config,
1367
1604
  isFrameworkPkgByJson(pkgJson) {
1368
- return !!pkgJson.svelte;
1605
+ let hasSvelteCondition = false;
1606
+ if (typeof pkgJson.exports === "object") {
1607
+ JSON.stringify(pkgJson.exports, (key, value) => {
1608
+ if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
1609
+ hasSvelteCondition = true;
1610
+ }
1611
+ return value;
1612
+ });
1613
+ }
1614
+ return hasSvelteCondition || !!pkgJson.svelte;
1369
1615
  },
1370
1616
  isSemiFrameworkPkgByJson(pkgJson) {
1371
1617
  return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
@@ -1384,7 +1630,7 @@ async function buildExtraConfigForDependencies(options, config) {
1384
1630
  depsConfig.optimizeDeps.exclude = [];
1385
1631
  const userExclude = config.optimizeDeps?.exclude;
1386
1632
  depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1387
- return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => (0, import_vitefu2.isDepExcluded)(d.trim(), userExclude));
1633
+ return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => (0, import_vitefu3.isDepExcluded)(d.trim(), userExclude));
1388
1634
  });
1389
1635
  }
1390
1636
  if (options.disableDependencyReinclusion === true) {
@@ -1406,7 +1652,7 @@ async function buildExtraConfigForDependencies(options, config) {
1406
1652
  function buildExtraConfigForSvelte(config) {
1407
1653
  const include = [];
1408
1654
  const exclude = ["svelte-hmr"];
1409
- if (!(0, import_vitefu2.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1655
+ if (!(0, import_vitefu3.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1410
1656
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1411
1657
  log.debug(
1412
1658
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
@@ -1417,7 +1663,7 @@ function buildExtraConfigForSvelte(config) {
1417
1663
  }
1418
1664
  const noExternal = [];
1419
1665
  const external = [];
1420
- if (!(0, import_vitefu2.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1666
+ if (!(0, import_vitefu3.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1421
1667
  noExternal.push("svelte", /^svelte\//);
1422
1668
  }
1423
1669
  return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
@@ -1431,114 +1677,9 @@ function patchResolvedViteConfig(viteConfig, options) {
1431
1677
  }
1432
1678
  }
1433
1679
 
1434
- // src/utils/vite-plugin-svelte-cache.ts
1435
- var VitePluginSvelteCache = class {
1436
- constructor() {
1437
- this._css = /* @__PURE__ */ new Map();
1438
- this._js = /* @__PURE__ */ new Map();
1439
- this._dependencies = /* @__PURE__ */ new Map();
1440
- this._dependants = /* @__PURE__ */ new Map();
1441
- this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1442
- this._errors = /* @__PURE__ */ new Map();
1443
- }
1444
- update(compileData) {
1445
- this._errors.delete(compileData.normalizedFilename);
1446
- this.updateCSS(compileData);
1447
- this.updateJS(compileData);
1448
- this.updateDependencies(compileData);
1449
- }
1450
- has(svelteRequest) {
1451
- const id = svelteRequest.normalizedFilename;
1452
- return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1453
- }
1454
- setError(svelteRequest, error) {
1455
- this.remove(svelteRequest, true);
1456
- this._errors.set(svelteRequest.normalizedFilename, error);
1457
- }
1458
- updateCSS(compileData) {
1459
- this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1460
- }
1461
- updateJS(compileData) {
1462
- if (!compileData.ssr) {
1463
- this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1464
- }
1465
- }
1466
- updateDependencies(compileData) {
1467
- const id = compileData.normalizedFilename;
1468
- const prevDependencies = this._dependencies.get(id) || [];
1469
- const dependencies = compileData.dependencies;
1470
- this._dependencies.set(id, dependencies);
1471
- const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1472
- const added = dependencies.filter((d) => !prevDependencies.includes(d));
1473
- added.forEach((d) => {
1474
- if (!this._dependants.has(d)) {
1475
- this._dependants.set(d, /* @__PURE__ */ new Set());
1476
- }
1477
- this._dependants.get(d).add(compileData.filename);
1478
- });
1479
- removed.forEach((d) => {
1480
- this._dependants.get(d).delete(compileData.filename);
1481
- });
1482
- }
1483
- remove(svelteRequest, keepDependencies = false) {
1484
- const id = svelteRequest.normalizedFilename;
1485
- let removed = false;
1486
- if (this._errors.delete(id)) {
1487
- removed = true;
1488
- }
1489
- if (this._js.delete(id)) {
1490
- removed = true;
1491
- }
1492
- if (this._css.delete(id)) {
1493
- removed = true;
1494
- }
1495
- if (!keepDependencies) {
1496
- const dependencies = this._dependencies.get(id);
1497
- if (dependencies) {
1498
- removed = true;
1499
- dependencies.forEach((d) => {
1500
- const dependants = this._dependants.get(d);
1501
- if (dependants && dependants.has(svelteRequest.filename)) {
1502
- dependants.delete(svelteRequest.filename);
1503
- }
1504
- });
1505
- this._dependencies.delete(id);
1506
- }
1507
- }
1508
- return removed;
1509
- }
1510
- getCSS(svelteRequest) {
1511
- return this._css.get(svelteRequest.normalizedFilename);
1512
- }
1513
- getJS(svelteRequest) {
1514
- if (!svelteRequest.ssr) {
1515
- return this._js.get(svelteRequest.normalizedFilename);
1516
- }
1517
- }
1518
- getError(svelteRequest) {
1519
- return this._errors.get(svelteRequest.normalizedFilename);
1520
- }
1521
- getDependants(path9) {
1522
- const dependants = this._dependants.get(path9);
1523
- return dependants ? [...dependants] : [];
1524
- }
1525
- getResolvedSvelteField(name, importer) {
1526
- return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1527
- }
1528
- setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1529
- this._resolvedSvelteFields.set(
1530
- this._getResolvedSvelteFieldKey(importee, importer),
1531
- resolvedSvelte
1532
- );
1533
- }
1534
- _getResolvedSvelteFieldKey(importee, importer) {
1535
- return importer ? `${importer} > ${importee}` : importee;
1536
- }
1537
- };
1538
-
1539
1680
  // src/utils/watch.ts
1540
- var import_fs3 = __toESM(require("fs"), 1);
1541
- var import_path5 = __toESM(require("path"), 1);
1681
+ var import_fs4 = __toESM(require("fs"), 1);
1682
+ var import_path6 = __toESM(require("path"), 1);
1542
1683
  function setupWatchers(options, cache, requestParser) {
1543
1684
  const { server, configFile: svelteConfigFile } = options;
1544
1685
  if (!server) {
@@ -1549,7 +1690,7 @@ function setupWatchers(options, cache, requestParser) {
1549
1690
  const emitChangeEventOnDependants = (filename) => {
1550
1691
  const dependants = cache.getDependants(filename);
1551
1692
  dependants.forEach((dependant) => {
1552
- if (import_fs3.default.existsSync(dependant)) {
1693
+ if (import_fs4.default.existsSync(dependant)) {
1553
1694
  log.debug(
1554
1695
  `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1555
1696
  );
@@ -1585,7 +1726,7 @@ function setupWatchers(options, cache, requestParser) {
1585
1726
  unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
1586
1727
  };
1587
1728
  if (svelteConfigFile !== false) {
1588
- const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path5.default.join(root, cfg));
1729
+ const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path6.default.join(root, cfg));
1589
1730
  const restartOnConfigAdd = (filename) => {
1590
1731
  if (possibleSvelteConfigs.includes(filename)) {
1591
1732
  triggerViteRestart(filename);
@@ -1610,13 +1751,13 @@ function setupWatchers(options, cache, requestParser) {
1610
1751
  });
1611
1752
  }
1612
1753
  function ensureWatchedFile(watcher, file, root) {
1613
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs3.default.existsSync(file)) {
1614
- watcher.add(import_path5.default.resolve(file));
1754
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs4.default.existsSync(file)) {
1755
+ watcher.add(import_path6.default.resolve(file));
1615
1756
  }
1616
1757
  }
1617
1758
 
1618
1759
  // src/utils/resolve.ts
1619
- var import_path6 = __toESM(require("path"), 1);
1760
+ var import_path7 = __toESM(require("path"), 1);
1620
1761
  var import_module2 = require("module");
1621
1762
  async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1622
1763
  if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
@@ -1628,7 +1769,7 @@ async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1628
1769
  if (pkgData) {
1629
1770
  const { pkg, dir } = pkgData;
1630
1771
  if (pkg.svelte) {
1631
- const result = import_path6.default.resolve(dir, pkg.svelte);
1772
+ const result = import_path7.default.resolve(dir, pkg.svelte);
1632
1773
  cache.setResolvedSvelteField(importee, importer, result);
1633
1774
  return result;
1634
1775
  }
@@ -1639,7 +1780,7 @@ function isNodeInternal(importee) {
1639
1780
  return importee.startsWith("node:") || import_module2.builtinModules.includes(importee);
1640
1781
  }
1641
1782
  function isBareImport(importee) {
1642
- if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path6.default.isAbsolute(importee)) {
1783
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path7.default.isAbsolute(importee)) {
1643
1784
  return false;
1644
1785
  }
1645
1786
  const parts = importee.split("/");
@@ -1654,8 +1795,8 @@ function isBareImport(importee) {
1654
1795
  }
1655
1796
 
1656
1797
  // src/utils/optimizer.ts
1657
- var import_fs4 = require("fs");
1658
- var import_path7 = __toESM(require("path"), 1);
1798
+ var import_fs5 = require("fs");
1799
+ var import_path8 = __toESM(require("path"), 1);
1659
1800
  var PREBUNDLE_SENSITIVE_OPTIONS = [
1660
1801
  "compilerOptions",
1661
1802
  "configFile",
@@ -1666,17 +1807,17 @@ var PREBUNDLE_SENSITIVE_OPTIONS = [
1666
1807
  ];
1667
1808
  async function saveSvelteMetadata(cacheDir, options) {
1668
1809
  const svelteMetadata = generateSvelteMetadata(options);
1669
- const svelteMetadataPath = import_path7.default.resolve(cacheDir, "_svelte_metadata.json");
1810
+ const svelteMetadataPath = import_path8.default.resolve(cacheDir, "_svelte_metadata.json");
1670
1811
  const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => {
1671
1812
  return typeof value === "function" ? value.toString() : value;
1672
1813
  });
1673
1814
  let existingSvelteMetadata;
1674
1815
  try {
1675
- existingSvelteMetadata = await import_fs4.promises.readFile(svelteMetadataPath, "utf8");
1816
+ existingSvelteMetadata = await import_fs5.promises.readFile(svelteMetadataPath, "utf8");
1676
1817
  } catch {
1677
1818
  }
1678
- await import_fs4.promises.mkdir(cacheDir, { recursive: true });
1679
- await import_fs4.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1819
+ await import_fs5.promises.mkdir(cacheDir, { recursive: true });
1820
+ await import_fs5.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1680
1821
  return currentSvelteMetadata !== existingSvelteMetadata;
1681
1822
  }
1682
1823
  function generateSvelteMetadata(options) {
@@ -1688,10 +1829,10 @@ function generateSvelteMetadata(options) {
1688
1829
  }
1689
1830
 
1690
1831
  // src/ui/inspector/plugin.ts
1691
- var import_vite4 = require("vite");
1692
- var import_path8 = __toESM(require("path"), 1);
1832
+ var import_vite5 = require("vite");
1833
+ var import_path9 = __toESM(require("path"), 1);
1693
1834
  var import_url2 = require("url");
1694
- var import_fs5 = __toESM(require("fs"), 1);
1835
+ var import_fs6 = __toESM(require("fs"), 1);
1695
1836
 
1696
1837
  // src/ui/inspector/utils.ts
1697
1838
  var FS_PREFIX = `/@fs/`;
@@ -1716,7 +1857,7 @@ var defaultInspectorOptions = {
1716
1857
  customStyles: true
1717
1858
  };
1718
1859
  function getInspectorPath() {
1719
- const pluginPath = (0, import_vite4.normalizePath)(import_path8.default.dirname((0, import_url2.fileURLToPath)(importMetaUrl)));
1860
+ const pluginPath = (0, import_vite5.normalizePath)(import_path9.default.dirname((0, import_url2.fileURLToPath)(importMetaUrl)));
1720
1861
  return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, "/vite-plugin-svelte/src/ui/inspector/");
1721
1862
  }
1722
1863
  function svelteInspector() {
@@ -1742,7 +1883,7 @@ function svelteInspector() {
1742
1883
  disabled = true;
1743
1884
  } else {
1744
1885
  if (vps.api.options.kit && !inspectorOptions.appendTo) {
1745
- const out_dir = import_path8.default.basename(vps.api.options.kit.outDir || ".svelte-kit");
1886
+ const out_dir = import_path9.default.basename(vps.api.options.kit.outDir || ".svelte-kit");
1746
1887
  inspectorOptions.appendTo = `${out_dir}/generated/root.svelte`;
1747
1888
  }
1748
1889
  appendTo = inspectorOptions.appendTo;
@@ -1768,8 +1909,8 @@ function svelteInspector() {
1768
1909
  return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1769
1910
  } else if (id.startsWith(inspectorPath)) {
1770
1911
  const file = idToFile(id);
1771
- if (import_fs5.default.existsSync(file)) {
1772
- return await import_fs5.default.promises.readFile(file, "utf-8");
1912
+ if (import_fs6.default.existsSync(file)) {
1913
+ return await import_fs6.default.promises.readFile(file, "utf-8");
1773
1914
  } else {
1774
1915
  log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1775
1916
  }
@@ -1805,6 +1946,111 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1805
1946
  };
1806
1947
  }
1807
1948
 
1949
+ // src/utils/vite-plugin-svelte-cache.ts
1950
+ var VitePluginSvelteCache = class {
1951
+ constructor() {
1952
+ this._css = /* @__PURE__ */ new Map();
1953
+ this._js = /* @__PURE__ */ new Map();
1954
+ this._dependencies = /* @__PURE__ */ new Map();
1955
+ this._dependants = /* @__PURE__ */ new Map();
1956
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1957
+ this._errors = /* @__PURE__ */ new Map();
1958
+ }
1959
+ update(compileData) {
1960
+ this._errors.delete(compileData.normalizedFilename);
1961
+ this.updateCSS(compileData);
1962
+ this.updateJS(compileData);
1963
+ this.updateDependencies(compileData);
1964
+ }
1965
+ has(svelteRequest) {
1966
+ const id = svelteRequest.normalizedFilename;
1967
+ return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1968
+ }
1969
+ setError(svelteRequest, error) {
1970
+ this.remove(svelteRequest, true);
1971
+ this._errors.set(svelteRequest.normalizedFilename, error);
1972
+ }
1973
+ updateCSS(compileData) {
1974
+ this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1975
+ }
1976
+ updateJS(compileData) {
1977
+ if (!compileData.ssr) {
1978
+ this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1979
+ }
1980
+ }
1981
+ updateDependencies(compileData) {
1982
+ const id = compileData.normalizedFilename;
1983
+ const prevDependencies = this._dependencies.get(id) || [];
1984
+ const dependencies = compileData.dependencies;
1985
+ this._dependencies.set(id, dependencies);
1986
+ const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1987
+ const added = dependencies.filter((d) => !prevDependencies.includes(d));
1988
+ added.forEach((d) => {
1989
+ if (!this._dependants.has(d)) {
1990
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1991
+ }
1992
+ this._dependants.get(d).add(compileData.filename);
1993
+ });
1994
+ removed.forEach((d) => {
1995
+ this._dependants.get(d).delete(compileData.filename);
1996
+ });
1997
+ }
1998
+ remove(svelteRequest, keepDependencies = false) {
1999
+ const id = svelteRequest.normalizedFilename;
2000
+ let removed = false;
2001
+ if (this._errors.delete(id)) {
2002
+ removed = true;
2003
+ }
2004
+ if (this._js.delete(id)) {
2005
+ removed = true;
2006
+ }
2007
+ if (this._css.delete(id)) {
2008
+ removed = true;
2009
+ }
2010
+ if (!keepDependencies) {
2011
+ const dependencies = this._dependencies.get(id);
2012
+ if (dependencies) {
2013
+ removed = true;
2014
+ dependencies.forEach((d) => {
2015
+ const dependants = this._dependants.get(d);
2016
+ if (dependants && dependants.has(svelteRequest.filename)) {
2017
+ dependants.delete(svelteRequest.filename);
2018
+ }
2019
+ });
2020
+ this._dependencies.delete(id);
2021
+ }
2022
+ }
2023
+ return removed;
2024
+ }
2025
+ getCSS(svelteRequest) {
2026
+ return this._css.get(svelteRequest.normalizedFilename);
2027
+ }
2028
+ getJS(svelteRequest) {
2029
+ if (!svelteRequest.ssr) {
2030
+ return this._js.get(svelteRequest.normalizedFilename);
2031
+ }
2032
+ }
2033
+ getError(svelteRequest) {
2034
+ return this._errors.get(svelteRequest.normalizedFilename);
2035
+ }
2036
+ getDependants(path9) {
2037
+ const dependants = this._dependants.get(path9);
2038
+ return dependants ? [...dependants] : [];
2039
+ }
2040
+ getResolvedSvelteField(name, importer) {
2041
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
2042
+ }
2043
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
2044
+ this._resolvedSvelteFields.set(
2045
+ this._getResolvedSvelteFieldKey(importee, importer),
2046
+ resolvedSvelte
2047
+ );
2048
+ }
2049
+ _getResolvedSvelteFieldKey(importee, importer) {
2050
+ return importer ? `${importer} > ${importee}` : importee;
2051
+ }
2052
+ };
2053
+
1808
2054
  // src/index.ts
1809
2055
  function svelte(inlineOptions) {
1810
2056
  if (process.env.DEBUG != null) {
@@ -1869,7 +2115,7 @@ function svelte(inlineOptions) {
1869
2115
  }
1870
2116
  if (viteConfig.assetsInclude(filename)) {
1871
2117
  log.debug(`load returns raw content for ${filename}`);
1872
- return import_fs6.default.readFileSync(filename, "utf-8");
2118
+ return import_fs7.default.readFileSync(filename, "utf-8");
1873
2119
  }
1874
2120
  }
1875
2121
  },
@@ -1903,7 +2149,7 @@ function svelte(inlineOptions) {
1903
2149
  return resolvedSvelteSSR;
1904
2150
  }
1905
2151
  const scan = !!opts?.scan;
1906
- const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !(0, import_vitefu3.isDepExcluded)(importee, viteConfig.optimizeDeps?.exclude ?? []);
2152
+ const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !(0, import_vitefu4.isDepExcluded)(importee, viteConfig.optimizeDeps?.exclude ?? []);
1907
2153
  if (ssr || scan || !isPrebundled) {
1908
2154
  try {
1909
2155
  const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
@@ -1963,6 +2209,9 @@ function svelte(inlineOptions) {
1963
2209
  throw toRollupError(e, options);
1964
2210
  }
1965
2211
  }
2212
+ },
2213
+ async buildEnd() {
2214
+ await options.stats?.finishAll();
1966
2215
  }
1967
2216
  }
1968
2217
  ];