@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.cjs CHANGED
@@ -31,12 +31,13 @@ __export(src_exports, {
31
31
  });
32
32
  module.exports = __toCommonJS(src_exports);
33
33
 
34
- // ../../node_modules/.pnpm/tsup@6.4.0/node_modules/tsup/assets/cjs_shims.js
34
+ // ../../node_modules/.pnpm/tsup@6.5.0/node_modules/tsup/assets/cjs_shims.js
35
35
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
36
36
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
37
37
 
38
38
  // src/index.ts
39
39
  var import_fs7 = __toESM(require("fs"), 1);
40
+ var import_vitefu4 = require("vitefu");
40
41
 
41
42
  // src/utils/log.ts
42
43
  var import_colors = require("kleur/colors");
@@ -317,80 +318,105 @@ function toSafe(base64) {
317
318
 
318
319
  // src/utils/compile.ts
319
320
  var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
320
- var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
321
- const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
322
- const { emitCss = true } = options;
323
- const dependencies = [];
324
- const compileOptions = {
325
- ...options.compilerOptions,
326
- filename,
327
- generate: ssr ? "ssr" : "dom",
328
- format: "esm"
329
- };
330
- if (options.hot && options.emitCss) {
331
- const hash = `s-${safeBase64Hash(normalizedFilename)}`;
332
- log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
333
- compileOptions.cssHash = () => hash;
334
- }
335
- if (ssr && compileOptions.enableSourcemap !== false) {
336
- if (typeof compileOptions.enableSourcemap === "object") {
337
- compileOptions.enableSourcemap.css = false;
338
- } else {
339
- 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
+ }
340
343
  }
341
- }
342
- let preprocessed;
343
- if (options.preprocess) {
344
- try {
345
- preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
346
- } catch (e) {
347
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
348
- 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;
349
354
  }
350
- if (preprocessed.dependencies)
351
- dependencies.push(...preprocessed.dependencies);
352
- if (preprocessed.map)
353
- compileOptions.sourcemap = preprocessed.map;
354
- }
355
- const finalCode = preprocessed ? preprocessed.code : code;
356
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
357
- filename,
358
- code: finalCode,
359
- compileOptions
360
- });
361
- if (dynamicCompileOptions && log.debug.enabled) {
362
- log.debug(
363
- `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
364
- );
365
- }
366
- const finalCompileOptions = dynamicCompileOptions ? {
367
- ...compileOptions,
368
- ...dynamicCompileOptions
369
- } : compileOptions;
370
- const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
371
- if (emitCss && compiled.css.code) {
372
- 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 += `
373
398
  import ${JSON.stringify(cssId)};
374
399
  `;
375
- }
376
- if (!ssr && makeHot) {
377
- compiled.js.code = makeHot({
378
- id: filename,
379
- compiledCode: compiled.js.code,
380
- hotOptions: options.hot,
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",
381
416
  compiled,
382
- originalCode: code,
383
- compileOptions: finalCompileOptions
384
- });
385
- }
386
- compiled.js.dependencies = dependencies;
387
- return {
388
- filename,
389
- normalizedFilename,
390
- lang: code.match(scriptLangRE)?.[1] || "js",
391
- compiled,
392
- ssr,
393
- dependencies
417
+ ssr,
418
+ dependencies
419
+ };
394
420
  };
395
421
  };
396
422
  function buildMakeHot(options) {
@@ -598,186 +624,14 @@ var SVELTE_HMR_IMPORTS = [
598
624
  "svelte-hmr/runtime/proxy-adapter-dom.js",
599
625
  "svelte-hmr"
600
626
  ];
627
+ var SVELTE_EXPORT_CONDITIONS = ["svelte"];
601
628
 
602
629
  // src/utils/options.ts
603
630
  var import_path4 = __toESM(require("path"), 1);
604
631
 
605
- // src/utils/dependencies.ts
606
- var import_path2 = __toESM(require("path"), 1);
607
- var import_fs2 = __toESM(require("fs"), 1);
608
- var import_module2 = require("module");
609
- function findRootSvelteDependencies(root, cwdFallback = true) {
610
- log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
611
- const pkgFile = import_path2.default.join(root, "package.json");
612
- if (!import_fs2.default.existsSync(pkgFile)) {
613
- if (cwdFallback) {
614
- const cwd = process.cwd();
615
- if (root !== cwd) {
616
- log.debug(`no package.json found in vite root ${root}`);
617
- return findRootSvelteDependencies(cwd, false);
618
- }
619
- }
620
- log.warn(`no package.json found, findRootSvelteDependencies failed`);
621
- return [];
622
- }
623
- const pkg = parsePkg(root);
624
- if (!pkg) {
625
- return [];
626
- }
627
- const deps = [
628
- ...Object.keys(pkg.dependencies || {}),
629
- ...Object.keys(pkg.devDependencies || {})
630
- ].filter((dep) => !is_common_without_svelte_field(dep));
631
- return getSvelteDependencies(deps, root);
632
- }
633
- function getSvelteDependencies(deps, pkgDir, path9 = []) {
634
- const result = [];
635
- const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
636
- const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
637
- for (const { pkg, dir } of resolvedDeps) {
638
- const type = getSvelteDependencyType(pkg);
639
- if (!type)
640
- continue;
641
- result.push({ name: pkg.name, type, pkg, dir, path: path9 });
642
- if (type === "component-library" && pkg.dependencies) {
643
- let dependencyNames = Object.keys(pkg.dependencies);
644
- const circular = dependencyNames.filter((name) => path9.includes(name));
645
- if (circular.length > 0) {
646
- log.warn.enabled && log.warn(
647
- `skipping circular svelte dependencies in automated vite optimizeDeps handling`,
648
- circular.map((x) => path9.concat(x).join(">"))
649
- );
650
- dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
651
- }
652
- if (path9.length === 3) {
653
- log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
654
- }
655
- result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
656
- }
657
- }
658
- return result;
659
- }
660
- function resolveDependencyData(dep, localRequire) {
661
- try {
662
- const pkgJson = `${dep}/package.json`;
663
- const pkg = localRequire(pkgJson);
664
- const dir = import_path2.default.dirname(localRequire.resolve(pkgJson));
665
- return { dir, pkg };
666
- } catch (e) {
667
- log.debug.once(`dependency ${dep} does not export package.json`, e);
668
- try {
669
- let dir = import_path2.default.dirname(localRequire.resolve(dep));
670
- while (dir) {
671
- const pkg = parsePkg(dir, true);
672
- if (pkg && pkg.name === dep) {
673
- return { dir, pkg };
674
- }
675
- const parent = import_path2.default.dirname(dir);
676
- if (parent === dir) {
677
- break;
678
- }
679
- dir = parent;
680
- }
681
- } catch (e2) {
682
- log.debug.once(`error while trying to find package.json of ${dep}`, e2);
683
- }
684
- }
685
- log.debug.once(`failed to resolve ${dep}`);
686
- }
687
- function parsePkg(dir, silent = false) {
688
- const pkgFile = import_path2.default.join(dir, "package.json");
689
- try {
690
- return JSON.parse(import_fs2.default.readFileSync(pkgFile, "utf-8"));
691
- } catch (e) {
692
- !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
693
- }
694
- }
695
- function getSvelteDependencyType(pkg) {
696
- if (isSvelteComponentLib(pkg)) {
697
- return "component-library";
698
- } else if (isSvelteLib(pkg)) {
699
- return "js-library";
700
- } else {
701
- return void 0;
702
- }
703
- }
704
- function isSvelteComponentLib(pkg) {
705
- return !!pkg.svelte;
706
- }
707
- function isSvelteLib(pkg) {
708
- return !!pkg.dependencies?.svelte || !!pkg.peerDependencies?.svelte;
709
- }
710
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
711
- "@lukeed/uuid",
712
- "@playwright/test",
713
- "@sveltejs/vite-plugin-svelte",
714
- "@sveltejs/kit",
715
- "autoprefixer",
716
- "cookie",
717
- "dotenv",
718
- "esbuild",
719
- "eslint",
720
- "jest",
721
- "mdsvex",
722
- "playwright",
723
- "postcss",
724
- "prettier",
725
- "svelte",
726
- "svelte-check",
727
- "svelte-hmr",
728
- "svelte-preprocess",
729
- "tslib",
730
- "typescript",
731
- "vite",
732
- "vitest",
733
- "__vite-browser-external"
734
- ];
735
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
736
- "@fontsource/",
737
- "@postcss-plugins/",
738
- "@rollup/",
739
- "@sveltejs/adapter-",
740
- "@types/",
741
- "@typescript-eslint/",
742
- "eslint-",
743
- "jest-",
744
- "postcss-plugin-",
745
- "prettier-plugin-",
746
- "rollup-plugin-",
747
- "vite-plugin-"
748
- ];
749
- function is_common_without_svelte_field(dependency) {
750
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
751
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
752
- );
753
- }
754
- function needsOptimization(dep, localRequire) {
755
- const depData = resolveDependencyData(dep, localRequire);
756
- if (!depData)
757
- return false;
758
- const pkg = depData.pkg;
759
- const hasEsmFields = pkg.module || pkg.exports;
760
- if (hasEsmFields)
761
- return false;
762
- if (pkg.main) {
763
- const entryExt = import_path2.default.extname(pkg.main);
764
- return !entryExt || entryExt === ".js" || entryExt === ".cjs";
765
- } else {
766
- try {
767
- localRequire.resolve(`${dep}/index.js`);
768
- return true;
769
- } catch {
770
- return false;
771
- }
772
- }
773
- }
774
-
775
- // src/utils/options.ts
776
- var import_module3 = require("module");
777
-
778
632
  // src/utils/esbuild.ts
779
- var import_fs3 = require("fs");
780
- var import_compiler2 = require("svelte/compiler");
633
+ var import_fs2 = require("fs");
634
+ var import_compiler3 = require("svelte/compiler");
781
635
 
782
636
  // src/utils/error.ts
783
637
  function toRollupError(error, options) {
@@ -832,7 +686,38 @@ function formatFrameForVite(frame) {
832
686
  return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
833
687
  }
834
688
 
689
+ // src/utils/svelte-version.ts
690
+ var import_compiler2 = require("svelte/compiler");
691
+ var svelteVersion = parseVersion(import_compiler2.VERSION);
692
+ function parseVersion(version) {
693
+ const segments = version.split(".", 3).map((s) => parseInt(s, 10));
694
+ while (segments.length < 3) {
695
+ segments.push(0);
696
+ }
697
+ return segments;
698
+ }
699
+ function compareToSvelte(version) {
700
+ const parsedVersion = parseVersion(version);
701
+ for (let i = 0; i < svelteVersion.length; i++) {
702
+ const a = parsedVersion[i];
703
+ const b = svelteVersion[i];
704
+ if (a === b) {
705
+ continue;
706
+ } else if (a > b) {
707
+ return 1;
708
+ } else {
709
+ return -1;
710
+ }
711
+ }
712
+ return 0;
713
+ }
714
+ function atLeastSvelte(version) {
715
+ const result = compareToSvelte(version) <= 0;
716
+ return result;
717
+ }
718
+
835
719
  // src/utils/esbuild.ts
720
+ var isCssString = atLeastSvelte("3.53.0");
836
721
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
837
722
  function esbuildSveltePlugin(options) {
838
723
  return {
@@ -842,22 +727,35 @@ function esbuildSveltePlugin(options) {
842
727
  return;
843
728
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
844
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
+ });
845
736
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
846
- const code = await import_fs3.promises.readFile(filename, "utf8");
737
+ const code = (0, import_fs2.readFileSync)(filename, "utf8");
847
738
  try {
848
- const contents = await compileSvelte(options, { filename, code });
739
+ const contents = await compileSvelte(options, { filename, code }, statsCollection);
849
740
  return { contents };
850
741
  } catch (e) {
851
742
  return { errors: [toESBuildError(e, options)] };
852
743
  }
853
744
  });
745
+ build.onEnd(() => {
746
+ statsCollection?.finish();
747
+ });
854
748
  }
855
749
  };
856
750
  }
857
- async function compileSvelte(options, { filename, code }) {
751
+ async function compileSvelte(options, { filename, code }, statsCollection) {
752
+ let css = options.compilerOptions.css;
753
+ if (css !== "none") {
754
+ css = isCssString ? "injected" : true;
755
+ }
858
756
  const compileOptions = {
859
757
  ...options.compilerOptions,
860
- css: true,
758
+ css,
861
759
  filename,
862
760
  format: "esm",
863
761
  generate: "dom"
@@ -865,7 +763,7 @@ async function compileSvelte(options, { filename, code }) {
865
763
  let preprocessed;
866
764
  if (options.preprocess) {
867
765
  try {
868
- preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
766
+ preprocessed = await (0, import_compiler3.preprocess)(code, options.preprocess, { filename });
869
767
  } catch (e) {
870
768
  e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
871
769
  throw e;
@@ -886,14 +784,18 @@ async function compileSvelte(options, { filename, code }) {
886
784
  ...compileOptions,
887
785
  ...dynamicCompileOptions
888
786
  } : compileOptions;
889
- const compiled = (0, import_compiler2.compile)(finalCode, finalCompileOptions);
787
+ const endStat = statsCollection?.start(filename);
788
+ const compiled = (0, import_compiler3.compile)(finalCode, finalCompileOptions);
789
+ if (endStat) {
790
+ endStat();
791
+ }
890
792
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
891
793
  }
892
794
 
893
795
  // src/utils/preprocess.ts
894
796
  var vite = __toESM(require("vite"), 1);
895
797
  var import_magic_string2 = __toESM(require("magic-string"), 1);
896
- var import_compiler3 = require("svelte/compiler");
798
+ var import_compiler4 = require("svelte/compiler");
897
799
 
898
800
  // src/utils/sourcemap.ts
899
801
  var import_magic_string = __toESM(require("magic-string"), 1);
@@ -944,7 +846,7 @@ async function buildSourceMap(from, to, filename) {
944
846
  }
945
847
 
946
848
  // src/utils/preprocess.ts
947
- var import_path3 = __toESM(require("path"), 1);
849
+ var import_path2 = __toESM(require("path"), 1);
948
850
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
949
851
  var supportedScriptLangs = ["ts"];
950
852
  function createViteScriptPreprocessor() {
@@ -977,7 +879,7 @@ function createViteStylePreprocessor(config) {
977
879
  const moduleId = `${filename}.${lang}`;
978
880
  const result = await transform(content, moduleId);
979
881
  if (result.map?.sources?.[0] === moduleId) {
980
- result.map.sources[0] = import_path3.default.basename(filename);
882
+ result.map.sources[0] = import_path2.default.basename(filename);
981
883
  }
982
884
  return {
983
885
  code: result.code,
@@ -1005,7 +907,7 @@ function getCssTransformFn(config) {
1005
907
  function createVitePreprocessorGroup(config) {
1006
908
  return {
1007
909
  markup({ content, filename }) {
1008
- return (0, import_compiler3.preprocess)(
910
+ return (0, import_compiler4.preprocess)(
1009
911
  content,
1010
912
  {
1011
913
  script: createViteScriptPreprocessor(),
@@ -1024,7 +926,7 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
1024
926
  return {
1025
927
  code: s.toString(),
1026
928
  map: s.generateDecodedMap({
1027
- source: filename ? import_path3.default.basename(filename) : void 0,
929
+ source: filename ? import_path2.default.basename(filename) : void 0,
1028
930
  hires: true
1029
931
  })
1030
932
  };
@@ -1148,99 +1050,320 @@ function validateSourceMapOutputWrapper(group, i) {
1148
1050
 
1149
1051
  // src/utils/options.ts
1150
1052
  var import_deepmerge = __toESM(require("deepmerge"), 1);
1151
- var allowedPluginOptions = /* @__PURE__ */ new Set([
1152
- "include",
1153
- "exclude",
1154
- "emitCss",
1155
- "hot",
1156
- "ignorePluginPreprocessors",
1157
- "disableDependencyReinclusion",
1158
- "prebundleSvelteLibraries",
1159
- "experimental"
1160
- ]);
1161
- var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions", "preprocess", "onwarn"]);
1162
- var allowedInlineOptions = /* @__PURE__ */ new Set([
1163
- "configFile",
1164
- "kit",
1165
- ...allowedPluginOptions,
1166
- ...knownRootOptions
1167
- ]);
1168
- function validateInlineOptions(inlineOptions) {
1169
- const invalidKeys = Object.keys(inlineOptions || {}).filter(
1170
- (key) => !allowedInlineOptions.has(key)
1171
- );
1172
- if (invalidKeys.length) {
1173
- log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in inline config`, inlineOptions);
1174
- }
1175
- }
1176
- function convertPluginOptions(config) {
1177
- if (!config) {
1178
- return;
1179
- }
1180
- const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
1181
- if (invalidRootOptions.length > 0) {
1182
- throw new Error(
1183
- `Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(
1184
- ", "
1185
- )}`
1186
- );
1187
- }
1188
- if (!config.vitePlugin) {
1189
- return config;
1190
- }
1191
- const pluginOptions = config.vitePlugin;
1192
- const pluginOptionKeys = Object.keys(pluginOptions);
1193
- const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
1194
- if (rootOptionsInPluginOptions.length > 0) {
1195
- throw new Error(
1196
- `Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(
1197
- ", "
1198
- )}`
1199
- );
1200
- }
1201
- const duplicateOptions = pluginOptionKeys.filter(
1202
- (key) => Object.prototype.hasOwnProperty.call(config, key)
1203
- );
1204
- if (duplicateOptions.length > 0) {
1205
- throw new Error(
1206
- `Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(
1207
- ", "
1208
- )}`
1209
- );
1210
- }
1211
- const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
1212
- if (unknownPluginOptions.length > 0) {
1213
- log.warn(
1214
- `ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(
1215
- ", "
1216
- )}`
1217
- );
1218
- unknownPluginOptions.forEach((unkownOption) => {
1219
- delete pluginOptions[unkownOption];
1220
- });
1053
+ var import_vitefu3 = require("vitefu");
1054
+
1055
+ // src/utils/dependencies.ts
1056
+ var import_path3 = __toESM(require("path"), 1);
1057
+ var import_promises = __toESM(require("fs/promises"), 1);
1058
+ var import_vitefu = require("vitefu");
1059
+ async function resolveDependencyData(dep, parent) {
1060
+ const depDataPath = await (0, import_vitefu.findDepPkgJsonPath)(dep, parent);
1061
+ if (!depDataPath)
1062
+ return void 0;
1063
+ try {
1064
+ return {
1065
+ dir: import_path3.default.dirname(depDataPath),
1066
+ pkg: JSON.parse(await import_promises.default.readFile(depDataPath, "utf-8"))
1067
+ };
1068
+ } catch {
1069
+ return void 0;
1221
1070
  }
1222
- const result = {
1223
- ...config,
1224
- ...pluginOptions
1225
- };
1226
- delete result.vitePlugin;
1227
- return result;
1228
1071
  }
1229
- async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1230
- const viteConfigWithResolvedRoot = {
1231
- ...viteUserConfig,
1232
- root: resolveViteRoot(viteUserConfig)
1072
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
1073
+ "@lukeed/uuid",
1074
+ "@playwright/test",
1075
+ "@sveltejs/vite-plugin-svelte",
1076
+ "@sveltejs/kit",
1077
+ "autoprefixer",
1078
+ "cookie",
1079
+ "dotenv",
1080
+ "esbuild",
1081
+ "eslint",
1082
+ "jest",
1083
+ "mdsvex",
1084
+ "playwright",
1085
+ "postcss",
1086
+ "prettier",
1087
+ "svelte",
1088
+ "svelte-check",
1089
+ "svelte-hmr",
1090
+ "svelte-preprocess",
1091
+ "tslib",
1092
+ "typescript",
1093
+ "vite",
1094
+ "vitest",
1095
+ "__vite-browser-external"
1096
+ ];
1097
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
1098
+ "@fontsource/",
1099
+ "@postcss-plugins/",
1100
+ "@rollup/",
1101
+ "@sveltejs/adapter-",
1102
+ "@types/",
1103
+ "@typescript-eslint/",
1104
+ "eslint-",
1105
+ "jest-",
1106
+ "postcss-plugin-",
1107
+ "prettier-plugin-",
1108
+ "rollup-plugin-",
1109
+ "vite-plugin-"
1110
+ ];
1111
+ function isCommonDepWithoutSvelteField(dependency) {
1112
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
1113
+ (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
1114
+ );
1115
+ }
1116
+
1117
+ // src/utils/vite-plugin-svelte-stats.ts
1118
+ var import_vitefu2 = require("vitefu");
1119
+ var import_fs3 = require("fs");
1120
+ var import_perf_hooks = require("perf_hooks");
1121
+ var defaultCollectionOptions = {
1122
+ logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
1123
+ logResult: () => true
1124
+ };
1125
+ function humanDuration(n) {
1126
+ return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1e3).toFixed(2)}s`;
1127
+ }
1128
+ function formatPackageStats(pkgStats) {
1129
+ const statLines = pkgStats.map((pkgStat) => {
1130
+ const duration = pkgStat.duration;
1131
+ const avg = duration / pkgStat.files;
1132
+ return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
1133
+ });
1134
+ statLines.unshift(["package", "files", "time", "avg"]);
1135
+ const columnWidths = statLines.reduce(
1136
+ (widths, row) => {
1137
+ for (let i = 0; i < row.length; i++) {
1138
+ const cell = row[i];
1139
+ if (widths[i] < cell.length) {
1140
+ widths[i] = cell.length;
1141
+ }
1142
+ }
1143
+ return widths;
1144
+ },
1145
+ statLines[0].map(() => 0)
1146
+ );
1147
+ const table = statLines.map(
1148
+ (row) => row.map((cell, i) => {
1149
+ if (i === 0) {
1150
+ return cell.padEnd(columnWidths[i], " ");
1151
+ } else {
1152
+ return cell.padStart(columnWidths[i], " ");
1153
+ }
1154
+ }).join(" ")
1155
+ ).join("\n");
1156
+ return table;
1157
+ }
1158
+ var VitePluginSvelteStats = class {
1159
+ constructor() {
1160
+ this._packages = [];
1161
+ this._collections = [];
1162
+ }
1163
+ startCollection(name, opts) {
1164
+ const options = {
1165
+ ...defaultCollectionOptions,
1166
+ ...opts
1167
+ };
1168
+ const stats = [];
1169
+ const collectionStart = import_perf_hooks.performance.now();
1170
+ const _this = this;
1171
+ let hasLoggedProgress = false;
1172
+ const collection = {
1173
+ name,
1174
+ options,
1175
+ stats,
1176
+ collectionStart,
1177
+ finished: false,
1178
+ start(file) {
1179
+ if (collection.finished) {
1180
+ throw new Error("called after finish() has been used");
1181
+ }
1182
+ const start = import_perf_hooks.performance.now();
1183
+ const stat = { file, start, end: start };
1184
+ return () => {
1185
+ const now = import_perf_hooks.performance.now();
1186
+ stat.end = now;
1187
+ stats.push(stat);
1188
+ if (!hasLoggedProgress && options.logInProgress(collection, now)) {
1189
+ hasLoggedProgress = true;
1190
+ log.info(`${name} in progress ...`);
1191
+ }
1192
+ };
1193
+ },
1194
+ async finish() {
1195
+ await _this._finish(collection);
1196
+ }
1197
+ };
1198
+ _this._collections.push(collection);
1199
+ return collection;
1200
+ }
1201
+ async finishAll() {
1202
+ await Promise.all(this._collections.map((c) => c.finish()));
1203
+ }
1204
+ async _finish(collection) {
1205
+ collection.finished = true;
1206
+ const now = import_perf_hooks.performance.now();
1207
+ collection.duration = now - collection.collectionStart;
1208
+ const logResult = collection.options.logResult(collection);
1209
+ if (logResult) {
1210
+ await this._aggregateStatsResult(collection);
1211
+ log.info(`${collection.name} done.`, formatPackageStats(collection.packageStats));
1212
+ }
1213
+ const index = this._collections.indexOf(collection);
1214
+ this._collections.splice(index, 1);
1215
+ collection.stats.length = 0;
1216
+ collection.stats = [];
1217
+ if (collection.packageStats) {
1218
+ collection.packageStats.length = 0;
1219
+ collection.packageStats = [];
1220
+ }
1221
+ collection.start = () => () => {
1222
+ };
1223
+ collection.finish = () => {
1224
+ };
1225
+ }
1226
+ async _aggregateStatsResult(collection) {
1227
+ const stats = collection.stats;
1228
+ for (const stat of stats) {
1229
+ let pkg = this._packages.find((p) => stat.file.startsWith(p.path));
1230
+ if (!pkg) {
1231
+ let pkgPath = await (0, import_vitefu2.findClosestPkgJsonPath)(stat.file);
1232
+ if (pkgPath) {
1233
+ let path9 = pkgPath?.replace(/package.json$/, "");
1234
+ let name = JSON.parse((0, import_fs3.readFileSync)(pkgPath, "utf-8")).name;
1235
+ if (!name) {
1236
+ pkgPath = await (0, import_vitefu2.findClosestPkgJsonPath)(path9);
1237
+ if (pkgPath) {
1238
+ path9 = pkgPath?.replace(/package.json$/, "");
1239
+ name = JSON.parse((0, import_fs3.readFileSync)(pkgPath, "utf-8")).name;
1240
+ }
1241
+ }
1242
+ if (path9 && name) {
1243
+ pkg = { path: path9, name };
1244
+ this._packages.push(pkg);
1245
+ }
1246
+ }
1247
+ }
1248
+ stat.pkg = pkg?.name ?? "$unknown";
1249
+ }
1250
+ const grouped = {};
1251
+ stats.forEach((stat) => {
1252
+ const pkg = stat.pkg;
1253
+ let group = grouped[pkg];
1254
+ if (!group) {
1255
+ group = grouped[pkg] = {
1256
+ files: 0,
1257
+ duration: 0,
1258
+ pkg
1259
+ };
1260
+ }
1261
+ group.files += 1;
1262
+ group.duration += stat.end - stat.start;
1263
+ });
1264
+ const groups = Object.values(grouped);
1265
+ groups.sort((a, b) => b.duration - a.duration);
1266
+ collection.packageStats = groups;
1267
+ }
1268
+ };
1269
+
1270
+ // src/utils/options.ts
1271
+ var cssAsString = atLeastSvelte("3.53.0");
1272
+ var allowedPluginOptions = /* @__PURE__ */ new Set([
1273
+ "include",
1274
+ "exclude",
1275
+ "emitCss",
1276
+ "hot",
1277
+ "ignorePluginPreprocessors",
1278
+ "disableDependencyReinclusion",
1279
+ "prebundleSvelteLibraries",
1280
+ "experimental"
1281
+ ]);
1282
+ var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions", "preprocess", "onwarn"]);
1283
+ var allowedInlineOptions = /* @__PURE__ */ new Set([
1284
+ "configFile",
1285
+ "kit",
1286
+ ...allowedPluginOptions,
1287
+ ...knownRootOptions
1288
+ ]);
1289
+ function validateInlineOptions(inlineOptions) {
1290
+ const invalidKeys = Object.keys(inlineOptions || {}).filter(
1291
+ (key) => !allowedInlineOptions.has(key)
1292
+ );
1293
+ if (invalidKeys.length) {
1294
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in inline config`, inlineOptions);
1295
+ }
1296
+ }
1297
+ function convertPluginOptions(config) {
1298
+ if (!config) {
1299
+ return;
1300
+ }
1301
+ const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
1302
+ if (invalidRootOptions.length > 0) {
1303
+ throw new Error(
1304
+ `Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(
1305
+ ", "
1306
+ )}`
1307
+ );
1308
+ }
1309
+ if (!config.vitePlugin) {
1310
+ return config;
1311
+ }
1312
+ const pluginOptions = config.vitePlugin;
1313
+ const pluginOptionKeys = Object.keys(pluginOptions);
1314
+ const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
1315
+ if (rootOptionsInPluginOptions.length > 0) {
1316
+ throw new Error(
1317
+ `Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(
1318
+ ", "
1319
+ )}`
1320
+ );
1321
+ }
1322
+ const duplicateOptions = pluginOptionKeys.filter(
1323
+ (key) => Object.prototype.hasOwnProperty.call(config, key)
1324
+ );
1325
+ if (duplicateOptions.length > 0) {
1326
+ throw new Error(
1327
+ `Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(
1328
+ ", "
1329
+ )}`
1330
+ );
1331
+ }
1332
+ const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
1333
+ if (unknownPluginOptions.length > 0) {
1334
+ log.warn(
1335
+ `ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(
1336
+ ", "
1337
+ )}`
1338
+ );
1339
+ unknownPluginOptions.forEach((unkownOption) => {
1340
+ delete pluginOptions[unkownOption];
1341
+ });
1342
+ }
1343
+ const result = {
1344
+ ...config,
1345
+ ...pluginOptions
1346
+ };
1347
+ delete result.vitePlugin;
1348
+ return result;
1349
+ }
1350
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1351
+ const viteConfigWithResolvedRoot = {
1352
+ ...viteUserConfig,
1353
+ root: resolveViteRoot(viteUserConfig)
1233
1354
  };
1355
+ const isBuild = viteEnv.command === "build";
1234
1356
  const defaultOptions = {
1235
1357
  extensions: [".svelte"],
1236
- emitCss: true
1358
+ emitCss: true,
1359
+ prebundleSvelteLibraries: !isBuild
1237
1360
  };
1238
1361
  const svelteConfig = convertPluginOptions(
1239
1362
  await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
1240
1363
  );
1241
1364
  const extraOptions = {
1242
1365
  root: viteConfigWithResolvedRoot.root,
1243
- isBuild: viteEnv.command === "build",
1366
+ isBuild,
1244
1367
  isServe: viteEnv.command === "serve",
1245
1368
  isDebug: process.env.DEBUG != null
1246
1369
  };
@@ -1265,13 +1388,14 @@ function mergeConfigs(...configs) {
1265
1388
  return result;
1266
1389
  }
1267
1390
  function resolveOptions(preResolveOptions2, viteConfig) {
1391
+ const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1268
1392
  const defaultOptions = {
1269
1393
  hot: viteConfig.isProduction ? false : {
1270
- injectCss: !preResolveOptions2.emitCss,
1394
+ injectCss: css === true || css === "injected",
1271
1395
  partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1272
1396
  },
1273
1397
  compilerOptions: {
1274
- css: !preResolveOptions2.emitCss,
1398
+ css,
1275
1399
  dev: !viteConfig.isProduction
1276
1400
  }
1277
1401
  };
@@ -1286,6 +1410,12 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1286
1410
  addExtraPreprocessors(merged, viteConfig);
1287
1411
  enforceOptionsForHmr(merged);
1288
1412
  enforceOptionsForProduction(merged);
1413
+ const isLogLevelInfo = [void 0, "info"].includes(viteConfig.logLevel);
1414
+ const disableCompileStats = merged.experimental?.disableCompileStats;
1415
+ const statsEnabled = disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? "build" : "dev");
1416
+ if (statsEnabled && isLogLevelInfo) {
1417
+ merged.stats = new VitePluginSvelteStats();
1418
+ }
1289
1419
  return merged;
1290
1420
  }
1291
1421
  function enforceOptionsForHmr(options) {
@@ -1299,11 +1429,13 @@ function enforceOptionsForHmr(options) {
1299
1429
  log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1300
1430
  options.hot.injectCss = false;
1301
1431
  }
1302
- if (options.compilerOptions.css) {
1432
+ const css = options.compilerOptions.css;
1433
+ if (css === true || css === "injected") {
1434
+ const forcedCss = cssAsString ? "external" : false;
1303
1435
  log.warn(
1304
- "hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false"
1436
+ `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
1305
1437
  );
1306
- options.compilerOptions.css = false;
1438
+ options.compilerOptions.css = forcedCss;
1307
1439
  }
1308
1440
  } else {
1309
1441
  if (options.hot === true || !options.hot.injectCss) {
@@ -1316,11 +1448,13 @@ function enforceOptionsForHmr(options) {
1316
1448
  options.hot.injectCss = true;
1317
1449
  }
1318
1450
  }
1319
- if (!options.compilerOptions.css) {
1451
+ const css = options.compilerOptions.css;
1452
+ if (!(css === true || css === "injected")) {
1453
+ const forcedCss = cssAsString ? "injected" : true;
1320
1454
  log.warn(
1321
- "hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true"
1455
+ `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
1322
1456
  );
1323
- options.compilerOptions.css = true;
1457
+ options.compilerOptions.css = forcedCss;
1324
1458
  }
1325
1459
  }
1326
1460
  }
@@ -1358,16 +1492,9 @@ function removeIgnoredOptions(options) {
1358
1492
  }
1359
1493
  }
1360
1494
  function addSvelteKitOptions(options) {
1361
- if (options?.kit != null) {
1362
- const kit_browser_hydrate = options.kit.browser?.hydrate;
1363
- const hydratable = kit_browser_hydrate !== false;
1364
- if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1365
- log.warn(
1366
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
1367
- );
1368
- }
1369
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1370
- options.compilerOptions.hydratable = hydratable;
1495
+ if (options?.kit != null && options.compilerOptions.hydratable == null) {
1496
+ log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
1497
+ options.compilerOptions.hydratable = true;
1371
1498
  }
1372
1499
  }
1373
1500
  function handleDeprecatedOptions(options) {
@@ -1381,19 +1508,44 @@ function handleDeprecatedOptions(options) {
1381
1508
  function resolveViteRoot(viteConfig) {
1382
1509
  return (0, import_vite3.normalizePath)(viteConfig.root ? import_path4.default.resolve(viteConfig.root) : process.cwd());
1383
1510
  }
1384
- function buildExtraViteConfig(options, config) {
1385
- const svelteDeps = findRootSvelteDependencies(options.root);
1511
+ async function buildExtraViteConfig(options, config) {
1386
1512
  const extraViteConfig = {
1387
1513
  resolve: {
1388
1514
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1389
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1515
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1516
+ conditions: [...SVELTE_EXPORT_CONDITIONS]
1390
1517
  }
1391
1518
  };
1392
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
1393
- svelteDeps,
1394
- options,
1395
- config.optimizeDeps
1396
- );
1519
+ const extraSvelteConfig = buildExtraConfigForSvelte(config);
1520
+ const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
1521
+ extraViteConfig.optimizeDeps = {
1522
+ include: [
1523
+ ...extraSvelteConfig.optimizeDeps.include,
1524
+ ...extraDepsConfig.optimizeDeps.include.filter(
1525
+ (dep) => !(0, import_vitefu3.isDepExcluded)(dep, extraSvelteConfig.optimizeDeps.exclude)
1526
+ )
1527
+ ],
1528
+ exclude: [
1529
+ ...extraSvelteConfig.optimizeDeps.exclude,
1530
+ ...extraDepsConfig.optimizeDeps.exclude.filter(
1531
+ (dep) => !(0, import_vitefu3.isDepIncluded)(dep, extraSvelteConfig.optimizeDeps.include)
1532
+ )
1533
+ ]
1534
+ };
1535
+ extraViteConfig.ssr = {
1536
+ external: [
1537
+ ...extraSvelteConfig.ssr.external,
1538
+ ...extraDepsConfig.ssr.external.filter(
1539
+ (dep) => !(0, import_vitefu3.isDepNoExternaled)(dep, extraSvelteConfig.ssr.noExternal)
1540
+ )
1541
+ ],
1542
+ noExternal: [
1543
+ ...extraSvelteConfig.ssr.noExternal,
1544
+ ...extraDepsConfig.ssr.noExternal.filter(
1545
+ (dep) => !(0, import_vitefu3.isDepExternaled)(dep, extraSvelteConfig.ssr.external)
1546
+ )
1547
+ ]
1548
+ };
1397
1549
  if (options.prebundleSvelteLibraries) {
1398
1550
  extraViteConfig.optimizeDeps = {
1399
1551
  ...extraViteConfig.optimizeDeps,
@@ -1404,77 +1556,111 @@ function buildExtraViteConfig(options, config) {
1404
1556
  }
1405
1557
  };
1406
1558
  }
1407
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1408
1559
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1409
1560
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1410
1561
  extraViteConfig.experimental = { hmrPartialAccept: true };
1411
1562
  }
1563
+ validateViteConfig(extraViteConfig, config, options);
1412
1564
  return extraViteConfig;
1413
1565
  }
1414
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1566
+ function validateViteConfig(extraViteConfig, config, options) {
1567
+ const { prebundleSvelteLibraries, isBuild } = options;
1568
+ if (prebundleSvelteLibraries) {
1569
+ const isEnabled = (option) => option !== true && option !== (isBuild ? "build" : "dev");
1570
+ const logWarning = (name, value, recommendation) => log.warn.once(
1571
+ `Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
1572
+ value
1573
+ )}\` ${isBuild ? "during build." : "."} ${recommendation}`
1574
+ );
1575
+ const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? "build";
1576
+ const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
1577
+ if (!isBuild && !isOptimizeDepsEnabled) {
1578
+ logWarning(
1579
+ "optimizeDeps.disabled",
1580
+ viteOptimizeDepsDisabled,
1581
+ 'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
1582
+ );
1583
+ extraViteConfig.optimizeDeps.disabled = "build";
1584
+ } else if (isBuild && isOptimizeDepsEnabled) {
1585
+ logWarning(
1586
+ "optimizeDeps.disabled",
1587
+ viteOptimizeDepsDisabled,
1588
+ "Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors."
1589
+ );
1590
+ }
1591
+ }
1592
+ }
1593
+ async function buildExtraConfigForDependencies(options, config) {
1594
+ const depsConfig = await (0, import_vitefu3.crawlFrameworkPkgs)({
1595
+ root: options.root,
1596
+ isBuild: options.isBuild,
1597
+ viteUserConfig: config,
1598
+ isFrameworkPkgByJson(pkgJson) {
1599
+ let hasSvelteCondition = false;
1600
+ if (typeof pkgJson.exports === "object") {
1601
+ JSON.stringify(pkgJson.exports, (key, value) => {
1602
+ if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
1603
+ hasSvelteCondition = true;
1604
+ }
1605
+ return value;
1606
+ });
1607
+ }
1608
+ return hasSvelteCondition || !!pkgJson.svelte;
1609
+ },
1610
+ isSemiFrameworkPkgByJson(pkgJson) {
1611
+ return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
1612
+ },
1613
+ isFrameworkPkgByName(pkgName) {
1614
+ const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
1615
+ if (isNotSveltePackage) {
1616
+ return false;
1617
+ } else {
1618
+ return void 0;
1619
+ }
1620
+ }
1621
+ });
1622
+ log.debug("extra config for dependencies generated by vitefu", depsConfig);
1623
+ if (options.prebundleSvelteLibraries) {
1624
+ depsConfig.optimizeDeps.exclude = [];
1625
+ const userExclude = config.optimizeDeps?.exclude;
1626
+ depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1627
+ return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => (0, import_vitefu3.isDepExcluded)(d.trim(), userExclude));
1628
+ });
1629
+ }
1630
+ if (options.disableDependencyReinclusion === true) {
1631
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
1632
+ (dep) => !dep.includes(">")
1633
+ );
1634
+ } else if (Array.isArray(options.disableDependencyReinclusion)) {
1635
+ const disabledDeps = options.disableDependencyReinclusion;
1636
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
1637
+ if (!dep.includes(">"))
1638
+ return true;
1639
+ const trimDep = dep.replace(/\s+/g, "");
1640
+ return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
1641
+ });
1642
+ }
1643
+ log.debug("post-processed extra config for dependencies", depsConfig);
1644
+ return depsConfig;
1645
+ }
1646
+ function buildExtraConfigForSvelte(config) {
1415
1647
  const include = [];
1416
1648
  const exclude = ["svelte-hmr"];
1417
- const isIncluded = (dep) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
1418
- const isExcluded = (dep) => {
1419
- return exclude.includes(dep) || optimizeDeps?.exclude?.some((id) => dep === id || id.startsWith(`${dep}/`));
1420
- };
1421
- if (!isExcluded("svelte")) {
1649
+ if (!(0, import_vitefu3.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1422
1650
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1423
1651
  log.debug(
1424
1652
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1425
1653
  );
1426
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1654
+ include.push(...svelteImportsToInclude);
1427
1655
  } else {
1428
1656
  log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1429
1657
  }
1430
- if (options.prebundleSvelteLibraries) {
1431
- return { include, exclude };
1432
- }
1433
- svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1434
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
1435
- (dep) => !isIncluded(dep)
1436
- );
1437
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1438
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1439
- if (options.disableDependencyReinclusion !== true) {
1440
- const disabledReinclusions = options.disableDependencyReinclusion || [];
1441
- if (disabledReinclusions.length > 0) {
1442
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1443
- }
1444
- const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1445
- const localRequire = (0, import_module3.createRequire)(`${dep.dir}/package.json`);
1446
- return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1447
- });
1448
- log.debug(
1449
- `reincluding transitive dependencies of excluded svelte dependencies`,
1450
- transitiveDepsToInclude
1451
- );
1452
- include.push(...transitiveDepsToInclude);
1453
- }
1454
- return { include, exclude };
1455
- }
1456
- function buildSSROptionsForSvelte(svelteDeps, options, config) {
1457
1658
  const noExternal = [];
1458
- if (!config.ssr?.external?.includes("svelte")) {
1659
+ const external = [];
1660
+ if (!(0, import_vitefu3.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1459
1661
  noExternal.push("svelte", /^svelte\//);
1460
1662
  }
1461
- noExternal.push(
1462
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
1463
- (x) => !config.ssr?.external?.includes(x)
1464
- )
1465
- );
1466
- const ssr = {
1467
- noExternal,
1468
- external: []
1469
- };
1470
- if (options.isServe) {
1471
- ssr.external = Array.from(
1472
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
1473
- ).filter(
1474
- (dep) => !ssr.noExternal.includes(dep) && !config.ssr?.external?.includes(dep)
1475
- );
1476
- }
1477
- return ssr;
1663
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1478
1664
  }
1479
1665
  function patchResolvedViteConfig(viteConfig, options) {
1480
1666
  const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
@@ -1485,111 +1671,6 @@ function patchResolvedViteConfig(viteConfig, options) {
1485
1671
  }
1486
1672
  }
1487
1673
 
1488
- // src/utils/vite-plugin-svelte-cache.ts
1489
- var VitePluginSvelteCache = class {
1490
- constructor() {
1491
- this._css = /* @__PURE__ */ new Map();
1492
- this._js = /* @__PURE__ */ new Map();
1493
- this._dependencies = /* @__PURE__ */ new Map();
1494
- this._dependants = /* @__PURE__ */ new Map();
1495
- this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1496
- this._errors = /* @__PURE__ */ new Map();
1497
- }
1498
- update(compileData) {
1499
- this._errors.delete(compileData.normalizedFilename);
1500
- this.updateCSS(compileData);
1501
- this.updateJS(compileData);
1502
- this.updateDependencies(compileData);
1503
- }
1504
- has(svelteRequest) {
1505
- const id = svelteRequest.normalizedFilename;
1506
- return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1507
- }
1508
- setError(svelteRequest, error) {
1509
- this.remove(svelteRequest, true);
1510
- this._errors.set(svelteRequest.normalizedFilename, error);
1511
- }
1512
- updateCSS(compileData) {
1513
- this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1514
- }
1515
- updateJS(compileData) {
1516
- if (!compileData.ssr) {
1517
- this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1518
- }
1519
- }
1520
- updateDependencies(compileData) {
1521
- const id = compileData.normalizedFilename;
1522
- const prevDependencies = this._dependencies.get(id) || [];
1523
- const dependencies = compileData.dependencies;
1524
- this._dependencies.set(id, dependencies);
1525
- const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1526
- const added = dependencies.filter((d) => !prevDependencies.includes(d));
1527
- added.forEach((d) => {
1528
- if (!this._dependants.has(d)) {
1529
- this._dependants.set(d, /* @__PURE__ */ new Set());
1530
- }
1531
- this._dependants.get(d).add(compileData.filename);
1532
- });
1533
- removed.forEach((d) => {
1534
- this._dependants.get(d).delete(compileData.filename);
1535
- });
1536
- }
1537
- remove(svelteRequest, keepDependencies = false) {
1538
- const id = svelteRequest.normalizedFilename;
1539
- let removed = false;
1540
- if (this._errors.delete(id)) {
1541
- removed = true;
1542
- }
1543
- if (this._js.delete(id)) {
1544
- removed = true;
1545
- }
1546
- if (this._css.delete(id)) {
1547
- removed = true;
1548
- }
1549
- if (!keepDependencies) {
1550
- const dependencies = this._dependencies.get(id);
1551
- if (dependencies) {
1552
- removed = true;
1553
- dependencies.forEach((d) => {
1554
- const dependants = this._dependants.get(d);
1555
- if (dependants && dependants.has(svelteRequest.filename)) {
1556
- dependants.delete(svelteRequest.filename);
1557
- }
1558
- });
1559
- this._dependencies.delete(id);
1560
- }
1561
- }
1562
- return removed;
1563
- }
1564
- getCSS(svelteRequest) {
1565
- return this._css.get(svelteRequest.normalizedFilename);
1566
- }
1567
- getJS(svelteRequest) {
1568
- if (!svelteRequest.ssr) {
1569
- return this._js.get(svelteRequest.normalizedFilename);
1570
- }
1571
- }
1572
- getError(svelteRequest) {
1573
- return this._errors.get(svelteRequest.normalizedFilename);
1574
- }
1575
- getDependants(path9) {
1576
- const dependants = this._dependants.get(path9);
1577
- return dependants ? [...dependants] : [];
1578
- }
1579
- getResolvedSvelteField(name, importer) {
1580
- return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1581
- }
1582
- setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1583
- this._resolvedSvelteFields.set(
1584
- this._getResolvedSvelteFieldKey(importee, importer),
1585
- resolvedSvelte
1586
- );
1587
- }
1588
- _getResolvedSvelteFieldKey(importee, importer) {
1589
- return importer ? `${importer} > ${importee}` : importee;
1590
- }
1591
- };
1592
-
1593
1674
  // src/utils/watch.ts
1594
1675
  var import_fs4 = __toESM(require("fs"), 1);
1595
1676
  var import_path5 = __toESM(require("path"), 1);
@@ -1671,15 +1752,14 @@ function ensureWatchedFile(watcher, file, root) {
1671
1752
 
1672
1753
  // src/utils/resolve.ts
1673
1754
  var import_path6 = __toESM(require("path"), 1);
1674
- var import_module4 = require("module");
1675
- function resolveViaPackageJsonSvelte(importee, importer, cache) {
1676
- if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1755
+ var import_module2 = require("module");
1756
+ async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1757
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
1677
1758
  const cached = cache.getResolvedSvelteField(importee, importer);
1678
1759
  if (cached) {
1679
1760
  return cached;
1680
1761
  }
1681
- const localRequire = (0, import_module4.createRequire)(importer);
1682
- const pkgData = resolveDependencyData(importee, localRequire);
1762
+ const pkgData = await resolveDependencyData(importee, importer);
1683
1763
  if (pkgData) {
1684
1764
  const { pkg, dir } = pkgData;
1685
1765
  if (pkg.svelte) {
@@ -1691,7 +1771,7 @@ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1691
1771
  }
1692
1772
  }
1693
1773
  function isNodeInternal(importee) {
1694
- return importee.startsWith("node:") || import_module4.builtinModules.includes(importee);
1774
+ return importee.startsWith("node:") || import_module2.builtinModules.includes(importee);
1695
1775
  }
1696
1776
  function isBareImport(importee) {
1697
1777
  if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path6.default.isAbsolute(importee)) {
@@ -1860,6 +1940,111 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1860
1940
  };
1861
1941
  }
1862
1942
 
1943
+ // src/utils/vite-plugin-svelte-cache.ts
1944
+ var VitePluginSvelteCache = class {
1945
+ constructor() {
1946
+ this._css = /* @__PURE__ */ new Map();
1947
+ this._js = /* @__PURE__ */ new Map();
1948
+ this._dependencies = /* @__PURE__ */ new Map();
1949
+ this._dependants = /* @__PURE__ */ new Map();
1950
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1951
+ this._errors = /* @__PURE__ */ new Map();
1952
+ }
1953
+ update(compileData) {
1954
+ this._errors.delete(compileData.normalizedFilename);
1955
+ this.updateCSS(compileData);
1956
+ this.updateJS(compileData);
1957
+ this.updateDependencies(compileData);
1958
+ }
1959
+ has(svelteRequest) {
1960
+ const id = svelteRequest.normalizedFilename;
1961
+ return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1962
+ }
1963
+ setError(svelteRequest, error) {
1964
+ this.remove(svelteRequest, true);
1965
+ this._errors.set(svelteRequest.normalizedFilename, error);
1966
+ }
1967
+ updateCSS(compileData) {
1968
+ this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1969
+ }
1970
+ updateJS(compileData) {
1971
+ if (!compileData.ssr) {
1972
+ this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1973
+ }
1974
+ }
1975
+ updateDependencies(compileData) {
1976
+ const id = compileData.normalizedFilename;
1977
+ const prevDependencies = this._dependencies.get(id) || [];
1978
+ const dependencies = compileData.dependencies;
1979
+ this._dependencies.set(id, dependencies);
1980
+ const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1981
+ const added = dependencies.filter((d) => !prevDependencies.includes(d));
1982
+ added.forEach((d) => {
1983
+ if (!this._dependants.has(d)) {
1984
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1985
+ }
1986
+ this._dependants.get(d).add(compileData.filename);
1987
+ });
1988
+ removed.forEach((d) => {
1989
+ this._dependants.get(d).delete(compileData.filename);
1990
+ });
1991
+ }
1992
+ remove(svelteRequest, keepDependencies = false) {
1993
+ const id = svelteRequest.normalizedFilename;
1994
+ let removed = false;
1995
+ if (this._errors.delete(id)) {
1996
+ removed = true;
1997
+ }
1998
+ if (this._js.delete(id)) {
1999
+ removed = true;
2000
+ }
2001
+ if (this._css.delete(id)) {
2002
+ removed = true;
2003
+ }
2004
+ if (!keepDependencies) {
2005
+ const dependencies = this._dependencies.get(id);
2006
+ if (dependencies) {
2007
+ removed = true;
2008
+ dependencies.forEach((d) => {
2009
+ const dependants = this._dependants.get(d);
2010
+ if (dependants && dependants.has(svelteRequest.filename)) {
2011
+ dependants.delete(svelteRequest.filename);
2012
+ }
2013
+ });
2014
+ this._dependencies.delete(id);
2015
+ }
2016
+ }
2017
+ return removed;
2018
+ }
2019
+ getCSS(svelteRequest) {
2020
+ return this._css.get(svelteRequest.normalizedFilename);
2021
+ }
2022
+ getJS(svelteRequest) {
2023
+ if (!svelteRequest.ssr) {
2024
+ return this._js.get(svelteRequest.normalizedFilename);
2025
+ }
2026
+ }
2027
+ getError(svelteRequest) {
2028
+ return this._errors.get(svelteRequest.normalizedFilename);
2029
+ }
2030
+ getDependants(path9) {
2031
+ const dependants = this._dependants.get(path9);
2032
+ return dependants ? [...dependants] : [];
2033
+ }
2034
+ getResolvedSvelteField(name, importer) {
2035
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
2036
+ }
2037
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
2038
+ this._resolvedSvelteFields.set(
2039
+ this._getResolvedSvelteFieldKey(importee, importer),
2040
+ resolvedSvelte
2041
+ );
2042
+ }
2043
+ _getResolvedSvelteFieldKey(importee, importer) {
2044
+ return importer ? `${importer} > ${importee}` : importee;
2045
+ }
2046
+ };
2047
+
1863
2048
  // src/index.ts
1864
2049
  function svelte(inlineOptions) {
1865
2050
  if (process.env.DEBUG != null) {
@@ -1885,7 +2070,7 @@ function svelte(inlineOptions) {
1885
2070
  log.setLevel(config.logLevel);
1886
2071
  }
1887
2072
  options = await preResolveOptions(inlineOptions, config, configEnv);
1888
- const extraViteConfig = buildExtraViteConfig(options, config);
2073
+ const extraViteConfig = await buildExtraViteConfig(options, config);
1889
2074
  log.debug("additional vite config", extraViteConfig);
1890
2075
  return extraViteConfig;
1891
2076
  },
@@ -1957,19 +2142,23 @@ function svelte(inlineOptions) {
1957
2142
  }
1958
2143
  return resolvedSvelteSSR;
1959
2144
  }
1960
- try {
1961
- const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1962
- if (resolved) {
1963
- log.debug(
1964
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2145
+ const scan = !!opts?.scan;
2146
+ const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !(0, import_vitefu4.isDepExcluded)(importee, viteConfig.optimizeDeps?.exclude ?? []);
2147
+ if (ssr || scan || !isPrebundled) {
2148
+ try {
2149
+ const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
2150
+ if (resolved) {
2151
+ log.debug(
2152
+ `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2153
+ );
2154
+ return resolved;
2155
+ }
2156
+ } catch (e) {
2157
+ log.debug.once(
2158
+ `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
2159
+ e
1965
2160
  );
1966
- return resolved;
1967
2161
  }
1968
- } catch (e) {
1969
- log.debug.once(
1970
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1971
- e
1972
- );
1973
2162
  }
1974
2163
  },
1975
2164
  async transform(code, id, opts) {
@@ -2014,6 +2203,9 @@ function svelte(inlineOptions) {
2014
2203
  throw toRollupError(e, options);
2015
2204
  }
2016
2205
  }
2206
+ },
2207
+ async buildEnd() {
2208
+ await options.stats?.finishAll();
2017
2209
  }
2018
2210
  }
2019
2211
  ];