@sveltejs/vite-plugin-svelte 1.0.0-next.3 → 1.0.0-next.33

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 ADDED
@@ -0,0 +1,1565 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
21
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
22
+ }) : x)(function(x) {
23
+ if (typeof require !== "undefined")
24
+ return require.apply(this, arguments);
25
+ throw new Error('Dynamic require of "' + x + '" is not supported');
26
+ });
27
+
28
+ // src/index.ts
29
+ import fs7 from "fs";
30
+
31
+ // src/utils/log.ts
32
+ import { cyan, yellow, red } from "kleur/colors";
33
+ import debug from "debug";
34
+ var levels = ["debug", "info", "warn", "error", "silent"];
35
+ var prefix = "vite-plugin-svelte";
36
+ var loggers = {
37
+ debug: {
38
+ log: debug(`vite:${prefix}`),
39
+ enabled: false,
40
+ isDebug: true
41
+ },
42
+ info: {
43
+ color: cyan,
44
+ log: console.log,
45
+ enabled: true
46
+ },
47
+ warn: {
48
+ color: yellow,
49
+ log: console.warn,
50
+ enabled: true
51
+ },
52
+ error: {
53
+ color: red,
54
+ log: console.error,
55
+ enabled: true
56
+ },
57
+ silent: {
58
+ enabled: false
59
+ }
60
+ };
61
+ var _level = "info";
62
+ function setLevel(level) {
63
+ if (level === _level) {
64
+ return;
65
+ }
66
+ const levelIndex = levels.indexOf(level);
67
+ if (levelIndex > -1) {
68
+ _level = level;
69
+ for (let i = 0; i < levels.length; i++) {
70
+ loggers[levels[i]].enabled = i >= levelIndex;
71
+ }
72
+ } else {
73
+ _log(loggers.error, `invalid log level: ${level} `);
74
+ }
75
+ }
76
+ function _log(logger, message, payload) {
77
+ if (!logger.enabled) {
78
+ return;
79
+ }
80
+ if (logger.isDebug) {
81
+ payload !== void 0 ? logger.log(message, payload) : logger.log(message);
82
+ } else {
83
+ logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
84
+ if (payload) {
85
+ logger.log(payload);
86
+ }
87
+ }
88
+ }
89
+ function createLogger(level) {
90
+ const logger = loggers[level];
91
+ const logFn = _log.bind(null, logger);
92
+ const logged = new Set();
93
+ const once = function(message, payload) {
94
+ if (logged.has(message)) {
95
+ return;
96
+ }
97
+ logged.add(message);
98
+ logFn.apply(null, [message, payload]);
99
+ };
100
+ Object.defineProperty(logFn, "enabled", {
101
+ get() {
102
+ return logger.enabled;
103
+ }
104
+ });
105
+ Object.defineProperty(logFn, "once", {
106
+ get() {
107
+ return once;
108
+ }
109
+ });
110
+ return logFn;
111
+ }
112
+ var log = {
113
+ debug: createLogger("debug"),
114
+ info: createLogger("info"),
115
+ warn: createLogger("warn"),
116
+ error: createLogger("error"),
117
+ setLevel
118
+ };
119
+ function logCompilerWarnings(warnings, options) {
120
+ const { emitCss, onwarn, isBuild } = options;
121
+ const warn = isBuild ? warnBuild : warnDev;
122
+ const notIgnoredWarnings = warnings == null ? void 0 : warnings.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
123
+ const extraWarnings = buildExtraWarnings(warnings, isBuild);
124
+ [...notIgnoredWarnings, ...extraWarnings].forEach((warning) => {
125
+ if (onwarn) {
126
+ onwarn(warning, warn);
127
+ } else {
128
+ warn(warning);
129
+ }
130
+ });
131
+ }
132
+ function ignoreCompilerWarning(warning, isBuild, emitCss) {
133
+ return !emitCss && warning.code === "css-unused-selector" || !isBuild && isNoScopableElementWarning(warning);
134
+ }
135
+ function isNoScopableElementWarning(warning) {
136
+ return warning.code === "css-unused-selector" && warning.message.includes('"*"');
137
+ }
138
+ function buildExtraWarnings(warnings, isBuild) {
139
+ const extraWarnings = [];
140
+ if (!isBuild) {
141
+ const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w));
142
+ if (noScopableElementWarnings.length > 0) {
143
+ const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1];
144
+ extraWarnings.push(__spreadProps(__spreadValues({}, noScopableElementWarning), {
145
+ code: "vite-plugin-svelte-css-no-scopable-elements",
146
+ 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.`
147
+ }));
148
+ }
149
+ }
150
+ return extraWarnings;
151
+ }
152
+ function warnDev(w) {
153
+ log.info.enabled && log.info(buildExtendedLogMessage(w));
154
+ }
155
+ function warnBuild(w) {
156
+ log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
157
+ }
158
+ function buildExtendedLogMessage(w) {
159
+ const parts = [];
160
+ if (w.filename) {
161
+ parts.push(w.filename);
162
+ }
163
+ if (w.start) {
164
+ parts.push(":", w.start.line, ":", w.start.column);
165
+ }
166
+ if (w.message) {
167
+ parts.push(" ", w.message);
168
+ }
169
+ return parts.join("");
170
+ }
171
+
172
+ // src/handle-hot-update.ts
173
+ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) {
174
+ const { read, server } = ctx;
175
+ const cachedJS = cache.getJS(svelteRequest);
176
+ if (!cachedJS) {
177
+ log.debug(`handleHotUpdate first call ${svelteRequest.id}`);
178
+ return;
179
+ }
180
+ const cachedCss = cache.getCSS(svelteRequest);
181
+ const content = await read();
182
+ const compileData = await compileSvelte2(svelteRequest, content, options);
183
+ cache.update(compileData);
184
+ const affectedModules = new Set();
185
+ const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
186
+ const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
187
+ const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
188
+ if (cssUpdated) {
189
+ log.debug("handleHotUpdate css changed");
190
+ affectedModules.add(cssModule);
191
+ }
192
+ const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
193
+ if (jsUpdated) {
194
+ log.debug("handleHotUpdate js changed");
195
+ affectedModules.add(mainModule);
196
+ }
197
+ if (!jsUpdated) {
198
+ logCompilerWarnings(compileData.compiled.warnings, options);
199
+ }
200
+ const result = [...affectedModules].filter(Boolean);
201
+ const ssrModulesToInvalidate = result.filter((m) => !!m.ssrTransformResult);
202
+ if (ssrModulesToInvalidate.length > 0) {
203
+ log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
204
+ ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
205
+ }
206
+ if (result.length > 0) {
207
+ log.debug(`handleHotUpdate for ${svelteRequest.id} result: ${result.map((m) => m.id).join(", ")}`);
208
+ }
209
+ return result;
210
+ }
211
+ function cssChanged(prev, next) {
212
+ return !isCodeEqual(prev == null ? void 0 : prev.code, next == null ? void 0 : next.code);
213
+ }
214
+ function jsChanged(prev, next, filename) {
215
+ const prevJs = prev == null ? void 0 : prev.code;
216
+ const nextJs = next == null ? void 0 : next.code;
217
+ const isStrictEqual = isCodeEqual(prevJs, nextJs);
218
+ if (isStrictEqual) {
219
+ return false;
220
+ }
221
+ const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
222
+ if (!isStrictEqual && isLooseEqual) {
223
+ log.warn(`ignoring compiler output js change for ${filename} as it is equal to previous output after normalization`);
224
+ }
225
+ return !isLooseEqual;
226
+ }
227
+ function isCodeEqual(prev, next) {
228
+ if (!prev && !next) {
229
+ return true;
230
+ }
231
+ if (!prev && next || prev && !next) {
232
+ return false;
233
+ }
234
+ return prev === next;
235
+ }
236
+ function normalizeJsCode(code) {
237
+ if (!code) {
238
+ return code;
239
+ }
240
+ return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, "");
241
+ }
242
+
243
+ // src/utils/compile.ts
244
+ import { compile, preprocess, walk } from "svelte/compiler";
245
+ import { createMakeHot } from "svelte-hmr";
246
+
247
+ // src/utils/hash.ts
248
+ import {
249
+ createHash
250
+ } from "crypto";
251
+ var hashes = Object.create(null);
252
+ var hash_length = 12;
253
+ function safeBase64Hash(input) {
254
+ if (hashes[input]) {
255
+ return hashes[input];
256
+ }
257
+ const md5 = createHash("md5");
258
+ md5.update(input);
259
+ const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
260
+ hashes[input] = hash;
261
+ return hash;
262
+ }
263
+ var replacements = {
264
+ "+": "-",
265
+ "/": "_",
266
+ "=": ""
267
+ };
268
+ var replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
269
+ function toSafe(base64) {
270
+ return base64.replace(replaceRE, (x) => replacements[x]);
271
+ }
272
+
273
+ // src/utils/compile.ts
274
+ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
275
+ var _a, _b;
276
+ const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
277
+ const { emitCss = true } = options;
278
+ const dependencies = [];
279
+ const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
280
+ filename,
281
+ generate: ssr ? "ssr" : "dom"
282
+ });
283
+ if (options.hot && options.emitCss) {
284
+ const hash = `s-${safeBase64Hash(normalizedFilename)}`;
285
+ log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
286
+ compileOptions.cssHash = () => hash;
287
+ }
288
+ if (ssr && compileOptions.enableSourcemap !== false) {
289
+ if (typeof compileOptions.enableSourcemap === "object") {
290
+ compileOptions.enableSourcemap.css = false;
291
+ } else {
292
+ compileOptions.enableSourcemap = { js: true, css: false };
293
+ }
294
+ }
295
+ let preprocessed;
296
+ if (options.preprocess) {
297
+ preprocessed = await preprocess(code, options.preprocess, { filename });
298
+ if (preprocessed.dependencies)
299
+ dependencies.push(...preprocessed.dependencies);
300
+ if (preprocessed.map)
301
+ compileOptions.sourcemap = preprocessed.map;
302
+ }
303
+ const finalCode = preprocessed ? preprocessed.code : code;
304
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
305
+ filename,
306
+ code: finalCode,
307
+ compileOptions
308
+ }));
309
+ if (dynamicCompileOptions && log.debug.enabled) {
310
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
311
+ }
312
+ const finalCompileOptions = dynamicCompileOptions ? __spreadValues(__spreadValues({}, compileOptions), dynamicCompileOptions) : compileOptions;
313
+ const compiled = compile(finalCode, finalCompileOptions);
314
+ if (emitCss && compiled.css.code) {
315
+ compiled.js.code += `
316
+ import ${JSON.stringify(cssId)};
317
+ `;
318
+ }
319
+ if (!ssr && makeHot) {
320
+ compiled.js.code = makeHot({
321
+ id: filename,
322
+ compiledCode: compiled.js.code,
323
+ hotOptions: options.hot,
324
+ compiled,
325
+ originalCode: code,
326
+ compileOptions: finalCompileOptions
327
+ });
328
+ }
329
+ compiled.js.dependencies = dependencies;
330
+ return {
331
+ filename,
332
+ normalizedFilename,
333
+ compiled,
334
+ ssr,
335
+ dependencies
336
+ };
337
+ };
338
+ function buildMakeHot(options) {
339
+ var _a, _b;
340
+ const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
341
+ if (needsMakeHot) {
342
+ const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
343
+ const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
344
+ return createMakeHot({
345
+ walk,
346
+ hotApi,
347
+ adapter,
348
+ hotOptions: __spreadValues({ noOverlay: true }, options.hot)
349
+ });
350
+ }
351
+ }
352
+ function createCompileSvelte(options) {
353
+ const makeHot = buildMakeHot(options);
354
+ return _createCompileSvelte(makeHot);
355
+ }
356
+
357
+ // src/utils/id.ts
358
+ import { createFilter } from "@rollup/pluginutils";
359
+ import { normalizePath } from "vite";
360
+ import {
361
+ existsSync
362
+ } from "fs";
363
+ var VITE_FS_PREFIX = "/@fs/";
364
+ var IS_WINDOWS = process.platform === "win32";
365
+ function splitId(id) {
366
+ const parts = id.split(`?`, 2);
367
+ const filename = parts[0];
368
+ const rawQuery = parts[1];
369
+ return { filename, rawQuery };
370
+ }
371
+ function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
372
+ const query = parseRequestQuery(rawQuery);
373
+ if (query.url || query.raw) {
374
+ return;
375
+ }
376
+ const normalizedFilename = normalize(filename, root);
377
+ const cssId = createVirtualImportId(filename, root, "style");
378
+ return {
379
+ id,
380
+ filename,
381
+ normalizedFilename,
382
+ cssId,
383
+ query,
384
+ timestamp,
385
+ ssr
386
+ };
387
+ }
388
+ function createVirtualImportId(filename, root, type) {
389
+ const parts = ["svelte", `type=${type}`];
390
+ if (type === "style") {
391
+ parts.push("lang.css");
392
+ }
393
+ if (existsInRoot(filename, root)) {
394
+ filename = root + filename;
395
+ } else if (filename.startsWith(VITE_FS_PREFIX)) {
396
+ filename = IS_WINDOWS ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
397
+ }
398
+ return `${filename}?${parts.join("&")}`;
399
+ }
400
+ function parseRequestQuery(rawQuery) {
401
+ const query = Object.fromEntries(new URLSearchParams(rawQuery));
402
+ for (const key in query) {
403
+ if (query[key] === "") {
404
+ query[key] = true;
405
+ }
406
+ }
407
+ return query;
408
+ }
409
+ function normalize(filename, normalizedRoot) {
410
+ return stripRoot(normalizePath(filename), normalizedRoot);
411
+ }
412
+ function existsInRoot(filename, root) {
413
+ if (filename.startsWith(VITE_FS_PREFIX)) {
414
+ return false;
415
+ }
416
+ return existsSync(root + filename);
417
+ }
418
+ function stripRoot(normalizedFilename, normalizedRoot) {
419
+ return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
420
+ }
421
+ function buildFilter(include, exclude, extensions) {
422
+ const rollupFilter = createFilter(include, exclude);
423
+ return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
424
+ }
425
+ function buildIdParser(options) {
426
+ const { include, exclude, extensions, root } = options;
427
+ const normalizedRoot = normalizePath(root);
428
+ const filter = buildFilter(include, exclude, extensions);
429
+ return (id, ssr, timestamp = Date.now()) => {
430
+ const { filename, rawQuery } = splitId(id);
431
+ if (filter(filename)) {
432
+ return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
433
+ }
434
+ };
435
+ }
436
+
437
+ // src/utils/options.ts
438
+ import {
439
+ normalizePath as normalizePath2
440
+ } from "vite";
441
+
442
+ // src/utils/load-svelte-config.ts
443
+ import { createRequire } from "module";
444
+ import path from "path";
445
+ import fs2 from "fs";
446
+ import { pathToFileURL } from "url";
447
+ var esmRequire;
448
+ var knownSvelteConfigNames = [
449
+ "svelte.config.js",
450
+ "svelte.config.cjs",
451
+ "svelte.config.mjs"
452
+ ];
453
+ var dynamicImportDefault = new Function("path", 'return import(path + "?t=" + Date.now()).then(m => m.default)');
454
+ async function loadSvelteConfig(viteConfig, inlineOptions) {
455
+ const configFile = findConfigToLoad(viteConfig, inlineOptions);
456
+ if (configFile) {
457
+ let err;
458
+ if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
459
+ try {
460
+ const result = await dynamicImportDefault(pathToFileURL(configFile).href);
461
+ if (result != null) {
462
+ return __spreadProps(__spreadValues({}, result), {
463
+ configFile
464
+ });
465
+ } else {
466
+ throw new Error(`invalid export in ${configFile}`);
467
+ }
468
+ } catch (e) {
469
+ log.error(`failed to import config ${configFile}`, e);
470
+ err = e;
471
+ }
472
+ }
473
+ if (!configFile.endsWith(".mjs")) {
474
+ try {
475
+ const _require = import.meta.url ? esmRequire ?? (esmRequire = createRequire(import.meta.url)) : __require;
476
+ delete _require.cache[_require.resolve(configFile)];
477
+ const result = _require(configFile);
478
+ if (result != null) {
479
+ return __spreadProps(__spreadValues({}, result), {
480
+ configFile
481
+ });
482
+ } else {
483
+ throw new Error(`invalid export in ${configFile}`);
484
+ }
485
+ } catch (e) {
486
+ log.error(`failed to require config ${configFile}`, e);
487
+ if (!err) {
488
+ err = e;
489
+ }
490
+ }
491
+ }
492
+ throw err;
493
+ }
494
+ }
495
+ function findConfigToLoad(viteConfig, inlineOptions) {
496
+ const root = viteConfig.root || process.cwd();
497
+ if (inlineOptions.configFile) {
498
+ const abolutePath = path.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : path.resolve(root, inlineOptions.configFile);
499
+ if (!fs2.existsSync(abolutePath)) {
500
+ throw new Error(`failed to find svelte config file ${abolutePath}.`);
501
+ }
502
+ return abolutePath;
503
+ } else {
504
+ const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => path.resolve(root, candidate)).filter((file) => fs2.existsSync(file));
505
+ if (existingKnownConfigFiles.length === 0) {
506
+ log.debug(`no svelte config found at ${root}`);
507
+ return;
508
+ } else if (existingKnownConfigFiles.length > 1) {
509
+ log.warn(`found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`, existingKnownConfigFiles);
510
+ }
511
+ return existingKnownConfigFiles[0];
512
+ }
513
+ }
514
+
515
+ // src/utils/constants.ts
516
+ var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
517
+ var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
518
+ var SVELTE_IMPORTS = [
519
+ "svelte/animate",
520
+ "svelte/easing",
521
+ "svelte/internal",
522
+ "svelte/motion",
523
+ "svelte/ssr",
524
+ "svelte/store",
525
+ "svelte/transition",
526
+ "svelte"
527
+ ];
528
+ var SVELTE_HMR_IMPORTS = [
529
+ "svelte-hmr/runtime/hot-api-esm.js",
530
+ "svelte-hmr/runtime/proxy-adapter-dom.js",
531
+ "svelte-hmr"
532
+ ];
533
+
534
+ // src/utils/options.ts
535
+ import path3 from "path";
536
+
537
+ // src/utils/dependencies.ts
538
+ import path2 from "path";
539
+ import fs3 from "fs";
540
+ import { createRequire as createRequire2 } from "module";
541
+ function findRootSvelteDependencies(root, cwdFallback = true) {
542
+ log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
543
+ const pkgFile = path2.join(root, "package.json");
544
+ if (!fs3.existsSync(pkgFile)) {
545
+ if (cwdFallback) {
546
+ const cwd = process.cwd();
547
+ if (root !== cwd) {
548
+ log.debug(`no package.json found in vite root ${root}`);
549
+ return findRootSvelteDependencies(cwd, false);
550
+ }
551
+ }
552
+ log.warn(`no package.json found, findRootSvelteDependencies failed`);
553
+ return [];
554
+ }
555
+ const pkg = parsePkg(root);
556
+ if (!pkg) {
557
+ return [];
558
+ }
559
+ const deps = [
560
+ ...Object.keys(pkg.dependencies || {}),
561
+ ...Object.keys(pkg.devDependencies || {})
562
+ ].filter((dep) => !is_common_without_svelte_field(dep));
563
+ return getSvelteDependencies(deps, root);
564
+ }
565
+ function getSvelteDependencies(deps, pkgDir, path6 = []) {
566
+ const result = [];
567
+ const localRequire = createRequire2(`${pkgDir}/package.json`);
568
+ const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
569
+ for (const { pkg, dir } of resolvedDeps) {
570
+ const type = getSvelteDependencyType(pkg);
571
+ if (!type)
572
+ continue;
573
+ result.push({ name: pkg.name, type, pkg, dir, path: path6 });
574
+ if (type === "component-library" && pkg.dependencies) {
575
+ let dependencyNames = Object.keys(pkg.dependencies);
576
+ const circular = dependencyNames.filter((name) => path6.includes(name));
577
+ if (circular.length > 0) {
578
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
579
+ dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
580
+ }
581
+ if (path6.length === 3) {
582
+ log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
583
+ }
584
+ result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
585
+ }
586
+ }
587
+ return result;
588
+ }
589
+ function resolveDependencyData(dep, localRequire) {
590
+ try {
591
+ const pkgJson = `${dep}/package.json`;
592
+ const pkg = localRequire(pkgJson);
593
+ const dir = path2.dirname(localRequire.resolve(pkgJson));
594
+ return { dir, pkg };
595
+ } catch (e) {
596
+ log.debug.once(`dependency ${dep} does not export package.json`, e);
597
+ try {
598
+ let dir = path2.dirname(localRequire.resolve(dep));
599
+ while (dir) {
600
+ const pkg = parsePkg(dir, true);
601
+ if (pkg && pkg.name === dep) {
602
+ return { dir, pkg };
603
+ }
604
+ const parent = path2.dirname(dir);
605
+ if (parent === dir) {
606
+ break;
607
+ }
608
+ dir = parent;
609
+ }
610
+ } catch (e2) {
611
+ log.debug.once(`error while trying to find package.json of ${dep}`, e2);
612
+ }
613
+ }
614
+ log.debug.once(`failed to resolve ${dep}`);
615
+ }
616
+ function parsePkg(dir, silent = false) {
617
+ const pkgFile = path2.join(dir, "package.json");
618
+ try {
619
+ return JSON.parse(fs3.readFileSync(pkgFile, "utf-8"));
620
+ } catch (e) {
621
+ !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
622
+ }
623
+ }
624
+ function getSvelteDependencyType(pkg) {
625
+ if (isSvelteComponentLib(pkg)) {
626
+ return "component-library";
627
+ } else if (isSvelteLib(pkg)) {
628
+ return "js-library";
629
+ } else {
630
+ return void 0;
631
+ }
632
+ }
633
+ function isSvelteComponentLib(pkg) {
634
+ return !!pkg.svelte;
635
+ }
636
+ function isSvelteLib(pkg) {
637
+ var _a, _b;
638
+ return !!((_a = pkg.dependencies) == null ? void 0 : _a.svelte) || !!((_b = pkg.peerDependencies) == null ? void 0 : _b.svelte);
639
+ }
640
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
641
+ "@lukeed/uuid",
642
+ "@sveltejs/vite-plugin-svelte",
643
+ "@sveltejs/kit",
644
+ "autoprefixer",
645
+ "cookie",
646
+ "dotenv",
647
+ "esbuild",
648
+ "eslint",
649
+ "jest",
650
+ "mdsvex",
651
+ "postcss",
652
+ "prettier",
653
+ "svelte",
654
+ "svelte-check",
655
+ "svelte-hmr",
656
+ "svelte-preprocess",
657
+ "tslib",
658
+ "typescript",
659
+ "vite"
660
+ ];
661
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
662
+ "@fontsource/",
663
+ "@postcss-plugins/",
664
+ "@rollup/",
665
+ "@sveltejs/adapter-",
666
+ "@types/",
667
+ "@typescript-eslint/",
668
+ "eslint-",
669
+ "jest-",
670
+ "postcss-plugin-",
671
+ "prettier-plugin-",
672
+ "rollup-plugin-",
673
+ "vite-plugin-"
674
+ ];
675
+ function is_common_without_svelte_field(dependency) {
676
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some((prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2));
677
+ }
678
+ function needsOptimization(dep, localRequire) {
679
+ const depData = resolveDependencyData(dep, localRequire);
680
+ if (!depData)
681
+ return false;
682
+ const pkg = depData.pkg;
683
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
684
+ if (!isCjs)
685
+ return false;
686
+ const entryExt = path2.extname(pkg.main);
687
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
688
+ }
689
+
690
+ // src/utils/options.ts
691
+ import { createRequire as createRequire3 } from "module";
692
+
693
+ // src/utils/esbuild.ts
694
+ import { promises as fs4 } from "fs";
695
+ import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
696
+
697
+ // src/utils/error.ts
698
+ function toRollupError(error) {
699
+ const { filename, frame, start, code, name } = error;
700
+ const rollupError = {
701
+ name,
702
+ id: filename,
703
+ message: buildExtendedLogMessage(error),
704
+ frame: formatFrameForVite(frame),
705
+ code,
706
+ stack: ""
707
+ };
708
+ if (start) {
709
+ rollupError.loc = {
710
+ line: start.line,
711
+ column: start.column,
712
+ file: filename
713
+ };
714
+ }
715
+ return rollupError;
716
+ }
717
+ function toESBuildError(error) {
718
+ const { filename, frame, start } = error;
719
+ const partialMessage = {
720
+ text: buildExtendedLogMessage(error)
721
+ };
722
+ if (start) {
723
+ partialMessage.location = {
724
+ line: start.line,
725
+ column: start.column,
726
+ file: filename,
727
+ lineText: lineFromFrame(start.line, frame)
728
+ };
729
+ }
730
+ return partialMessage;
731
+ }
732
+ function lineFromFrame(lineNo, frame) {
733
+ if (!frame) {
734
+ return "";
735
+ }
736
+ const lines = frame.split("\n");
737
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
738
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
739
+ }
740
+ function formatFrameForVite(frame) {
741
+ if (!frame) {
742
+ return "";
743
+ }
744
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
745
+ }
746
+
747
+ // src/utils/esbuild.ts
748
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
749
+ function esbuildSveltePlugin(options) {
750
+ return {
751
+ name: "vite-plugin-svelte:optimize-svelte",
752
+ setup(build) {
753
+ disableVitePrebundleSvelte(build);
754
+ const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
755
+ const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
756
+ build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
757
+ const code = await fs4.readFile(filename, "utf8");
758
+ try {
759
+ const contents = await compileSvelte(options, { filename, code });
760
+ return { contents };
761
+ } catch (e) {
762
+ return { errors: [toESBuildError(e)] };
763
+ }
764
+ });
765
+ }
766
+ };
767
+ }
768
+ function disableVitePrebundleSvelte(build) {
769
+ var _a;
770
+ const viteDepPrebundlePlugin = (_a = build.initialOptions.plugins) == null ? void 0 : _a.find((v) => v.name === "vite:dep-pre-bundle");
771
+ if (!viteDepPrebundlePlugin)
772
+ return;
773
+ const _setup = viteDepPrebundlePlugin.setup.bind(viteDepPrebundlePlugin);
774
+ viteDepPrebundlePlugin.setup = function(build2) {
775
+ const _onResolve = build2.onResolve.bind(build2);
776
+ build2.onResolve = function(options, callback) {
777
+ if (options.filter.source.includes("svelte")) {
778
+ options.filter = new RegExp(options.filter.source.replace("|svelte", ""), options.filter.flags);
779
+ }
780
+ return _onResolve(options, callback);
781
+ };
782
+ return _setup(build2);
783
+ };
784
+ }
785
+ async function compileSvelte(options, { filename, code }) {
786
+ var _a, _b;
787
+ const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
788
+ css: true,
789
+ filename,
790
+ format: "esm",
791
+ generate: "dom"
792
+ });
793
+ let preprocessed;
794
+ if (options.preprocess) {
795
+ preprocessed = await preprocess2(code, options.preprocess, { filename });
796
+ if (preprocessed.map)
797
+ compileOptions.sourcemap = preprocessed.map;
798
+ }
799
+ const finalCode = preprocessed ? preprocessed.code : code;
800
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
801
+ filename,
802
+ code: finalCode,
803
+ compileOptions
804
+ }));
805
+ if (dynamicCompileOptions && log.debug.enabled) {
806
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
807
+ }
808
+ const finalCompileOptions = dynamicCompileOptions ? __spreadValues(__spreadValues({}, compileOptions), dynamicCompileOptions) : compileOptions;
809
+ const compiled = compile2(finalCode, finalCompileOptions);
810
+ return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
811
+ }
812
+
813
+ // src/utils/preprocess.ts
814
+ import {
815
+ transformWithEsbuild
816
+ } from "vite";
817
+ import MagicString2 from "magic-string";
818
+ import { preprocess as preprocess3 } from "svelte/compiler";
819
+
820
+ // src/utils/sourcemap.ts
821
+ import MagicString from "magic-string";
822
+ async function buildMagicString(from, to, options) {
823
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
824
+ try {
825
+ const dmpPkg = await import("diff-match-patch");
826
+ diff_match_patch = dmpPkg.diff_match_patch;
827
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
828
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
829
+ } catch (e) {
830
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
831
+ return null;
832
+ }
833
+ const dmp = new diff_match_patch();
834
+ const diffs = dmp.diff_main(from, to);
835
+ dmp.diff_cleanupSemantic(diffs);
836
+ const m = new MagicString(from, options);
837
+ let pos = 0;
838
+ for (let i = 0; i < diffs.length; i++) {
839
+ const diff = diffs[i];
840
+ const nextDiff = diffs[i + 1];
841
+ if (diff[0] === DIFF_DELETE) {
842
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
843
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
844
+ i++;
845
+ } else {
846
+ m.remove(pos, pos + diff[1].length);
847
+ }
848
+ pos += diff[1].length;
849
+ } else if (diff[0] === DIFF_INSERT) {
850
+ if (nextDiff) {
851
+ m.appendRight(pos, diff[1]);
852
+ } else {
853
+ m.append(diff[1]);
854
+ }
855
+ } else {
856
+ pos += diff[1].length;
857
+ }
858
+ }
859
+ return m;
860
+ }
861
+ async function buildSourceMap(from, to, filename) {
862
+ const m = await buildMagicString(from, to, { filename });
863
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
864
+ }
865
+
866
+ // src/utils/preprocess.ts
867
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
868
+ var supportedScriptLangs = ["ts"];
869
+ function createViteScriptPreprocessor() {
870
+ return async ({ attributes, content, filename = "" }) => {
871
+ const lang = attributes.lang;
872
+ if (!supportedScriptLangs.includes(lang))
873
+ return;
874
+ const transformResult = await transformWithEsbuild(content, filename, {
875
+ loader: lang,
876
+ tsconfigRaw: {
877
+ compilerOptions: {
878
+ importsNotUsedAsValues: "preserve"
879
+ }
880
+ }
881
+ });
882
+ return {
883
+ code: transformResult.code,
884
+ map: transformResult.map
885
+ };
886
+ };
887
+ }
888
+ function createViteStylePreprocessor(config) {
889
+ const pluginName = "vite:css";
890
+ const plugin = config.plugins.find((p) => p.name === pluginName);
891
+ if (!plugin) {
892
+ throw new Error(`failed to find plugin ${pluginName}`);
893
+ }
894
+ if (!plugin.transform) {
895
+ throw new Error(`plugin ${pluginName} has no transform`);
896
+ }
897
+ const pluginTransform = plugin.transform.bind(null);
898
+ return async ({ attributes, content, filename = "" }) => {
899
+ var _a, _b;
900
+ const lang = attributes.lang;
901
+ if (!supportedStyleLangs.includes(lang))
902
+ return;
903
+ const moduleId = `${filename}.${lang}`;
904
+ const transformResult = await pluginTransform(content, moduleId);
905
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
906
+ transformResult.map.sources[0] = filename;
907
+ }
908
+ return {
909
+ code: transformResult.code,
910
+ map: transformResult.map ?? void 0
911
+ };
912
+ };
913
+ }
914
+ function createVitePreprocessorGroup(config) {
915
+ return {
916
+ markup({ content, filename }) {
917
+ return preprocess3(content, {
918
+ script: createViteScriptPreprocessor(),
919
+ style: createViteStylePreprocessor(config)
920
+ }, { filename });
921
+ }
922
+ };
923
+ }
924
+ function createInjectScopeEverythingRulePreprocessorGroup() {
925
+ return {
926
+ style({ content, filename }) {
927
+ const s = new MagicString2(content);
928
+ s.append(" *{}");
929
+ return {
930
+ code: s.toString(),
931
+ map: s.generateDecodedMap({ source: filename, hires: true })
932
+ };
933
+ }
934
+ };
935
+ }
936
+ function buildExtraPreprocessors(options, config) {
937
+ var _a, _b;
938
+ const prependPreprocessors = [];
939
+ const appendPreprocessors = [];
940
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
941
+ log.debug("adding vite preprocessor");
942
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
943
+ }
944
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
945
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
946
+ log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
947
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
948
+ if (!p.api) {
949
+ p.api = {};
950
+ }
951
+ if (p.api.sveltePreprocess === void 0) {
952
+ p.api.sveltePreprocess = p.sveltePreprocess;
953
+ } else {
954
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
955
+ }
956
+ });
957
+ }
958
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
959
+ var _a2;
960
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
961
+ });
962
+ const ignored = [], included = [];
963
+ for (const p of pluginsWithPreprocessors) {
964
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
965
+ ignored.push(p);
966
+ } else {
967
+ included.push(p);
968
+ }
969
+ }
970
+ if (ignored.length > 0) {
971
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
972
+ }
973
+ if (included.length > 0) {
974
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
975
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
976
+ }
977
+ if (options.hot && options.emitCss) {
978
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
979
+ }
980
+ return { prependPreprocessors, appendPreprocessors };
981
+ }
982
+ function addExtraPreprocessors(options, config) {
983
+ var _a;
984
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
985
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
986
+ if (!options.preprocess) {
987
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
988
+ } else if (Array.isArray(options.preprocess)) {
989
+ options.preprocess.unshift(...prependPreprocessors);
990
+ options.preprocess.push(...appendPreprocessors);
991
+ } else {
992
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
993
+ }
994
+ }
995
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
996
+ if (options.preprocess && generateMissingSourceMaps) {
997
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
998
+ }
999
+ }
1000
+ function validateSourceMapOutputWrapper(group, i) {
1001
+ const wrapper = {};
1002
+ for (const [processorType, processorFn] of Object.entries(group)) {
1003
+ wrapper[processorType] = async (options) => {
1004
+ var _a;
1005
+ const result = await processorFn(options);
1006
+ if (result && result.code !== options.content) {
1007
+ let invalidMap = false;
1008
+ if (!result.map) {
1009
+ invalidMap = true;
1010
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1011
+ filename: options.filename,
1012
+ type: processorType,
1013
+ processor: processorFn.toString()
1014
+ });
1015
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1016
+ invalidMap = true;
1017
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1018
+ filename: options.filename,
1019
+ type: processorType,
1020
+ processor: processorFn.toString()
1021
+ });
1022
+ }
1023
+ if (invalidMap) {
1024
+ try {
1025
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1026
+ if (map) {
1027
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1028
+ result.map = map;
1029
+ }
1030
+ } catch (e) {
1031
+ log.error(`failed to build sourcemap`, e);
1032
+ }
1033
+ }
1034
+ }
1035
+ return result;
1036
+ };
1037
+ }
1038
+ return wrapper;
1039
+ }
1040
+
1041
+ // src/utils/options.ts
1042
+ var knownOptions = new Set([
1043
+ "configFile",
1044
+ "include",
1045
+ "exclude",
1046
+ "extensions",
1047
+ "emitCss",
1048
+ "compilerOptions",
1049
+ "onwarn",
1050
+ "preprocess",
1051
+ "hot",
1052
+ "ignorePluginPreprocessors",
1053
+ "disableDependencyReinclusion",
1054
+ "experimental"
1055
+ ]);
1056
+ function validateInlineOptions(inlineOptions) {
1057
+ const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
1058
+ if (invalidKeys.length) {
1059
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1060
+ }
1061
+ }
1062
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1063
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1064
+ root: resolveViteRoot(viteUserConfig)
1065
+ });
1066
+ const defaultOptions = {
1067
+ extensions: [".svelte"],
1068
+ emitCss: true,
1069
+ compilerOptions: {
1070
+ format: "esm"
1071
+ }
1072
+ };
1073
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1074
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1075
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1076
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1077
+ root: viteConfigWithResolvedRoot.root,
1078
+ isBuild: viteEnv.command === "build",
1079
+ isServe: viteEnv.command === "serve"
1080
+ });
1081
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1082
+ merged.configFile = svelteConfig.configFile;
1083
+ }
1084
+ return merged;
1085
+ }
1086
+ function resolveOptions(preResolveOptions2, viteConfig) {
1087
+ const defaultOptions = {
1088
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1089
+ compilerOptions: {
1090
+ css: !preResolveOptions2.emitCss,
1091
+ dev: !viteConfig.isProduction
1092
+ }
1093
+ };
1094
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1095
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1096
+ isProduction: viteConfig.isProduction
1097
+ });
1098
+ addExtraPreprocessors(merged, viteConfig);
1099
+ enforceOptionsForHmr(merged);
1100
+ enforceOptionsForProduction(merged);
1101
+ return merged;
1102
+ }
1103
+ function enforceOptionsForHmr(options) {
1104
+ if (options.hot) {
1105
+ if (!options.compilerOptions.dev) {
1106
+ log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
1107
+ options.compilerOptions.dev = true;
1108
+ }
1109
+ if (options.emitCss) {
1110
+ if (options.hot !== true && options.hot.injectCss) {
1111
+ log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1112
+ options.hot.injectCss = false;
1113
+ }
1114
+ if (options.compilerOptions.css) {
1115
+ log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
1116
+ options.compilerOptions.css = false;
1117
+ }
1118
+ } else {
1119
+ if (options.hot === true || !options.hot.injectCss) {
1120
+ log.warn("hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true");
1121
+ if (options.hot === true) {
1122
+ options.hot = { injectCss: true };
1123
+ } else {
1124
+ options.hot.injectCss = true;
1125
+ }
1126
+ }
1127
+ if (!options.compilerOptions.css) {
1128
+ log.warn("hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true");
1129
+ options.compilerOptions.css = true;
1130
+ }
1131
+ }
1132
+ }
1133
+ }
1134
+ function enforceOptionsForProduction(options) {
1135
+ if (options.isProduction) {
1136
+ if (options.hot) {
1137
+ log.warn("options.hot is enabled but does not work on production build, forcing it to false");
1138
+ options.hot = false;
1139
+ }
1140
+ if (options.compilerOptions.dev) {
1141
+ log.warn("you are building for production but compilerOptions.dev is true, forcing it to false");
1142
+ options.compilerOptions.dev = false;
1143
+ }
1144
+ }
1145
+ }
1146
+ function resolveViteRoot(viteConfig) {
1147
+ return normalizePath2(viteConfig.root ? path3.resolve(viteConfig.root) : process.cwd());
1148
+ }
1149
+ function buildExtraViteConfig(options, config, configEnv) {
1150
+ const svelteDeps = findRootSvelteDependencies(options.root);
1151
+ const extraViteConfig = {
1152
+ resolve: {
1153
+ mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1154
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1155
+ }
1156
+ };
1157
+ if (configEnv.command === "serve") {
1158
+ extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(svelteDeps, options, config.optimizeDeps);
1159
+ }
1160
+ extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
1161
+ return extraViteConfig;
1162
+ }
1163
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1164
+ const include = [];
1165
+ const exclude = ["svelte-hmr"];
1166
+ const isIncluded = (dep) => {
1167
+ var _a;
1168
+ return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1169
+ };
1170
+ const isExcluded = (dep) => {
1171
+ var _a;
1172
+ return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1173
+ };
1174
+ if (!isExcluded("svelte")) {
1175
+ const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1176
+ log.debug(`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `);
1177
+ include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1178
+ } else {
1179
+ log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1180
+ }
1181
+ if (options.experimental.prebundleSvelteLibraries) {
1182
+ return {
1183
+ include,
1184
+ exclude,
1185
+ esbuildOptions: {
1186
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1187
+ } }]
1188
+ }
1189
+ };
1190
+ }
1191
+ svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1192
+ const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter((dep) => !isIncluded(dep));
1193
+ log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1194
+ exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1195
+ if (options.disableDependencyReinclusion !== true) {
1196
+ const disabledReinclusions = options.disableDependencyReinclusion || [];
1197
+ if (disabledReinclusions.length > 0) {
1198
+ log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1199
+ }
1200
+ const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1201
+ const localRequire = createRequire3(`${dep.dir}/package.json`);
1202
+ return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1203
+ });
1204
+ log.debug(`reincluding transitive dependencies of excluded svelte dependencies`, transitiveDepsToInclude);
1205
+ include.push(...transitiveDepsToInclude);
1206
+ }
1207
+ return { include, exclude };
1208
+ }
1209
+ function buildSSROptionsForSvelte(svelteDeps, options, config) {
1210
+ var _a, _b, _c;
1211
+ const noExternal = [];
1212
+ if (options.isBuild && ((_a = config.build) == null ? void 0 : _a.ssr)) {
1213
+ if (!((_c = (_b = config.ssr) == null ? void 0 : _b.external) == null ? void 0 : _c.includes("svelte"))) {
1214
+ noExternal.push("svelte");
1215
+ }
1216
+ } else {
1217
+ svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1218
+ }
1219
+ noExternal.push(...Array.from(new Set(svelteDeps.map((s) => s.name))).filter((x) => {
1220
+ var _a2, _b2, _c2, _d;
1221
+ return !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(x)) && !((_d = (_c2 = config.optimizeDeps) == null ? void 0 : _c2.include) == null ? void 0 : _d.includes(x));
1222
+ }));
1223
+ return {
1224
+ noExternal
1225
+ };
1226
+ }
1227
+ function patchResolvedViteConfig(viteConfig, options) {
1228
+ var _a, _b;
1229
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1230
+ if (facadeEsbuildSveltePlugin) {
1231
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1232
+ }
1233
+ }
1234
+
1235
+ // src/utils/vite-plugin-svelte-cache.ts
1236
+ var VitePluginSvelteCache = class {
1237
+ constructor() {
1238
+ this._css = new Map();
1239
+ this._js = new Map();
1240
+ this._dependencies = new Map();
1241
+ this._dependants = new Map();
1242
+ }
1243
+ update(compileData) {
1244
+ this.updateCSS(compileData);
1245
+ this.updateJS(compileData);
1246
+ this.updateDependencies(compileData);
1247
+ }
1248
+ updateCSS(compileData) {
1249
+ this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1250
+ }
1251
+ updateJS(compileData) {
1252
+ if (!compileData.ssr) {
1253
+ this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1254
+ }
1255
+ }
1256
+ updateDependencies(compileData) {
1257
+ const id = compileData.normalizedFilename;
1258
+ const prevDependencies = this._dependencies.get(id) || [];
1259
+ const dependencies = compileData.dependencies;
1260
+ this._dependencies.set(id, dependencies);
1261
+ const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1262
+ const added = dependencies.filter((d) => !prevDependencies.includes(d));
1263
+ added.forEach((d) => {
1264
+ if (!this._dependants.has(d)) {
1265
+ this._dependants.set(d, new Set());
1266
+ }
1267
+ this._dependants.get(d).add(compileData.filename);
1268
+ });
1269
+ removed.forEach((d) => {
1270
+ this._dependants.get(d).delete(compileData.filename);
1271
+ });
1272
+ }
1273
+ remove(svelteRequest) {
1274
+ const id = svelteRequest.normalizedFilename;
1275
+ let removed = false;
1276
+ if (this._js.delete(id)) {
1277
+ removed = true;
1278
+ }
1279
+ if (this._css.delete(id)) {
1280
+ removed = true;
1281
+ }
1282
+ const dependencies = this._dependencies.get(id);
1283
+ if (dependencies) {
1284
+ removed = true;
1285
+ dependencies.forEach((d) => {
1286
+ const dependants = this._dependants.get(d);
1287
+ if (dependants && dependants.has(svelteRequest.filename)) {
1288
+ dependants.delete(svelteRequest.filename);
1289
+ }
1290
+ });
1291
+ this._dependencies.delete(id);
1292
+ }
1293
+ return removed;
1294
+ }
1295
+ getCSS(svelteRequest) {
1296
+ return this._css.get(svelteRequest.normalizedFilename);
1297
+ }
1298
+ getJS(svelteRequest) {
1299
+ if (!svelteRequest.ssr) {
1300
+ return this._js.get(svelteRequest.normalizedFilename);
1301
+ }
1302
+ }
1303
+ getDependants(path6) {
1304
+ const dependants = this._dependants.get(path6);
1305
+ return dependants ? [...dependants] : [];
1306
+ }
1307
+ };
1308
+
1309
+ // src/utils/watch.ts
1310
+ import fs5 from "fs";
1311
+ import path4 from "path";
1312
+ function setupWatchers(options, cache, requestParser) {
1313
+ const { server, configFile: svelteConfigFile } = options;
1314
+ if (!server) {
1315
+ return;
1316
+ }
1317
+ const { watcher, ws } = server;
1318
+ const { root, server: serverConfig } = server.config;
1319
+ const emitChangeEventOnDependants = (filename) => {
1320
+ const dependants = cache.getDependants(filename);
1321
+ dependants.forEach((dependant) => {
1322
+ if (fs5.existsSync(dependant)) {
1323
+ log.debug(`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`);
1324
+ watcher.emit("change", dependant);
1325
+ }
1326
+ });
1327
+ };
1328
+ const removeUnlinkedFromCache = (filename) => {
1329
+ const svelteRequest = requestParser(filename, false);
1330
+ if (svelteRequest) {
1331
+ const removedFromCache = cache.remove(svelteRequest);
1332
+ if (removedFromCache) {
1333
+ log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
1334
+ }
1335
+ }
1336
+ };
1337
+ const triggerViteRestart = (filename) => {
1338
+ var _a;
1339
+ if (serverConfig.middlewareMode) {
1340
+ const message = "Svelte config change detected, restart your dev process to apply the changes.";
1341
+ log.info(message, filename);
1342
+ ws.send({
1343
+ type: "error",
1344
+ err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1345
+ });
1346
+ } else {
1347
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1348
+ server.restart(!!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries));
1349
+ }
1350
+ };
1351
+ const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path4.join(root, cfg));
1352
+ const restartOnConfigAdd = (filename) => {
1353
+ if (possibleSvelteConfigs.includes(filename)) {
1354
+ triggerViteRestart(filename);
1355
+ }
1356
+ };
1357
+ const restartOnConfigChange = (filename) => {
1358
+ if (filename === svelteConfigFile) {
1359
+ triggerViteRestart(filename);
1360
+ }
1361
+ };
1362
+ const listenerCollection = {
1363
+ add: [],
1364
+ change: [emitChangeEventOnDependants],
1365
+ unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
1366
+ };
1367
+ if (svelteConfigFile) {
1368
+ listenerCollection.change.push(restartOnConfigChange);
1369
+ listenerCollection.unlink.push(restartOnConfigChange);
1370
+ } else {
1371
+ listenerCollection.add.push(restartOnConfigAdd);
1372
+ }
1373
+ Object.entries(listenerCollection).forEach(([evt, listeners]) => {
1374
+ if (listeners.length > 0) {
1375
+ watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
1376
+ }
1377
+ });
1378
+ }
1379
+ function ensureWatchedFile(watcher, file, root) {
1380
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs5.existsSync(file)) {
1381
+ watcher.add(path4.resolve(file));
1382
+ }
1383
+ }
1384
+
1385
+ // src/utils/resolve.ts
1386
+ import path5 from "path";
1387
+ import fs6 from "fs";
1388
+ import relative from "require-relative";
1389
+ function resolveViaPackageJsonSvelte(importee, importer) {
1390
+ if (importer && isBareImport(importee)) {
1391
+ const importeePkgFile = relative.resolve(`${importee}/package.json`, path5.dirname(importer));
1392
+ const importeePkg = JSON.parse(fs6.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1393
+ if (importeePkg.svelte) {
1394
+ return path5.resolve(path5.dirname(importeePkgFile), importeePkg.svelte);
1395
+ }
1396
+ }
1397
+ }
1398
+ function isBareImport(importee) {
1399
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || path5.isAbsolute(importee)) {
1400
+ return false;
1401
+ }
1402
+ const parts = importee.split("/");
1403
+ switch (parts.length) {
1404
+ case 1:
1405
+ return true;
1406
+ case 2:
1407
+ return parts[0].startsWith("@");
1408
+ default:
1409
+ return false;
1410
+ }
1411
+ }
1412
+
1413
+ // src/index.ts
1414
+ function svelte(inlineOptions) {
1415
+ if (process.env.DEBUG != null) {
1416
+ log.setLevel("debug");
1417
+ }
1418
+ validateInlineOptions(inlineOptions);
1419
+ const cache = new VitePluginSvelteCache();
1420
+ const pkg_export_errors = new Set();
1421
+ let requestParser;
1422
+ let options;
1423
+ let viteConfig;
1424
+ let compileSvelte2;
1425
+ let resolvedSvelteSSR;
1426
+ return {
1427
+ name: "vite-plugin-svelte",
1428
+ enforce: "pre",
1429
+ async config(config, configEnv) {
1430
+ if (process.env.DEBUG) {
1431
+ log.setLevel("debug");
1432
+ } else if (config.logLevel) {
1433
+ log.setLevel(config.logLevel);
1434
+ }
1435
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1436
+ const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1437
+ log.debug("additional vite config", extraViteConfig);
1438
+ return extraViteConfig;
1439
+ },
1440
+ async configResolved(config) {
1441
+ options = resolveOptions(options, config);
1442
+ patchResolvedViteConfig(config, options);
1443
+ requestParser = buildIdParser(options);
1444
+ compileSvelte2 = createCompileSvelte(options);
1445
+ viteConfig = config;
1446
+ log.debug("resolved options", options);
1447
+ },
1448
+ configureServer(server) {
1449
+ options.server = server;
1450
+ setupWatchers(options, cache, requestParser);
1451
+ },
1452
+ load(id, opts) {
1453
+ const ssr = opts === true || (opts == null ? void 0 : opts.ssr);
1454
+ const svelteRequest = requestParser(id, !!ssr);
1455
+ if (svelteRequest) {
1456
+ const { filename, query } = svelteRequest;
1457
+ if (query.svelte && query.type === "style") {
1458
+ const css = cache.getCSS(svelteRequest);
1459
+ if (css) {
1460
+ log.debug(`load returns css for ${filename}`);
1461
+ return css;
1462
+ }
1463
+ }
1464
+ if (viteConfig.assetsInclude(filename)) {
1465
+ log.debug(`load returns raw content for ${filename}`);
1466
+ return fs7.readFileSync(filename, "utf-8");
1467
+ }
1468
+ }
1469
+ },
1470
+ async resolveId(importee, importer, opts) {
1471
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1472
+ const svelteRequest = requestParser(importee, ssr);
1473
+ if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1474
+ if (svelteRequest.query.type === "style") {
1475
+ log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
1476
+ return svelteRequest.cssId;
1477
+ }
1478
+ log.debug(`resolveId resolved ${importee}`);
1479
+ return importee;
1480
+ }
1481
+ if (ssr && importee === "svelte") {
1482
+ if (!resolvedSvelteSSR) {
1483
+ resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then((svelteSSR) => {
1484
+ log.debug("resolved svelte to svelte/ssr");
1485
+ return svelteSSR;
1486
+ }, (err) => {
1487
+ log.debug("failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it", err);
1488
+ return null;
1489
+ });
1490
+ }
1491
+ return resolvedSvelteSSR;
1492
+ }
1493
+ try {
1494
+ const resolved = resolveViaPackageJsonSvelte(importee, importer);
1495
+ if (resolved) {
1496
+ log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1497
+ return resolved;
1498
+ }
1499
+ } catch (err) {
1500
+ switch (err.code) {
1501
+ case "ERR_PACKAGE_PATH_NOT_EXPORTED":
1502
+ pkg_export_errors.add(importee);
1503
+ return null;
1504
+ case "MODULE_NOT_FOUND":
1505
+ return null;
1506
+ default:
1507
+ throw err;
1508
+ }
1509
+ }
1510
+ },
1511
+ async transform(code, id, opts) {
1512
+ var _a;
1513
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1514
+ const svelteRequest = requestParser(id, ssr);
1515
+ if (!svelteRequest) {
1516
+ return;
1517
+ }
1518
+ const { filename, query } = svelteRequest;
1519
+ if (query.svelte) {
1520
+ if (query.type === "style") {
1521
+ const css = cache.getCSS(svelteRequest);
1522
+ if (css) {
1523
+ log.debug(`transform returns css for ${filename}`);
1524
+ return css;
1525
+ }
1526
+ }
1527
+ log.error("failed to transform tagged svelte request", svelteRequest);
1528
+ throw new Error(`failed to transform tagged svelte request for id ${id}`);
1529
+ }
1530
+ let compileData;
1531
+ try {
1532
+ compileData = await compileSvelte2(svelteRequest, code, options);
1533
+ } catch (e) {
1534
+ throw toRollupError(e);
1535
+ }
1536
+ logCompilerWarnings(compileData.compiled.warnings, options);
1537
+ cache.update(compileData);
1538
+ if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
1539
+ compileData.dependencies.forEach((d) => {
1540
+ ensureWatchedFile(options.server.watcher, d, options.root);
1541
+ });
1542
+ }
1543
+ log.debug(`transform returns compiled js for ${filename}`);
1544
+ return compileData.compiled.js;
1545
+ },
1546
+ handleHotUpdate(ctx) {
1547
+ if (!options.hot || !options.emitCss) {
1548
+ return;
1549
+ }
1550
+ const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
1551
+ if (svelteRequest) {
1552
+ return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
1553
+ }
1554
+ },
1555
+ buildEnd() {
1556
+ if (pkg_export_errors.size > 0) {
1557
+ 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"));
1558
+ }
1559
+ }
1560
+ };
1561
+ }
1562
+ export {
1563
+ svelte
1564
+ };
1565
+ //# sourceMappingURL=index.js.map