@sveltejs/vite-plugin-svelte 1.1.1 → 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,8 @@ 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
+ import { isDepExcluded as isDepExcluded2 } from "vitefu";
11
12
 
12
13
  // src/utils/log.ts
13
14
  import { cyan, yellow, red } from "kleur/colors";
@@ -288,80 +289,105 @@ function toSafe(base64) {
288
289
 
289
290
  // src/utils/compile.ts
290
291
  var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
291
- var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
292
- const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
293
- const { emitCss = true } = options;
294
- const dependencies = [];
295
- const compileOptions = {
296
- ...options.compilerOptions,
297
- filename,
298
- generate: ssr ? "ssr" : "dom",
299
- format: "esm"
300
- };
301
- if (options.hot && options.emitCss) {
302
- const hash = `s-${safeBase64Hash(normalizedFilename)}`;
303
- log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
304
- compileOptions.cssHash = () => hash;
305
- }
306
- if (ssr && compileOptions.enableSourcemap !== false) {
307
- if (typeof compileOptions.enableSourcemap === "object") {
308
- compileOptions.enableSourcemap.css = false;
309
- } else {
310
- 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
+ }
311
314
  }
312
- }
313
- let preprocessed;
314
- if (options.preprocess) {
315
- try {
316
- preprocessed = await preprocess(code, options.preprocess, { filename });
317
- } catch (e) {
318
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
319
- 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;
320
325
  }
321
- if (preprocessed.dependencies)
322
- dependencies.push(...preprocessed.dependencies);
323
- if (preprocessed.map)
324
- compileOptions.sourcemap = preprocessed.map;
325
- }
326
- const finalCode = preprocessed ? preprocessed.code : code;
327
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
328
- filename,
329
- code: finalCode,
330
- compileOptions
331
- });
332
- if (dynamicCompileOptions && log.debug.enabled) {
333
- log.debug(
334
- `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
335
- );
336
- }
337
- const finalCompileOptions = dynamicCompileOptions ? {
338
- ...compileOptions,
339
- ...dynamicCompileOptions
340
- } : compileOptions;
341
- const compiled = compile(finalCode, finalCompileOptions);
342
- if (emitCss && compiled.css.code) {
343
- 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 += `
344
369
  import ${JSON.stringify(cssId)};
345
370
  `;
346
- }
347
- if (!ssr && makeHot) {
348
- compiled.js.code = makeHot({
349
- id: filename,
350
- compiledCode: compiled.js.code,
351
- hotOptions: options.hot,
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",
352
387
  compiled,
353
- originalCode: code,
354
- compileOptions: finalCompileOptions
355
- });
356
- }
357
- compiled.js.dependencies = dependencies;
358
- return {
359
- filename,
360
- normalizedFilename,
361
- lang: code.match(scriptLangRE)?.[1] || "js",
362
- compiled,
363
- ssr,
364
- dependencies
388
+ ssr,
389
+ dependencies
390
+ };
365
391
  };
366
392
  };
367
393
  function buildMakeHot(options) {
@@ -461,9 +487,7 @@ function buildIdParser(options) {
461
487
  }
462
488
 
463
489
  // src/utils/options.ts
464
- import {
465
- normalizePath as normalizePath2
466
- } from "vite";
490
+ import { normalizePath as normalizePath2 } from "vite";
467
491
 
468
492
  // src/utils/load-svelte-config.ts
469
493
  import { createRequire } from "module";
@@ -571,185 +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
- // src/utils/dependencies.ts
579
- import path2 from "path";
580
- import fs3 from "fs";
581
- import { createRequire as createRequire2 } from "module";
582
- function findRootSvelteDependencies(root, cwdFallback = true) {
583
- log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
584
- const pkgFile = path2.join(root, "package.json");
585
- if (!fs3.existsSync(pkgFile)) {
586
- if (cwdFallback) {
587
- const cwd = process.cwd();
588
- if (root !== cwd) {
589
- log.debug(`no package.json found in vite root ${root}`);
590
- return findRootSvelteDependencies(cwd, false);
591
- }
592
- }
593
- log.warn(`no package.json found, findRootSvelteDependencies failed`);
594
- return [];
595
- }
596
- const pkg = parsePkg(root);
597
- if (!pkg) {
598
- return [];
599
- }
600
- const deps = [
601
- ...Object.keys(pkg.dependencies || {}),
602
- ...Object.keys(pkg.devDependencies || {})
603
- ].filter((dep) => !is_common_without_svelte_field(dep));
604
- return getSvelteDependencies(deps, root);
605
- }
606
- function getSvelteDependencies(deps, pkgDir, path9 = []) {
607
- const result = [];
608
- const localRequire = createRequire2(`${pkgDir}/package.json`);
609
- const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
610
- for (const { pkg, dir } of resolvedDeps) {
611
- const type = getSvelteDependencyType(pkg);
612
- if (!type)
613
- continue;
614
- result.push({ name: pkg.name, type, pkg, dir, path: path9 });
615
- if (type === "component-library" && pkg.dependencies) {
616
- let dependencyNames = Object.keys(pkg.dependencies);
617
- const circular = dependencyNames.filter((name) => path9.includes(name));
618
- if (circular.length > 0) {
619
- log.warn.enabled && log.warn(
620
- `skipping circular svelte dependencies in automated vite optimizeDeps handling`,
621
- circular.map((x) => path9.concat(x).join(">"))
622
- );
623
- dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
624
- }
625
- if (path9.length === 3) {
626
- log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
627
- }
628
- result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
629
- }
630
- }
631
- return result;
632
- }
633
- function resolveDependencyData(dep, localRequire) {
634
- try {
635
- const pkgJson = `${dep}/package.json`;
636
- const pkg = localRequire(pkgJson);
637
- const dir = path2.dirname(localRequire.resolve(pkgJson));
638
- return { dir, pkg };
639
- } catch (e) {
640
- log.debug.once(`dependency ${dep} does not export package.json`, e);
641
- try {
642
- let dir = path2.dirname(localRequire.resolve(dep));
643
- while (dir) {
644
- const pkg = parsePkg(dir, true);
645
- if (pkg && pkg.name === dep) {
646
- return { dir, pkg };
647
- }
648
- const parent = path2.dirname(dir);
649
- if (parent === dir) {
650
- break;
651
- }
652
- dir = parent;
653
- }
654
- } catch (e2) {
655
- log.debug.once(`error while trying to find package.json of ${dep}`, e2);
656
- }
657
- }
658
- log.debug.once(`failed to resolve ${dep}`);
659
- }
660
- function parsePkg(dir, silent = false) {
661
- const pkgFile = path2.join(dir, "package.json");
662
- try {
663
- return JSON.parse(fs3.readFileSync(pkgFile, "utf-8"));
664
- } catch (e) {
665
- !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
666
- }
667
- }
668
- function getSvelteDependencyType(pkg) {
669
- if (isSvelteComponentLib(pkg)) {
670
- return "component-library";
671
- } else if (isSvelteLib(pkg)) {
672
- return "js-library";
673
- } else {
674
- return void 0;
675
- }
676
- }
677
- function isSvelteComponentLib(pkg) {
678
- return !!pkg.svelte;
679
- }
680
- function isSvelteLib(pkg) {
681
- return !!pkg.dependencies?.svelte || !!pkg.peerDependencies?.svelte;
682
- }
683
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
684
- "@lukeed/uuid",
685
- "@playwright/test",
686
- "@sveltejs/vite-plugin-svelte",
687
- "@sveltejs/kit",
688
- "autoprefixer",
689
- "cookie",
690
- "dotenv",
691
- "esbuild",
692
- "eslint",
693
- "jest",
694
- "mdsvex",
695
- "playwright",
696
- "postcss",
697
- "prettier",
698
- "svelte",
699
- "svelte-check",
700
- "svelte-hmr",
701
- "svelte-preprocess",
702
- "tslib",
703
- "typescript",
704
- "vite",
705
- "vitest",
706
- "__vite-browser-external"
707
- ];
708
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
709
- "@fontsource/",
710
- "@postcss-plugins/",
711
- "@rollup/",
712
- "@sveltejs/adapter-",
713
- "@types/",
714
- "@typescript-eslint/",
715
- "eslint-",
716
- "jest-",
717
- "postcss-plugin-",
718
- "prettier-plugin-",
719
- "rollup-plugin-",
720
- "vite-plugin-"
721
- ];
722
- function is_common_without_svelte_field(dependency) {
723
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
724
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
725
- );
726
- }
727
- function needsOptimization(dep, localRequire) {
728
- const depData = resolveDependencyData(dep, localRequire);
729
- if (!depData)
730
- return false;
731
- const pkg = depData.pkg;
732
- const hasEsmFields = pkg.module || pkg.exports;
733
- if (hasEsmFields)
734
- return false;
735
- if (pkg.main) {
736
- const entryExt = path2.extname(pkg.main);
737
- return !entryExt || entryExt === ".js" || entryExt === ".cjs";
738
- } else {
739
- try {
740
- localRequire.resolve(`${dep}/index.js`);
741
- return true;
742
- } catch {
743
- return false;
744
- }
745
- }
746
- }
747
-
748
- // src/utils/options.ts
749
- import { createRequire as createRequire3 } from "module";
750
-
751
603
  // src/utils/esbuild.ts
752
- import { promises as fs4 } from "fs";
604
+ import { readFileSync } from "fs";
753
605
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
754
606
 
755
607
  // src/utils/error.ts
@@ -805,7 +657,38 @@ function formatFrameForVite(frame) {
805
657
  return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
806
658
  }
807
659
 
660
+ // src/utils/svelte-version.ts
661
+ import { VERSION } from "svelte/compiler";
662
+ var svelteVersion = parseVersion(VERSION);
663
+ function parseVersion(version) {
664
+ const segments = version.split(".", 3).map((s) => parseInt(s, 10));
665
+ while (segments.length < 3) {
666
+ segments.push(0);
667
+ }
668
+ return segments;
669
+ }
670
+ function compareToSvelte(version) {
671
+ const parsedVersion = parseVersion(version);
672
+ for (let i = 0; i < svelteVersion.length; i++) {
673
+ const a = parsedVersion[i];
674
+ const b = svelteVersion[i];
675
+ if (a === b) {
676
+ continue;
677
+ } else if (a > b) {
678
+ return 1;
679
+ } else {
680
+ return -1;
681
+ }
682
+ }
683
+ return 0;
684
+ }
685
+ function atLeastSvelte(version) {
686
+ const result = compareToSvelte(version) <= 0;
687
+ return result;
688
+ }
689
+
808
690
  // src/utils/esbuild.ts
691
+ var isCssString = atLeastSvelte("3.53.0");
809
692
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
810
693
  function esbuildSveltePlugin(options) {
811
694
  return {
@@ -815,22 +698,35 @@ function esbuildSveltePlugin(options) {
815
698
  return;
816
699
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
817
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
+ });
818
707
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
819
- const code = await fs4.readFile(filename, "utf8");
708
+ const code = readFileSync(filename, "utf8");
820
709
  try {
821
- const contents = await compileSvelte(options, { filename, code });
710
+ const contents = await compileSvelte(options, { filename, code }, statsCollection);
822
711
  return { contents };
823
712
  } catch (e) {
824
713
  return { errors: [toESBuildError(e, options)] };
825
714
  }
826
715
  });
716
+ build.onEnd(() => {
717
+ statsCollection?.finish();
718
+ });
827
719
  }
828
720
  };
829
721
  }
830
- async function compileSvelte(options, { filename, code }) {
722
+ async function compileSvelte(options, { filename, code }, statsCollection) {
723
+ let css = options.compilerOptions.css;
724
+ if (css !== "none") {
725
+ css = isCssString ? "injected" : true;
726
+ }
831
727
  const compileOptions = {
832
728
  ...options.compilerOptions,
833
- css: true,
729
+ css,
834
730
  filename,
835
731
  format: "esm",
836
732
  generate: "dom"
@@ -859,7 +755,11 @@ async function compileSvelte(options, { filename, code }) {
859
755
  ...compileOptions,
860
756
  ...dynamicCompileOptions
861
757
  } : compileOptions;
758
+ const endStat = statsCollection?.start(filename);
862
759
  const compiled = compile2(finalCode, finalCompileOptions);
760
+ if (endStat) {
761
+ endStat();
762
+ }
863
763
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
864
764
  }
865
765
 
@@ -917,7 +817,7 @@ async function buildSourceMap(from, to, filename) {
917
817
  }
918
818
 
919
819
  // src/utils/preprocess.ts
920
- import path3 from "path";
820
+ import path2 from "path";
921
821
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
922
822
  var supportedScriptLangs = ["ts"];
923
823
  function createViteScriptPreprocessor() {
@@ -950,7 +850,7 @@ function createViteStylePreprocessor(config) {
950
850
  const moduleId = `${filename}.${lang}`;
951
851
  const result = await transform(content, moduleId);
952
852
  if (result.map?.sources?.[0] === moduleId) {
953
- result.map.sources[0] = path3.basename(filename);
853
+ result.map.sources[0] = path2.basename(filename);
954
854
  }
955
855
  return {
956
856
  code: result.code,
@@ -997,7 +897,7 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
997
897
  return {
998
898
  code: s.toString(),
999
899
  map: s.generateDecodedMap({
1000
- source: filename ? path3.basename(filename) : void 0,
900
+ source: filename ? path2.basename(filename) : void 0,
1001
901
  hires: true
1002
902
  })
1003
903
  };
@@ -1121,6 +1021,231 @@ function validateSourceMapOutputWrapper(group, i) {
1121
1021
 
1122
1022
  // src/utils/options.ts
1123
1023
  import deepmerge from "deepmerge";
1024
+ import {
1025
+ crawlFrameworkPkgs,
1026
+ isDepExcluded,
1027
+ isDepExternaled,
1028
+ isDepIncluded,
1029
+ isDepNoExternaled
1030
+ } from "vitefu";
1031
+
1032
+ // src/utils/dependencies.ts
1033
+ import path3 from "path";
1034
+ import fs3 from "fs/promises";
1035
+ import { findDepPkgJsonPath } from "vitefu";
1036
+ async function resolveDependencyData(dep, parent) {
1037
+ const depDataPath = await findDepPkgJsonPath(dep, parent);
1038
+ if (!depDataPath)
1039
+ return void 0;
1040
+ try {
1041
+ return {
1042
+ dir: path3.dirname(depDataPath),
1043
+ pkg: JSON.parse(await fs3.readFile(depDataPath, "utf-8"))
1044
+ };
1045
+ } catch {
1046
+ return void 0;
1047
+ }
1048
+ }
1049
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
1050
+ "@lukeed/uuid",
1051
+ "@playwright/test",
1052
+ "@sveltejs/vite-plugin-svelte",
1053
+ "@sveltejs/kit",
1054
+ "autoprefixer",
1055
+ "cookie",
1056
+ "dotenv",
1057
+ "esbuild",
1058
+ "eslint",
1059
+ "jest",
1060
+ "mdsvex",
1061
+ "playwright",
1062
+ "postcss",
1063
+ "prettier",
1064
+ "svelte",
1065
+ "svelte-check",
1066
+ "svelte-hmr",
1067
+ "svelte-preprocess",
1068
+ "tslib",
1069
+ "typescript",
1070
+ "vite",
1071
+ "vitest",
1072
+ "__vite-browser-external"
1073
+ ];
1074
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
1075
+ "@fontsource/",
1076
+ "@postcss-plugins/",
1077
+ "@rollup/",
1078
+ "@sveltejs/adapter-",
1079
+ "@types/",
1080
+ "@typescript-eslint/",
1081
+ "eslint-",
1082
+ "jest-",
1083
+ "postcss-plugin-",
1084
+ "prettier-plugin-",
1085
+ "rollup-plugin-",
1086
+ "vite-plugin-"
1087
+ ];
1088
+ function isCommonDepWithoutSvelteField(dependency) {
1089
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
1090
+ (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
1091
+ );
1092
+ }
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
+
1247
+ // src/utils/options.ts
1248
+ var cssAsString = atLeastSvelte("3.53.0");
1124
1249
  var allowedPluginOptions = /* @__PURE__ */ new Set([
1125
1250
  "include",
1126
1251
  "exclude",
@@ -1204,16 +1329,18 @@ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1204
1329
  ...viteUserConfig,
1205
1330
  root: resolveViteRoot(viteUserConfig)
1206
1331
  };
1332
+ const isBuild = viteEnv.command === "build";
1207
1333
  const defaultOptions = {
1208
1334
  extensions: [".svelte"],
1209
- emitCss: true
1335
+ emitCss: true,
1336
+ prebundleSvelteLibraries: !isBuild
1210
1337
  };
1211
1338
  const svelteConfig = convertPluginOptions(
1212
1339
  await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
1213
1340
  );
1214
1341
  const extraOptions = {
1215
1342
  root: viteConfigWithResolvedRoot.root,
1216
- isBuild: viteEnv.command === "build",
1343
+ isBuild,
1217
1344
  isServe: viteEnv.command === "serve",
1218
1345
  isDebug: process.env.DEBUG != null
1219
1346
  };
@@ -1238,13 +1365,14 @@ function mergeConfigs(...configs) {
1238
1365
  return result;
1239
1366
  }
1240
1367
  function resolveOptions(preResolveOptions2, viteConfig) {
1368
+ const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1241
1369
  const defaultOptions = {
1242
1370
  hot: viteConfig.isProduction ? false : {
1243
- injectCss: !preResolveOptions2.emitCss,
1371
+ injectCss: css === true || css === "injected",
1244
1372
  partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1245
1373
  },
1246
1374
  compilerOptions: {
1247
- css: !preResolveOptions2.emitCss,
1375
+ css,
1248
1376
  dev: !viteConfig.isProduction
1249
1377
  }
1250
1378
  };
@@ -1259,6 +1387,12 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1259
1387
  addExtraPreprocessors(merged, viteConfig);
1260
1388
  enforceOptionsForHmr(merged);
1261
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
+ }
1262
1396
  return merged;
1263
1397
  }
1264
1398
  function enforceOptionsForHmr(options) {
@@ -1272,11 +1406,13 @@ function enforceOptionsForHmr(options) {
1272
1406
  log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1273
1407
  options.hot.injectCss = false;
1274
1408
  }
1275
- if (options.compilerOptions.css) {
1409
+ const css = options.compilerOptions.css;
1410
+ if (css === true || css === "injected") {
1411
+ const forcedCss = cssAsString ? "external" : false;
1276
1412
  log.warn(
1277
- "hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false"
1413
+ `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
1278
1414
  );
1279
- options.compilerOptions.css = false;
1415
+ options.compilerOptions.css = forcedCss;
1280
1416
  }
1281
1417
  } else {
1282
1418
  if (options.hot === true || !options.hot.injectCss) {
@@ -1289,11 +1425,13 @@ function enforceOptionsForHmr(options) {
1289
1425
  options.hot.injectCss = true;
1290
1426
  }
1291
1427
  }
1292
- if (!options.compilerOptions.css) {
1428
+ const css = options.compilerOptions.css;
1429
+ if (!(css === true || css === "injected")) {
1430
+ const forcedCss = cssAsString ? "injected" : true;
1293
1431
  log.warn(
1294
- "hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true"
1432
+ `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
1295
1433
  );
1296
- options.compilerOptions.css = true;
1434
+ options.compilerOptions.css = forcedCss;
1297
1435
  }
1298
1436
  }
1299
1437
  }
@@ -1331,16 +1469,9 @@ function removeIgnoredOptions(options) {
1331
1469
  }
1332
1470
  }
1333
1471
  function addSvelteKitOptions(options) {
1334
- if (options?.kit != null) {
1335
- const kit_browser_hydrate = options.kit.browser?.hydrate;
1336
- const hydratable = kit_browser_hydrate !== false;
1337
- if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1338
- log.warn(
1339
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
1340
- );
1341
- }
1342
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1343
- options.compilerOptions.hydratable = hydratable;
1472
+ if (options?.kit != null && options.compilerOptions.hydratable == null) {
1473
+ log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
1474
+ options.compilerOptions.hydratable = true;
1344
1475
  }
1345
1476
  }
1346
1477
  function handleDeprecatedOptions(options) {
@@ -1354,19 +1485,44 @@ function handleDeprecatedOptions(options) {
1354
1485
  function resolveViteRoot(viteConfig) {
1355
1486
  return normalizePath2(viteConfig.root ? path4.resolve(viteConfig.root) : process.cwd());
1356
1487
  }
1357
- function buildExtraViteConfig(options, config) {
1358
- const svelteDeps = findRootSvelteDependencies(options.root);
1488
+ async function buildExtraViteConfig(options, config) {
1359
1489
  const extraViteConfig = {
1360
1490
  resolve: {
1361
1491
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1362
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1492
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1493
+ conditions: [...SVELTE_EXPORT_CONDITIONS]
1363
1494
  }
1364
1495
  };
1365
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
1366
- svelteDeps,
1367
- options,
1368
- config.optimizeDeps
1369
- );
1496
+ const extraSvelteConfig = buildExtraConfigForSvelte(config);
1497
+ const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
1498
+ extraViteConfig.optimizeDeps = {
1499
+ include: [
1500
+ ...extraSvelteConfig.optimizeDeps.include,
1501
+ ...extraDepsConfig.optimizeDeps.include.filter(
1502
+ (dep) => !isDepExcluded(dep, extraSvelteConfig.optimizeDeps.exclude)
1503
+ )
1504
+ ],
1505
+ exclude: [
1506
+ ...extraSvelteConfig.optimizeDeps.exclude,
1507
+ ...extraDepsConfig.optimizeDeps.exclude.filter(
1508
+ (dep) => !isDepIncluded(dep, extraSvelteConfig.optimizeDeps.include)
1509
+ )
1510
+ ]
1511
+ };
1512
+ extraViteConfig.ssr = {
1513
+ external: [
1514
+ ...extraSvelteConfig.ssr.external,
1515
+ ...extraDepsConfig.ssr.external.filter(
1516
+ (dep) => !isDepNoExternaled(dep, extraSvelteConfig.ssr.noExternal)
1517
+ )
1518
+ ],
1519
+ noExternal: [
1520
+ ...extraSvelteConfig.ssr.noExternal,
1521
+ ...extraDepsConfig.ssr.noExternal.filter(
1522
+ (dep) => !isDepExternaled(dep, extraSvelteConfig.ssr.external)
1523
+ )
1524
+ ]
1525
+ };
1370
1526
  if (options.prebundleSvelteLibraries) {
1371
1527
  extraViteConfig.optimizeDeps = {
1372
1528
  ...extraViteConfig.optimizeDeps,
@@ -1377,77 +1533,111 @@ function buildExtraViteConfig(options, config) {
1377
1533
  }
1378
1534
  };
1379
1535
  }
1380
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1381
1536
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1382
1537
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1383
1538
  extraViteConfig.experimental = { hmrPartialAccept: true };
1384
1539
  }
1540
+ validateViteConfig(extraViteConfig, config, options);
1385
1541
  return extraViteConfig;
1386
1542
  }
1387
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
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
+ }
1570
+ async function buildExtraConfigForDependencies(options, config) {
1571
+ const depsConfig = await crawlFrameworkPkgs({
1572
+ root: options.root,
1573
+ isBuild: options.isBuild,
1574
+ viteUserConfig: config,
1575
+ isFrameworkPkgByJson(pkgJson) {
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;
1586
+ },
1587
+ isSemiFrameworkPkgByJson(pkgJson) {
1588
+ return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
1589
+ },
1590
+ isFrameworkPkgByName(pkgName) {
1591
+ const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
1592
+ if (isNotSveltePackage) {
1593
+ return false;
1594
+ } else {
1595
+ return void 0;
1596
+ }
1597
+ }
1598
+ });
1599
+ log.debug("extra config for dependencies generated by vitefu", depsConfig);
1600
+ if (options.prebundleSvelteLibraries) {
1601
+ depsConfig.optimizeDeps.exclude = [];
1602
+ const userExclude = config.optimizeDeps?.exclude;
1603
+ depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1604
+ return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => isDepExcluded(d.trim(), userExclude));
1605
+ });
1606
+ }
1607
+ if (options.disableDependencyReinclusion === true) {
1608
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
1609
+ (dep) => !dep.includes(">")
1610
+ );
1611
+ } else if (Array.isArray(options.disableDependencyReinclusion)) {
1612
+ const disabledDeps = options.disableDependencyReinclusion;
1613
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
1614
+ if (!dep.includes(">"))
1615
+ return true;
1616
+ const trimDep = dep.replace(/\s+/g, "");
1617
+ return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
1618
+ });
1619
+ }
1620
+ log.debug("post-processed extra config for dependencies", depsConfig);
1621
+ return depsConfig;
1622
+ }
1623
+ function buildExtraConfigForSvelte(config) {
1388
1624
  const include = [];
1389
1625
  const exclude = ["svelte-hmr"];
1390
- const isIncluded = (dep) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
1391
- const isExcluded = (dep) => {
1392
- return exclude.includes(dep) || optimizeDeps?.exclude?.some((id) => dep === id || id.startsWith(`${dep}/`));
1393
- };
1394
- if (!isExcluded("svelte")) {
1626
+ if (!isDepExcluded("svelte", config.optimizeDeps?.exclude ?? [])) {
1395
1627
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1396
1628
  log.debug(
1397
1629
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1398
1630
  );
1399
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1631
+ include.push(...svelteImportsToInclude);
1400
1632
  } else {
1401
1633
  log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1402
1634
  }
1403
- if (options.prebundleSvelteLibraries) {
1404
- return { include, exclude };
1405
- }
1406
- svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1407
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
1408
- (dep) => !isIncluded(dep)
1409
- );
1410
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1411
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1412
- if (options.disableDependencyReinclusion !== true) {
1413
- const disabledReinclusions = options.disableDependencyReinclusion || [];
1414
- if (disabledReinclusions.length > 0) {
1415
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1416
- }
1417
- const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1418
- const localRequire = createRequire3(`${dep.dir}/package.json`);
1419
- return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1420
- });
1421
- log.debug(
1422
- `reincluding transitive dependencies of excluded svelte dependencies`,
1423
- transitiveDepsToInclude
1424
- );
1425
- include.push(...transitiveDepsToInclude);
1426
- }
1427
- return { include, exclude };
1428
- }
1429
- function buildSSROptionsForSvelte(svelteDeps, options, config) {
1430
1635
  const noExternal = [];
1431
- if (!config.ssr?.external?.includes("svelte")) {
1636
+ const external = [];
1637
+ if (!isDepExternaled("svelte", config.ssr?.external ?? [])) {
1432
1638
  noExternal.push("svelte", /^svelte\//);
1433
1639
  }
1434
- noExternal.push(
1435
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
1436
- (x) => !config.ssr?.external?.includes(x)
1437
- )
1438
- );
1439
- const ssr = {
1440
- noExternal,
1441
- external: []
1442
- };
1443
- if (options.isServe) {
1444
- ssr.external = Array.from(
1445
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
1446
- ).filter(
1447
- (dep) => !ssr.noExternal.includes(dep) && !config.ssr?.external?.includes(dep)
1448
- );
1449
- }
1450
- return ssr;
1640
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1451
1641
  }
1452
1642
  function patchResolvedViteConfig(viteConfig, options) {
1453
1643
  const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
@@ -1458,113 +1648,8 @@ function patchResolvedViteConfig(viteConfig, options) {
1458
1648
  }
1459
1649
  }
1460
1650
 
1461
- // src/utils/vite-plugin-svelte-cache.ts
1462
- var VitePluginSvelteCache = class {
1463
- constructor() {
1464
- this._css = /* @__PURE__ */ new Map();
1465
- this._js = /* @__PURE__ */ new Map();
1466
- this._dependencies = /* @__PURE__ */ new Map();
1467
- this._dependants = /* @__PURE__ */ new Map();
1468
- this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1469
- this._errors = /* @__PURE__ */ new Map();
1470
- }
1471
- update(compileData) {
1472
- this._errors.delete(compileData.normalizedFilename);
1473
- this.updateCSS(compileData);
1474
- this.updateJS(compileData);
1475
- this.updateDependencies(compileData);
1476
- }
1477
- has(svelteRequest) {
1478
- const id = svelteRequest.normalizedFilename;
1479
- return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1480
- }
1481
- setError(svelteRequest, error) {
1482
- this.remove(svelteRequest, true);
1483
- this._errors.set(svelteRequest.normalizedFilename, error);
1484
- }
1485
- updateCSS(compileData) {
1486
- this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1487
- }
1488
- updateJS(compileData) {
1489
- if (!compileData.ssr) {
1490
- this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1491
- }
1492
- }
1493
- updateDependencies(compileData) {
1494
- const id = compileData.normalizedFilename;
1495
- const prevDependencies = this._dependencies.get(id) || [];
1496
- const dependencies = compileData.dependencies;
1497
- this._dependencies.set(id, dependencies);
1498
- const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1499
- const added = dependencies.filter((d) => !prevDependencies.includes(d));
1500
- added.forEach((d) => {
1501
- if (!this._dependants.has(d)) {
1502
- this._dependants.set(d, /* @__PURE__ */ new Set());
1503
- }
1504
- this._dependants.get(d).add(compileData.filename);
1505
- });
1506
- removed.forEach((d) => {
1507
- this._dependants.get(d).delete(compileData.filename);
1508
- });
1509
- }
1510
- remove(svelteRequest, keepDependencies = false) {
1511
- const id = svelteRequest.normalizedFilename;
1512
- let removed = false;
1513
- if (this._errors.delete(id)) {
1514
- removed = true;
1515
- }
1516
- if (this._js.delete(id)) {
1517
- removed = true;
1518
- }
1519
- if (this._css.delete(id)) {
1520
- removed = true;
1521
- }
1522
- if (!keepDependencies) {
1523
- const dependencies = this._dependencies.get(id);
1524
- if (dependencies) {
1525
- removed = true;
1526
- dependencies.forEach((d) => {
1527
- const dependants = this._dependants.get(d);
1528
- if (dependants && dependants.has(svelteRequest.filename)) {
1529
- dependants.delete(svelteRequest.filename);
1530
- }
1531
- });
1532
- this._dependencies.delete(id);
1533
- }
1534
- }
1535
- return removed;
1536
- }
1537
- getCSS(svelteRequest) {
1538
- return this._css.get(svelteRequest.normalizedFilename);
1539
- }
1540
- getJS(svelteRequest) {
1541
- if (!svelteRequest.ssr) {
1542
- return this._js.get(svelteRequest.normalizedFilename);
1543
- }
1544
- }
1545
- getError(svelteRequest) {
1546
- return this._errors.get(svelteRequest.normalizedFilename);
1547
- }
1548
- getDependants(path9) {
1549
- const dependants = this._dependants.get(path9);
1550
- return dependants ? [...dependants] : [];
1551
- }
1552
- getResolvedSvelteField(name, importer) {
1553
- return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1554
- }
1555
- setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1556
- this._resolvedSvelteFields.set(
1557
- this._getResolvedSvelteFieldKey(importee, importer),
1558
- resolvedSvelte
1559
- );
1560
- }
1561
- _getResolvedSvelteFieldKey(importee, importer) {
1562
- return importer ? `${importer} > ${importee}` : importee;
1563
- }
1564
- };
1565
-
1566
1651
  // src/utils/watch.ts
1567
- import fs5 from "fs";
1652
+ import fs4 from "fs";
1568
1653
  import path5 from "path";
1569
1654
  function setupWatchers(options, cache, requestParser) {
1570
1655
  const { server, configFile: svelteConfigFile } = options;
@@ -1576,7 +1661,7 @@ function setupWatchers(options, cache, requestParser) {
1576
1661
  const emitChangeEventOnDependants = (filename) => {
1577
1662
  const dependants = cache.getDependants(filename);
1578
1663
  dependants.forEach((dependant) => {
1579
- if (fs5.existsSync(dependant)) {
1664
+ if (fs4.existsSync(dependant)) {
1580
1665
  log.debug(
1581
1666
  `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1582
1667
  );
@@ -1637,22 +1722,21 @@ function setupWatchers(options, cache, requestParser) {
1637
1722
  });
1638
1723
  }
1639
1724
  function ensureWatchedFile(watcher, file, root) {
1640
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs5.existsSync(file)) {
1725
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs4.existsSync(file)) {
1641
1726
  watcher.add(path5.resolve(file));
1642
1727
  }
1643
1728
  }
1644
1729
 
1645
1730
  // src/utils/resolve.ts
1646
1731
  import path6 from "path";
1647
- import { builtinModules, createRequire as createRequire4 } from "module";
1648
- function resolveViaPackageJsonSvelte(importee, importer, cache) {
1649
- if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1732
+ import { builtinModules } from "module";
1733
+ async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1734
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
1650
1735
  const cached = cache.getResolvedSvelteField(importee, importer);
1651
1736
  if (cached) {
1652
1737
  return cached;
1653
1738
  }
1654
- const localRequire = createRequire4(importer);
1655
- const pkgData = resolveDependencyData(importee, localRequire);
1739
+ const pkgData = await resolveDependencyData(importee, importer);
1656
1740
  if (pkgData) {
1657
1741
  const { pkg, dir } = pkgData;
1658
1742
  if (pkg.svelte) {
@@ -1682,7 +1766,7 @@ function isBareImport(importee) {
1682
1766
  }
1683
1767
 
1684
1768
  // src/utils/optimizer.ts
1685
- import { promises as fs6 } from "fs";
1769
+ import { promises as fs5 } from "fs";
1686
1770
  import path7 from "path";
1687
1771
  var PREBUNDLE_SENSITIVE_OPTIONS = [
1688
1772
  "compilerOptions",
@@ -1700,11 +1784,11 @@ async function saveSvelteMetadata(cacheDir, options) {
1700
1784
  });
1701
1785
  let existingSvelteMetadata;
1702
1786
  try {
1703
- existingSvelteMetadata = await fs6.readFile(svelteMetadataPath, "utf8");
1787
+ existingSvelteMetadata = await fs5.readFile(svelteMetadataPath, "utf8");
1704
1788
  } catch {
1705
1789
  }
1706
- await fs6.mkdir(cacheDir, { recursive: true });
1707
- await fs6.writeFile(svelteMetadataPath, currentSvelteMetadata);
1790
+ await fs5.mkdir(cacheDir, { recursive: true });
1791
+ await fs5.writeFile(svelteMetadataPath, currentSvelteMetadata);
1708
1792
  return currentSvelteMetadata !== existingSvelteMetadata;
1709
1793
  }
1710
1794
  function generateSvelteMetadata(options) {
@@ -1719,7 +1803,7 @@ function generateSvelteMetadata(options) {
1719
1803
  import { normalizePath as normalizePath3 } from "vite";
1720
1804
  import path8 from "path";
1721
1805
  import { fileURLToPath } from "url";
1722
- import fs7 from "fs";
1806
+ import fs6 from "fs";
1723
1807
 
1724
1808
  // src/ui/inspector/utils.ts
1725
1809
  var FS_PREFIX = `/@fs/`;
@@ -1796,8 +1880,8 @@ function svelteInspector() {
1796
1880
  return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1797
1881
  } else if (id.startsWith(inspectorPath)) {
1798
1882
  const file = idToFile(id);
1799
- if (fs7.existsSync(file)) {
1800
- return await fs7.promises.readFile(file, "utf-8");
1883
+ if (fs6.existsSync(file)) {
1884
+ return await fs6.promises.readFile(file, "utf-8");
1801
1885
  } else {
1802
1886
  log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1803
1887
  }
@@ -1833,6 +1917,111 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1833
1917
  };
1834
1918
  }
1835
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
+
1836
2025
  // src/index.ts
1837
2026
  function svelte(inlineOptions) {
1838
2027
  if (process.env.DEBUG != null) {
@@ -1858,7 +2047,7 @@ function svelte(inlineOptions) {
1858
2047
  log.setLevel(config.logLevel);
1859
2048
  }
1860
2049
  options = await preResolveOptions(inlineOptions, config, configEnv);
1861
- const extraViteConfig = buildExtraViteConfig(options, config);
2050
+ const extraViteConfig = await buildExtraViteConfig(options, config);
1862
2051
  log.debug("additional vite config", extraViteConfig);
1863
2052
  return extraViteConfig;
1864
2053
  },
@@ -1897,7 +2086,7 @@ function svelte(inlineOptions) {
1897
2086
  }
1898
2087
  if (viteConfig.assetsInclude(filename)) {
1899
2088
  log.debug(`load returns raw content for ${filename}`);
1900
- return fs8.readFileSync(filename, "utf-8");
2089
+ return fs7.readFileSync(filename, "utf-8");
1901
2090
  }
1902
2091
  }
1903
2092
  },
@@ -1930,19 +2119,23 @@ function svelte(inlineOptions) {
1930
2119
  }
1931
2120
  return resolvedSvelteSSR;
1932
2121
  }
1933
- try {
1934
- const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1935
- if (resolved) {
1936
- log.debug(
1937
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2122
+ const scan = !!opts?.scan;
2123
+ const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !isDepExcluded2(importee, viteConfig.optimizeDeps?.exclude ?? []);
2124
+ if (ssr || scan || !isPrebundled) {
2125
+ try {
2126
+ const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
2127
+ if (resolved) {
2128
+ log.debug(
2129
+ `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2130
+ );
2131
+ return resolved;
2132
+ }
2133
+ } catch (e) {
2134
+ log.debug.once(
2135
+ `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
2136
+ e
1938
2137
  );
1939
- return resolved;
1940
2138
  }
1941
- } catch (e) {
1942
- log.debug.once(
1943
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1944
- e
1945
- );
1946
2139
  }
1947
2140
  },
1948
2141
  async transform(code, id, opts) {
@@ -1987,6 +2180,9 @@ function svelte(inlineOptions) {
1987
2180
  throw toRollupError(e, options);
1988
2181
  }
1989
2182
  }
2183
+ },
2184
+ async buildEnd() {
2185
+ await options.stats?.finishAll();
1990
2186
  }
1991
2187
  }
1992
2188
  ];