@sveltejs/vite-plugin-svelte 1.0.0-next.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,71 +1,37 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
10
- var __assign = (a, b) => {
11
- for (var prop in b || (b = {}))
12
- if (__hasOwnProp.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- if (__getOwnPropSymbols)
15
- for (var prop of __getOwnPropSymbols(b)) {
16
- if (__propIsEnum.call(b, prop))
17
- __defNormalProp(a, prop, b[prop]);
18
- }
19
- return a;
20
- };
21
- var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
22
- var __export = (target, all) => {
23
- for (var name in all)
24
- __defProp(target, name, {get: all[name], enumerable: true});
25
- };
26
- var __exportStar = (target, module2, desc) => {
27
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
28
- for (let key of __getOwnPropNames(module2))
29
- if (!__hasOwnProp.call(target, key) && key !== "default")
30
- __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
31
- }
32
- return target;
33
- };
34
- var __toModule = (module2) => {
35
- return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2);
36
- };
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
37
8
 
38
9
  // src/index.ts
39
- __markAsModule(exports);
40
- __export(exports, {
41
- default: () => vitePluginSvelte
42
- });
43
- var path2 = __toModule(require("path"));
44
- var relative = __toModule(require("require-relative"));
10
+ import fs8 from "fs";
45
11
 
46
12
  // src/utils/log.ts
47
- var import_chalk = __toModule(require("chalk"));
48
- var import_debug = __toModule(require("debug"));
13
+ import { cyan, yellow, red } from "kleur/colors";
14
+ import debug from "debug";
49
15
  var levels = ["debug", "info", "warn", "error", "silent"];
50
16
  var prefix = "vite-plugin-svelte";
51
17
  var loggers = {
52
18
  debug: {
53
- log: (0, import_debug.default)(`vite:${prefix}`),
19
+ log: debug(`vite:${prefix}`),
54
20
  enabled: false,
55
21
  isDebug: true
56
22
  },
57
23
  info: {
58
- color: import_chalk.default.cyan,
24
+ color: cyan,
59
25
  log: console.log,
60
26
  enabled: true
61
27
  },
62
28
  warn: {
63
- color: import_chalk.default.yellow,
29
+ color: yellow,
64
30
  log: console.warn,
65
31
  enabled: true
66
32
  },
67
33
  error: {
68
- color: import_chalk.default.red,
34
+ color: red,
69
35
  log: console.error,
70
36
  enabled: true
71
37
  },
@@ -88,10 +54,6 @@ function setLevel(level) {
88
54
  _log(loggers.error, `invalid log level: ${level} `);
89
55
  }
90
56
  }
91
- var _viteLogOverwriteProtection = false;
92
- function setViteLogOverwriteProtection(viteLogOverwriteProtection) {
93
- _viteLogOverwriteProtection = viteLogOverwriteProtection;
94
- }
95
57
  function _log(logger, message, payload) {
96
58
  if (!logger.enabled) {
97
59
  return;
@@ -99,23 +61,33 @@ function _log(logger, message, payload) {
99
61
  if (logger.isDebug) {
100
62
  payload !== void 0 ? logger.log(message, payload) : logger.log(message);
101
63
  } else {
102
- logger.log(logger.color(`[${prefix}] ${message}`));
64
+ logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
103
65
  if (payload) {
104
66
  logger.log(payload);
105
67
  }
106
68
  }
107
- if (_viteLogOverwriteProtection) {
108
- logger.log("");
109
- }
110
69
  }
111
70
  function createLogger(level) {
112
71
  const logger = loggers[level];
113
72
  const logFn = _log.bind(null, logger);
73
+ const logged = /* @__PURE__ */ new Set();
74
+ const once = function(message, payload) {
75
+ if (logged.has(message)) {
76
+ return;
77
+ }
78
+ logged.add(message);
79
+ logFn.apply(null, [message, payload]);
80
+ };
114
81
  Object.defineProperty(logFn, "enabled", {
115
82
  get() {
116
83
  return logger.enabled;
117
84
  }
118
85
  });
86
+ Object.defineProperty(logFn, "once", {
87
+ get() {
88
+ return once;
89
+ }
90
+ });
119
91
  return logFn;
120
92
  }
121
93
  var log = {
@@ -123,40 +95,132 @@ var log = {
123
95
  info: createLogger("info"),
124
96
  warn: createLogger("warn"),
125
97
  error: createLogger("error"),
126
- setLevel,
127
- setViteLogOverwriteProtection
98
+ setLevel
128
99
  };
100
+ function logCompilerWarnings(svelteRequest, warnings, options) {
101
+ var _a, _b, _c;
102
+ const { emitCss, onwarn, isBuild } = options;
103
+ const sendViaWS = !isBuild && ((_a = options.experimental) == null ? void 0 : _a.sendWarningsToBrowser);
104
+ let warn = isBuild ? warnBuild : warnDev;
105
+ const handledByDefaultWarn = [];
106
+ const notIgnored = warnings == null ? void 0 : warnings.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
107
+ const extra = buildExtraWarnings(warnings, isBuild);
108
+ const allWarnings = [...notIgnored, ...extra];
109
+ if (sendViaWS) {
110
+ const _warn = warn;
111
+ warn = (w) => {
112
+ handledByDefaultWarn.push(w);
113
+ _warn(w);
114
+ };
115
+ }
116
+ allWarnings.forEach((warning) => {
117
+ if (onwarn) {
118
+ onwarn(warning, warn);
119
+ } else {
120
+ warn(warning);
121
+ }
122
+ });
123
+ if (sendViaWS) {
124
+ const message = {
125
+ id: svelteRequest.id,
126
+ filename: svelteRequest.filename,
127
+ normalizedFilename: svelteRequest.normalizedFilename,
128
+ timestamp: svelteRequest.timestamp,
129
+ warnings: handledByDefaultWarn,
130
+ allWarnings,
131
+ rawWarnings: warnings
132
+ };
133
+ log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`);
134
+ (_c = (_b = options.server) == null ? void 0 : _b.ws) == null ? void 0 : _c.send("svelte:warnings", message);
135
+ }
136
+ }
137
+ function ignoreCompilerWarning(warning, isBuild, emitCss) {
138
+ return !emitCss && warning.code === "css-unused-selector" || !isBuild && isNoScopableElementWarning(warning);
139
+ }
140
+ function isNoScopableElementWarning(warning) {
141
+ return warning.code === "css-unused-selector" && warning.message.includes('"*"');
142
+ }
143
+ function buildExtraWarnings(warnings, isBuild) {
144
+ const extraWarnings = [];
145
+ if (!isBuild) {
146
+ const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w));
147
+ if (noScopableElementWarnings.length > 0) {
148
+ const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1];
149
+ extraWarnings.push({
150
+ ...noScopableElementWarning,
151
+ code: "vite-plugin-svelte-css-no-scopable-elements",
152
+ message: `No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#where-should-i-put-my-global-styles.`
153
+ });
154
+ }
155
+ }
156
+ return extraWarnings;
157
+ }
158
+ function warnDev(w) {
159
+ log.info.enabled && log.info(buildExtendedLogMessage(w));
160
+ }
161
+ function warnBuild(w) {
162
+ log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
163
+ }
164
+ function buildExtendedLogMessage(w) {
165
+ const parts = [];
166
+ if (w.filename) {
167
+ parts.push(w.filename);
168
+ }
169
+ if (w.start) {
170
+ parts.push(":", w.start.line, ":", w.start.column);
171
+ }
172
+ if (w.message) {
173
+ if (parts.length > 0) {
174
+ parts.push(" ");
175
+ }
176
+ parts.push(w.message);
177
+ }
178
+ return parts.join("");
179
+ }
129
180
 
130
- // src/handleHotUpdate.ts
131
- async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) {
132
- const {read, server} = ctx;
133
- const cachedJS = cache.getJS(svelteRequest);
134
- if (!cachedJS) {
135
- log.debug(`handleHotUpdate first call ${svelteRequest.id}`);
181
+ // src/handle-hot-update.ts
182
+ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) {
183
+ if (!cache.has(svelteRequest)) {
184
+ log.debug(`handleHotUpdate called before initial transform for ${svelteRequest.id}`);
136
185
  return;
137
186
  }
187
+ const { read, server } = ctx;
188
+ const cachedJS = cache.getJS(svelteRequest);
138
189
  const cachedCss = cache.getCSS(svelteRequest);
139
190
  const content = await read();
140
- const compileData = await compileSvelte(svelteRequest, content, options);
141
- cache.update(compileData);
142
- const affectedModules = new Set();
191
+ let compileData;
192
+ try {
193
+ compileData = await compileSvelte2(svelteRequest, content, options);
194
+ cache.update(compileData);
195
+ } catch (e) {
196
+ cache.setError(svelteRequest, e);
197
+ throw e;
198
+ }
199
+ const affectedModules = /* @__PURE__ */ new Set();
143
200
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
144
201
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
145
- if (cssModule && cssChanged(cachedCss, compileData.compiled.css)) {
146
- log.debug("handleHotUpdate css changed");
202
+ const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
203
+ if (cssUpdated) {
204
+ log.debug(`handleHotUpdate css changed for ${svelteRequest.cssId}`);
147
205
  affectedModules.add(cssModule);
148
206
  }
149
- if (mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename)) {
150
- log.debug("handleHotUpdate js changed");
207
+ const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
208
+ if (jsUpdated) {
209
+ log.debug(`handleHotUpdate js changed for ${svelteRequest.id}`);
151
210
  affectedModules.add(mainModule);
152
211
  }
212
+ if (!jsUpdated) {
213
+ logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
214
+ }
153
215
  const result = [...affectedModules].filter(Boolean);
154
- log.debug(`handleHotUpdate result for ${svelteRequest.id}`, result);
155
216
  const ssrModulesToInvalidate = result.filter((m) => !!m.ssrTransformResult);
156
217
  if (ssrModulesToInvalidate.length > 0) {
157
218
  log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
158
219
  ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
159
220
  }
221
+ if (result.length > 0) {
222
+ log.debug(`handleHotUpdate for ${svelteRequest.id} result: ${result.map((m) => m.id).join(", ")}`);
223
+ }
160
224
  return result;
161
225
  }
162
226
  function cssChanged(prev, next) {
@@ -192,12 +256,12 @@ function normalizeJsCode(code) {
192
256
  }
193
257
 
194
258
  // src/utils/compile.ts
195
- var import_compiler = __toModule(require("svelte/compiler"));
196
- var import_svelte_hmr = __toModule(require("svelte-hmr"));
259
+ import { compile, preprocess, walk } from "svelte/compiler";
260
+ import { createMakeHot } from "svelte-hmr";
197
261
 
198
262
  // src/utils/hash.ts
199
- var crypto = __toModule(require("crypto"));
200
- var hashes = Object.create(null);
263
+ import * as crypto from "crypto";
264
+ var hashes = /* @__PURE__ */ Object.create(null);
201
265
  var hash_length = 12;
202
266
  function safeBase64Hash(input) {
203
267
  if (hashes[input]) {
@@ -205,7 +269,7 @@ function safeBase64Hash(input) {
205
269
  }
206
270
  const md5 = crypto.createHash("md5");
207
271
  md5.update(input);
208
- const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
272
+ const hash = toSafe(md5.digest("base64")).slice(0, hash_length);
209
273
  hashes[input] = hash;
210
274
  return hash;
211
275
  }
@@ -220,36 +284,57 @@ function toSafe(base64) {
220
284
  }
221
285
 
222
286
  // src/utils/compile.ts
223
- var _createCompileSvelte = (makeHot) => async function compileSvelte(svelteRequest, code, options) {
224
- const {filename, normalizedFilename, cssId, ssr} = svelteRequest;
225
- const {onwarn, emitCss = true} = options;
287
+ var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
288
+ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
289
+ var _a, _b, _c;
290
+ const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
291
+ const { emitCss = true } = options;
226
292
  const dependencies = [];
227
- const finalCompilerOptions = __assign(__assign({}, options.compilerOptions), {
293
+ const compileOptions = {
294
+ ...options.compilerOptions,
228
295
  filename,
229
296
  generate: ssr ? "ssr" : "dom",
230
- css: !emitCss,
231
- hydratable: true
232
- });
233
- if (options.hot) {
297
+ format: "esm"
298
+ };
299
+ if (options.hot && options.emitCss) {
234
300
  const hash = `s-${safeBase64Hash(normalizedFilename)}`;
235
301
  log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
236
- finalCompilerOptions.cssHash = () => hash;
302
+ compileOptions.cssHash = () => hash;
303
+ }
304
+ if (ssr && compileOptions.enableSourcemap !== false) {
305
+ if (typeof compileOptions.enableSourcemap === "object") {
306
+ compileOptions.enableSourcemap.css = false;
307
+ } else {
308
+ compileOptions.enableSourcemap = { js: true, css: false };
309
+ }
237
310
  }
238
311
  let preprocessed;
239
312
  if (options.preprocess) {
240
- preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, {filename});
313
+ try {
314
+ preprocessed = await preprocess(code, options.preprocess, { filename });
315
+ } catch (e) {
316
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
317
+ throw e;
318
+ }
241
319
  if (preprocessed.dependencies)
242
320
  dependencies.push(...preprocessed.dependencies);
243
321
  if (preprocessed.map)
244
- finalCompilerOptions.sourcemap = preprocessed.map;
322
+ compileOptions.sourcemap = preprocessed.map;
245
323
  }
246
- const compiled = (0, import_compiler.compile)(preprocessed ? preprocessed.code : code, finalCompilerOptions);
247
- (compiled.warnings || []).forEach((warning) => {
248
- if (!emitCss && warning.code === "css-unused-selector")
249
- return;
250
- if (onwarn)
251
- onwarn(warning);
252
- });
324
+ const finalCode = preprocessed ? preprocessed.code : code;
325
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
326
+ filename,
327
+ code: finalCode,
328
+ compileOptions
329
+ }));
330
+ if (dynamicCompileOptions && log.debug.enabled) {
331
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
332
+ }
333
+ const finalCompileOptions = dynamicCompileOptions ? {
334
+ ...compileOptions,
335
+ ...dynamicCompileOptions
336
+ } : compileOptions;
337
+ const compiled = compile(finalCode, finalCompileOptions);
253
338
  if (emitCss && compiled.css.code) {
254
339
  compiled.js.code += `
255
340
  import ${JSON.stringify(cssId)};
@@ -262,13 +347,14 @@ import ${JSON.stringify(cssId)};
262
347
  hotOptions: options.hot,
263
348
  compiled,
264
349
  originalCode: code,
265
- compileOptions: finalCompilerOptions
350
+ compileOptions: finalCompileOptions
266
351
  });
267
352
  }
268
353
  compiled.js.dependencies = dependencies;
269
354
  return {
270
355
  filename,
271
356
  normalizedFilename,
357
+ lang: ((_c = code.match(scriptLangRE)) == null ? void 0 : _c[1]) || "js",
272
358
  compiled,
273
359
  ssr,
274
360
  dependencies
@@ -280,11 +366,11 @@ function buildMakeHot(options) {
280
366
  if (needsMakeHot) {
281
367
  const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
282
368
  const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
283
- return (0, import_svelte_hmr.createMakeHot)({
284
- walk: import_compiler.walk,
369
+ return createMakeHot({
370
+ walk,
285
371
  hotApi,
286
372
  adapter,
287
- hotOptions: __assign({noOverlay: true}, options.hot)
373
+ hotOptions: { noOverlay: true, ...options.hot }
288
374
  });
289
375
  }
290
376
  }
@@ -294,22 +380,21 @@ function createCompileSvelte(options) {
294
380
  }
295
381
 
296
382
  // src/utils/id.ts
297
- var import_querystring = __toModule(require("querystring"));
298
- var import_pluginutils = __toModule(require("@rollup/pluginutils"));
299
- var import_vite = __toModule(require("vite"));
300
- var fs = __toModule(require("fs"));
383
+ import { createFilter } from "@rollup/pluginutils";
384
+ import { normalizePath } from "vite";
385
+ import * as fs from "fs";
301
386
  var VITE_FS_PREFIX = "/@fs/";
302
387
  var IS_WINDOWS = process.platform === "win32";
303
388
  function splitId(id) {
304
389
  const parts = id.split(`?`, 2);
305
390
  const filename = parts[0];
306
391
  const rawQuery = parts[1];
307
- return {filename, rawQuery};
392
+ return { filename, rawQuery };
308
393
  }
309
394
  function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
310
- const query = import_querystring.default.parse(rawQuery);
311
- if (query.svelte != null) {
312
- query.svelte = true;
395
+ const query = parseRequestQuery(rawQuery);
396
+ if (query.url || query.raw) {
397
+ return;
313
398
  }
314
399
  const normalizedFilename = normalize(filename, root);
315
400
  const cssId = createVirtualImportId(filename, root, "style");
@@ -335,8 +420,17 @@ function createVirtualImportId(filename, root, type) {
335
420
  }
336
421
  return `${filename}?${parts.join("&")}`;
337
422
  }
423
+ function parseRequestQuery(rawQuery) {
424
+ const query = Object.fromEntries(new URLSearchParams(rawQuery));
425
+ for (const key in query) {
426
+ if (query[key] === "") {
427
+ query[key] = true;
428
+ }
429
+ }
430
+ return query;
431
+ }
338
432
  function normalize(filename, normalizedRoot) {
339
- return stripRoot((0, import_vite.normalizePath)(filename), normalizedRoot);
433
+ return stripRoot(normalizePath(filename), normalizedRoot);
340
434
  }
341
435
  function existsInRoot(filename, root) {
342
436
  if (filename.startsWith(VITE_FS_PREFIX)) {
@@ -348,59 +442,94 @@ function stripRoot(normalizedFilename, normalizedRoot) {
348
442
  return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
349
443
  }
350
444
  function buildFilter(include, exclude, extensions) {
351
- const rollupFilter = (0, import_pluginutils.createFilter)(include, exclude);
445
+ const rollupFilter = createFilter(include, exclude);
352
446
  return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
353
447
  }
354
448
  function buildIdParser(options) {
355
- const {include, exclude, extensions, root} = options;
356
- const normalizedRoot = (0, import_vite.normalizePath)(root);
449
+ const { include, exclude, extensions, root } = options;
450
+ const normalizedRoot = normalizePath(root);
357
451
  const filter = buildFilter(include, exclude, extensions);
358
452
  return (id, ssr, timestamp = Date.now()) => {
359
- const {filename, rawQuery} = splitId(id);
453
+ const { filename, rawQuery } = splitId(id);
360
454
  if (filter(filename)) {
361
455
  return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
362
456
  }
363
457
  };
364
458
  }
365
459
 
366
- // src/utils/loadSvelteConfig.ts
367
- var import_path = __toModule(require("path"));
368
- var import_fs = __toModule(require("fs"));
369
- var knownSvelteConfigNames = ["svelte.config.js", "svelte.config.cjs", "svelte.config.mjs"];
370
- var dynamicImportDefault = new Function("path", "return import(path).then(m => m.default)");
460
+ // src/utils/options.ts
461
+ import {
462
+ normalizePath as normalizePath2
463
+ } from "vite";
464
+
465
+ // src/utils/load-svelte-config.ts
466
+ import { createRequire } from "module";
467
+ import path from "path";
468
+ import fs2 from "fs";
469
+ import { pathToFileURL } from "url";
470
+ var esmRequire;
471
+ var knownSvelteConfigNames = [
472
+ "svelte.config.js",
473
+ "svelte.config.cjs",
474
+ "svelte.config.mjs"
475
+ ];
476
+ var dynamicImportDefault = new Function("path", "timestamp", 'return import(path + "?t=" + timestamp).then(m => m.default)');
371
477
  async function loadSvelteConfig(viteConfig, inlineOptions) {
478
+ if ((inlineOptions == null ? void 0 : inlineOptions.configFile) === false) {
479
+ return;
480
+ }
372
481
  const configFile = findConfigToLoad(viteConfig, inlineOptions);
373
482
  if (configFile) {
374
483
  let err;
375
484
  if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
376
485
  try {
377
- return await dynamicImportDefault(configFile);
486
+ const result = await dynamicImportDefault(pathToFileURL(configFile).href, fs2.statSync(configFile).mtimeMs);
487
+ if (result != null) {
488
+ return {
489
+ ...result,
490
+ configFile
491
+ };
492
+ } else {
493
+ throw new Error(`invalid export in ${configFile}`);
494
+ }
378
495
  } catch (e) {
379
- log.debug(`failed to import config ${configFile}`, e);
496
+ log.error(`failed to import config ${configFile}`, e);
380
497
  err = e;
381
498
  }
382
499
  }
383
- try {
384
- return require(configFile);
385
- } catch (e) {
386
- log.error(`failed to require config ${configFile}`, e);
387
- if (!err) {
388
- err = e;
500
+ if (!configFile.endsWith(".mjs")) {
501
+ try {
502
+ const _require = import.meta.url ? esmRequire ?? (esmRequire = createRequire(import.meta.url)) : __require;
503
+ delete _require.cache[_require.resolve(configFile)];
504
+ const result = _require(configFile);
505
+ if (result != null) {
506
+ return {
507
+ ...result,
508
+ configFile
509
+ };
510
+ } else {
511
+ throw new Error(`invalid export in ${configFile}`);
512
+ }
513
+ } catch (e) {
514
+ log.error(`failed to require config ${configFile}`, e);
515
+ if (!err) {
516
+ err = e;
517
+ }
389
518
  }
390
519
  }
391
520
  throw err;
392
521
  }
393
522
  }
394
523
  function findConfigToLoad(viteConfig, inlineOptions) {
395
- const root = viteConfig.root || process.cwd();
396
- if (inlineOptions.configFile) {
397
- const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile);
398
- if (!import_fs.default.existsSync(abolutePath)) {
524
+ const root = (viteConfig == null ? void 0 : viteConfig.root) || process.cwd();
525
+ if (inlineOptions == null ? void 0 : inlineOptions.configFile) {
526
+ const abolutePath = path.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : path.resolve(root, inlineOptions.configFile);
527
+ if (!fs2.existsSync(abolutePath)) {
399
528
  throw new Error(`failed to find svelte config file ${abolutePath}.`);
400
529
  }
401
530
  return abolutePath;
402
531
  } else {
403
- const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file));
532
+ const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => path.resolve(root, candidate)).filter((file) => fs2.existsSync(file));
404
533
  if (existingKnownConfigFiles.length === 0) {
405
534
  log.debug(`no svelte config found at ${root}`);
406
535
  return;
@@ -411,10 +540,393 @@ function findConfigToLoad(viteConfig, inlineOptions) {
411
540
  }
412
541
  }
413
542
 
543
+ // src/utils/constants.ts
544
+ var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
545
+ var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
546
+ var SVELTE_IMPORTS = [
547
+ "svelte/animate",
548
+ "svelte/easing",
549
+ "svelte/internal",
550
+ "svelte/motion",
551
+ "svelte/ssr",
552
+ "svelte/store",
553
+ "svelte/transition",
554
+ "svelte"
555
+ ];
556
+ var SVELTE_HMR_IMPORTS = [
557
+ "svelte-hmr/runtime/hot-api-esm.js",
558
+ "svelte-hmr/runtime/proxy-adapter-dom.js",
559
+ "svelte-hmr"
560
+ ];
561
+
562
+ // src/utils/options.ts
563
+ import path4 from "path";
564
+
565
+ // src/utils/dependencies.ts
566
+ import path2 from "path";
567
+ import fs3 from "fs";
568
+ import { createRequire as createRequire2 } from "module";
569
+ function findRootSvelteDependencies(root, cwdFallback = true) {
570
+ log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
571
+ const pkgFile = path2.join(root, "package.json");
572
+ if (!fs3.existsSync(pkgFile)) {
573
+ if (cwdFallback) {
574
+ const cwd = process.cwd();
575
+ if (root !== cwd) {
576
+ log.debug(`no package.json found in vite root ${root}`);
577
+ return findRootSvelteDependencies(cwd, false);
578
+ }
579
+ }
580
+ log.warn(`no package.json found, findRootSvelteDependencies failed`);
581
+ return [];
582
+ }
583
+ const pkg = parsePkg(root);
584
+ if (!pkg) {
585
+ return [];
586
+ }
587
+ const deps = [
588
+ ...Object.keys(pkg.dependencies || {}),
589
+ ...Object.keys(pkg.devDependencies || {})
590
+ ].filter((dep) => !is_common_without_svelte_field(dep));
591
+ return getSvelteDependencies(deps, root);
592
+ }
593
+ function getSvelteDependencies(deps, pkgDir, path9 = []) {
594
+ const result = [];
595
+ const localRequire = createRequire2(`${pkgDir}/package.json`);
596
+ const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
597
+ for (const { pkg, dir } of resolvedDeps) {
598
+ const type = getSvelteDependencyType(pkg);
599
+ if (!type)
600
+ continue;
601
+ result.push({ name: pkg.name, type, pkg, dir, path: path9 });
602
+ if (type === "component-library" && pkg.dependencies) {
603
+ let dependencyNames = Object.keys(pkg.dependencies);
604
+ const circular = dependencyNames.filter((name) => path9.includes(name));
605
+ if (circular.length > 0) {
606
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path9.concat(x).join(">")));
607
+ dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
608
+ }
609
+ if (path9.length === 3) {
610
+ log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
611
+ }
612
+ result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
613
+ }
614
+ }
615
+ return result;
616
+ }
617
+ function resolveDependencyData(dep, localRequire) {
618
+ try {
619
+ const pkgJson = `${dep}/package.json`;
620
+ const pkg = localRequire(pkgJson);
621
+ const dir = path2.dirname(localRequire.resolve(pkgJson));
622
+ return { dir, pkg };
623
+ } catch (e) {
624
+ log.debug.once(`dependency ${dep} does not export package.json`, e);
625
+ try {
626
+ let dir = path2.dirname(localRequire.resolve(dep));
627
+ while (dir) {
628
+ const pkg = parsePkg(dir, true);
629
+ if (pkg && pkg.name === dep) {
630
+ return { dir, pkg };
631
+ }
632
+ const parent = path2.dirname(dir);
633
+ if (parent === dir) {
634
+ break;
635
+ }
636
+ dir = parent;
637
+ }
638
+ } catch (e2) {
639
+ log.debug.once(`error while trying to find package.json of ${dep}`, e2);
640
+ }
641
+ }
642
+ log.debug.once(`failed to resolve ${dep}`);
643
+ }
644
+ function parsePkg(dir, silent = false) {
645
+ const pkgFile = path2.join(dir, "package.json");
646
+ try {
647
+ return JSON.parse(fs3.readFileSync(pkgFile, "utf-8"));
648
+ } catch (e) {
649
+ !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
650
+ }
651
+ }
652
+ function getSvelteDependencyType(pkg) {
653
+ if (isSvelteComponentLib(pkg)) {
654
+ return "component-library";
655
+ } else if (isSvelteLib(pkg)) {
656
+ return "js-library";
657
+ } else {
658
+ return void 0;
659
+ }
660
+ }
661
+ function isSvelteComponentLib(pkg) {
662
+ return !!pkg.svelte;
663
+ }
664
+ function isSvelteLib(pkg) {
665
+ var _a, _b;
666
+ return !!((_a = pkg.dependencies) == null ? void 0 : _a.svelte) || !!((_b = pkg.peerDependencies) == null ? void 0 : _b.svelte);
667
+ }
668
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
669
+ "@lukeed/uuid",
670
+ "@playwright/test",
671
+ "@sveltejs/vite-plugin-svelte",
672
+ "@sveltejs/kit",
673
+ "autoprefixer",
674
+ "cookie",
675
+ "dotenv",
676
+ "esbuild",
677
+ "eslint",
678
+ "jest",
679
+ "mdsvex",
680
+ "playwright",
681
+ "postcss",
682
+ "prettier",
683
+ "svelte",
684
+ "svelte-check",
685
+ "svelte-hmr",
686
+ "svelte-preprocess",
687
+ "tslib",
688
+ "typescript",
689
+ "vite",
690
+ "vitest",
691
+ "__vite-browser-external"
692
+ ];
693
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
694
+ "@fontsource/",
695
+ "@postcss-plugins/",
696
+ "@rollup/",
697
+ "@sveltejs/adapter-",
698
+ "@types/",
699
+ "@typescript-eslint/",
700
+ "eslint-",
701
+ "jest-",
702
+ "postcss-plugin-",
703
+ "prettier-plugin-",
704
+ "rollup-plugin-",
705
+ "vite-plugin-"
706
+ ];
707
+ function is_common_without_svelte_field(dependency) {
708
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some((prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2));
709
+ }
710
+ function needsOptimization(dep, localRequire) {
711
+ const depData = resolveDependencyData(dep, localRequire);
712
+ if (!depData)
713
+ return false;
714
+ const pkg = depData.pkg;
715
+ const hasEsmFields = pkg.module || pkg.exports;
716
+ if (hasEsmFields)
717
+ return false;
718
+ if (pkg.main) {
719
+ const entryExt = path2.extname(pkg.main);
720
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
721
+ } else {
722
+ try {
723
+ localRequire.resolve(`${dep}/index.js`);
724
+ return true;
725
+ } catch {
726
+ return false;
727
+ }
728
+ }
729
+ }
730
+
731
+ // src/utils/options.ts
732
+ import { createRequire as createRequire3 } from "module";
733
+
734
+ // src/utils/esbuild.ts
735
+ import { promises as fs4 } from "fs";
736
+ import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
737
+
738
+ // src/utils/error.ts
739
+ function toRollupError(error, options) {
740
+ const { filename, frame, start, code, name, stack } = error;
741
+ const rollupError = {
742
+ name,
743
+ id: filename,
744
+ message: buildExtendedLogMessage(error),
745
+ frame: formatFrameForVite(frame),
746
+ code,
747
+ stack: options.isBuild || options.isDebug || !frame ? stack : ""
748
+ };
749
+ if (start) {
750
+ rollupError.loc = {
751
+ line: start.line,
752
+ column: start.column,
753
+ file: filename
754
+ };
755
+ }
756
+ return rollupError;
757
+ }
758
+ function toESBuildError(error, options) {
759
+ const { filename, frame, start, stack } = error;
760
+ const partialMessage = {
761
+ text: buildExtendedLogMessage(error)
762
+ };
763
+ if (start) {
764
+ partialMessage.location = {
765
+ line: start.line,
766
+ column: start.column,
767
+ file: filename,
768
+ lineText: lineFromFrame(start.line, frame)
769
+ };
770
+ }
771
+ if (options.isBuild || options.isDebug || !frame) {
772
+ partialMessage.detail = stack;
773
+ }
774
+ return partialMessage;
775
+ }
776
+ function lineFromFrame(lineNo, frame) {
777
+ if (!frame) {
778
+ return "";
779
+ }
780
+ const lines = frame.split("\n");
781
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
782
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
783
+ }
784
+ function formatFrameForVite(frame) {
785
+ if (!frame) {
786
+ return "";
787
+ }
788
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
789
+ }
790
+
791
+ // src/utils/esbuild.ts
792
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
793
+ function esbuildSveltePlugin(options) {
794
+ return {
795
+ name: "vite-plugin-svelte:optimize-svelte",
796
+ setup(build) {
797
+ var _a;
798
+ if ((_a = build.initialOptions.plugins) == null ? void 0 : _a.some((v) => v.name === "vite:dep-scan"))
799
+ return;
800
+ const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
801
+ const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
802
+ build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
803
+ const code = await fs4.readFile(filename, "utf8");
804
+ try {
805
+ const contents = await compileSvelte(options, { filename, code });
806
+ return { contents };
807
+ } catch (e) {
808
+ return { errors: [toESBuildError(e, options)] };
809
+ }
810
+ });
811
+ }
812
+ };
813
+ }
814
+ async function compileSvelte(options, { filename, code }) {
815
+ var _a, _b;
816
+ const compileOptions = {
817
+ ...options.compilerOptions,
818
+ css: true,
819
+ filename,
820
+ format: "esm",
821
+ generate: "dom"
822
+ };
823
+ let preprocessed;
824
+ if (options.preprocess) {
825
+ try {
826
+ preprocessed = await preprocess2(code, options.preprocess, { filename });
827
+ } catch (e) {
828
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
829
+ throw e;
830
+ }
831
+ if (preprocessed.map)
832
+ compileOptions.sourcemap = preprocessed.map;
833
+ }
834
+ const finalCode = preprocessed ? preprocessed.code : code;
835
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
836
+ filename,
837
+ code: finalCode,
838
+ compileOptions
839
+ }));
840
+ if (dynamicCompileOptions && log.debug.enabled) {
841
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
842
+ }
843
+ const finalCompileOptions = dynamicCompileOptions ? {
844
+ ...compileOptions,
845
+ ...dynamicCompileOptions
846
+ } : compileOptions;
847
+ const compiled = compile2(finalCode, finalCompileOptions);
848
+ return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
849
+ }
850
+
414
851
  // src/utils/preprocess.ts
852
+ import {
853
+ transformWithEsbuild
854
+ } from "vite";
855
+ import MagicString2 from "magic-string";
856
+ import { preprocess as preprocess3 } from "svelte/compiler";
857
+
858
+ // src/utils/sourcemap.ts
859
+ import MagicString from "magic-string";
860
+ async function buildMagicString(from, to, options) {
861
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
862
+ try {
863
+ const dmpPkg = await import("diff-match-patch");
864
+ diff_match_patch = dmpPkg.diff_match_patch;
865
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
866
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
867
+ } catch (e) {
868
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
869
+ return null;
870
+ }
871
+ const dmp = new diff_match_patch();
872
+ const diffs = dmp.diff_main(from, to);
873
+ dmp.diff_cleanupSemantic(diffs);
874
+ const m = new MagicString(from, options);
875
+ let pos = 0;
876
+ for (let i = 0; i < diffs.length; i++) {
877
+ const diff = diffs[i];
878
+ const nextDiff = diffs[i + 1];
879
+ if (diff[0] === DIFF_DELETE) {
880
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
881
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
882
+ i++;
883
+ } else {
884
+ m.remove(pos, pos + diff[1].length);
885
+ }
886
+ pos += diff[1].length;
887
+ } else if (diff[0] === DIFF_INSERT) {
888
+ if (nextDiff) {
889
+ m.appendRight(pos, diff[1]);
890
+ } else {
891
+ m.append(diff[1]);
892
+ }
893
+ } else {
894
+ pos += diff[1].length;
895
+ }
896
+ }
897
+ return m;
898
+ }
899
+ async function buildSourceMap(from, to, filename) {
900
+ const m = await buildMagicString(from, to, { filename });
901
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
902
+ }
903
+
904
+ // src/utils/preprocess.ts
905
+ import path3 from "path";
415
906
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
416
907
  var supportedScriptLangs = ["ts"];
417
- function createPreprocessorFromVitePlugin(config, options, pluginName, supportedLangs) {
908
+ function createViteScriptPreprocessor() {
909
+ return async ({ attributes, content, filename = "" }) => {
910
+ const lang = attributes.lang;
911
+ if (!supportedScriptLangs.includes(lang))
912
+ return;
913
+ const transformResult = await transformWithEsbuild(content, filename, {
914
+ loader: lang,
915
+ tsconfigRaw: {
916
+ compilerOptions: {
917
+ importsNotUsedAsValues: "preserve",
918
+ preserveValueImports: true
919
+ }
920
+ }
921
+ });
922
+ return {
923
+ code: transformResult.code,
924
+ map: transformResult.map
925
+ };
926
+ };
927
+ }
928
+ function createViteStylePreprocessor(config) {
929
+ const pluginName = "vite:css";
418
930
  const plugin = config.plugins.find((p) => p.name === pluginName);
419
931
  if (!plugin) {
420
932
  throw new Error(`failed to find plugin ${pluginName}`);
@@ -423,110 +935,261 @@ function createPreprocessorFromVitePlugin(config, options, pluginName, supported
423
935
  throw new Error(`plugin ${pluginName} has no transform`);
424
936
  }
425
937
  const pluginTransform = plugin.transform.bind(null);
426
- return async ({attributes, content, filename}) => {
427
- var _a, _b, _c, _d;
938
+ return async ({ attributes, content, filename = "" }) => {
939
+ var _a, _b;
428
940
  const lang = attributes.lang;
429
- if (!supportedLangs.includes(lang)) {
430
- return {code: content};
431
- }
941
+ if (!supportedStyleLangs.includes(lang))
942
+ return;
432
943
  const moduleId = `${filename}.${lang}`;
433
- const moduleGraph = (_a = options.server) == null ? void 0 : _a.moduleGraph;
434
- if (moduleGraph && !moduleGraph.getModuleById(moduleId)) {
435
- await moduleGraph.ensureEntryFromUrl(moduleId);
436
- }
437
944
  const transformResult = await pluginTransform(content, moduleId);
438
- const hasMap = !!((_b = transformResult.map) == null ? void 0 : _b.mappings);
439
- if (((_d = (_c = transformResult.map) == null ? void 0 : _c.sources) == null ? void 0 : _d[0]) === moduleId) {
440
- transformResult.map.sources[0] = filename;
945
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
946
+ transformResult.map.sources[0] = path3.basename(filename);
441
947
  }
442
948
  return {
443
949
  code: transformResult.code,
444
- map: hasMap ? transformResult.map : null,
445
- dependencies: transformResult.deps
950
+ map: transformResult.map ?? void 0
446
951
  };
447
952
  };
448
953
  }
449
- function createVitePreprocessorGroup(config, options) {
954
+ function createVitePreprocessorGroup(config) {
450
955
  return {
451
- script: createPreprocessorFromVitePlugin(config, options, "vite:esbuild", supportedScriptLangs),
452
- style: createPreprocessorFromVitePlugin(config, options, "vite:css", supportedStyleLangs)
956
+ markup({ content, filename }) {
957
+ return preprocess3(content, {
958
+ script: createViteScriptPreprocessor(),
959
+ style: createViteStylePreprocessor(config)
960
+ }, { filename });
961
+ }
453
962
  };
454
963
  }
455
964
  function createInjectScopeEverythingRulePreprocessorGroup() {
456
965
  return {
457
- style({content}) {
966
+ style({ content, filename }) {
967
+ const s = new MagicString2(content);
968
+ s.append(" *{}");
458
969
  return {
459
- code: `${content} *{}`
970
+ code: s.toString(),
971
+ map: s.generateDecodedMap({
972
+ source: filename ? path3.basename(filename) : void 0,
973
+ hires: true
974
+ })
460
975
  };
461
976
  }
462
977
  };
463
978
  }
464
979
  function buildExtraPreprocessors(options, config) {
465
- const extraPreprocessors = [];
466
- if (options.useVitePreprocess) {
980
+ var _a, _b;
981
+ const prependPreprocessors = [];
982
+ const appendPreprocessors = [];
983
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
467
984
  log.debug("adding vite preprocessor");
468
- extraPreprocessors.push(createVitePreprocessorGroup(config, options));
985
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
986
+ }
987
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
988
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
989
+ 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(", ")}`);
990
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
991
+ if (!p.api) {
992
+ p.api = {};
993
+ }
994
+ if (p.api.sveltePreprocess === void 0) {
995
+ p.api.sveltePreprocess = p.sveltePreprocess;
996
+ } else {
997
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
998
+ }
999
+ });
1000
+ }
1001
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
1002
+ var _a2;
1003
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1004
+ });
1005
+ const ignored = [], included = [];
1006
+ for (const p of pluginsWithPreprocessors) {
1007
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1008
+ ignored.push(p);
1009
+ } else {
1010
+ included.push(p);
1011
+ }
1012
+ }
1013
+ if (ignored.length > 0) {
1014
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
469
1015
  }
470
- const pluginsWithPreprocessors = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
471
- if (pluginsWithPreprocessors.length > 0) {
472
- log.debug(`adding preprocessors from other vite plugins: ${pluginsWithPreprocessors.map((p) => p.name).join(", ")}`);
473
- extraPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.sveltePreprocess));
1016
+ if (included.length > 0) {
1017
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1018
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
474
1019
  }
475
- if (options.hot && !options.disableCssHmr) {
476
- extraPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1020
+ if (options.hot && options.emitCss) {
1021
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
477
1022
  }
478
- return extraPreprocessors;
1023
+ return { prependPreprocessors, appendPreprocessors };
479
1024
  }
480
1025
  function addExtraPreprocessors(options, config) {
481
- const extra = buildExtraPreprocessors(options, config);
482
- if ((extra == null ? void 0 : extra.length) > 0) {
1026
+ var _a;
1027
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1028
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
483
1029
  if (!options.preprocess) {
484
- options.preprocess = extra;
1030
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
485
1031
  } else if (Array.isArray(options.preprocess)) {
486
- options.preprocess.push(...extra);
1032
+ options.preprocess.unshift(...prependPreprocessors);
1033
+ options.preprocess.push(...appendPreprocessors);
487
1034
  } else {
488
- options.preprocess = [options.preprocess, ...extra];
1035
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
489
1036
  }
490
1037
  }
1038
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1039
+ if (options.preprocess && generateMissingSourceMaps) {
1040
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1041
+ }
1042
+ }
1043
+ function validateSourceMapOutputWrapper(group, i) {
1044
+ const wrapper = {};
1045
+ for (const [processorType, processorFn] of Object.entries(group)) {
1046
+ wrapper[processorType] = async (options) => {
1047
+ var _a;
1048
+ const result = await processorFn(options);
1049
+ if (result && result.code !== options.content) {
1050
+ let invalidMap = false;
1051
+ if (!result.map) {
1052
+ invalidMap = true;
1053
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1054
+ filename: options.filename,
1055
+ type: processorType,
1056
+ processor: processorFn.toString()
1057
+ });
1058
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1059
+ invalidMap = true;
1060
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1061
+ filename: options.filename,
1062
+ type: processorType,
1063
+ processor: processorFn.toString()
1064
+ });
1065
+ }
1066
+ if (invalidMap) {
1067
+ try {
1068
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1069
+ if (map) {
1070
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1071
+ result.map = map;
1072
+ }
1073
+ } catch (e) {
1074
+ log.error(`failed to build sourcemap`, e);
1075
+ }
1076
+ }
1077
+ }
1078
+ return result;
1079
+ };
1080
+ }
1081
+ return wrapper;
491
1082
  }
492
1083
 
493
1084
  // src/utils/options.ts
494
- var knownOptions = new Set([
495
- "configFile",
1085
+ import deepmerge from "deepmerge";
1086
+ var allowedPluginOptions = /* @__PURE__ */ new Set([
496
1087
  "include",
497
1088
  "exclude",
498
- "extensions",
499
1089
  "emitCss",
500
- "compilerOptions",
501
- "preprocess",
502
1090
  "hot",
503
- "disableCssHmr",
504
- "useVitePreprocess"
1091
+ "ignorePluginPreprocessors",
1092
+ "disableDependencyReinclusion",
1093
+ "experimental"
1094
+ ]);
1095
+ var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions", "preprocess", "onwarn"]);
1096
+ var allowedInlineOptions = /* @__PURE__ */ new Set([
1097
+ "configFile",
1098
+ "kit",
1099
+ ...allowedPluginOptions,
1100
+ ...knownRootOptions
505
1101
  ]);
506
- function buildDefaultOptions({isProduction}, options) {
507
- const disableCssHmr = !!(options == null ? void 0 : options.disableCssHmr);
508
- const emitCss = isProduction || !disableCssHmr;
509
- const hot = isProduction ? false : {
510
- injectCss: !emitCss
1102
+ function validateInlineOptions(inlineOptions) {
1103
+ const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !allowedInlineOptions.has(key));
1104
+ if (invalidKeys.length) {
1105
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in inline config`, inlineOptions);
1106
+ }
1107
+ }
1108
+ function convertPluginOptions(config) {
1109
+ if (!config) {
1110
+ return;
1111
+ }
1112
+ const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
1113
+ if (invalidRootOptions.length > 0) {
1114
+ throw new Error(`Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(", ")}`);
1115
+ }
1116
+ if (!config.vitePlugin) {
1117
+ return config;
1118
+ }
1119
+ const pluginOptions = config.vitePlugin;
1120
+ const pluginOptionKeys = Object.keys(pluginOptions);
1121
+ const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
1122
+ if (rootOptionsInPluginOptions.length > 0) {
1123
+ throw new Error(`Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(", ")}`);
1124
+ }
1125
+ const duplicateOptions = pluginOptionKeys.filter((key) => Object.prototype.hasOwnProperty.call(config, key));
1126
+ if (duplicateOptions.length > 0) {
1127
+ throw new Error(`Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(", ")}`);
1128
+ }
1129
+ const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
1130
+ if (unknownPluginOptions.length > 0) {
1131
+ log.warn(`ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(", ")}`);
1132
+ unknownPluginOptions.forEach((unkownOption) => {
1133
+ delete pluginOptions[unkownOption];
1134
+ });
1135
+ }
1136
+ const result = {
1137
+ ...config,
1138
+ ...pluginOptions
1139
+ };
1140
+ delete result.vitePlugin;
1141
+ return result;
1142
+ }
1143
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1144
+ const viteConfigWithResolvedRoot = {
1145
+ ...viteUserConfig,
1146
+ root: resolveViteRoot(viteUserConfig)
511
1147
  };
512
1148
  const defaultOptions = {
513
1149
  extensions: [".svelte"],
514
- hot,
515
- emitCss,
516
- compilerOptions: {
517
- format: "esm",
518
- css: !emitCss,
519
- dev: !isProduction
520
- }
1150
+ emitCss: true
521
1151
  };
522
- log.debug(`default options for ${isProduction ? "production" : "development"} ${!isProduction && disableCssHmr ? " with css hmr disabled" : ""}`, defaultOptions);
523
- return defaultOptions;
1152
+ const svelteConfig = convertPluginOptions(await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions));
1153
+ const extraOptions = {
1154
+ root: viteConfigWithResolvedRoot.root,
1155
+ isBuild: viteEnv.command === "build",
1156
+ isServe: viteEnv.command === "serve",
1157
+ isDebug: process.env.DEBUG != null
1158
+ };
1159
+ const merged = mergeConfigs(defaultOptions, svelteConfig, inlineOptions, extraOptions);
1160
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1161
+ merged.configFile = svelteConfig.configFile;
1162
+ }
1163
+ return merged;
524
1164
  }
525
- function validateInlineOptions(inlineOptions) {
526
- const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
527
- if (invalidKeys.length) {
528
- log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1165
+ function mergeConfigs(...configs) {
1166
+ let result = {};
1167
+ for (const config of configs.filter(Boolean)) {
1168
+ result = deepmerge(result, config, {
1169
+ arrayMerge: (target, source) => source ?? target
1170
+ });
529
1171
  }
1172
+ return result;
1173
+ }
1174
+ function resolveOptions(preResolveOptions2, viteConfig) {
1175
+ const defaultOptions = {
1176
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1177
+ compilerOptions: {
1178
+ css: !preResolveOptions2.emitCss,
1179
+ dev: !viteConfig.isProduction
1180
+ }
1181
+ };
1182
+ const extraOptions = {
1183
+ root: viteConfig.root,
1184
+ isProduction: viteConfig.isProduction
1185
+ };
1186
+ const merged = mergeConfigs(defaultOptions, preResolveOptions2, extraOptions);
1187
+ removeIgnoredOptions(merged);
1188
+ addSvelteKitOptions(merged);
1189
+ addExtraPreprocessors(merged, viteConfig);
1190
+ enforceOptionsForHmr(merged);
1191
+ enforceOptionsForProduction(merged);
1192
+ return merged;
530
1193
  }
531
1194
  function enforceOptionsForHmr(options) {
532
1195
  if (options.hot) {
@@ -543,6 +1206,19 @@ function enforceOptionsForHmr(options) {
543
1206
  log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
544
1207
  options.compilerOptions.css = false;
545
1208
  }
1209
+ } else {
1210
+ if (options.hot === true || !options.hot.injectCss) {
1211
+ log.warn("hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true");
1212
+ if (options.hot === true) {
1213
+ options.hot = { injectCss: true };
1214
+ } else {
1215
+ options.hot.injectCss = true;
1216
+ }
1217
+ }
1218
+ if (!options.compilerOptions.css) {
1219
+ log.warn("hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true");
1220
+ options.compilerOptions.css = true;
1221
+ }
546
1222
  }
547
1223
  }
548
1224
  }
@@ -552,49 +1228,158 @@ function enforceOptionsForProduction(options) {
552
1228
  log.warn("options.hot is enabled but does not work on production build, forcing it to false");
553
1229
  options.hot = false;
554
1230
  }
555
- if (!options.emitCss) {
556
- log.warn("you are building for production but emitCss is disabled. forcing it to true");
557
- options.emitCss = true;
558
- }
559
1231
  if (options.compilerOptions.dev) {
560
1232
  log.warn("you are building for production but compilerOptions.dev is true, forcing it to false");
561
1233
  options.compilerOptions.dev = false;
562
1234
  }
563
1235
  }
564
1236
  }
565
- function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig) {
566
- return __assign(__assign(__assign(__assign({}, defaultOptions), svelteConfig), inlineOptions), {
567
- compilerOptions: __assign(__assign(__assign({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
568
- root: viteConfig.root,
569
- isProduction: viteConfig.isProduction,
570
- isBuild: viteConfig.command === "build",
571
- isServe: viteConfig.command === "serve"
572
- });
1237
+ function removeIgnoredOptions(options) {
1238
+ const ignoredCompilerOptions = ["generate", "format", "filename"];
1239
+ if (options.hot && options.emitCss) {
1240
+ ignoredCompilerOptions.push("cssHash");
1241
+ }
1242
+ const passedCompilerOptions = Object.keys(options.compilerOptions || {});
1243
+ const passedIgnored = passedCompilerOptions.filter((o) => ignoredCompilerOptions.includes(o));
1244
+ if (passedIgnored.length) {
1245
+ log.warn(`The following Svelte compilerOptions are controlled by vite-plugin-svelte and essential to its functionality. User-specified values are ignored. Please remove them from your configuration: ${passedIgnored.join(", ")}`);
1246
+ passedIgnored.forEach((ignored) => {
1247
+ delete options.compilerOptions[ignored];
1248
+ });
1249
+ }
1250
+ }
1251
+ function addSvelteKitOptions(options) {
1252
+ var _a;
1253
+ if ((options == null ? void 0 : options.kit) != null) {
1254
+ const kit_browser_hydrate = (_a = options.kit.browser) == null ? void 0 : _a.hydrate;
1255
+ const hydratable = kit_browser_hydrate !== false;
1256
+ if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1257
+ log.warn(`Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`);
1258
+ }
1259
+ log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1260
+ options.compilerOptions.hydratable = hydratable;
1261
+ }
1262
+ }
1263
+ function resolveViteRoot(viteConfig) {
1264
+ return normalizePath2(viteConfig.root ? path4.resolve(viteConfig.root) : process.cwd());
1265
+ }
1266
+ function buildExtraViteConfig(options, config) {
1267
+ var _a;
1268
+ const svelteDeps = findRootSvelteDependencies(options.root);
1269
+ const extraViteConfig = {
1270
+ resolve: {
1271
+ mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1272
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1273
+ }
1274
+ };
1275
+ extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(svelteDeps, options, config.optimizeDeps);
1276
+ if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) {
1277
+ extraViteConfig.optimizeDeps = {
1278
+ ...extraViteConfig.optimizeDeps,
1279
+ extensions: options.extensions ?? [".svelte"],
1280
+ esbuildOptions: {
1281
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1282
+ } }]
1283
+ }
1284
+ };
1285
+ }
1286
+ extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1287
+ return extraViteConfig;
573
1288
  }
574
- async function resolveOptions(inlineOptions = {}, viteConfig) {
575
- const defaultOptions = buildDefaultOptions(viteConfig, inlineOptions);
576
- const svelteConfig = await loadSvelteConfig(viteConfig, inlineOptions) || {};
577
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig);
578
- enforceOptionsForProduction(resolvedOptions);
579
- enforceOptionsForHmr(resolvedOptions);
580
- addExtraPreprocessors(resolvedOptions, viteConfig);
581
- log.debug("resolved options", resolvedOptions);
582
- return resolvedOptions;
1289
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1290
+ var _a;
1291
+ const include = [];
1292
+ const exclude = ["svelte-hmr"];
1293
+ const isIncluded = (dep) => {
1294
+ var _a2;
1295
+ return include.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a2.includes(dep));
1296
+ };
1297
+ const isExcluded = (dep) => {
1298
+ var _a2;
1299
+ return exclude.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a2.some((id) => dep === id || id.startsWith(`${dep}/`)));
1300
+ };
1301
+ if (!isExcluded("svelte")) {
1302
+ const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1303
+ log.debug(`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `);
1304
+ include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1305
+ } else {
1306
+ log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1307
+ }
1308
+ if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) {
1309
+ return { include, exclude };
1310
+ }
1311
+ svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1312
+ const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter((dep) => !isIncluded(dep));
1313
+ log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1314
+ exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1315
+ if (options.disableDependencyReinclusion !== true) {
1316
+ const disabledReinclusions = options.disableDependencyReinclusion || [];
1317
+ if (disabledReinclusions.length > 0) {
1318
+ log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1319
+ }
1320
+ const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1321
+ const localRequire = createRequire3(`${dep.dir}/package.json`);
1322
+ return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1323
+ });
1324
+ log.debug(`reincluding transitive dependencies of excluded svelte dependencies`, transitiveDepsToInclude);
1325
+ include.push(...transitiveDepsToInclude);
1326
+ }
1327
+ return { include, exclude };
1328
+ }
1329
+ function buildSSROptionsForSvelte(svelteDeps, options, config) {
1330
+ var _a, _b;
1331
+ const noExternal = [];
1332
+ if (!((_b = (_a = config.ssr) == null ? void 0 : _a.external) == null ? void 0 : _b.includes("svelte"))) {
1333
+ noExternal.push("svelte", /^svelte\//);
1334
+ }
1335
+ noExternal.push(...Array.from(new Set(svelteDeps.map((s) => s.name))).filter((x) => {
1336
+ var _a2, _b2;
1337
+ return !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(x));
1338
+ }));
1339
+ const ssr = {
1340
+ noExternal,
1341
+ external: []
1342
+ };
1343
+ if (options.isServe) {
1344
+ ssr.external = Array.from(new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))).filter((dep) => {
1345
+ var _a2, _b2;
1346
+ return !ssr.noExternal.includes(dep) && !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(dep));
1347
+ });
1348
+ }
1349
+ return ssr;
1350
+ }
1351
+ function patchResolvedViteConfig(viteConfig, options) {
1352
+ var _a, _b;
1353
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1354
+ if (facadeEsbuildSveltePlugin) {
1355
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1356
+ }
583
1357
  }
584
1358
 
585
- // src/utils/VitePluginSvelteCache.ts
1359
+ // src/utils/vite-plugin-svelte-cache.ts
586
1360
  var VitePluginSvelteCache = class {
587
1361
  constructor() {
588
- this._css = new Map();
589
- this._js = new Map();
590
- this._dependencies = new Map();
591
- this._dependants = new Map();
1362
+ this._css = /* @__PURE__ */ new Map();
1363
+ this._js = /* @__PURE__ */ new Map();
1364
+ this._dependencies = /* @__PURE__ */ new Map();
1365
+ this._dependants = /* @__PURE__ */ new Map();
1366
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1367
+ this._errors = /* @__PURE__ */ new Map();
592
1368
  }
593
1369
  update(compileData) {
1370
+ this._errors.delete(compileData.normalizedFilename);
594
1371
  this.updateCSS(compileData);
595
1372
  this.updateJS(compileData);
596
1373
  this.updateDependencies(compileData);
597
1374
  }
1375
+ has(svelteRequest) {
1376
+ const id = svelteRequest.normalizedFilename;
1377
+ return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1378
+ }
1379
+ setError(svelteRequest, error) {
1380
+ this.remove(svelteRequest, true);
1381
+ this._errors.set(svelteRequest.normalizedFilename, error);
1382
+ }
598
1383
  updateCSS(compileData) {
599
1384
  this._css.set(compileData.normalizedFilename, compileData.compiled.css);
600
1385
  }
@@ -612,7 +1397,7 @@ var VitePluginSvelteCache = class {
612
1397
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
613
1398
  added.forEach((d) => {
614
1399
  if (!this._dependants.has(d)) {
615
- this._dependants.set(d, new Set());
1400
+ this._dependants.set(d, /* @__PURE__ */ new Set());
616
1401
  }
617
1402
  this._dependants.get(d).add(compileData.filename);
618
1403
  });
@@ -620,25 +1405,30 @@ var VitePluginSvelteCache = class {
620
1405
  this._dependants.get(d).delete(compileData.filename);
621
1406
  });
622
1407
  }
623
- remove(svelteRequest) {
1408
+ remove(svelteRequest, keepDependencies = false) {
624
1409
  const id = svelteRequest.normalizedFilename;
625
1410
  let removed = false;
1411
+ if (this._errors.delete(id)) {
1412
+ removed = true;
1413
+ }
626
1414
  if (this._js.delete(id)) {
627
1415
  removed = true;
628
1416
  }
629
1417
  if (this._css.delete(id)) {
630
1418
  removed = true;
631
1419
  }
632
- const dependencies = this._dependencies.get(id);
633
- if (dependencies) {
634
- removed = true;
635
- dependencies.forEach((d) => {
636
- const dependants = this._dependants.get(d);
637
- if (dependants && dependants.has(svelteRequest.filename)) {
638
- dependants.delete(svelteRequest.filename);
639
- }
640
- });
641
- this._dependencies.delete(id);
1420
+ if (!keepDependencies) {
1421
+ const dependencies = this._dependencies.get(id);
1422
+ if (dependencies) {
1423
+ removed = true;
1424
+ dependencies.forEach((d) => {
1425
+ const dependants = this._dependants.get(d);
1426
+ if (dependants && dependants.has(svelteRequest.filename)) {
1427
+ dependants.delete(svelteRequest.filename);
1428
+ }
1429
+ });
1430
+ this._dependencies.delete(id);
1431
+ }
642
1432
  }
643
1433
  return removed;
644
1434
  }
@@ -650,36 +1440,38 @@ var VitePluginSvelteCache = class {
650
1440
  return this._js.get(svelteRequest.normalizedFilename);
651
1441
  }
652
1442
  }
653
- getDependants(path3) {
654
- const dependants = this._dependants.get(path3);
1443
+ getError(svelteRequest) {
1444
+ return this._errors.get(svelteRequest.normalizedFilename);
1445
+ }
1446
+ getDependants(path9) {
1447
+ const dependants = this._dependants.get(path9);
655
1448
  return dependants ? [...dependants] : [];
656
1449
  }
1450
+ getResolvedSvelteField(name, importer) {
1451
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1452
+ }
1453
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1454
+ this._resolvedSvelteFields.set(this._getResolvedSvelteFieldKey(importee, importer), resolvedSvelte);
1455
+ }
1456
+ _getResolvedSvelteFieldKey(importee, importer) {
1457
+ return importer ? `${importer} > ${importee}` : importee;
1458
+ }
657
1459
  };
658
1460
 
659
- // src/utils/constants.ts
660
- var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
661
- var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
662
- var SVELTE_IMPORTS = [
663
- "svelte/animate",
664
- "svelte/easing",
665
- "svelte/internal",
666
- "svelte/motion",
667
- "svelte/store",
668
- "svelte/transition",
669
- "svelte",
670
- "svelte-hmr/runtime/hot-api-esm.js",
671
- "svelte-hmr/runtime/proxy-adapter-dom.js",
672
- "svelte-hmr"
673
- ];
674
-
675
1461
  // src/utils/watch.ts
676
- var import_fs2 = __toModule(require("fs"));
677
- function setupWatchers(server, cache, requestParser) {
678
- const watcher = server.watcher;
1462
+ import fs5 from "fs";
1463
+ import path5 from "path";
1464
+ function setupWatchers(options, cache, requestParser) {
1465
+ const { server, configFile: svelteConfigFile } = options;
1466
+ if (!server) {
1467
+ return;
1468
+ }
1469
+ const { watcher, ws } = server;
1470
+ const { root, server: serverConfig } = server.config;
679
1471
  const emitChangeEventOnDependants = (filename) => {
680
1472
  const dependants = cache.getDependants(filename);
681
1473
  dependants.forEach((dependant) => {
682
- if (import_fs2.default.existsSync(dependant)) {
1474
+ if (fs5.existsSync(dependant)) {
683
1475
  log.debug(`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`);
684
1476
  watcher.emit("change", dependant);
685
1477
  }
@@ -694,167 +1486,379 @@ function setupWatchers(server, cache, requestParser) {
694
1486
  }
695
1487
  }
696
1488
  };
697
- watcher.on("change", emitChangeEventOnDependants);
698
- watcher.on("unlink", (filename) => {
699
- removeUnlinkedFromCache(filename);
700
- emitChangeEventOnDependants(filename);
1489
+ const triggerViteRestart = (filename) => {
1490
+ if (serverConfig.middlewareMode) {
1491
+ const message = "Svelte config change detected, restart your dev process to apply the changes.";
1492
+ log.info(message, filename);
1493
+ ws.send({
1494
+ type: "error",
1495
+ err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1496
+ });
1497
+ } else {
1498
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1499
+ server.restart();
1500
+ }
1501
+ };
1502
+ const listenerCollection = {
1503
+ add: [],
1504
+ change: [emitChangeEventOnDependants],
1505
+ unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
1506
+ };
1507
+ if (svelteConfigFile !== false) {
1508
+ const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path5.join(root, cfg));
1509
+ const restartOnConfigAdd = (filename) => {
1510
+ if (possibleSvelteConfigs.includes(filename)) {
1511
+ triggerViteRestart(filename);
1512
+ }
1513
+ };
1514
+ const restartOnConfigChange = (filename) => {
1515
+ if (filename === svelteConfigFile) {
1516
+ triggerViteRestart(filename);
1517
+ }
1518
+ };
1519
+ if (svelteConfigFile) {
1520
+ listenerCollection.change.push(restartOnConfigChange);
1521
+ listenerCollection.unlink.push(restartOnConfigChange);
1522
+ } else {
1523
+ listenerCollection.add.push(restartOnConfigAdd);
1524
+ }
1525
+ }
1526
+ Object.entries(listenerCollection).forEach(([evt, listeners]) => {
1527
+ if (listeners.length > 0) {
1528
+ watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
1529
+ }
701
1530
  });
702
1531
  }
1532
+ function ensureWatchedFile(watcher, file, root) {
1533
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs5.existsSync(file)) {
1534
+ watcher.add(path5.resolve(file));
1535
+ }
1536
+ }
703
1537
 
704
- // src/index.ts
705
- var pkg_export_errors = new Set();
706
- function vitePluginSvelte(inlineOptions) {
707
- if (process.env.DEBUG != null) {
708
- log.setLevel("debug");
1538
+ // src/utils/resolve.ts
1539
+ import path6 from "path";
1540
+ import { builtinModules, createRequire as createRequire4 } from "module";
1541
+ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1542
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1543
+ const cached = cache.getResolvedSvelteField(importee, importer);
1544
+ if (cached) {
1545
+ return cached;
1546
+ }
1547
+ const localRequire = createRequire4(importer);
1548
+ const pkgData = resolveDependencyData(importee, localRequire);
1549
+ if (pkgData) {
1550
+ const { pkg, dir } = pkgData;
1551
+ if (pkg.svelte) {
1552
+ const result = path6.resolve(dir, pkg.svelte);
1553
+ cache.setResolvedSvelteField(importee, importer, result);
1554
+ return result;
1555
+ }
1556
+ }
709
1557
  }
710
- validateInlineOptions(inlineOptions);
711
- const cache = new VitePluginSvelteCache();
712
- let requestParser;
713
- let options;
714
- let compileSvelte;
1558
+ }
1559
+ function isNodeInternal(importee) {
1560
+ return importee.startsWith("node:") || builtinModules.includes(importee);
1561
+ }
1562
+ function isBareImport(importee) {
1563
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || path6.isAbsolute(importee)) {
1564
+ return false;
1565
+ }
1566
+ const parts = importee.split("/");
1567
+ switch (parts.length) {
1568
+ case 1:
1569
+ return true;
1570
+ case 2:
1571
+ return parts[0].startsWith("@");
1572
+ default:
1573
+ return false;
1574
+ }
1575
+ }
1576
+
1577
+ // src/utils/optimizer.ts
1578
+ import { promises as fs6 } from "fs";
1579
+ import path7 from "path";
1580
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1581
+ "compilerOptions",
1582
+ "configFile",
1583
+ "experimental",
1584
+ "extensions",
1585
+ "ignorePluginPreprocessors",
1586
+ "preprocess"
1587
+ ];
1588
+ async function saveSvelteMetadata(cacheDir, options) {
1589
+ const svelteMetadata = generateSvelteMetadata(options);
1590
+ const svelteMetadataPath = path7.resolve(cacheDir, "_svelte_metadata.json");
1591
+ const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => {
1592
+ return typeof value === "function" ? value.toString() : value;
1593
+ });
1594
+ let existingSvelteMetadata;
1595
+ try {
1596
+ existingSvelteMetadata = await fs6.readFile(svelteMetadataPath, "utf8");
1597
+ } catch {
1598
+ }
1599
+ await fs6.mkdir(cacheDir, { recursive: true });
1600
+ await fs6.writeFile(svelteMetadataPath, currentSvelteMetadata);
1601
+ return currentSvelteMetadata !== existingSvelteMetadata;
1602
+ }
1603
+ function generateSvelteMetadata(options) {
1604
+ const metadata = {};
1605
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1606
+ metadata[key] = options[key];
1607
+ }
1608
+ return metadata;
1609
+ }
1610
+
1611
+ // src/ui/inspector/plugin.ts
1612
+ import { normalizePath as normalizePath3 } from "vite";
1613
+ import path8 from "path";
1614
+ import { fileURLToPath } from "url";
1615
+ import fs7 from "fs";
1616
+ var defaultInspectorOptions = {
1617
+ toggleKeyCombo: process.platform === "win32" ? "control-shift" : "meta-shift",
1618
+ holdMode: false,
1619
+ showToggleButton: "active",
1620
+ toggleButtonPos: "top-right",
1621
+ customStyles: true
1622
+ };
1623
+ function getInspectorPath() {
1624
+ const pluginPath = normalizePath3(path8.dirname(fileURLToPath(import.meta.url)));
1625
+ return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, "/vite-plugin-svelte/src/ui/inspector/");
1626
+ }
1627
+ function svelteInspector() {
1628
+ const inspectorPath = getInspectorPath();
1629
+ log.debug.enabled && log.debug(`svelte inspector path: ${inspectorPath}`);
1630
+ let inspectorOptions;
1631
+ let appendTo;
1632
+ let disabled = false;
715
1633
  return {
716
- name: "vite-plugin-svelte",
1634
+ name: "vite-plugin-svelte:inspector",
1635
+ apply: "serve",
717
1636
  enforce: "pre",
718
- config(config) {
719
- if (process.env.DEBUG) {
720
- log.setLevel("debug");
721
- } else if (config.logLevel) {
722
- log.setLevel(config.logLevel);
723
- }
724
- const extraViteConfig = {
725
- optimizeDeps: {
726
- exclude: [...SVELTE_IMPORTS]
727
- },
728
- resolve: {
729
- mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
730
- dedupe: [...SVELTE_IMPORTS]
731
- }
732
- };
733
- if (inlineOptions == null ? void 0 : inlineOptions.useVitePreprocess) {
734
- extraViteConfig.esbuild = {
735
- tsconfigRaw: {
736
- compilerOptions: {
737
- importsNotUsedAsValues: "preserve"
738
- }
739
- }
1637
+ configResolved(config) {
1638
+ var _a, _b, _c;
1639
+ const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte");
1640
+ if ((_c = (_b = (_a = vps == null ? void 0 : vps.api) == null ? void 0 : _a.options) == null ? void 0 : _b.experimental) == null ? void 0 : _c.inspector) {
1641
+ inspectorOptions = {
1642
+ ...defaultInspectorOptions,
1643
+ ...vps.api.options.experimental.inspector
740
1644
  };
741
1645
  }
742
- log.debug("additional vite config", extraViteConfig);
743
- return extraViteConfig;
744
- },
745
- async configResolved(config) {
746
- options = await resolveOptions(inlineOptions, config);
747
- requestParser = buildIdParser(options);
748
- compileSvelte = createCompileSvelte(options);
749
- },
750
- configureServer(server) {
751
- options.server = server;
752
- setupWatchers(server, cache, requestParser);
753
- },
754
- load(id, ssr) {
755
- const svelteRequest = requestParser(id, !!ssr);
756
- if (!svelteRequest) {
757
- return;
758
- }
759
- log.debug("load", svelteRequest);
760
- const {filename, query} = svelteRequest;
761
- if (query.svelte) {
762
- if (query.type === "style") {
763
- const css = cache.getCSS(svelteRequest);
764
- if (css) {
765
- log.debug(`load returns css for ${filename}`);
766
- return css;
767
- }
1646
+ if (!vps || !inspectorOptions) {
1647
+ log.debug("inspector disabled, could not find config");
1648
+ disabled = true;
1649
+ } else {
1650
+ if (vps.api.options.kit && !inspectorOptions.appendTo) {
1651
+ const out_dir = path8.basename(vps.api.options.kit.outDir || ".svelte-kit");
1652
+ inspectorOptions.appendTo = `${out_dir}/runtime/client/start.js`;
768
1653
  }
1654
+ appendTo = inspectorOptions.appendTo;
769
1655
  }
770
1656
  },
771
- async resolveId(importee, importer, customOptions, ssr) {
772
- const svelteRequest = requestParser(importee, !!ssr);
773
- log.debug("resolveId", svelteRequest || importee);
774
- if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
775
- if (svelteRequest.query.type === "style") {
776
- log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
777
- return svelteRequest.cssId;
778
- }
779
- log.debug(`resolveId resolved ${importee}`);
780
- return importee;
781
- }
782
- if (!importer || importee[0] === "." || importee[0] === "\0" || path2.isAbsolute(importee)) {
783
- return null;
784
- }
785
- const parts = importee.split("/");
786
- let dir, pkg, name = parts.shift();
787
- if (name && name[0] === "@") {
788
- name += `/${parts.shift()}`;
789
- }
790
- try {
791
- const file = `${name}/package.json`;
792
- const resolved = relative.resolve(file, path2.dirname(importer));
793
- dir = path2.dirname(resolved);
794
- pkg = require(resolved);
795
- } catch (err) {
796
- if (err.code === "MODULE_NOT_FOUND")
797
- return null;
798
- if (err.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
799
- pkg_export_errors.add(name);
800
- return null;
801
- }
802
- throw err;
1657
+ async resolveId(importee, importer, options) {
1658
+ if ((options == null ? void 0 : options.ssr) || disabled) {
1659
+ return;
803
1660
  }
804
- if (parts.length === 0 && pkg.svelte) {
805
- return path2.resolve(dir, pkg.svelte);
1661
+ if (importee.startsWith("virtual:svelte-inspector-options")) {
1662
+ return importee;
1663
+ } else if (importee.startsWith("virtual:svelte-inspector-path:")) {
1664
+ const resolved = importee.replace("virtual:svelte-inspector-path:", inspectorPath);
1665
+ log.debug.enabled && log.debug(`resolved ${importee} with ${resolved}`);
1666
+ return resolved;
806
1667
  }
807
- log.debug(`resolveId did not resolve ${importee}`);
808
1668
  },
809
- async transform(code, id, ssr) {
810
- var _a;
811
- const svelteRequest = requestParser(id, !!ssr);
812
- if (!svelteRequest) {
1669
+ async load(id, options) {
1670
+ if ((options == null ? void 0 : options.ssr) || disabled) {
813
1671
  return;
814
1672
  }
815
- log.debug("transform", svelteRequest);
816
- const {filename, query} = svelteRequest;
817
- if (query.svelte) {
818
- if (query.type === "style") {
819
- const css = cache.getCSS(svelteRequest);
820
- if (css) {
821
- log.debug(`transform returns css for ${filename}`);
822
- return css;
823
- }
824
- }
825
- log.error("failed to transform tagged svelte request", svelteRequest);
826
- throw new Error(`failed to transform tagged svelte request for id ${id}`);
827
- }
828
- const compileData = await compileSvelte(svelteRequest, code, options);
829
- cache.update(compileData);
830
- if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
831
- compileData.dependencies.forEach((d) => this.addWatchFile(d));
1673
+ if (id === "virtual:svelte-inspector-options") {
1674
+ return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1675
+ } else if (id.startsWith(inspectorPath)) {
1676
+ return await fs7.promises.readFile(id, "utf-8");
832
1677
  }
833
- log.debug(`transform returns compiled js for ${filename}`);
834
- return compileData.compiled.js;
835
1678
  },
836
- handleHotUpdate(ctx) {
837
- if (!options.emitCss || options.disableCssHmr) {
1679
+ transform(code, id, options) {
1680
+ if ((options == null ? void 0 : options.ssr) || disabled || !appendTo) {
838
1681
  return;
839
1682
  }
840
- const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
841
- if (!svelteRequest) {
842
- return;
1683
+ if (id.endsWith(appendTo)) {
1684
+ return { code: `${code}
1685
+ import 'virtual:svelte-inspector-path:load-inspector.js'` };
843
1686
  }
844
- log.debug("handleHotUpdate", svelteRequest);
845
- return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options);
846
- },
847
- transformIndexHtml(html, ctx) {
848
- log.debug("transformIndexHtml", html);
849
1687
  },
850
- buildEnd() {
851
- if (pkg_export_errors.size > 0) {
852
- log.warn(`The following packages did not export their \`package.json\` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.`, Array.from(pkg_export_errors, (s) => `- ${s}`).join("\n"));
1688
+ transformIndexHtml(html) {
1689
+ if (disabled || appendTo) {
1690
+ return;
853
1691
  }
1692
+ return {
1693
+ html,
1694
+ tags: [
1695
+ {
1696
+ tag: "script",
1697
+ injectTo: "body",
1698
+ attrs: {
1699
+ type: "module",
1700
+ src: "/@id/virtual:svelte-inspector-path:load-inspector.js"
1701
+ }
1702
+ }
1703
+ ]
1704
+ };
854
1705
  }
855
1706
  };
856
1707
  }
857
- module.exports = vitePluginSvelte;
858
- vitePluginSvelte["default"] = vitePluginSvelte;
859
- // Annotate the CommonJS export names for ESM import in node:
860
- 0 && (module.exports = {});
1708
+
1709
+ // src/index.ts
1710
+ function svelte(inlineOptions) {
1711
+ if (process.env.DEBUG != null) {
1712
+ log.setLevel("debug");
1713
+ }
1714
+ validateInlineOptions(inlineOptions);
1715
+ const cache = new VitePluginSvelteCache();
1716
+ let requestParser;
1717
+ let options;
1718
+ let viteConfig;
1719
+ let compileSvelte2;
1720
+ let resolvedSvelteSSR;
1721
+ const api = {};
1722
+ const plugins = [
1723
+ {
1724
+ name: "vite-plugin-svelte",
1725
+ enforce: "pre",
1726
+ api,
1727
+ async config(config, configEnv) {
1728
+ if (process.env.DEBUG) {
1729
+ log.setLevel("debug");
1730
+ } else if (config.logLevel) {
1731
+ log.setLevel(config.logLevel);
1732
+ }
1733
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1734
+ const extraViteConfig = buildExtraViteConfig(options, config);
1735
+ log.debug("additional vite config", extraViteConfig);
1736
+ return extraViteConfig;
1737
+ },
1738
+ async configResolved(config) {
1739
+ options = resolveOptions(options, config);
1740
+ patchResolvedViteConfig(config, options);
1741
+ requestParser = buildIdParser(options);
1742
+ compileSvelte2 = createCompileSvelte(options);
1743
+ viteConfig = config;
1744
+ api.options = options;
1745
+ log.debug("resolved options", options);
1746
+ },
1747
+ async buildStart() {
1748
+ var _a;
1749
+ if (!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries))
1750
+ return;
1751
+ const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options);
1752
+ if (isSvelteMetadataChanged) {
1753
+ viteConfig.optimizeDeps.force = true;
1754
+ }
1755
+ },
1756
+ configureServer(server) {
1757
+ options.server = server;
1758
+ setupWatchers(options, cache, requestParser);
1759
+ },
1760
+ load(id, opts) {
1761
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1762
+ const svelteRequest = requestParser(id, !!ssr);
1763
+ if (svelteRequest) {
1764
+ const { filename, query } = svelteRequest;
1765
+ if (query.svelte && query.type === "style") {
1766
+ const css = cache.getCSS(svelteRequest);
1767
+ if (css) {
1768
+ log.debug(`load returns css for ${filename}`);
1769
+ return css;
1770
+ }
1771
+ }
1772
+ if (viteConfig.assetsInclude(filename)) {
1773
+ log.debug(`load returns raw content for ${filename}`);
1774
+ return fs8.readFileSync(filename, "utf-8");
1775
+ }
1776
+ }
1777
+ },
1778
+ async resolveId(importee, importer, opts) {
1779
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1780
+ const svelteRequest = requestParser(importee, ssr);
1781
+ if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1782
+ if (svelteRequest.query.type === "style") {
1783
+ log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
1784
+ return svelteRequest.cssId;
1785
+ }
1786
+ log.debug(`resolveId resolved ${importee}`);
1787
+ return importee;
1788
+ }
1789
+ if (ssr && importee === "svelte") {
1790
+ if (!resolvedSvelteSSR) {
1791
+ resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then((svelteSSR) => {
1792
+ log.debug("resolved svelte to svelte/ssr");
1793
+ return svelteSSR;
1794
+ }, (err) => {
1795
+ log.debug("failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it", err);
1796
+ return null;
1797
+ });
1798
+ }
1799
+ return resolvedSvelteSSR;
1800
+ }
1801
+ try {
1802
+ const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1803
+ if (resolved) {
1804
+ log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1805
+ return resolved;
1806
+ }
1807
+ } catch (e) {
1808
+ log.debug.once(`error trying to resolve ${importee} from ${importer} via package.json svelte field `, e);
1809
+ }
1810
+ },
1811
+ async transform(code, id, opts) {
1812
+ var _a;
1813
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1814
+ const svelteRequest = requestParser(id, ssr);
1815
+ if (!svelteRequest || svelteRequest.query.svelte) {
1816
+ return;
1817
+ }
1818
+ let compileData;
1819
+ try {
1820
+ compileData = await compileSvelte2(svelteRequest, code, options);
1821
+ } catch (e) {
1822
+ cache.setError(svelteRequest, e);
1823
+ throw toRollupError(e, options);
1824
+ }
1825
+ logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
1826
+ cache.update(compileData);
1827
+ if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
1828
+ compileData.dependencies.forEach((d) => {
1829
+ ensureWatchedFile(options.server.watcher, d, options.root);
1830
+ });
1831
+ }
1832
+ log.debug(`transform returns compiled js for ${svelteRequest.filename}`);
1833
+ return {
1834
+ ...compileData.compiled.js,
1835
+ meta: {
1836
+ vite: {
1837
+ lang: compileData.lang
1838
+ }
1839
+ }
1840
+ };
1841
+ },
1842
+ handleHotUpdate(ctx) {
1843
+ if (!options.hot || !options.emitCss) {
1844
+ return;
1845
+ }
1846
+ const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
1847
+ if (svelteRequest) {
1848
+ try {
1849
+ return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
1850
+ } catch (e) {
1851
+ throw toRollupError(e, options);
1852
+ }
1853
+ }
1854
+ }
1855
+ }
1856
+ ];
1857
+ plugins.push(svelteInspector());
1858
+ return plugins.filter(Boolean);
1859
+ }
1860
+ export {
1861
+ loadSvelteConfig,
1862
+ svelte
1863
+ };
1864
+ //# sourceMappingURL=index.js.map