@sveltejs/vite-plugin-svelte 1.0.0-next.9 → 1.0.2

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