@sveltejs/vite-plugin-svelte 1.0.0-next.30 → 1.0.0-next.34

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
@@ -26,7 +26,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
26
26
  });
27
27
 
28
28
  // src/index.ts
29
- import fs7 from "fs";
29
+ import fs8 from "fs";
30
30
 
31
31
  // src/utils/log.ts
32
32
  import { cyan, yellow, red } from "kleur/colors";
@@ -89,7 +89,7 @@ function _log(logger, message, payload) {
89
89
  function createLogger(level) {
90
90
  const logger = loggers[level];
91
91
  const logFn = _log.bind(null, logger);
92
- const logged = new Set();
92
+ const logged = /* @__PURE__ */ new Set();
93
93
  const once = function(message, payload) {
94
94
  if (logged.has(message)) {
95
95
  return;
@@ -181,7 +181,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
181
181
  const content = await read();
182
182
  const compileData = await compileSvelte2(svelteRequest, content, options);
183
183
  cache.update(compileData);
184
- const affectedModules = new Set();
184
+ const affectedModules = /* @__PURE__ */ new Set();
185
185
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
186
186
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
187
187
  const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
@@ -245,16 +245,14 @@ import { compile, preprocess, walk } from "svelte/compiler";
245
245
  import { createMakeHot } from "svelte-hmr";
246
246
 
247
247
  // src/utils/hash.ts
248
- import {
249
- createHash
250
- } from "crypto";
251
- var hashes = Object.create(null);
248
+ import * as crypto from "crypto";
249
+ var hashes = /* @__PURE__ */ Object.create(null);
252
250
  var hash_length = 12;
253
251
  function safeBase64Hash(input) {
254
252
  if (hashes[input]) {
255
253
  return hashes[input];
256
254
  }
257
- const md5 = createHash("md5");
255
+ const md5 = crypto.createHash("md5");
258
256
  md5.update(input);
259
257
  const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
260
258
  hashes[input] = hash;
@@ -357,9 +355,7 @@ function createCompileSvelte(options) {
357
355
  // src/utils/id.ts
358
356
  import { createFilter } from "@rollup/pluginutils";
359
357
  import { normalizePath } from "vite";
360
- import {
361
- existsSync
362
- } from "fs";
358
+ import * as fs from "fs";
363
359
  var VITE_FS_PREFIX = "/@fs/";
364
360
  var IS_WINDOWS = process.platform === "win32";
365
361
  function splitId(id) {
@@ -413,7 +409,7 @@ function existsInRoot(filename, root) {
413
409
  if (filename.startsWith(VITE_FS_PREFIX)) {
414
410
  return false;
415
411
  }
416
- return existsSync(root + filename);
412
+ return fs.existsSync(root + filename);
417
413
  }
418
414
  function stripRoot(normalizedFilename, normalizedRoot) {
419
415
  return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
@@ -435,7 +431,9 @@ function buildIdParser(options) {
435
431
  }
436
432
 
437
433
  // src/utils/options.ts
438
- import { normalizePath as normalizePath2 } from "vite";
434
+ import {
435
+ normalizePath as normalizePath2
436
+ } from "vite";
439
437
 
440
438
  // src/utils/load-svelte-config.ts
441
439
  import { createRequire } from "module";
@@ -470,7 +468,7 @@ async function loadSvelteConfig(viteConfig, inlineOptions) {
470
468
  }
471
469
  if (!configFile.endsWith(".mjs")) {
472
470
  try {
473
- const _require = import.meta.url ? esmRequire != null ? esmRequire : esmRequire = createRequire(import.meta.url) : __require;
471
+ const _require = import.meta.url ? esmRequire ?? (esmRequire = createRequire(import.meta.url)) : __require;
474
472
  delete _require.cache[_require.resolve(configFile)];
475
473
  const result = _require(configFile);
476
474
  if (result != null) {
@@ -560,7 +558,7 @@ function findRootSvelteDependencies(root, cwdFallback = true) {
560
558
  ].filter((dep) => !is_common_without_svelte_field(dep));
561
559
  return getSvelteDependencies(deps, root);
562
560
  }
563
- function getSvelteDependencies(deps, pkgDir, path6 = []) {
561
+ function getSvelteDependencies(deps, pkgDir, path7 = []) {
564
562
  const result = [];
565
563
  const localRequire = createRequire2(`${pkgDir}/package.json`);
566
564
  const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
@@ -568,18 +566,18 @@ function getSvelteDependencies(deps, pkgDir, path6 = []) {
568
566
  const type = getSvelteDependencyType(pkg);
569
567
  if (!type)
570
568
  continue;
571
- result.push({ name: pkg.name, type, pkg, dir, path: path6 });
569
+ result.push({ name: pkg.name, type, pkg, dir, path: path7 });
572
570
  if (type === "component-library" && pkg.dependencies) {
573
571
  let dependencyNames = Object.keys(pkg.dependencies);
574
- const circular = dependencyNames.filter((name) => path6.includes(name));
572
+ const circular = dependencyNames.filter((name) => path7.includes(name));
575
573
  if (circular.length > 0) {
576
- log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
577
- dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
574
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path7.concat(x).join(">")));
575
+ dependencyNames = dependencyNames.filter((name) => !path7.includes(name));
578
576
  }
579
- if (path6.length === 3) {
580
- log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
577
+ if (path7.length === 3) {
578
+ log.debug.once(`encountered deep svelte dependency tree: ${path7.join(">")}`);
581
579
  }
582
- result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
580
+ result.push(...getSvelteDependencies(dependencyNames, dir, path7.concat(pkg.name)));
583
581
  }
584
582
  }
585
583
  return result;
@@ -678,7 +676,11 @@ function needsOptimization(dep, localRequire) {
678
676
  if (!depData)
679
677
  return false;
680
678
  const pkg = depData.pkg;
681
- return pkg.main && !pkg.module && !pkg.exports;
679
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
680
+ if (!isCjs)
681
+ return false;
682
+ const entryExt = path2.extname(pkg.main);
683
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
682
684
  }
683
685
 
684
686
  // src/utils/options.ts
@@ -687,18 +689,74 @@ import { createRequire as createRequire3 } from "module";
687
689
  // src/utils/esbuild.ts
688
690
  import { promises as fs4 } from "fs";
689
691
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
692
+
693
+ // src/utils/error.ts
694
+ function toRollupError(error) {
695
+ const { filename, frame, start, code, name } = error;
696
+ const rollupError = {
697
+ name,
698
+ id: filename,
699
+ message: buildExtendedLogMessage(error),
700
+ frame: formatFrameForVite(frame),
701
+ code,
702
+ stack: ""
703
+ };
704
+ if (start) {
705
+ rollupError.loc = {
706
+ line: start.line,
707
+ column: start.column,
708
+ file: filename
709
+ };
710
+ }
711
+ return rollupError;
712
+ }
713
+ function toESBuildError(error) {
714
+ const { filename, frame, start } = error;
715
+ const partialMessage = {
716
+ text: buildExtendedLogMessage(error)
717
+ };
718
+ if (start) {
719
+ partialMessage.location = {
720
+ line: start.line,
721
+ column: start.column,
722
+ file: filename,
723
+ lineText: lineFromFrame(start.line, frame)
724
+ };
725
+ }
726
+ return partialMessage;
727
+ }
728
+ function lineFromFrame(lineNo, frame) {
729
+ if (!frame) {
730
+ return "";
731
+ }
732
+ const lines = frame.split("\n");
733
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
734
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
735
+ }
736
+ function formatFrameForVite(frame) {
737
+ if (!frame) {
738
+ return "";
739
+ }
740
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
741
+ }
742
+
743
+ // src/utils/esbuild.ts
744
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
690
745
  function esbuildSveltePlugin(options) {
691
746
  return {
692
747
  name: "vite-plugin-svelte:optimize-svelte",
693
748
  setup(build) {
694
- var _a;
695
749
  disableVitePrebundleSvelte(build);
696
- const svelteExtensions = ((_a = options.extensions) != null ? _a : [".svelte"]).map((ext) => ext.slice(1));
750
+ const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
697
751
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
698
752
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
699
753
  const code = await fs4.readFile(filename, "utf8");
700
- const contents = await compileSvelte(options, { filename, code });
701
- return { contents };
754
+ try {
755
+ const contents = await compileSvelte(options, { filename, code });
756
+ return { contents };
757
+ } catch (e) {
758
+ return { errors: [toESBuildError(e)] };
759
+ }
702
760
  });
703
761
  }
704
762
  };
@@ -725,6 +783,7 @@ async function compileSvelte(options, { filename, code }) {
725
783
  const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
726
784
  css: true,
727
785
  filename,
786
+ format: "esm",
728
787
  generate: "dom"
729
788
  });
730
789
  let preprocessed;
@@ -747,8 +806,237 @@ async function compileSvelte(options, { filename, code }) {
747
806
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
748
807
  }
749
808
 
809
+ // src/utils/preprocess.ts
810
+ import {
811
+ transformWithEsbuild
812
+ } from "vite";
813
+ import MagicString2 from "magic-string";
814
+ import { preprocess as preprocess3 } from "svelte/compiler";
815
+
816
+ // src/utils/sourcemap.ts
817
+ import MagicString from "magic-string";
818
+ async function buildMagicString(from, to, options) {
819
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
820
+ try {
821
+ const dmpPkg = await import("diff-match-patch");
822
+ diff_match_patch = dmpPkg.diff_match_patch;
823
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
824
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
825
+ } catch (e) {
826
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
827
+ return null;
828
+ }
829
+ const dmp = new diff_match_patch();
830
+ const diffs = dmp.diff_main(from, to);
831
+ dmp.diff_cleanupSemantic(diffs);
832
+ const m = new MagicString(from, options);
833
+ let pos = 0;
834
+ for (let i = 0; i < diffs.length; i++) {
835
+ const diff = diffs[i];
836
+ const nextDiff = diffs[i + 1];
837
+ if (diff[0] === DIFF_DELETE) {
838
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
839
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
840
+ i++;
841
+ } else {
842
+ m.remove(pos, pos + diff[1].length);
843
+ }
844
+ pos += diff[1].length;
845
+ } else if (diff[0] === DIFF_INSERT) {
846
+ if (nextDiff) {
847
+ m.appendRight(pos, diff[1]);
848
+ } else {
849
+ m.append(diff[1]);
850
+ }
851
+ } else {
852
+ pos += diff[1].length;
853
+ }
854
+ }
855
+ return m;
856
+ }
857
+ async function buildSourceMap(from, to, filename) {
858
+ const m = await buildMagicString(from, to, { filename });
859
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
860
+ }
861
+
862
+ // src/utils/preprocess.ts
863
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
864
+ var supportedScriptLangs = ["ts"];
865
+ function createViteScriptPreprocessor() {
866
+ return async ({ attributes, content, filename = "" }) => {
867
+ const lang = attributes.lang;
868
+ if (!supportedScriptLangs.includes(lang))
869
+ return;
870
+ const transformResult = await transformWithEsbuild(content, filename, {
871
+ loader: lang,
872
+ tsconfigRaw: {
873
+ compilerOptions: {
874
+ importsNotUsedAsValues: "preserve",
875
+ preserveValueImports: true
876
+ }
877
+ }
878
+ });
879
+ return {
880
+ code: transformResult.code,
881
+ map: transformResult.map
882
+ };
883
+ };
884
+ }
885
+ function createViteStylePreprocessor(config) {
886
+ const pluginName = "vite:css";
887
+ const plugin = config.plugins.find((p) => p.name === pluginName);
888
+ if (!plugin) {
889
+ throw new Error(`failed to find plugin ${pluginName}`);
890
+ }
891
+ if (!plugin.transform) {
892
+ throw new Error(`plugin ${pluginName} has no transform`);
893
+ }
894
+ const pluginTransform = plugin.transform.bind(null);
895
+ return async ({ attributes, content, filename = "" }) => {
896
+ var _a, _b;
897
+ const lang = attributes.lang;
898
+ if (!supportedStyleLangs.includes(lang))
899
+ return;
900
+ const moduleId = `${filename}.${lang}`;
901
+ const transformResult = await pluginTransform(content, moduleId);
902
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
903
+ transformResult.map.sources[0] = filename;
904
+ }
905
+ return {
906
+ code: transformResult.code,
907
+ map: transformResult.map ?? void 0
908
+ };
909
+ };
910
+ }
911
+ function createVitePreprocessorGroup(config) {
912
+ return {
913
+ markup({ content, filename }) {
914
+ return preprocess3(content, {
915
+ script: createViteScriptPreprocessor(),
916
+ style: createViteStylePreprocessor(config)
917
+ }, { filename });
918
+ }
919
+ };
920
+ }
921
+ function createInjectScopeEverythingRulePreprocessorGroup() {
922
+ return {
923
+ style({ content, filename }) {
924
+ const s = new MagicString2(content);
925
+ s.append(" *{}");
926
+ return {
927
+ code: s.toString(),
928
+ map: s.generateDecodedMap({ source: filename, hires: true })
929
+ };
930
+ }
931
+ };
932
+ }
933
+ function buildExtraPreprocessors(options, config) {
934
+ var _a, _b;
935
+ const prependPreprocessors = [];
936
+ const appendPreprocessors = [];
937
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
938
+ log.debug("adding vite preprocessor");
939
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
940
+ }
941
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
942
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
943
+ log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
944
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
945
+ if (!p.api) {
946
+ p.api = {};
947
+ }
948
+ if (p.api.sveltePreprocess === void 0) {
949
+ p.api.sveltePreprocess = p.sveltePreprocess;
950
+ } else {
951
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
952
+ }
953
+ });
954
+ }
955
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
956
+ var _a2;
957
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
958
+ });
959
+ const ignored = [], included = [];
960
+ for (const p of pluginsWithPreprocessors) {
961
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
962
+ ignored.push(p);
963
+ } else {
964
+ included.push(p);
965
+ }
966
+ }
967
+ if (ignored.length > 0) {
968
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
969
+ }
970
+ if (included.length > 0) {
971
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
972
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
973
+ }
974
+ if (options.hot && options.emitCss) {
975
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
976
+ }
977
+ return { prependPreprocessors, appendPreprocessors };
978
+ }
979
+ function addExtraPreprocessors(options, config) {
980
+ var _a;
981
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
982
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
983
+ if (!options.preprocess) {
984
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
985
+ } else if (Array.isArray(options.preprocess)) {
986
+ options.preprocess.unshift(...prependPreprocessors);
987
+ options.preprocess.push(...appendPreprocessors);
988
+ } else {
989
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
990
+ }
991
+ }
992
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
993
+ if (options.preprocess && generateMissingSourceMaps) {
994
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
995
+ }
996
+ }
997
+ function validateSourceMapOutputWrapper(group, i) {
998
+ const wrapper = {};
999
+ for (const [processorType, processorFn] of Object.entries(group)) {
1000
+ wrapper[processorType] = async (options) => {
1001
+ var _a;
1002
+ const result = await processorFn(options);
1003
+ if (result && result.code !== options.content) {
1004
+ let invalidMap = false;
1005
+ if (!result.map) {
1006
+ invalidMap = true;
1007
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1008
+ filename: options.filename,
1009
+ type: processorType,
1010
+ processor: processorFn.toString()
1011
+ });
1012
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1013
+ invalidMap = true;
1014
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1015
+ filename: options.filename,
1016
+ type: processorType,
1017
+ processor: processorFn.toString()
1018
+ });
1019
+ }
1020
+ if (invalidMap) {
1021
+ try {
1022
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1023
+ if (map) {
1024
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1025
+ result.map = map;
1026
+ }
1027
+ } catch (e) {
1028
+ log.error(`failed to build sourcemap`, e);
1029
+ }
1030
+ }
1031
+ }
1032
+ return result;
1033
+ };
1034
+ }
1035
+ return wrapper;
1036
+ }
1037
+
750
1038
  // src/utils/options.ts
751
- var knownOptions = new Set([
1039
+ var knownOptions = /* @__PURE__ */ new Set([
752
1040
  "configFile",
753
1041
  "include",
754
1042
  "exclude",
@@ -762,30 +1050,55 @@ var knownOptions = new Set([
762
1050
  "disableDependencyReinclusion",
763
1051
  "experimental"
764
1052
  ]);
765
- function buildDefaultOptions(isProduction, emitCss = true) {
766
- const hot = isProduction ? false : {
767
- injectCss: !emitCss
768
- };
769
- const defaultOptions = {
770
- extensions: [".svelte"],
771
- hot,
772
- emitCss,
773
- compilerOptions: {
774
- format: "esm",
775
- css: !emitCss,
776
- dev: !isProduction
777
- }
778
- };
779
- log.debug(`default options for ${isProduction ? "production" : "development"}`, defaultOptions);
780
- return defaultOptions;
781
- }
782
1053
  function validateInlineOptions(inlineOptions) {
783
1054
  const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
784
1055
  if (invalidKeys.length) {
785
1056
  log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
786
1057
  }
787
1058
  }
788
- function enforceOptionsForHmr(options) {
1059
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1060
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1061
+ root: resolveViteRoot(viteUserConfig)
1062
+ });
1063
+ const defaultOptions = {
1064
+ extensions: [".svelte"],
1065
+ emitCss: true,
1066
+ compilerOptions: {
1067
+ format: "esm"
1068
+ }
1069
+ };
1070
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1071
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1072
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1073
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1074
+ root: viteConfigWithResolvedRoot.root,
1075
+ isBuild: viteEnv.command === "build",
1076
+ isServe: viteEnv.command === "serve"
1077
+ });
1078
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1079
+ merged.configFile = svelteConfig.configFile;
1080
+ }
1081
+ return merged;
1082
+ }
1083
+ function resolveOptions(preResolveOptions2, viteConfig) {
1084
+ const defaultOptions = {
1085
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1086
+ compilerOptions: {
1087
+ css: !preResolveOptions2.emitCss,
1088
+ dev: !viteConfig.isProduction
1089
+ }
1090
+ };
1091
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1092
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1093
+ root: viteConfig.root,
1094
+ isProduction: viteConfig.isProduction
1095
+ });
1096
+ addExtraPreprocessors(merged, viteConfig);
1097
+ enforceOptionsForHmr(merged);
1098
+ enforceOptionsForProduction(merged);
1099
+ return merged;
1100
+ }
1101
+ function enforceOptionsForHmr(options) {
789
1102
  if (options.hot) {
790
1103
  if (!options.compilerOptions.dev) {
791
1104
  log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
@@ -828,32 +1141,6 @@ function enforceOptionsForProduction(options) {
828
1141
  }
829
1142
  }
830
1143
  }
831
- function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig, viteEnv) {
832
- const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
833
- compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
834
- experimental: __spreadValues(__spreadValues({}, (svelteConfig == null ? void 0 : svelteConfig.experimental) || {}), (inlineOptions == null ? void 0 : inlineOptions.experimental) || {}),
835
- root: viteConfig.root,
836
- isProduction: viteEnv.mode === "production",
837
- isBuild: viteEnv.command === "build",
838
- isServe: viteEnv.command === "serve"
839
- });
840
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
841
- merged.configFile = svelteConfig.configFile;
842
- }
843
- return merged;
844
- }
845
- async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
846
- var _a;
847
- const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
848
- root: resolveViteRoot(viteConfig)
849
- });
850
- const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
851
- const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", (_a = inlineOptions.emitCss) != null ? _a : svelteConfig.emitCss);
852
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
853
- enforceOptionsForProduction(resolvedOptions);
854
- enforceOptionsForHmr(resolvedOptions);
855
- return resolvedOptions;
856
- }
857
1144
  function resolveViteRoot(viteConfig) {
858
1145
  return normalizePath2(viteConfig.root ? path3.resolve(viteConfig.root) : process.cwd());
859
1146
  }
@@ -871,16 +1158,16 @@ function buildExtraViteConfig(options, config, configEnv) {
871
1158
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
872
1159
  return extraViteConfig;
873
1160
  }
874
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1161
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
875
1162
  const include = [];
876
1163
  const exclude = ["svelte-hmr"];
877
1164
  const isIncluded = (dep) => {
878
1165
  var _a;
879
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1166
+ return include.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.include) == null ? void 0 : _a.includes(dep));
880
1167
  };
881
1168
  const isExcluded = (dep) => {
882
1169
  var _a;
883
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1170
+ return exclude.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
884
1171
  };
885
1172
  if (!isExcluded("svelte")) {
886
1173
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -894,7 +1181,8 @@ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
894
1181
  include,
895
1182
  exclude,
896
1183
  esbuildOptions: {
897
- plugins: [esbuildSveltePlugin(options)]
1184
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1185
+ } }]
898
1186
  }
899
1187
  };
900
1188
  }
@@ -934,14 +1222,21 @@ function buildSSROptionsForSvelte(svelteDeps, options, config) {
934
1222
  noExternal
935
1223
  };
936
1224
  }
1225
+ function patchResolvedViteConfig(viteConfig, options) {
1226
+ var _a, _b;
1227
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1228
+ if (facadeEsbuildSveltePlugin) {
1229
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1230
+ }
1231
+ }
937
1232
 
938
1233
  // src/utils/vite-plugin-svelte-cache.ts
939
1234
  var VitePluginSvelteCache = class {
940
1235
  constructor() {
941
- this._css = new Map();
942
- this._js = new Map();
943
- this._dependencies = new Map();
944
- this._dependants = new Map();
1236
+ this._css = /* @__PURE__ */ new Map();
1237
+ this._js = /* @__PURE__ */ new Map();
1238
+ this._dependencies = /* @__PURE__ */ new Map();
1239
+ this._dependants = /* @__PURE__ */ new Map();
945
1240
  }
946
1241
  update(compileData) {
947
1242
  this.updateCSS(compileData);
@@ -965,7 +1260,7 @@ var VitePluginSvelteCache = class {
965
1260
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
966
1261
  added.forEach((d) => {
967
1262
  if (!this._dependants.has(d)) {
968
- this._dependants.set(d, new Set());
1263
+ this._dependants.set(d, /* @__PURE__ */ new Set());
969
1264
  }
970
1265
  this._dependants.get(d).add(compileData.filename);
971
1266
  });
@@ -1003,8 +1298,8 @@ var VitePluginSvelteCache = class {
1003
1298
  return this._js.get(svelteRequest.normalizedFilename);
1004
1299
  }
1005
1300
  }
1006
- getDependants(path6) {
1007
- const dependants = this._dependants.get(path6);
1301
+ getDependants(path7) {
1302
+ const dependants = this._dependants.get(path7);
1008
1303
  return dependants ? [...dependants] : [];
1009
1304
  }
1010
1305
  };
@@ -1018,7 +1313,7 @@ function setupWatchers(options, cache, requestParser) {
1018
1313
  return;
1019
1314
  }
1020
1315
  const { watcher, ws } = server;
1021
- const { configFile: viteConfigFile, root, server: serverConfig } = server.config;
1316
+ const { root, server: serverConfig } = server.config;
1022
1317
  const emitChangeEventOnDependants = (filename) => {
1023
1318
  const dependants = cache.getDependants(filename);
1024
1319
  dependants.forEach((dependant) => {
@@ -1038,16 +1333,16 @@ function setupWatchers(options, cache, requestParser) {
1038
1333
  }
1039
1334
  };
1040
1335
  const triggerViteRestart = (filename) => {
1041
- if (!!viteConfigFile && !serverConfig.middlewareMode) {
1042
- log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1043
- watcher.emit("change", viteConfigFile);
1044
- } else {
1336
+ if (serverConfig.middlewareMode) {
1045
1337
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1046
1338
  log.info(message, filename);
1047
1339
  ws.send({
1048
1340
  type: "error",
1049
1341
  err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1050
1342
  });
1343
+ } else {
1344
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1345
+ server.restart();
1051
1346
  }
1052
1347
  };
1053
1348
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path4.join(root, cfg));
@@ -1098,7 +1393,7 @@ function resolveViaPackageJsonSvelte(importee, importer) {
1098
1393
  }
1099
1394
  }
1100
1395
  function isBareImport(importee) {
1101
- if (!importee || importee[0] === "." || importee[0] === "\0" || path5.isAbsolute(importee)) {
1396
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || path5.isAbsolute(importee)) {
1102
1397
  return false;
1103
1398
  }
1104
1399
  const parts = importee.split("/");
@@ -1112,233 +1407,42 @@ function isBareImport(importee) {
1112
1407
  }
1113
1408
  }
1114
1409
 
1115
- // src/utils/preprocess.ts
1116
- import {
1117
- transformWithEsbuild
1118
- } from "vite";
1119
- import MagicString2 from "magic-string";
1120
- import { preprocess as preprocess3 } from "svelte/compiler";
1121
-
1122
- // src/utils/sourcemap.ts
1123
- import MagicString from "magic-string";
1124
- async function buildMagicString(from, to, options) {
1125
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
1126
- try {
1127
- const dmpPkg = await import("diff-match-patch");
1128
- diff_match_patch = dmpPkg.diff_match_patch;
1129
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
1130
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
1131
- } catch (e) {
1132
- log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
1133
- return null;
1134
- }
1135
- const dmp = new diff_match_patch();
1136
- const diffs = dmp.diff_main(from, to);
1137
- dmp.diff_cleanupSemantic(diffs);
1138
- const m = new MagicString(from, options);
1139
- let pos = 0;
1140
- for (let i = 0; i < diffs.length; i++) {
1141
- const diff = diffs[i];
1142
- const nextDiff = diffs[i + 1];
1143
- if (diff[0] === DIFF_DELETE) {
1144
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
1145
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
1146
- i++;
1147
- } else {
1148
- m.remove(pos, pos + diff[1].length);
1149
- }
1150
- pos += diff[1].length;
1151
- } else if (diff[0] === DIFF_INSERT) {
1152
- if (nextDiff) {
1153
- m.appendRight(pos, diff[1]);
1154
- } else {
1155
- m.append(diff[1]);
1156
- }
1157
- } else {
1158
- pos += diff[1].length;
1159
- }
1160
- }
1161
- return m;
1162
- }
1163
- async function buildSourceMap(from, to, filename) {
1164
- const m = await buildMagicString(from, to, { filename });
1165
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
1166
- }
1167
-
1168
- // src/utils/preprocess.ts
1169
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
1170
- var supportedScriptLangs = ["ts"];
1171
- function createViteScriptPreprocessor() {
1172
- return async ({ attributes, content, filename = "" }) => {
1173
- const lang = attributes.lang;
1174
- if (!supportedScriptLangs.includes(lang))
1175
- return;
1176
- const transformResult = await transformWithEsbuild(content, filename, {
1177
- loader: lang,
1178
- tsconfigRaw: {
1179
- compilerOptions: {
1180
- importsNotUsedAsValues: "preserve"
1181
- }
1182
- }
1183
- });
1184
- return {
1185
- code: transformResult.code,
1186
- map: transformResult.map
1187
- };
1188
- };
1189
- }
1190
- function createViteStylePreprocessor(config) {
1191
- const pluginName = "vite:css";
1192
- const plugin = config.plugins.find((p) => p.name === pluginName);
1193
- if (!plugin) {
1194
- throw new Error(`failed to find plugin ${pluginName}`);
1195
- }
1196
- if (!plugin.transform) {
1197
- throw new Error(`plugin ${pluginName} has no transform`);
1198
- }
1199
- const pluginTransform = plugin.transform.bind(null);
1200
- return async ({ attributes, content, filename = "" }) => {
1201
- var _a, _b;
1202
- const lang = attributes.lang;
1203
- if (!supportedStyleLangs.includes(lang))
1204
- return;
1205
- const moduleId = `${filename}.${lang}`;
1206
- const transformResult = await pluginTransform(content, moduleId);
1207
- const hasMap = transformResult.map && transformResult.map.mappings !== "";
1208
- if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
1209
- transformResult.map.sources[0] = filename;
1210
- }
1211
- return {
1212
- code: transformResult.code,
1213
- map: hasMap ? transformResult.map : void 0
1214
- };
1215
- };
1216
- }
1217
- function createVitePreprocessorGroup(config) {
1218
- return {
1219
- markup({ content, filename }) {
1220
- return preprocess3(content, {
1221
- script: createViteScriptPreprocessor(),
1222
- style: createViteStylePreprocessor(config)
1223
- }, { filename });
1224
- }
1225
- };
1226
- }
1227
- function createInjectScopeEverythingRulePreprocessorGroup() {
1228
- return {
1229
- style({ content, filename }) {
1230
- const s = new MagicString2(content);
1231
- s.append(" *{}");
1232
- return {
1233
- code: s.toString(),
1234
- map: s.generateDecodedMap({ source: filename, hires: true })
1235
- };
1236
- }
1237
- };
1238
- }
1239
- function buildExtraPreprocessors(options, config) {
1240
- var _a, _b;
1241
- const prependPreprocessors = [];
1242
- const appendPreprocessors = [];
1243
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
1244
- log.debug("adding vite preprocessor");
1245
- prependPreprocessors.push(createVitePreprocessorGroup(config));
1246
- }
1247
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
1248
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
1249
- log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
1250
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
1251
- if (!p.api) {
1252
- p.api = {};
1253
- }
1254
- if (p.api.sveltePreprocess === void 0) {
1255
- p.api.sveltePreprocess = p.sveltePreprocess;
1256
- } else {
1257
- log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
1258
- }
1259
- });
1260
- }
1261
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1262
- var _a2;
1263
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1410
+ // src/utils/optimizer.ts
1411
+ import fs7 from "fs";
1412
+ import path6 from "path";
1413
+ import { optimizeDeps } from "vite";
1414
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1415
+ "compilerOptions",
1416
+ "configFile",
1417
+ "experimental",
1418
+ "extensions",
1419
+ "ignorePluginPreprocessors",
1420
+ "preprocess"
1421
+ ];
1422
+ async function handleOptimizeDeps(options, viteConfig) {
1423
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1424
+ return;
1425
+ const viteMetadataPath = path6.resolve(viteConfig.cacheDir, "_metadata.json");
1426
+ if (!fs7.existsSync(viteMetadataPath))
1427
+ return;
1428
+ const svelteMetadataPath = path6.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1429
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1430
+ return typeof value === "function" ? value.toString() : value;
1264
1431
  });
1265
- const ignored = [], included = [];
1266
- for (const p of pluginsWithPreprocessors) {
1267
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1268
- ignored.push(p);
1269
- } else {
1270
- included.push(p);
1271
- }
1272
- }
1273
- if (ignored.length > 0) {
1274
- log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1275
- }
1276
- if (included.length > 0) {
1277
- log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1278
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1279
- }
1280
- if (options.hot && options.emitCss) {
1281
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1432
+ if (fs7.existsSync(svelteMetadataPath)) {
1433
+ const existingSvelteMetadata = fs7.readFileSync(svelteMetadataPath, "utf8");
1434
+ if (existingSvelteMetadata === currentSvelteMetadata)
1435
+ return;
1282
1436
  }
1283
- return { prependPreprocessors, appendPreprocessors };
1437
+ await optimizeDeps(viteConfig, true);
1438
+ fs7.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1284
1439
  }
1285
- function addExtraPreprocessors(options, config) {
1286
- var _a;
1287
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1288
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1289
- if (!options.preprocess) {
1290
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1291
- } else if (Array.isArray(options.preprocess)) {
1292
- options.preprocess.unshift(...prependPreprocessors);
1293
- options.preprocess.push(...appendPreprocessors);
1294
- } else {
1295
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1296
- }
1297
- }
1298
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1299
- if (options.preprocess && generateMissingSourceMaps) {
1300
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1440
+ function generateSvelteMetadata(options) {
1441
+ const metadata = {};
1442
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1443
+ metadata[key] = options[key];
1301
1444
  }
1302
- }
1303
- function validateSourceMapOutputWrapper(group, i) {
1304
- const wrapper = {};
1305
- for (const [processorType, processorFn] of Object.entries(group)) {
1306
- wrapper[processorType] = async (options) => {
1307
- var _a;
1308
- const result = await processorFn(options);
1309
- if (result && result.code !== options.content) {
1310
- let invalidMap = false;
1311
- if (!result.map) {
1312
- invalidMap = true;
1313
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1314
- filename: options.filename,
1315
- type: processorType,
1316
- processor: processorFn.toString()
1317
- });
1318
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1319
- invalidMap = true;
1320
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1321
- filename: options.filename,
1322
- type: processorType,
1323
- processor: processorFn.toString()
1324
- });
1325
- }
1326
- if (invalidMap) {
1327
- try {
1328
- const map = await buildSourceMap(options.content, result.code, options.filename);
1329
- if (map) {
1330
- log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1331
- result.map = map;
1332
- }
1333
- } catch (e) {
1334
- log.error(`failed to build sourcemap`, e);
1335
- }
1336
- }
1337
- }
1338
- return result;
1339
- };
1340
- }
1341
- return wrapper;
1445
+ return metadata;
1342
1446
  }
1343
1447
 
1344
1448
  // src/index.ts
@@ -1348,7 +1452,7 @@ function svelte(inlineOptions) {
1348
1452
  }
1349
1453
  validateInlineOptions(inlineOptions);
1350
1454
  const cache = new VitePluginSvelteCache();
1351
- const pkg_export_errors = new Set();
1455
+ const pkg_export_errors = /* @__PURE__ */ new Set();
1352
1456
  let requestParser;
1353
1457
  let options;
1354
1458
  let viteConfig;
@@ -1363,18 +1467,22 @@ function svelte(inlineOptions) {
1363
1467
  } else if (config.logLevel) {
1364
1468
  log.setLevel(config.logLevel);
1365
1469
  }
1366
- options = await resolveOptions(inlineOptions, config, configEnv);
1470
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1367
1471
  const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1368
1472
  log.debug("additional vite config", extraViteConfig);
1369
1473
  return extraViteConfig;
1370
1474
  },
1371
1475
  async configResolved(config) {
1372
- addExtraPreprocessors(options, config);
1476
+ options = resolveOptions(options, config);
1477
+ patchResolvedViteConfig(config, options);
1373
1478
  requestParser = buildIdParser(options);
1374
1479
  compileSvelte2 = createCompileSvelte(options);
1375
1480
  viteConfig = config;
1376
1481
  log.debug("resolved options", options);
1377
1482
  },
1483
+ async buildStart() {
1484
+ await handleOptimizeDeps(options, viteConfig);
1485
+ },
1378
1486
  configureServer(server) {
1379
1487
  options.server = server;
1380
1488
  setupWatchers(options, cache, requestParser);
@@ -1393,13 +1501,13 @@ function svelte(inlineOptions) {
1393
1501
  }
1394
1502
  if (viteConfig.assetsInclude(filename)) {
1395
1503
  log.debug(`load returns raw content for ${filename}`);
1396
- return fs7.readFileSync(filename, "utf-8");
1504
+ return fs8.readFileSync(filename, "utf-8");
1397
1505
  }
1398
1506
  }
1399
1507
  },
1400
- async resolveId(importee, importer, opts, _ssr) {
1401
- const ssr = _ssr === true || opts.ssr;
1402
- const svelteRequest = requestParser(importee, !!ssr);
1508
+ async resolveId(importee, importer, opts) {
1509
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1510
+ const svelteRequest = requestParser(importee, ssr);
1403
1511
  if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1404
1512
  if (svelteRequest.query.type === "style") {
1405
1513
  log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
@@ -1440,8 +1548,8 @@ function svelte(inlineOptions) {
1440
1548
  },
1441
1549
  async transform(code, id, opts) {
1442
1550
  var _a;
1443
- const ssr = opts === true || (opts == null ? void 0 : opts.ssr);
1444
- const svelteRequest = requestParser(id, !!ssr);
1551
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1552
+ const svelteRequest = requestParser(id, ssr);
1445
1553
  if (!svelteRequest) {
1446
1554
  return;
1447
1555
  }
@@ -1457,7 +1565,12 @@ function svelte(inlineOptions) {
1457
1565
  log.error("failed to transform tagged svelte request", svelteRequest);
1458
1566
  throw new Error(`failed to transform tagged svelte request for id ${id}`);
1459
1567
  }
1460
- const compileData = await compileSvelte2(svelteRequest, code, options);
1568
+ let compileData;
1569
+ try {
1570
+ compileData = await compileSvelte2(svelteRequest, code, options);
1571
+ } catch (e) {
1572
+ throw toRollupError(e);
1573
+ }
1461
1574
  logCompilerWarnings(compileData.compiled.warnings, options);
1462
1575
  cache.update(compileData);
1463
1576
  if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
@@ -1487,4 +1600,4 @@ function svelte(inlineOptions) {
1487
1600
  export {
1488
1601
  svelte
1489
1602
  };
1490
- //# sourceMappingURL=index.js.map
1603
+ //# sourceMappingURL=index.js.map