@sveltejs/vite-plugin-svelte 1.2.0 → 1.3.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.
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  });
8
8
 
9
9
  // src/index.ts
10
- import fs8 from "fs";
10
+ import fs7 from "fs";
11
11
  import { isDepExcluded as isDepExcluded2 } from "vitefu";
12
12
 
13
13
  // src/utils/log.ts
@@ -289,81 +289,105 @@ function toSafe(base64) {
289
289
 
290
290
  // src/utils/compile.ts
291
291
  var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
292
- var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
293
- const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
294
- const { emitCss = true } = options;
295
- const dependencies = [];
296
- const compileOptions = {
297
- ...options.compilerOptions,
298
- filename,
299
- generate: ssr ? "ssr" : "dom",
300
- format: "esm"
301
- };
302
- if (options.hot && options.emitCss) {
303
- const hash = `s-${safeBase64Hash(normalizedFilename)}`;
304
- log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
305
- compileOptions.cssHash = () => hash;
306
- }
307
- if (ssr && compileOptions.enableSourcemap !== false) {
308
- if (typeof compileOptions.enableSourcemap === "object") {
309
- compileOptions.enableSourcemap.css = false;
310
- } else {
311
- compileOptions.enableSourcemap = { js: true, css: false };
292
+ var _createCompileSvelte = (makeHot) => {
293
+ let stats;
294
+ return async function compileSvelte2(svelteRequest, code, options) {
295
+ const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
296
+ const { emitCss = true } = options;
297
+ const dependencies = [];
298
+ if (options.stats) {
299
+ if (options.isBuild) {
300
+ if (!stats) {
301
+ stats = options.stats.startCollection(`${ssr ? "ssr" : "dom"} compile`, {
302
+ logInProgress: () => false
303
+ });
304
+ }
305
+ } else {
306
+ if (ssr && !stats) {
307
+ stats = options.stats.startCollection("ssr compile");
308
+ }
309
+ if (!ssr && stats) {
310
+ stats.finish();
311
+ stats = void 0;
312
+ }
313
+ }
312
314
  }
313
- }
314
- let preprocessed;
315
- if (options.preprocess) {
316
- try {
317
- preprocessed = await preprocess(code, options.preprocess, { filename });
318
- } catch (e) {
319
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
320
- throw e;
315
+ const compileOptions = {
316
+ ...options.compilerOptions,
317
+ filename,
318
+ generate: ssr ? "ssr" : "dom",
319
+ format: "esm"
320
+ };
321
+ if (options.hot && options.emitCss) {
322
+ const hash = `s-${safeBase64Hash(normalizedFilename)}`;
323
+ log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
324
+ compileOptions.cssHash = () => hash;
321
325
  }
322
- if (preprocessed.dependencies)
323
- dependencies.push(...preprocessed.dependencies);
324
- if (preprocessed.map)
325
- compileOptions.sourcemap = preprocessed.map;
326
- }
327
- const finalCode = preprocessed ? preprocessed.code : code;
328
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
329
- filename,
330
- code: finalCode,
331
- compileOptions
332
- });
333
- if (dynamicCompileOptions && log.debug.enabled) {
334
- log.debug(
335
- `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
336
- );
337
- }
338
- const finalCompileOptions = dynamicCompileOptions ? {
339
- ...compileOptions,
340
- ...dynamicCompileOptions
341
- } : compileOptions;
342
- const compiled = compile(finalCode, finalCompileOptions);
343
- const hasCss = compiled.css?.code?.trim().length > 0;
344
- if (emitCss && hasCss) {
345
- compiled.js.code += `
326
+ if (ssr && compileOptions.enableSourcemap !== false) {
327
+ if (typeof compileOptions.enableSourcemap === "object") {
328
+ compileOptions.enableSourcemap.css = false;
329
+ } else {
330
+ compileOptions.enableSourcemap = { js: true, css: false };
331
+ }
332
+ }
333
+ let preprocessed;
334
+ if (options.preprocess) {
335
+ try {
336
+ preprocessed = await preprocess(code, options.preprocess, { filename });
337
+ } catch (e) {
338
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
339
+ throw e;
340
+ }
341
+ if (preprocessed.dependencies)
342
+ dependencies.push(...preprocessed.dependencies);
343
+ if (preprocessed.map)
344
+ compileOptions.sourcemap = preprocessed.map;
345
+ }
346
+ const finalCode = preprocessed ? preprocessed.code : code;
347
+ const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
348
+ filename,
349
+ code: finalCode,
350
+ compileOptions
351
+ });
352
+ if (dynamicCompileOptions && log.debug.enabled) {
353
+ log.debug(
354
+ `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
355
+ );
356
+ }
357
+ const finalCompileOptions = dynamicCompileOptions ? {
358
+ ...compileOptions,
359
+ ...dynamicCompileOptions
360
+ } : compileOptions;
361
+ const endStat = stats?.start(filename);
362
+ const compiled = compile(finalCode, finalCompileOptions);
363
+ if (endStat) {
364
+ endStat();
365
+ }
366
+ const hasCss = compiled.css?.code?.trim().length > 0;
367
+ if (emitCss && hasCss) {
368
+ compiled.js.code += `
346
369
  import ${JSON.stringify(cssId)};
347
370
  `;
348
- }
349
- if (!ssr && makeHot) {
350
- compiled.js.code = makeHot({
351
- id: filename,
352
- compiledCode: compiled.js.code,
353
- hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
371
+ }
372
+ if (!ssr && makeHot) {
373
+ compiled.js.code = makeHot({
374
+ id: filename,
375
+ compiledCode: compiled.js.code,
376
+ hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
377
+ compiled,
378
+ originalCode: code,
379
+ compileOptions: finalCompileOptions
380
+ });
381
+ }
382
+ compiled.js.dependencies = dependencies;
383
+ return {
384
+ filename,
385
+ normalizedFilename,
386
+ lang: code.match(scriptLangRE)?.[1] || "js",
354
387
  compiled,
355
- originalCode: code,
356
- compileOptions: finalCompileOptions
357
- });
358
- }
359
- compiled.js.dependencies = dependencies;
360
- return {
361
- filename,
362
- normalizedFilename,
363
- lang: code.match(scriptLangRE)?.[1] || "js",
364
- compiled,
365
- ssr,
366
- dependencies
388
+ ssr,
389
+ dependencies
390
+ };
367
391
  };
368
392
  };
369
393
  function buildMakeHot(options) {
@@ -571,12 +595,13 @@ var SVELTE_HMR_IMPORTS = [
571
595
  "svelte-hmr/runtime/proxy-adapter-dom.js",
572
596
  "svelte-hmr"
573
597
  ];
598
+ var SVELTE_EXPORT_CONDITIONS = ["svelte"];
574
599
 
575
600
  // src/utils/options.ts
576
601
  import path4 from "path";
577
602
 
578
603
  // src/utils/esbuild.ts
579
- import { promises as fs3 } from "fs";
604
+ import { readFileSync } from "fs";
580
605
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
581
606
 
582
607
  // src/utils/error.ts
@@ -673,19 +698,28 @@ function esbuildSveltePlugin(options) {
673
698
  return;
674
699
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
675
700
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
701
+ let statsCollection;
702
+ build.onStart(() => {
703
+ statsCollection = options.stats?.startCollection("prebundle libraries", {
704
+ logResult: (c) => c.stats.length > 1
705
+ });
706
+ });
676
707
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
677
- const code = await fs3.readFile(filename, "utf8");
708
+ const code = readFileSync(filename, "utf8");
678
709
  try {
679
- const contents = await compileSvelte(options, { filename, code });
710
+ const contents = await compileSvelte(options, { filename, code }, statsCollection);
680
711
  return { contents };
681
712
  } catch (e) {
682
713
  return { errors: [toESBuildError(e, options)] };
683
714
  }
684
715
  });
716
+ build.onEnd(() => {
717
+ statsCollection?.finish();
718
+ });
685
719
  }
686
720
  };
687
721
  }
688
- async function compileSvelte(options, { filename, code }) {
722
+ async function compileSvelte(options, { filename, code }, statsCollection) {
689
723
  let css = options.compilerOptions.css;
690
724
  if (css !== "none") {
691
725
  css = isCssString ? "injected" : true;
@@ -721,7 +755,11 @@ async function compileSvelte(options, { filename, code }) {
721
755
  ...compileOptions,
722
756
  ...dynamicCompileOptions
723
757
  } : compileOptions;
758
+ const endStat = statsCollection?.start(filename);
724
759
  const compiled = compile2(finalCode, finalCompileOptions);
760
+ if (endStat) {
761
+ endStat();
762
+ }
725
763
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
726
764
  }
727
765
 
@@ -993,7 +1031,7 @@ import {
993
1031
 
994
1032
  // src/utils/dependencies.ts
995
1033
  import path3 from "path";
996
- import fs4 from "fs/promises";
1034
+ import fs3 from "fs/promises";
997
1035
  import { findDepPkgJsonPath } from "vitefu";
998
1036
  async function resolveDependencyData(dep, parent) {
999
1037
  const depDataPath = await findDepPkgJsonPath(dep, parent);
@@ -1002,7 +1040,7 @@ async function resolveDependencyData(dep, parent) {
1002
1040
  try {
1003
1041
  return {
1004
1042
  dir: path3.dirname(depDataPath),
1005
- pkg: JSON.parse(await fs4.readFile(depDataPath, "utf-8"))
1043
+ pkg: JSON.parse(await fs3.readFile(depDataPath, "utf-8"))
1006
1044
  };
1007
1045
  } catch {
1008
1046
  return void 0;
@@ -1053,6 +1091,159 @@ function isCommonDepWithoutSvelteField(dependency) {
1053
1091
  );
1054
1092
  }
1055
1093
 
1094
+ // src/utils/vite-plugin-svelte-stats.ts
1095
+ import { findClosestPkgJsonPath } from "vitefu";
1096
+ import { readFileSync as readFileSync2 } from "fs";
1097
+ import { performance } from "perf_hooks";
1098
+ var defaultCollectionOptions = {
1099
+ logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
1100
+ logResult: () => true
1101
+ };
1102
+ function humanDuration(n) {
1103
+ return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1e3).toFixed(2)}s`;
1104
+ }
1105
+ function formatPackageStats(pkgStats) {
1106
+ const statLines = pkgStats.map((pkgStat) => {
1107
+ const duration = pkgStat.duration;
1108
+ const avg = duration / pkgStat.files;
1109
+ return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
1110
+ });
1111
+ statLines.unshift(["package", "files", "time", "avg"]);
1112
+ const columnWidths = statLines.reduce(
1113
+ (widths, row) => {
1114
+ for (let i = 0; i < row.length; i++) {
1115
+ const cell = row[i];
1116
+ if (widths[i] < cell.length) {
1117
+ widths[i] = cell.length;
1118
+ }
1119
+ }
1120
+ return widths;
1121
+ },
1122
+ statLines[0].map(() => 0)
1123
+ );
1124
+ const table = statLines.map(
1125
+ (row) => row.map((cell, i) => {
1126
+ if (i === 0) {
1127
+ return cell.padEnd(columnWidths[i], " ");
1128
+ } else {
1129
+ return cell.padStart(columnWidths[i], " ");
1130
+ }
1131
+ }).join(" ")
1132
+ ).join("\n");
1133
+ return table;
1134
+ }
1135
+ var VitePluginSvelteStats = class {
1136
+ constructor() {
1137
+ this._packages = [];
1138
+ this._collections = [];
1139
+ }
1140
+ startCollection(name, opts) {
1141
+ const options = {
1142
+ ...defaultCollectionOptions,
1143
+ ...opts
1144
+ };
1145
+ const stats = [];
1146
+ const collectionStart = performance.now();
1147
+ const _this = this;
1148
+ let hasLoggedProgress = false;
1149
+ const collection = {
1150
+ name,
1151
+ options,
1152
+ stats,
1153
+ collectionStart,
1154
+ finished: false,
1155
+ start(file) {
1156
+ if (collection.finished) {
1157
+ throw new Error("called after finish() has been used");
1158
+ }
1159
+ const start = performance.now();
1160
+ const stat = { file, start, end: start };
1161
+ return () => {
1162
+ const now = performance.now();
1163
+ stat.end = now;
1164
+ stats.push(stat);
1165
+ if (!hasLoggedProgress && options.logInProgress(collection, now)) {
1166
+ hasLoggedProgress = true;
1167
+ log.info(`${name} in progress ...`);
1168
+ }
1169
+ };
1170
+ },
1171
+ async finish() {
1172
+ await _this._finish(collection);
1173
+ }
1174
+ };
1175
+ _this._collections.push(collection);
1176
+ return collection;
1177
+ }
1178
+ async finishAll() {
1179
+ await Promise.all(this._collections.map((c) => c.finish()));
1180
+ }
1181
+ async _finish(collection) {
1182
+ collection.finished = true;
1183
+ const now = performance.now();
1184
+ collection.duration = now - collection.collectionStart;
1185
+ const logResult = collection.options.logResult(collection);
1186
+ if (logResult) {
1187
+ await this._aggregateStatsResult(collection);
1188
+ log.info(`${collection.name} done.`, formatPackageStats(collection.packageStats));
1189
+ }
1190
+ const index = this._collections.indexOf(collection);
1191
+ this._collections.splice(index, 1);
1192
+ collection.stats.length = 0;
1193
+ collection.stats = [];
1194
+ if (collection.packageStats) {
1195
+ collection.packageStats.length = 0;
1196
+ collection.packageStats = [];
1197
+ }
1198
+ collection.start = () => () => {
1199
+ };
1200
+ collection.finish = () => {
1201
+ };
1202
+ }
1203
+ async _aggregateStatsResult(collection) {
1204
+ const stats = collection.stats;
1205
+ for (const stat of stats) {
1206
+ let pkg = this._packages.find((p) => stat.file.startsWith(p.path));
1207
+ if (!pkg) {
1208
+ let pkgPath = await findClosestPkgJsonPath(stat.file);
1209
+ if (pkgPath) {
1210
+ let path9 = pkgPath?.replace(/package.json$/, "");
1211
+ let name = JSON.parse(readFileSync2(pkgPath, "utf-8")).name;
1212
+ if (!name) {
1213
+ pkgPath = await findClosestPkgJsonPath(path9);
1214
+ if (pkgPath) {
1215
+ path9 = pkgPath?.replace(/package.json$/, "");
1216
+ name = JSON.parse(readFileSync2(pkgPath, "utf-8")).name;
1217
+ }
1218
+ }
1219
+ if (path9 && name) {
1220
+ pkg = { path: path9, name };
1221
+ this._packages.push(pkg);
1222
+ }
1223
+ }
1224
+ }
1225
+ stat.pkg = pkg?.name ?? "$unknown";
1226
+ }
1227
+ const grouped = {};
1228
+ stats.forEach((stat) => {
1229
+ const pkg = stat.pkg;
1230
+ let group = grouped[pkg];
1231
+ if (!group) {
1232
+ group = grouped[pkg] = {
1233
+ files: 0,
1234
+ duration: 0,
1235
+ pkg
1236
+ };
1237
+ }
1238
+ group.files += 1;
1239
+ group.duration += stat.end - stat.start;
1240
+ });
1241
+ const groups = Object.values(grouped);
1242
+ groups.sort((a, b) => b.duration - a.duration);
1243
+ collection.packageStats = groups;
1244
+ }
1245
+ };
1246
+
1056
1247
  // src/utils/options.ts
1057
1248
  var cssAsString = atLeastSvelte("3.53.0");
1058
1249
  var allowedPluginOptions = /* @__PURE__ */ new Set([
@@ -1138,16 +1329,18 @@ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1138
1329
  ...viteUserConfig,
1139
1330
  root: resolveViteRoot(viteUserConfig)
1140
1331
  };
1332
+ const isBuild = viteEnv.command === "build";
1141
1333
  const defaultOptions = {
1142
1334
  extensions: [".svelte"],
1143
- emitCss: true
1335
+ emitCss: true,
1336
+ prebundleSvelteLibraries: !isBuild
1144
1337
  };
1145
1338
  const svelteConfig = convertPluginOptions(
1146
1339
  await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
1147
1340
  );
1148
1341
  const extraOptions = {
1149
1342
  root: viteConfigWithResolvedRoot.root,
1150
- isBuild: viteEnv.command === "build",
1343
+ isBuild,
1151
1344
  isServe: viteEnv.command === "serve",
1152
1345
  isDebug: process.env.DEBUG != null
1153
1346
  };
@@ -1194,6 +1387,12 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1194
1387
  addExtraPreprocessors(merged, viteConfig);
1195
1388
  enforceOptionsForHmr(merged);
1196
1389
  enforceOptionsForProduction(merged);
1390
+ const isLogLevelInfo = [void 0, "info"].includes(viteConfig.logLevel);
1391
+ const disableCompileStats = merged.experimental?.disableCompileStats;
1392
+ const statsEnabled = disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? "build" : "dev");
1393
+ if (statsEnabled && isLogLevelInfo) {
1394
+ merged.stats = new VitePluginSvelteStats();
1395
+ }
1197
1396
  return merged;
1198
1397
  }
1199
1398
  function enforceOptionsForHmr(options) {
@@ -1290,7 +1489,8 @@ async function buildExtraViteConfig(options, config) {
1290
1489
  const extraViteConfig = {
1291
1490
  resolve: {
1292
1491
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1293
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1492
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1493
+ conditions: [...SVELTE_EXPORT_CONDITIONS]
1294
1494
  }
1295
1495
  };
1296
1496
  const extraSvelteConfig = buildExtraConfigForSvelte(config);
@@ -1324,25 +1524,65 @@ async function buildExtraViteConfig(options, config) {
1324
1524
  ]
1325
1525
  };
1326
1526
  if (options.prebundleSvelteLibraries) {
1327
- extraViteConfig.optimizeDeps.extensions = options.extensions ?? [".svelte"];
1328
- extraViteConfig.optimizeDeps.esbuildOptions = {
1329
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1330
- } }]
1527
+ extraViteConfig.optimizeDeps = {
1528
+ ...extraViteConfig.optimizeDeps,
1529
+ extensions: options.extensions ?? [".svelte"],
1530
+ esbuildOptions: {
1531
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1532
+ } }]
1533
+ }
1331
1534
  };
1332
1535
  }
1333
1536
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1334
1537
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1335
1538
  extraViteConfig.experimental = { hmrPartialAccept: true };
1336
1539
  }
1540
+ validateViteConfig(extraViteConfig, config, options);
1337
1541
  return extraViteConfig;
1338
1542
  }
1543
+ function validateViteConfig(extraViteConfig, config, options) {
1544
+ const { prebundleSvelteLibraries, isBuild } = options;
1545
+ if (prebundleSvelteLibraries) {
1546
+ const isEnabled = (option) => option !== true && option !== (isBuild ? "build" : "dev");
1547
+ const logWarning = (name, value, recommendation) => log.warn.once(
1548
+ `Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
1549
+ value
1550
+ )}\` ${isBuild ? "during build." : "."} ${recommendation}`
1551
+ );
1552
+ const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? "build";
1553
+ const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
1554
+ if (!isBuild && !isOptimizeDepsEnabled) {
1555
+ logWarning(
1556
+ "optimizeDeps.disabled",
1557
+ viteOptimizeDepsDisabled,
1558
+ 'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
1559
+ );
1560
+ extraViteConfig.optimizeDeps.disabled = "build";
1561
+ } else if (isBuild && isOptimizeDepsEnabled) {
1562
+ logWarning(
1563
+ "optimizeDeps.disabled",
1564
+ viteOptimizeDepsDisabled,
1565
+ "Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors."
1566
+ );
1567
+ }
1568
+ }
1569
+ }
1339
1570
  async function buildExtraConfigForDependencies(options, config) {
1340
1571
  const depsConfig = await crawlFrameworkPkgs({
1341
1572
  root: options.root,
1342
1573
  isBuild: options.isBuild,
1343
1574
  viteUserConfig: config,
1344
1575
  isFrameworkPkgByJson(pkgJson) {
1345
- return !!pkgJson.svelte;
1576
+ let hasSvelteCondition = false;
1577
+ if (typeof pkgJson.exports === "object") {
1578
+ JSON.stringify(pkgJson.exports, (key, value) => {
1579
+ if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
1580
+ hasSvelteCondition = true;
1581
+ }
1582
+ return value;
1583
+ });
1584
+ }
1585
+ return hasSvelteCondition || !!pkgJson.svelte;
1346
1586
  },
1347
1587
  isSemiFrameworkPkgByJson(pkgJson) {
1348
1588
  return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
@@ -1408,113 +1648,8 @@ function patchResolvedViteConfig(viteConfig, options) {
1408
1648
  }
1409
1649
  }
1410
1650
 
1411
- // src/utils/vite-plugin-svelte-cache.ts
1412
- var VitePluginSvelteCache = class {
1413
- constructor() {
1414
- this._css = /* @__PURE__ */ new Map();
1415
- this._js = /* @__PURE__ */ new Map();
1416
- this._dependencies = /* @__PURE__ */ new Map();
1417
- this._dependants = /* @__PURE__ */ new Map();
1418
- this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1419
- this._errors = /* @__PURE__ */ new Map();
1420
- }
1421
- update(compileData) {
1422
- this._errors.delete(compileData.normalizedFilename);
1423
- this.updateCSS(compileData);
1424
- this.updateJS(compileData);
1425
- this.updateDependencies(compileData);
1426
- }
1427
- has(svelteRequest) {
1428
- const id = svelteRequest.normalizedFilename;
1429
- return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1430
- }
1431
- setError(svelteRequest, error) {
1432
- this.remove(svelteRequest, true);
1433
- this._errors.set(svelteRequest.normalizedFilename, error);
1434
- }
1435
- updateCSS(compileData) {
1436
- this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1437
- }
1438
- updateJS(compileData) {
1439
- if (!compileData.ssr) {
1440
- this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1441
- }
1442
- }
1443
- updateDependencies(compileData) {
1444
- const id = compileData.normalizedFilename;
1445
- const prevDependencies = this._dependencies.get(id) || [];
1446
- const dependencies = compileData.dependencies;
1447
- this._dependencies.set(id, dependencies);
1448
- const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1449
- const added = dependencies.filter((d) => !prevDependencies.includes(d));
1450
- added.forEach((d) => {
1451
- if (!this._dependants.has(d)) {
1452
- this._dependants.set(d, /* @__PURE__ */ new Set());
1453
- }
1454
- this._dependants.get(d).add(compileData.filename);
1455
- });
1456
- removed.forEach((d) => {
1457
- this._dependants.get(d).delete(compileData.filename);
1458
- });
1459
- }
1460
- remove(svelteRequest, keepDependencies = false) {
1461
- const id = svelteRequest.normalizedFilename;
1462
- let removed = false;
1463
- if (this._errors.delete(id)) {
1464
- removed = true;
1465
- }
1466
- if (this._js.delete(id)) {
1467
- removed = true;
1468
- }
1469
- if (this._css.delete(id)) {
1470
- removed = true;
1471
- }
1472
- if (!keepDependencies) {
1473
- const dependencies = this._dependencies.get(id);
1474
- if (dependencies) {
1475
- removed = true;
1476
- dependencies.forEach((d) => {
1477
- const dependants = this._dependants.get(d);
1478
- if (dependants && dependants.has(svelteRequest.filename)) {
1479
- dependants.delete(svelteRequest.filename);
1480
- }
1481
- });
1482
- this._dependencies.delete(id);
1483
- }
1484
- }
1485
- return removed;
1486
- }
1487
- getCSS(svelteRequest) {
1488
- return this._css.get(svelteRequest.normalizedFilename);
1489
- }
1490
- getJS(svelteRequest) {
1491
- if (!svelteRequest.ssr) {
1492
- return this._js.get(svelteRequest.normalizedFilename);
1493
- }
1494
- }
1495
- getError(svelteRequest) {
1496
- return this._errors.get(svelteRequest.normalizedFilename);
1497
- }
1498
- getDependants(path9) {
1499
- const dependants = this._dependants.get(path9);
1500
- return dependants ? [...dependants] : [];
1501
- }
1502
- getResolvedSvelteField(name, importer) {
1503
- return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1504
- }
1505
- setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1506
- this._resolvedSvelteFields.set(
1507
- this._getResolvedSvelteFieldKey(importee, importer),
1508
- resolvedSvelte
1509
- );
1510
- }
1511
- _getResolvedSvelteFieldKey(importee, importer) {
1512
- return importer ? `${importer} > ${importee}` : importee;
1513
- }
1514
- };
1515
-
1516
1651
  // src/utils/watch.ts
1517
- import fs5 from "fs";
1652
+ import fs4 from "fs";
1518
1653
  import path5 from "path";
1519
1654
  function setupWatchers(options, cache, requestParser) {
1520
1655
  const { server, configFile: svelteConfigFile } = options;
@@ -1526,7 +1661,7 @@ function setupWatchers(options, cache, requestParser) {
1526
1661
  const emitChangeEventOnDependants = (filename) => {
1527
1662
  const dependants = cache.getDependants(filename);
1528
1663
  dependants.forEach((dependant) => {
1529
- if (fs5.existsSync(dependant)) {
1664
+ if (fs4.existsSync(dependant)) {
1530
1665
  log.debug(
1531
1666
  `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1532
1667
  );
@@ -1587,7 +1722,7 @@ function setupWatchers(options, cache, requestParser) {
1587
1722
  });
1588
1723
  }
1589
1724
  function ensureWatchedFile(watcher, file, root) {
1590
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs5.existsSync(file)) {
1725
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs4.existsSync(file)) {
1591
1726
  watcher.add(path5.resolve(file));
1592
1727
  }
1593
1728
  }
@@ -1631,7 +1766,7 @@ function isBareImport(importee) {
1631
1766
  }
1632
1767
 
1633
1768
  // src/utils/optimizer.ts
1634
- import { promises as fs6 } from "fs";
1769
+ import { promises as fs5 } from "fs";
1635
1770
  import path7 from "path";
1636
1771
  var PREBUNDLE_SENSITIVE_OPTIONS = [
1637
1772
  "compilerOptions",
@@ -1649,11 +1784,11 @@ async function saveSvelteMetadata(cacheDir, options) {
1649
1784
  });
1650
1785
  let existingSvelteMetadata;
1651
1786
  try {
1652
- existingSvelteMetadata = await fs6.readFile(svelteMetadataPath, "utf8");
1787
+ existingSvelteMetadata = await fs5.readFile(svelteMetadataPath, "utf8");
1653
1788
  } catch {
1654
1789
  }
1655
- await fs6.mkdir(cacheDir, { recursive: true });
1656
- await fs6.writeFile(svelteMetadataPath, currentSvelteMetadata);
1790
+ await fs5.mkdir(cacheDir, { recursive: true });
1791
+ await fs5.writeFile(svelteMetadataPath, currentSvelteMetadata);
1657
1792
  return currentSvelteMetadata !== existingSvelteMetadata;
1658
1793
  }
1659
1794
  function generateSvelteMetadata(options) {
@@ -1668,7 +1803,7 @@ function generateSvelteMetadata(options) {
1668
1803
  import { normalizePath as normalizePath3 } from "vite";
1669
1804
  import path8 from "path";
1670
1805
  import { fileURLToPath } from "url";
1671
- import fs7 from "fs";
1806
+ import fs6 from "fs";
1672
1807
 
1673
1808
  // src/ui/inspector/utils.ts
1674
1809
  var FS_PREFIX = `/@fs/`;
@@ -1745,8 +1880,8 @@ function svelteInspector() {
1745
1880
  return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1746
1881
  } else if (id.startsWith(inspectorPath)) {
1747
1882
  const file = idToFile(id);
1748
- if (fs7.existsSync(file)) {
1749
- return await fs7.promises.readFile(file, "utf-8");
1883
+ if (fs6.existsSync(file)) {
1884
+ return await fs6.promises.readFile(file, "utf-8");
1750
1885
  } else {
1751
1886
  log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1752
1887
  }
@@ -1782,6 +1917,111 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1782
1917
  };
1783
1918
  }
1784
1919
 
1920
+ // src/utils/vite-plugin-svelte-cache.ts
1921
+ var VitePluginSvelteCache = class {
1922
+ constructor() {
1923
+ this._css = /* @__PURE__ */ new Map();
1924
+ this._js = /* @__PURE__ */ new Map();
1925
+ this._dependencies = /* @__PURE__ */ new Map();
1926
+ this._dependants = /* @__PURE__ */ new Map();
1927
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1928
+ this._errors = /* @__PURE__ */ new Map();
1929
+ }
1930
+ update(compileData) {
1931
+ this._errors.delete(compileData.normalizedFilename);
1932
+ this.updateCSS(compileData);
1933
+ this.updateJS(compileData);
1934
+ this.updateDependencies(compileData);
1935
+ }
1936
+ has(svelteRequest) {
1937
+ const id = svelteRequest.normalizedFilename;
1938
+ return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1939
+ }
1940
+ setError(svelteRequest, error) {
1941
+ this.remove(svelteRequest, true);
1942
+ this._errors.set(svelteRequest.normalizedFilename, error);
1943
+ }
1944
+ updateCSS(compileData) {
1945
+ this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1946
+ }
1947
+ updateJS(compileData) {
1948
+ if (!compileData.ssr) {
1949
+ this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1950
+ }
1951
+ }
1952
+ updateDependencies(compileData) {
1953
+ const id = compileData.normalizedFilename;
1954
+ const prevDependencies = this._dependencies.get(id) || [];
1955
+ const dependencies = compileData.dependencies;
1956
+ this._dependencies.set(id, dependencies);
1957
+ const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1958
+ const added = dependencies.filter((d) => !prevDependencies.includes(d));
1959
+ added.forEach((d) => {
1960
+ if (!this._dependants.has(d)) {
1961
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1962
+ }
1963
+ this._dependants.get(d).add(compileData.filename);
1964
+ });
1965
+ removed.forEach((d) => {
1966
+ this._dependants.get(d).delete(compileData.filename);
1967
+ });
1968
+ }
1969
+ remove(svelteRequest, keepDependencies = false) {
1970
+ const id = svelteRequest.normalizedFilename;
1971
+ let removed = false;
1972
+ if (this._errors.delete(id)) {
1973
+ removed = true;
1974
+ }
1975
+ if (this._js.delete(id)) {
1976
+ removed = true;
1977
+ }
1978
+ if (this._css.delete(id)) {
1979
+ removed = true;
1980
+ }
1981
+ if (!keepDependencies) {
1982
+ const dependencies = this._dependencies.get(id);
1983
+ if (dependencies) {
1984
+ removed = true;
1985
+ dependencies.forEach((d) => {
1986
+ const dependants = this._dependants.get(d);
1987
+ if (dependants && dependants.has(svelteRequest.filename)) {
1988
+ dependants.delete(svelteRequest.filename);
1989
+ }
1990
+ });
1991
+ this._dependencies.delete(id);
1992
+ }
1993
+ }
1994
+ return removed;
1995
+ }
1996
+ getCSS(svelteRequest) {
1997
+ return this._css.get(svelteRequest.normalizedFilename);
1998
+ }
1999
+ getJS(svelteRequest) {
2000
+ if (!svelteRequest.ssr) {
2001
+ return this._js.get(svelteRequest.normalizedFilename);
2002
+ }
2003
+ }
2004
+ getError(svelteRequest) {
2005
+ return this._errors.get(svelteRequest.normalizedFilename);
2006
+ }
2007
+ getDependants(path9) {
2008
+ const dependants = this._dependants.get(path9);
2009
+ return dependants ? [...dependants] : [];
2010
+ }
2011
+ getResolvedSvelteField(name, importer) {
2012
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
2013
+ }
2014
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
2015
+ this._resolvedSvelteFields.set(
2016
+ this._getResolvedSvelteFieldKey(importee, importer),
2017
+ resolvedSvelte
2018
+ );
2019
+ }
2020
+ _getResolvedSvelteFieldKey(importee, importer) {
2021
+ return importer ? `${importer} > ${importee}` : importee;
2022
+ }
2023
+ };
2024
+
1785
2025
  // src/index.ts
1786
2026
  function svelte(inlineOptions) {
1787
2027
  if (process.env.DEBUG != null) {
@@ -1846,7 +2086,7 @@ function svelte(inlineOptions) {
1846
2086
  }
1847
2087
  if (viteConfig.assetsInclude(filename)) {
1848
2088
  log.debug(`load returns raw content for ${filename}`);
1849
- return fs8.readFileSync(filename, "utf-8");
2089
+ return fs7.readFileSync(filename, "utf-8");
1850
2090
  }
1851
2091
  }
1852
2092
  },
@@ -1940,6 +2180,9 @@ function svelte(inlineOptions) {
1940
2180
  throw toRollupError(e, options);
1941
2181
  }
1942
2182
  }
2183
+ },
2184
+ async buildEnd() {
2185
+ await options.stats?.finishAll();
1943
2186
  }
1944
2187
  }
1945
2188
  ];