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