@sveltejs/vite-plugin-svelte 1.3.1 → 2.0.0-beta.0

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 DELETED
@@ -1,2226 +0,0 @@
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.5.0/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
- var import_vitefu4 = require("vitefu");
41
-
42
- // src/utils/log.ts
43
- var import_colors = require("kleur/colors");
44
- var import_debug = __toESM(require("debug"), 1);
45
- var levels = ["debug", "info", "warn", "error", "silent"];
46
- var prefix = "vite-plugin-svelte";
47
- var loggers = {
48
- debug: {
49
- log: (0, import_debug.default)(`vite:${prefix}`),
50
- enabled: false,
51
- isDebug: true
52
- },
53
- info: {
54
- color: import_colors.cyan,
55
- log: console.log,
56
- enabled: true
57
- },
58
- warn: {
59
- color: import_colors.yellow,
60
- log: console.warn,
61
- enabled: true
62
- },
63
- error: {
64
- color: import_colors.red,
65
- log: console.error,
66
- enabled: true
67
- },
68
- silent: {
69
- enabled: false
70
- }
71
- };
72
- var _level = "info";
73
- function setLevel(level) {
74
- if (level === _level) {
75
- return;
76
- }
77
- const levelIndex = levels.indexOf(level);
78
- if (levelIndex > -1) {
79
- _level = level;
80
- for (let i = 0; i < levels.length; i++) {
81
- loggers[levels[i]].enabled = i >= levelIndex;
82
- }
83
- } else {
84
- _log(loggers.error, `invalid log level: ${level} `);
85
- }
86
- }
87
- function _log(logger, message, payload) {
88
- if (!logger.enabled) {
89
- return;
90
- }
91
- if (logger.isDebug) {
92
- payload !== void 0 ? logger.log(message, payload) : logger.log(message);
93
- } else {
94
- logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
95
- if (payload) {
96
- logger.log(payload);
97
- }
98
- }
99
- }
100
- function createLogger(level) {
101
- const logger = loggers[level];
102
- const logFn = _log.bind(null, logger);
103
- const logged = /* @__PURE__ */ new Set();
104
- const once = function(message, payload) {
105
- if (logged.has(message)) {
106
- return;
107
- }
108
- logged.add(message);
109
- logFn.apply(null, [message, payload]);
110
- };
111
- Object.defineProperty(logFn, "enabled", {
112
- get() {
113
- return logger.enabled;
114
- }
115
- });
116
- Object.defineProperty(logFn, "once", {
117
- get() {
118
- return once;
119
- }
120
- });
121
- return logFn;
122
- }
123
- var log = {
124
- debug: createLogger("debug"),
125
- info: createLogger("info"),
126
- warn: createLogger("warn"),
127
- error: createLogger("error"),
128
- setLevel
129
- };
130
- function logCompilerWarnings(svelteRequest, warnings, options) {
131
- const { emitCss, onwarn, isBuild } = options;
132
- const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser;
133
- let warn = isBuild ? warnBuild : warnDev;
134
- const handledByDefaultWarn = [];
135
- const notIgnored = 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
- options.server?.ws?.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?.code, next?.code);
259
- }
260
- function jsChanged(prev, next, filename) {
261
- const prevJs = prev?.code;
262
- const nextJs = 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) => {
322
- let stats;
323
- return async function compileSvelte2(svelteRequest, code, options) {
324
- const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
325
- const { emitCss = true } = options;
326
- const dependencies = [];
327
- if (options.stats) {
328
- if (options.isBuild) {
329
- if (!stats) {
330
- stats = options.stats.startCollection(`${ssr ? "ssr" : "dom"} compile`, {
331
- logInProgress: () => false
332
- });
333
- }
334
- } else {
335
- if (ssr && !stats) {
336
- stats = options.stats.startCollection("ssr compile");
337
- }
338
- if (!ssr && stats) {
339
- stats.finish();
340
- stats = void 0;
341
- }
342
- }
343
- }
344
- const compileOptions = {
345
- ...options.compilerOptions,
346
- filename,
347
- generate: ssr ? "ssr" : "dom",
348
- format: "esm"
349
- };
350
- if (options.hot && options.emitCss) {
351
- const hash = `s-${safeBase64Hash(normalizedFilename)}`;
352
- log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
353
- compileOptions.cssHash = () => hash;
354
- }
355
- if (ssr && compileOptions.enableSourcemap !== false) {
356
- if (typeof compileOptions.enableSourcemap === "object") {
357
- compileOptions.enableSourcemap.css = false;
358
- } else {
359
- compileOptions.enableSourcemap = { js: true, css: false };
360
- }
361
- }
362
- let preprocessed;
363
- if (options.preprocess) {
364
- try {
365
- preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
366
- } catch (e) {
367
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
368
- throw e;
369
- }
370
- if (preprocessed.dependencies)
371
- dependencies.push(...preprocessed.dependencies);
372
- if (preprocessed.map)
373
- compileOptions.sourcemap = preprocessed.map;
374
- }
375
- const finalCode = preprocessed ? preprocessed.code : code;
376
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
377
- filename,
378
- code: finalCode,
379
- compileOptions
380
- });
381
- if (dynamicCompileOptions && log.debug.enabled) {
382
- log.debug(
383
- `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
384
- );
385
- }
386
- const finalCompileOptions = dynamicCompileOptions ? {
387
- ...compileOptions,
388
- ...dynamicCompileOptions
389
- } : compileOptions;
390
- const endStat = stats?.start(filename);
391
- const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
392
- if (endStat) {
393
- endStat();
394
- }
395
- const hasCss = compiled.css?.code?.trim().length > 0;
396
- if (emitCss && hasCss) {
397
- compiled.js.code += `
398
- import ${JSON.stringify(cssId)};
399
- `;
400
- }
401
- if (!ssr && makeHot) {
402
- compiled.js.code = makeHot({
403
- id: filename,
404
- compiledCode: compiled.js.code,
405
- hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
406
- compiled,
407
- originalCode: code,
408
- compileOptions: finalCompileOptions
409
- });
410
- }
411
- compiled.js.dependencies = dependencies;
412
- return {
413
- filename,
414
- normalizedFilename,
415
- lang: code.match(scriptLangRE)?.[1] || "js",
416
- compiled,
417
- ssr,
418
- dependencies
419
- };
420
- };
421
- };
422
- function buildMakeHot(options) {
423
- const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
424
- if (needsMakeHot) {
425
- const hotApi = options?.hot?.hotApi;
426
- const adapter = options?.hot?.adapter;
427
- return (0, import_svelte_hmr.createMakeHot)({
428
- walk: import_compiler.walk,
429
- hotApi,
430
- adapter,
431
- hotOptions: { noOverlay: true, ...options.hot }
432
- });
433
- }
434
- }
435
- function createCompileSvelte(options) {
436
- const makeHot = buildMakeHot(options);
437
- return _createCompileSvelte(makeHot);
438
- }
439
-
440
- // src/utils/id.ts
441
- var import_vite = require("vite");
442
- var import_vite2 = require("vite");
443
- var fs = __toESM(require("fs"), 1);
444
- var VITE_FS_PREFIX = "/@fs/";
445
- var IS_WINDOWS = process.platform === "win32";
446
- function splitId(id) {
447
- const parts = id.split(`?`, 2);
448
- const filename = parts[0];
449
- const rawQuery = parts[1];
450
- return { filename, rawQuery };
451
- }
452
- function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
453
- const query = parseRequestQuery(rawQuery);
454
- if (query.url || query.raw) {
455
- return;
456
- }
457
- const normalizedFilename = normalize(filename, root);
458
- const cssId = createVirtualImportId(filename, root, "style");
459
- return {
460
- id,
461
- filename,
462
- normalizedFilename,
463
- cssId,
464
- query,
465
- timestamp,
466
- ssr
467
- };
468
- }
469
- function createVirtualImportId(filename, root, type) {
470
- const parts = ["svelte", `type=${type}`];
471
- if (type === "style") {
472
- parts.push("lang.css");
473
- }
474
- if (existsInRoot(filename, root)) {
475
- filename = root + filename;
476
- } else if (filename.startsWith(VITE_FS_PREFIX)) {
477
- filename = IS_WINDOWS ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
478
- }
479
- return `${filename}?${parts.join("&")}`;
480
- }
481
- function parseRequestQuery(rawQuery) {
482
- const query = Object.fromEntries(new URLSearchParams(rawQuery));
483
- for (const key in query) {
484
- if (query[key] === "") {
485
- query[key] = true;
486
- }
487
- }
488
- return query;
489
- }
490
- function normalize(filename, normalizedRoot) {
491
- return stripRoot((0, import_vite2.normalizePath)(filename), normalizedRoot);
492
- }
493
- function existsInRoot(filename, root) {
494
- if (filename.startsWith(VITE_FS_PREFIX)) {
495
- return false;
496
- }
497
- return fs.existsSync(root + filename);
498
- }
499
- function stripRoot(normalizedFilename, normalizedRoot) {
500
- return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
501
- }
502
- function buildFilter(include, exclude, extensions) {
503
- const rollupFilter = (0, import_vite.createFilter)(include, exclude);
504
- return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
505
- }
506
- function buildIdParser(options) {
507
- const { include, exclude, extensions, root } = options;
508
- const normalizedRoot = (0, import_vite2.normalizePath)(root);
509
- const filter = buildFilter(include, exclude, extensions);
510
- return (id, ssr, timestamp = Date.now()) => {
511
- const { filename, rawQuery } = splitId(id);
512
- if (filter(filename)) {
513
- return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
514
- }
515
- };
516
- }
517
-
518
- // src/utils/options.ts
519
- var import_vite4 = require("vite");
520
-
521
- // src/utils/load-svelte-config.ts
522
- var import_module = require("module");
523
- var import_path = __toESM(require("path"), 1);
524
- var import_fs = __toESM(require("fs"), 1);
525
- var import_url = require("url");
526
- var esmRequire;
527
- var knownSvelteConfigNames = [
528
- "svelte.config.js",
529
- "svelte.config.cjs",
530
- "svelte.config.mjs"
531
- ];
532
- var dynamicImportDefault = new Function(
533
- "path",
534
- "timestamp",
535
- 'return import(path + "?t=" + timestamp).then(m => m.default)'
536
- );
537
- async function loadSvelteConfig(viteConfig, inlineOptions) {
538
- if (inlineOptions?.configFile === false) {
539
- return;
540
- }
541
- const configFile = findConfigToLoad(viteConfig, inlineOptions);
542
- if (configFile) {
543
- let err;
544
- if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
545
- try {
546
- const result = await dynamicImportDefault(
547
- (0, import_url.pathToFileURL)(configFile).href,
548
- import_fs.default.statSync(configFile).mtimeMs
549
- );
550
- if (result != null) {
551
- return {
552
- ...result,
553
- configFile
554
- };
555
- } else {
556
- throw new Error(`invalid export in ${configFile}`);
557
- }
558
- } catch (e) {
559
- log.error(`failed to import config ${configFile}`, e);
560
- err = e;
561
- }
562
- }
563
- if (!configFile.endsWith(".mjs")) {
564
- try {
565
- const _require = importMetaUrl ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrl)) : require;
566
- delete _require.cache[_require.resolve(configFile)];
567
- const result = _require(configFile);
568
- if (result != null) {
569
- return {
570
- ...result,
571
- configFile
572
- };
573
- } else {
574
- throw new Error(`invalid export in ${configFile}`);
575
- }
576
- } catch (e) {
577
- log.error(`failed to require config ${configFile}`, e);
578
- if (!err) {
579
- err = e;
580
- }
581
- }
582
- }
583
- throw err;
584
- }
585
- }
586
- function findConfigToLoad(viteConfig, inlineOptions) {
587
- const root = viteConfig?.root || process.cwd();
588
- if (inlineOptions?.configFile) {
589
- const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile);
590
- if (!import_fs.default.existsSync(abolutePath)) {
591
- throw new Error(`failed to find svelte config file ${abolutePath}.`);
592
- }
593
- return abolutePath;
594
- } else {
595
- const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file));
596
- if (existingKnownConfigFiles.length === 0) {
597
- log.debug(`no svelte config found at ${root}`);
598
- return;
599
- } else if (existingKnownConfigFiles.length > 1) {
600
- log.warn(
601
- `found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`,
602
- existingKnownConfigFiles
603
- );
604
- }
605
- return existingKnownConfigFiles[0];
606
- }
607
- }
608
-
609
- // src/utils/constants.ts
610
- var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
611
- var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
612
- var SVELTE_IMPORTS = [
613
- "svelte/animate",
614
- "svelte/easing",
615
- "svelte/internal",
616
- "svelte/motion",
617
- "svelte/ssr",
618
- "svelte/store",
619
- "svelte/transition",
620
- "svelte"
621
- ];
622
- var SVELTE_HMR_IMPORTS = [
623
- "svelte-hmr/runtime/hot-api-esm.js",
624
- "svelte-hmr/runtime/proxy-adapter-dom.js",
625
- "svelte-hmr"
626
- ];
627
- var SVELTE_EXPORT_CONDITIONS = ["svelte"];
628
-
629
- // src/utils/options.ts
630
- var import_path5 = __toESM(require("path"), 1);
631
-
632
- // src/utils/esbuild.ts
633
- var import_fs2 = require("fs");
634
- var import_compiler3 = require("svelte/compiler");
635
-
636
- // src/utils/error.ts
637
- function toRollupError(error, options) {
638
- const { filename, frame, start, code, name, stack } = error;
639
- const rollupError = {
640
- name,
641
- id: filename,
642
- message: buildExtendedLogMessage(error),
643
- frame: formatFrameForVite(frame),
644
- code,
645
- stack: options.isBuild || options.isDebug || !frame ? stack : ""
646
- };
647
- if (start) {
648
- rollupError.loc = {
649
- line: start.line,
650
- column: start.column,
651
- file: filename
652
- };
653
- }
654
- return rollupError;
655
- }
656
- function toESBuildError(error, options) {
657
- const { filename, frame, start, stack } = error;
658
- const partialMessage = {
659
- text: buildExtendedLogMessage(error)
660
- };
661
- if (start) {
662
- partialMessage.location = {
663
- line: start.line,
664
- column: start.column,
665
- file: filename,
666
- lineText: lineFromFrame(start.line, frame)
667
- };
668
- }
669
- if (options.isBuild || options.isDebug || !frame) {
670
- partialMessage.detail = stack;
671
- }
672
- return partialMessage;
673
- }
674
- function lineFromFrame(lineNo, frame) {
675
- if (!frame) {
676
- return "";
677
- }
678
- const lines = frame.split("\n");
679
- const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
680
- return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
681
- }
682
- function formatFrameForVite(frame) {
683
- if (!frame) {
684
- return "";
685
- }
686
- return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
687
- }
688
-
689
- // src/utils/svelte-version.ts
690
- var import_compiler2 = require("svelte/compiler");
691
- var svelteVersion = parseVersion(import_compiler2.VERSION);
692
- function parseVersion(version) {
693
- const segments = version.split(".", 3).map((s) => parseInt(s, 10));
694
- while (segments.length < 3) {
695
- segments.push(0);
696
- }
697
- return segments;
698
- }
699
- function compareToSvelte(version) {
700
- const parsedVersion = parseVersion(version);
701
- for (let i = 0; i < svelteVersion.length; i++) {
702
- const a = parsedVersion[i];
703
- const b = svelteVersion[i];
704
- if (a === b) {
705
- continue;
706
- } else if (a > b) {
707
- return 1;
708
- } else {
709
- return -1;
710
- }
711
- }
712
- return 0;
713
- }
714
- function atLeastSvelte(version) {
715
- const result = compareToSvelte(version) <= 0;
716
- return result;
717
- }
718
-
719
- // src/utils/esbuild.ts
720
- var isCssString = atLeastSvelte("3.53.0");
721
- var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
722
- function esbuildSveltePlugin(options) {
723
- return {
724
- name: "vite-plugin-svelte:optimize-svelte",
725
- setup(build) {
726
- if (build.initialOptions.plugins?.some((v) => v.name === "vite:dep-scan"))
727
- return;
728
- const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
729
- const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
730
- let statsCollection;
731
- build.onStart(() => {
732
- statsCollection = options.stats?.startCollection("prebundle libraries", {
733
- logResult: (c) => c.stats.length > 1
734
- });
735
- });
736
- build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
737
- const code = (0, import_fs2.readFileSync)(filename, "utf8");
738
- try {
739
- const contents = await compileSvelte(options, { filename, code }, statsCollection);
740
- return { contents };
741
- } catch (e) {
742
- return { errors: [toESBuildError(e, options)] };
743
- }
744
- });
745
- build.onEnd(() => {
746
- statsCollection?.finish();
747
- });
748
- }
749
- };
750
- }
751
- async function compileSvelte(options, { filename, code }, statsCollection) {
752
- let css = options.compilerOptions.css;
753
- if (css !== "none") {
754
- css = isCssString ? "injected" : true;
755
- }
756
- const compileOptions = {
757
- ...options.compilerOptions,
758
- css,
759
- filename,
760
- format: "esm",
761
- generate: "dom"
762
- };
763
- let preprocessed;
764
- if (options.preprocess) {
765
- try {
766
- preprocessed = await (0, import_compiler3.preprocess)(code, options.preprocess, { filename });
767
- } catch (e) {
768
- e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
769
- throw e;
770
- }
771
- if (preprocessed.map)
772
- compileOptions.sourcemap = preprocessed.map;
773
- }
774
- const finalCode = preprocessed ? preprocessed.code : code;
775
- const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
776
- filename,
777
- code: finalCode,
778
- compileOptions
779
- });
780
- if (dynamicCompileOptions && log.debug.enabled) {
781
- log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
782
- }
783
- const finalCompileOptions = dynamicCompileOptions ? {
784
- ...compileOptions,
785
- ...dynamicCompileOptions
786
- } : compileOptions;
787
- const endStat = statsCollection?.start(filename);
788
- const compiled = (0, import_compiler3.compile)(finalCode, finalCompileOptions);
789
- if (endStat) {
790
- endStat();
791
- }
792
- return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
793
- }
794
-
795
- // src/utils/preprocess.ts
796
- var vite = __toESM(require("vite"), 1);
797
- var import_magic_string2 = __toESM(require("magic-string"), 1);
798
- var import_compiler4 = require("svelte/compiler");
799
-
800
- // src/utils/sourcemap.ts
801
- var import_magic_string = __toESM(require("magic-string"), 1);
802
- async function buildMagicString(from, to, options) {
803
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
804
- try {
805
- const dmpPkg = await import("diff-match-patch");
806
- diff_match_patch = dmpPkg.diff_match_patch;
807
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
808
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
809
- } catch (e) {
810
- log.error.once(
811
- 'Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.'
812
- );
813
- return null;
814
- }
815
- const dmp = new diff_match_patch();
816
- const diffs = dmp.diff_main(from, to);
817
- dmp.diff_cleanupSemantic(diffs);
818
- const m = new import_magic_string.default(from, options);
819
- let pos = 0;
820
- for (let i = 0; i < diffs.length; i++) {
821
- const diff = diffs[i];
822
- const nextDiff = diffs[i + 1];
823
- if (diff[0] === DIFF_DELETE) {
824
- if (nextDiff?.[0] === DIFF_INSERT) {
825
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
826
- i++;
827
- } else {
828
- m.remove(pos, pos + diff[1].length);
829
- }
830
- pos += diff[1].length;
831
- } else if (diff[0] === DIFF_INSERT) {
832
- if (nextDiff) {
833
- m.appendRight(pos, diff[1]);
834
- } else {
835
- m.append(diff[1]);
836
- }
837
- } else {
838
- pos += diff[1].length;
839
- }
840
- }
841
- return m;
842
- }
843
- async function buildSourceMap(from, to, filename) {
844
- const m = await buildMagicString(from, to, { filename });
845
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
846
- }
847
-
848
- // src/utils/preprocess.ts
849
- var import_path2 = __toESM(require("path"), 1);
850
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
851
- var supportedScriptLangs = ["ts"];
852
- function createViteScriptPreprocessor() {
853
- return async ({ attributes, content, filename = "" }) => {
854
- const lang = attributes.lang;
855
- if (!supportedScriptLangs.includes(lang))
856
- return;
857
- const transformResult = await vite.transformWithEsbuild(content, filename, {
858
- loader: lang,
859
- target: "esnext",
860
- tsconfigRaw: {
861
- compilerOptions: {
862
- importsNotUsedAsValues: "preserve",
863
- preserveValueImports: true
864
- }
865
- }
866
- });
867
- return {
868
- code: transformResult.code,
869
- map: transformResult.map
870
- };
871
- };
872
- }
873
- function createViteStylePreprocessor(config) {
874
- const transform = getCssTransformFn(config);
875
- return async ({ attributes, content, filename = "" }) => {
876
- const lang = attributes.lang;
877
- if (!supportedStyleLangs.includes(lang))
878
- return;
879
- const moduleId = `${filename}.${lang}`;
880
- const result = await transform(content, moduleId);
881
- if (result.map?.sources?.[0] === moduleId) {
882
- result.map.sources[0] = import_path2.default.basename(filename);
883
- }
884
- return {
885
- code: result.code,
886
- map: result.map ?? void 0
887
- };
888
- };
889
- }
890
- function getCssTransformFn(config) {
891
- if (vite.preprocessCSS) {
892
- return async (code, filename) => {
893
- return vite.preprocessCSS(code, filename, config);
894
- };
895
- } else {
896
- const pluginName = "vite:css";
897
- const plugin = config.plugins.find((p) => p.name === pluginName);
898
- if (!plugin) {
899
- throw new Error(`failed to find plugin ${pluginName}`);
900
- }
901
- if (!plugin.transform) {
902
- throw new Error(`plugin ${pluginName} has no transform`);
903
- }
904
- return plugin.transform.bind(null);
905
- }
906
- }
907
- function createVitePreprocessorGroup(config) {
908
- return {
909
- markup({ content, filename }) {
910
- return (0, import_compiler4.preprocess)(
911
- content,
912
- {
913
- script: createViteScriptPreprocessor(),
914
- style: createViteStylePreprocessor(config)
915
- },
916
- { filename }
917
- );
918
- }
919
- };
920
- }
921
- function createInjectScopeEverythingRulePreprocessorGroup() {
922
- return {
923
- style({ content, filename }) {
924
- const s = new import_magic_string2.default(content);
925
- s.append(" *{}");
926
- return {
927
- code: s.toString(),
928
- map: s.generateDecodedMap({
929
- source: filename ? import_path2.default.basename(filename) : void 0,
930
- hires: true
931
- })
932
- };
933
- }
934
- };
935
- }
936
- function buildExtraPreprocessors(options, config) {
937
- const prependPreprocessors = [];
938
- const appendPreprocessors = [];
939
- if (options.experimental?.useVitePreprocess) {
940
- log.debug("adding vite preprocessor");
941
- prependPreprocessors.push(createVitePreprocessorGroup(config));
942
- }
943
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p?.sveltePreprocess);
944
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
945
- log.warn(
946
- `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
- );
948
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
949
- if (!p.api) {
950
- p.api = {};
951
- }
952
- if (p.api.sveltePreprocess === void 0) {
953
- p.api.sveltePreprocess = p.sveltePreprocess;
954
- } else {
955
- log.error(
956
- `ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`
957
- );
958
- }
959
- });
960
- }
961
- const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess);
962
- const ignored = [], included = [];
963
- for (const p of pluginsWithPreprocessors) {
964
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && options.ignorePluginPreprocessors?.includes(p.name)) {
965
- ignored.push(p);
966
- } else {
967
- included.push(p);
968
- }
969
- }
970
- if (ignored.length > 0) {
971
- log.debug(
972
- `Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`
973
- );
974
- }
975
- if (included.length > 0) {
976
- log.debug(
977
- `Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`
978
- );
979
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
980
- }
981
- if (options.hot && options.emitCss) {
982
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
983
- }
984
- return { prependPreprocessors, appendPreprocessors };
985
- }
986
- function addExtraPreprocessors(options, config) {
987
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
988
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
989
- if (!options.preprocess) {
990
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
991
- } else if (Array.isArray(options.preprocess)) {
992
- options.preprocess.unshift(...prependPreprocessors);
993
- options.preprocess.push(...appendPreprocessors);
994
- } else {
995
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
996
- }
997
- }
998
- const generateMissingSourceMaps = !!options.experimental?.generateMissingPreprocessorSourcemaps;
999
- if (options.preprocess && generateMissingSourceMaps) {
1000
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1001
- }
1002
- }
1003
- function validateSourceMapOutputWrapper(group, i) {
1004
- const wrapper = {};
1005
- for (const [processorType, processorFn] of Object.entries(group)) {
1006
- wrapper[processorType] = async (options) => {
1007
- const result = await processorFn(options);
1008
- if (result && result.code !== options.content) {
1009
- let invalidMap = false;
1010
- if (!result.map) {
1011
- invalidMap = true;
1012
- log.warn.enabled && log.warn.once(
1013
- `preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`,
1014
- {
1015
- filename: options.filename,
1016
- type: processorType,
1017
- processor: processorFn.toString()
1018
- }
1019
- );
1020
- } else if (result.map?.mappings === "") {
1021
- invalidMap = true;
1022
- log.warn.enabled && log.warn.once(
1023
- `preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`,
1024
- {
1025
- filename: options.filename,
1026
- type: processorType,
1027
- processor: processorFn.toString()
1028
- }
1029
- );
1030
- }
1031
- if (invalidMap) {
1032
- try {
1033
- const map = await buildSourceMap(options.content, result.code, options.filename);
1034
- if (map) {
1035
- log.debug.enabled && log.debug(
1036
- `adding generated sourcemap to preprocesor result for ${options.filename}`
1037
- );
1038
- result.map = map;
1039
- }
1040
- } catch (e) {
1041
- log.error(`failed to build sourcemap`, e);
1042
- }
1043
- }
1044
- }
1045
- return result;
1046
- };
1047
- }
1048
- return wrapper;
1049
- }
1050
-
1051
- // src/utils/options.ts
1052
- var import_deepmerge = __toESM(require("deepmerge"), 1);
1053
- var import_vitefu3 = require("vitefu");
1054
-
1055
- // src/utils/dependencies.ts
1056
- var import_path3 = __toESM(require("path"), 1);
1057
- var import_promises = __toESM(require("fs/promises"), 1);
1058
- var import_vitefu = require("vitefu");
1059
- async function resolveDependencyData(dep, parent) {
1060
- const depDataPath = await (0, import_vitefu.findDepPkgJsonPath)(dep, parent);
1061
- if (!depDataPath)
1062
- return void 0;
1063
- try {
1064
- return {
1065
- dir: import_path3.default.dirname(depDataPath),
1066
- pkg: JSON.parse(await import_promises.default.readFile(depDataPath, "utf-8"))
1067
- };
1068
- } catch {
1069
- return void 0;
1070
- }
1071
- }
1072
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
1073
- "@lukeed/uuid",
1074
- "@playwright/test",
1075
- "@sveltejs/vite-plugin-svelte",
1076
- "@sveltejs/kit",
1077
- "autoprefixer",
1078
- "cookie",
1079
- "dotenv",
1080
- "esbuild",
1081
- "eslint",
1082
- "jest",
1083
- "mdsvex",
1084
- "playwright",
1085
- "postcss",
1086
- "prettier",
1087
- "svelte",
1088
- "svelte-check",
1089
- "svelte-hmr",
1090
- "svelte-preprocess",
1091
- "tslib",
1092
- "typescript",
1093
- "vite",
1094
- "vitest",
1095
- "__vite-browser-external"
1096
- ];
1097
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
1098
- "@fontsource/",
1099
- "@postcss-plugins/",
1100
- "@rollup/",
1101
- "@sveltejs/adapter-",
1102
- "@types/",
1103
- "@typescript-eslint/",
1104
- "eslint-",
1105
- "jest-",
1106
- "postcss-plugin-",
1107
- "prettier-plugin-",
1108
- "rollup-plugin-",
1109
- "vite-plugin-"
1110
- ];
1111
- function isCommonDepWithoutSvelteField(dependency) {
1112
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
1113
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
1114
- );
1115
- }
1116
-
1117
- // src/utils/vite-plugin-svelte-stats.ts
1118
- var import_vitefu2 = require("vitefu");
1119
- var import_fs3 = require("fs");
1120
- var import_path4 = require("path");
1121
- var import_perf_hooks = require("perf_hooks");
1122
- var import_vite3 = require("vite");
1123
- var defaultCollectionOptions = {
1124
- logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
1125
- logResult: () => true
1126
- };
1127
- function humanDuration(n) {
1128
- return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1e3).toFixed(2)}s`;
1129
- }
1130
- function formatPackageStats(pkgStats) {
1131
- const statLines = pkgStats.map((pkgStat) => {
1132
- const duration = pkgStat.duration;
1133
- const avg = duration / pkgStat.files;
1134
- return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
1135
- });
1136
- statLines.unshift(["package", "files", "time", "avg"]);
1137
- const columnWidths = statLines.reduce(
1138
- (widths, row) => {
1139
- for (let i = 0; i < row.length; i++) {
1140
- const cell = row[i];
1141
- if (widths[i] < cell.length) {
1142
- widths[i] = cell.length;
1143
- }
1144
- }
1145
- return widths;
1146
- },
1147
- statLines[0].map(() => 0)
1148
- );
1149
- const table = statLines.map(
1150
- (row) => row.map((cell, i) => {
1151
- if (i === 0) {
1152
- return cell.padEnd(columnWidths[i], " ");
1153
- } else {
1154
- return cell.padStart(columnWidths[i], " ");
1155
- }
1156
- }).join(" ")
1157
- ).join("\n");
1158
- return table;
1159
- }
1160
- async function getClosestNamedPackage(file) {
1161
- let name = "$unknown";
1162
- let path9 = await (0, import_vitefu2.findClosestPkgJsonPath)(file, (pkgPath) => {
1163
- const pkg = JSON.parse((0, import_fs3.readFileSync)(pkgPath, "utf-8"));
1164
- if (pkg.name != null) {
1165
- name = pkg.name;
1166
- return true;
1167
- }
1168
- return false;
1169
- });
1170
- path9 = (0, import_vite3.normalizePath)((0, import_path4.dirname)(path9 ?? file)) + "/";
1171
- return { name, path: path9 };
1172
- }
1173
- var VitePluginSvelteStats = class {
1174
- constructor() {
1175
- this._packages = [];
1176
- this._collections = [];
1177
- }
1178
- startCollection(name, opts) {
1179
- const options = {
1180
- ...defaultCollectionOptions,
1181
- ...opts
1182
- };
1183
- const stats = [];
1184
- const collectionStart = import_perf_hooks.performance.now();
1185
- const _this = this;
1186
- let hasLoggedProgress = false;
1187
- const collection = {
1188
- name,
1189
- options,
1190
- stats,
1191
- collectionStart,
1192
- finished: false,
1193
- start(file) {
1194
- if (collection.finished) {
1195
- throw new Error("called after finish() has been used");
1196
- }
1197
- file = (0, import_vite3.normalizePath)(file);
1198
- const start = import_perf_hooks.performance.now();
1199
- const stat = { file, start, end: start };
1200
- return () => {
1201
- const now = import_perf_hooks.performance.now();
1202
- stat.end = now;
1203
- stats.push(stat);
1204
- if (!hasLoggedProgress && options.logInProgress(collection, now)) {
1205
- hasLoggedProgress = true;
1206
- log.info(`${name} in progress ...`);
1207
- }
1208
- };
1209
- },
1210
- async finish() {
1211
- await _this._finish(collection);
1212
- }
1213
- };
1214
- _this._collections.push(collection);
1215
- return collection;
1216
- }
1217
- async finishAll() {
1218
- await Promise.all(this._collections.map((c) => c.finish()));
1219
- }
1220
- async _finish(collection) {
1221
- try {
1222
- collection.finished = true;
1223
- const now = import_perf_hooks.performance.now();
1224
- collection.duration = now - collection.collectionStart;
1225
- const logResult = collection.options.logResult(collection);
1226
- if (logResult) {
1227
- await this._aggregateStatsResult(collection);
1228
- log.info(`${collection.name} done.`, formatPackageStats(collection.packageStats));
1229
- }
1230
- const index = this._collections.indexOf(collection);
1231
- this._collections.splice(index, 1);
1232
- collection.stats.length = 0;
1233
- collection.stats = [];
1234
- if (collection.packageStats) {
1235
- collection.packageStats.length = 0;
1236
- collection.packageStats = [];
1237
- }
1238
- collection.start = () => () => {
1239
- };
1240
- collection.finish = () => {
1241
- };
1242
- } catch (e) {
1243
- log.debug.once(`failed to finish stats for ${collection.name}`, e);
1244
- }
1245
- }
1246
- async _aggregateStatsResult(collection) {
1247
- const stats = collection.stats;
1248
- for (const stat of stats) {
1249
- let pkg = this._packages.find((p) => stat.file.startsWith(p.path));
1250
- if (!pkg) {
1251
- pkg = await getClosestNamedPackage(stat.file);
1252
- this._packages.push(pkg);
1253
- }
1254
- stat.pkg = pkg.name;
1255
- }
1256
- const grouped = {};
1257
- stats.forEach((stat) => {
1258
- const pkg = stat.pkg;
1259
- let group = grouped[pkg];
1260
- if (!group) {
1261
- group = grouped[pkg] = {
1262
- files: 0,
1263
- duration: 0,
1264
- pkg
1265
- };
1266
- }
1267
- group.files += 1;
1268
- group.duration += stat.end - stat.start;
1269
- });
1270
- const groups = Object.values(grouped);
1271
- groups.sort((a, b) => b.duration - a.duration);
1272
- collection.packageStats = groups;
1273
- }
1274
- };
1275
-
1276
- // src/utils/options.ts
1277
- var cssAsString = atLeastSvelte("3.53.0");
1278
- var allowedPluginOptions = /* @__PURE__ */ new Set([
1279
- "include",
1280
- "exclude",
1281
- "emitCss",
1282
- "hot",
1283
- "ignorePluginPreprocessors",
1284
- "disableDependencyReinclusion",
1285
- "prebundleSvelteLibraries",
1286
- "experimental"
1287
- ]);
1288
- var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions", "preprocess", "onwarn"]);
1289
- var allowedInlineOptions = /* @__PURE__ */ new Set([
1290
- "configFile",
1291
- "kit",
1292
- ...allowedPluginOptions,
1293
- ...knownRootOptions
1294
- ]);
1295
- function validateInlineOptions(inlineOptions) {
1296
- const invalidKeys = Object.keys(inlineOptions || {}).filter(
1297
- (key) => !allowedInlineOptions.has(key)
1298
- );
1299
- if (invalidKeys.length) {
1300
- log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in inline config`, inlineOptions);
1301
- }
1302
- }
1303
- function convertPluginOptions(config) {
1304
- if (!config) {
1305
- return;
1306
- }
1307
- const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
1308
- if (invalidRootOptions.length > 0) {
1309
- throw new Error(
1310
- `Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(
1311
- ", "
1312
- )}`
1313
- );
1314
- }
1315
- if (!config.vitePlugin) {
1316
- return config;
1317
- }
1318
- const pluginOptions = config.vitePlugin;
1319
- const pluginOptionKeys = Object.keys(pluginOptions);
1320
- const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
1321
- if (rootOptionsInPluginOptions.length > 0) {
1322
- throw new Error(
1323
- `Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(
1324
- ", "
1325
- )}`
1326
- );
1327
- }
1328
- const duplicateOptions = pluginOptionKeys.filter(
1329
- (key) => Object.prototype.hasOwnProperty.call(config, key)
1330
- );
1331
- if (duplicateOptions.length > 0) {
1332
- throw new Error(
1333
- `Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(
1334
- ", "
1335
- )}`
1336
- );
1337
- }
1338
- const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
1339
- if (unknownPluginOptions.length > 0) {
1340
- log.warn(
1341
- `ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(
1342
- ", "
1343
- )}`
1344
- );
1345
- unknownPluginOptions.forEach((unkownOption) => {
1346
- delete pluginOptions[unkownOption];
1347
- });
1348
- }
1349
- const result = {
1350
- ...config,
1351
- ...pluginOptions
1352
- };
1353
- delete result.vitePlugin;
1354
- return result;
1355
- }
1356
- async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1357
- const viteConfigWithResolvedRoot = {
1358
- ...viteUserConfig,
1359
- root: resolveViteRoot(viteUserConfig)
1360
- };
1361
- const isBuild = viteEnv.command === "build";
1362
- const defaultOptions = {
1363
- extensions: [".svelte"],
1364
- emitCss: true,
1365
- prebundleSvelteLibraries: !isBuild
1366
- };
1367
- const svelteConfig = convertPluginOptions(
1368
- await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
1369
- );
1370
- const extraOptions = {
1371
- root: viteConfigWithResolvedRoot.root,
1372
- isBuild,
1373
- isServe: viteEnv.command === "serve",
1374
- isDebug: process.env.DEBUG != null
1375
- };
1376
- const merged = mergeConfigs(
1377
- defaultOptions,
1378
- svelteConfig,
1379
- inlineOptions,
1380
- extraOptions
1381
- );
1382
- if (svelteConfig?.configFile) {
1383
- merged.configFile = svelteConfig.configFile;
1384
- }
1385
- return merged;
1386
- }
1387
- function mergeConfigs(...configs) {
1388
- let result = {};
1389
- for (const config of configs.filter((x) => x != null)) {
1390
- result = (0, import_deepmerge.default)(result, config, {
1391
- arrayMerge: (target, source) => source ?? target
1392
- });
1393
- }
1394
- return result;
1395
- }
1396
- function resolveOptions(preResolveOptions2, viteConfig) {
1397
- const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1398
- const defaultOptions = {
1399
- hot: viteConfig.isProduction ? false : {
1400
- injectCss: css === true || css === "injected",
1401
- partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1402
- },
1403
- compilerOptions: {
1404
- css,
1405
- dev: !viteConfig.isProduction
1406
- }
1407
- };
1408
- const extraOptions = {
1409
- root: viteConfig.root,
1410
- isProduction: viteConfig.isProduction
1411
- };
1412
- const merged = mergeConfigs(defaultOptions, preResolveOptions2, extraOptions);
1413
- removeIgnoredOptions(merged);
1414
- handleDeprecatedOptions(merged);
1415
- addSvelteKitOptions(merged);
1416
- addExtraPreprocessors(merged, viteConfig);
1417
- enforceOptionsForHmr(merged);
1418
- enforceOptionsForProduction(merged);
1419
- const isLogLevelInfo = [void 0, "info"].includes(viteConfig.logLevel);
1420
- const disableCompileStats = merged.experimental?.disableCompileStats;
1421
- const statsEnabled = disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? "build" : "dev");
1422
- if (statsEnabled && isLogLevelInfo) {
1423
- merged.stats = new VitePluginSvelteStats();
1424
- }
1425
- return merged;
1426
- }
1427
- function enforceOptionsForHmr(options) {
1428
- if (options.hot) {
1429
- if (!options.compilerOptions.dev) {
1430
- log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
1431
- options.compilerOptions.dev = true;
1432
- }
1433
- if (options.emitCss) {
1434
- if (options.hot !== true && options.hot.injectCss) {
1435
- log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1436
- options.hot.injectCss = false;
1437
- }
1438
- const css = options.compilerOptions.css;
1439
- if (css === true || css === "injected") {
1440
- const forcedCss = cssAsString ? "external" : false;
1441
- log.warn(
1442
- `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
1443
- );
1444
- options.compilerOptions.css = forcedCss;
1445
- }
1446
- } else {
1447
- if (options.hot === true || !options.hot.injectCss) {
1448
- log.warn(
1449
- "hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true"
1450
- );
1451
- if (options.hot === true) {
1452
- options.hot = { injectCss: true };
1453
- } else {
1454
- options.hot.injectCss = true;
1455
- }
1456
- }
1457
- const css = options.compilerOptions.css;
1458
- if (!(css === true || css === "injected")) {
1459
- const forcedCss = cssAsString ? "injected" : true;
1460
- log.warn(
1461
- `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
1462
- );
1463
- options.compilerOptions.css = forcedCss;
1464
- }
1465
- }
1466
- }
1467
- }
1468
- function enforceOptionsForProduction(options) {
1469
- if (options.isProduction) {
1470
- if (options.hot) {
1471
- log.warn("options.hot is enabled but does not work on production build, forcing it to false");
1472
- options.hot = false;
1473
- }
1474
- if (options.compilerOptions.dev) {
1475
- log.warn(
1476
- "you are building for production but compilerOptions.dev is true, forcing it to false"
1477
- );
1478
- options.compilerOptions.dev = false;
1479
- }
1480
- }
1481
- }
1482
- function removeIgnoredOptions(options) {
1483
- const ignoredCompilerOptions = ["generate", "format", "filename"];
1484
- if (options.hot && options.emitCss) {
1485
- ignoredCompilerOptions.push("cssHash");
1486
- }
1487
- const passedCompilerOptions = Object.keys(options.compilerOptions || {});
1488
- const passedIgnored = passedCompilerOptions.filter((o) => ignoredCompilerOptions.includes(o));
1489
- if (passedIgnored.length) {
1490
- log.warn(
1491
- `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(
1492
- ", "
1493
- )}`
1494
- );
1495
- passedIgnored.forEach((ignored) => {
1496
- delete options.compilerOptions[ignored];
1497
- });
1498
- }
1499
- }
1500
- function addSvelteKitOptions(options) {
1501
- if (options?.kit != null && options.compilerOptions.hydratable == null) {
1502
- log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
1503
- options.compilerOptions.hydratable = true;
1504
- }
1505
- }
1506
- function handleDeprecatedOptions(options) {
1507
- if (options.experimental?.prebundleSvelteLibraries) {
1508
- options.prebundleSvelteLibraries = options.experimental?.prebundleSvelteLibraries;
1509
- log.warn(
1510
- "experimental.prebundleSvelteLibraries is no longer experimental and has moved to prebundleSvelteLibraries"
1511
- );
1512
- }
1513
- }
1514
- function resolveViteRoot(viteConfig) {
1515
- return (0, import_vite4.normalizePath)(viteConfig.root ? import_path5.default.resolve(viteConfig.root) : process.cwd());
1516
- }
1517
- async function buildExtraViteConfig(options, config) {
1518
- const extraViteConfig = {
1519
- resolve: {
1520
- mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1521
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1522
- conditions: [...SVELTE_EXPORT_CONDITIONS]
1523
- }
1524
- };
1525
- const extraSvelteConfig = buildExtraConfigForSvelte(config);
1526
- const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
1527
- extraViteConfig.optimizeDeps = {
1528
- include: [
1529
- ...extraSvelteConfig.optimizeDeps.include,
1530
- ...extraDepsConfig.optimizeDeps.include.filter(
1531
- (dep) => !(0, import_vitefu3.isDepExcluded)(dep, extraSvelteConfig.optimizeDeps.exclude)
1532
- )
1533
- ],
1534
- exclude: [
1535
- ...extraSvelteConfig.optimizeDeps.exclude,
1536
- ...extraDepsConfig.optimizeDeps.exclude.filter(
1537
- (dep) => !(0, import_vitefu3.isDepIncluded)(dep, extraSvelteConfig.optimizeDeps.include)
1538
- )
1539
- ]
1540
- };
1541
- extraViteConfig.ssr = {
1542
- external: [
1543
- ...extraSvelteConfig.ssr.external,
1544
- ...extraDepsConfig.ssr.external.filter(
1545
- (dep) => !(0, import_vitefu3.isDepNoExternaled)(dep, extraSvelteConfig.ssr.noExternal)
1546
- )
1547
- ],
1548
- noExternal: [
1549
- ...extraSvelteConfig.ssr.noExternal,
1550
- ...extraDepsConfig.ssr.noExternal.filter(
1551
- (dep) => !(0, import_vitefu3.isDepExternaled)(dep, extraSvelteConfig.ssr.external)
1552
- )
1553
- ]
1554
- };
1555
- if (options.prebundleSvelteLibraries) {
1556
- extraViteConfig.optimizeDeps = {
1557
- ...extraViteConfig.optimizeDeps,
1558
- extensions: options.extensions ?? [".svelte"],
1559
- esbuildOptions: {
1560
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1561
- } }]
1562
- }
1563
- };
1564
- }
1565
- if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1566
- log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1567
- extraViteConfig.experimental = { hmrPartialAccept: true };
1568
- }
1569
- validateViteConfig(extraViteConfig, config, options);
1570
- return extraViteConfig;
1571
- }
1572
- function validateViteConfig(extraViteConfig, config, options) {
1573
- const { prebundleSvelteLibraries, isBuild } = options;
1574
- if (prebundleSvelteLibraries) {
1575
- const isEnabled = (option) => option !== true && option !== (isBuild ? "build" : "dev");
1576
- const logWarning = (name, value, recommendation) => log.warn.once(
1577
- `Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
1578
- value
1579
- )}\` ${isBuild ? "during build." : "."} ${recommendation}`
1580
- );
1581
- const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? "build";
1582
- const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
1583
- if (!isBuild && !isOptimizeDepsEnabled) {
1584
- logWarning(
1585
- "optimizeDeps.disabled",
1586
- viteOptimizeDepsDisabled,
1587
- 'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
1588
- );
1589
- extraViteConfig.optimizeDeps.disabled = "build";
1590
- } else if (isBuild && isOptimizeDepsEnabled) {
1591
- logWarning(
1592
- "optimizeDeps.disabled",
1593
- viteOptimizeDepsDisabled,
1594
- "Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors."
1595
- );
1596
- }
1597
- }
1598
- }
1599
- async function buildExtraConfigForDependencies(options, config) {
1600
- const depsConfig = await (0, import_vitefu3.crawlFrameworkPkgs)({
1601
- root: options.root,
1602
- isBuild: options.isBuild,
1603
- viteUserConfig: config,
1604
- isFrameworkPkgByJson(pkgJson) {
1605
- let hasSvelteCondition = false;
1606
- if (typeof pkgJson.exports === "object") {
1607
- JSON.stringify(pkgJson.exports, (key, value) => {
1608
- if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
1609
- hasSvelteCondition = true;
1610
- }
1611
- return value;
1612
- });
1613
- }
1614
- return hasSvelteCondition || !!pkgJson.svelte;
1615
- },
1616
- isSemiFrameworkPkgByJson(pkgJson) {
1617
- return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
1618
- },
1619
- isFrameworkPkgByName(pkgName) {
1620
- const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
1621
- if (isNotSveltePackage) {
1622
- return false;
1623
- } else {
1624
- return void 0;
1625
- }
1626
- }
1627
- });
1628
- log.debug("extra config for dependencies generated by vitefu", depsConfig);
1629
- if (options.prebundleSvelteLibraries) {
1630
- depsConfig.optimizeDeps.exclude = [];
1631
- const userExclude = config.optimizeDeps?.exclude;
1632
- depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1633
- return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => (0, import_vitefu3.isDepExcluded)(d.trim(), userExclude));
1634
- });
1635
- }
1636
- if (options.disableDependencyReinclusion === true) {
1637
- depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
1638
- (dep) => !dep.includes(">")
1639
- );
1640
- } else if (Array.isArray(options.disableDependencyReinclusion)) {
1641
- const disabledDeps = options.disableDependencyReinclusion;
1642
- depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
1643
- if (!dep.includes(">"))
1644
- return true;
1645
- const trimDep = dep.replace(/\s+/g, "");
1646
- return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
1647
- });
1648
- }
1649
- log.debug("post-processed extra config for dependencies", depsConfig);
1650
- return depsConfig;
1651
- }
1652
- function buildExtraConfigForSvelte(config) {
1653
- const include = [];
1654
- const exclude = ["svelte-hmr"];
1655
- if (!(0, import_vitefu3.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1656
- const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1657
- log.debug(
1658
- `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1659
- );
1660
- include.push(...svelteImportsToInclude);
1661
- } else {
1662
- log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1663
- }
1664
- const noExternal = [];
1665
- const external = [];
1666
- if (!(0, import_vitefu3.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1667
- noExternal.push("svelte", /^svelte\//);
1668
- }
1669
- return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1670
- }
1671
- function patchResolvedViteConfig(viteConfig, options) {
1672
- const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
1673
- (plugin) => plugin.name === facadeEsbuildSveltePluginName
1674
- );
1675
- if (facadeEsbuildSveltePlugin) {
1676
- Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1677
- }
1678
- }
1679
-
1680
- // src/utils/watch.ts
1681
- var import_fs4 = __toESM(require("fs"), 1);
1682
- var import_path6 = __toESM(require("path"), 1);
1683
- function setupWatchers(options, cache, requestParser) {
1684
- const { server, configFile: svelteConfigFile } = options;
1685
- if (!server) {
1686
- return;
1687
- }
1688
- const { watcher, ws } = server;
1689
- const { root, server: serverConfig } = server.config;
1690
- const emitChangeEventOnDependants = (filename) => {
1691
- const dependants = cache.getDependants(filename);
1692
- dependants.forEach((dependant) => {
1693
- if (import_fs4.default.existsSync(dependant)) {
1694
- log.debug(
1695
- `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1696
- );
1697
- watcher.emit("change", dependant);
1698
- }
1699
- });
1700
- };
1701
- const removeUnlinkedFromCache = (filename) => {
1702
- const svelteRequest = requestParser(filename, false);
1703
- if (svelteRequest) {
1704
- const removedFromCache = cache.remove(svelteRequest);
1705
- if (removedFromCache) {
1706
- log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
1707
- }
1708
- }
1709
- };
1710
- const triggerViteRestart = (filename) => {
1711
- if (serverConfig.middlewareMode) {
1712
- const message = "Svelte config change detected, restart your dev process to apply the changes.";
1713
- log.info(message, filename);
1714
- ws.send({
1715
- type: "error",
1716
- err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1717
- });
1718
- } else {
1719
- log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1720
- server.restart();
1721
- }
1722
- };
1723
- const listenerCollection = {
1724
- add: [],
1725
- change: [emitChangeEventOnDependants],
1726
- unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
1727
- };
1728
- if (svelteConfigFile !== false) {
1729
- const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path6.default.join(root, cfg));
1730
- const restartOnConfigAdd = (filename) => {
1731
- if (possibleSvelteConfigs.includes(filename)) {
1732
- triggerViteRestart(filename);
1733
- }
1734
- };
1735
- const restartOnConfigChange = (filename) => {
1736
- if (filename === svelteConfigFile) {
1737
- triggerViteRestart(filename);
1738
- }
1739
- };
1740
- if (svelteConfigFile) {
1741
- listenerCollection.change.push(restartOnConfigChange);
1742
- listenerCollection.unlink.push(restartOnConfigChange);
1743
- } else {
1744
- listenerCollection.add.push(restartOnConfigAdd);
1745
- }
1746
- }
1747
- Object.entries(listenerCollection).forEach(([evt, listeners]) => {
1748
- if (listeners.length > 0) {
1749
- watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
1750
- }
1751
- });
1752
- }
1753
- function ensureWatchedFile(watcher, file, root) {
1754
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs4.default.existsSync(file)) {
1755
- watcher.add(import_path6.default.resolve(file));
1756
- }
1757
- }
1758
-
1759
- // src/utils/resolve.ts
1760
- var import_path7 = __toESM(require("path"), 1);
1761
- var import_module2 = require("module");
1762
- async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1763
- if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
1764
- const cached = cache.getResolvedSvelteField(importee, importer);
1765
- if (cached) {
1766
- return cached;
1767
- }
1768
- const pkgData = await resolveDependencyData(importee, importer);
1769
- if (pkgData) {
1770
- const { pkg, dir } = pkgData;
1771
- if (pkg.svelte) {
1772
- const result = import_path7.default.resolve(dir, pkg.svelte);
1773
- cache.setResolvedSvelteField(importee, importer, result);
1774
- return result;
1775
- }
1776
- }
1777
- }
1778
- }
1779
- function isNodeInternal(importee) {
1780
- return importee.startsWith("node:") || import_module2.builtinModules.includes(importee);
1781
- }
1782
- function isBareImport(importee) {
1783
- if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path7.default.isAbsolute(importee)) {
1784
- return false;
1785
- }
1786
- const parts = importee.split("/");
1787
- switch (parts.length) {
1788
- case 1:
1789
- return true;
1790
- case 2:
1791
- return parts[0].startsWith("@");
1792
- default:
1793
- return false;
1794
- }
1795
- }
1796
-
1797
- // src/utils/optimizer.ts
1798
- var import_fs5 = require("fs");
1799
- var import_path8 = __toESM(require("path"), 1);
1800
- var PREBUNDLE_SENSITIVE_OPTIONS = [
1801
- "compilerOptions",
1802
- "configFile",
1803
- "experimental",
1804
- "extensions",
1805
- "ignorePluginPreprocessors",
1806
- "preprocess"
1807
- ];
1808
- async function saveSvelteMetadata(cacheDir, options) {
1809
- const svelteMetadata = generateSvelteMetadata(options);
1810
- const svelteMetadataPath = import_path8.default.resolve(cacheDir, "_svelte_metadata.json");
1811
- const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => {
1812
- return typeof value === "function" ? value.toString() : value;
1813
- });
1814
- let existingSvelteMetadata;
1815
- try {
1816
- existingSvelteMetadata = await import_fs5.promises.readFile(svelteMetadataPath, "utf8");
1817
- } catch {
1818
- }
1819
- await import_fs5.promises.mkdir(cacheDir, { recursive: true });
1820
- await import_fs5.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1821
- return currentSvelteMetadata !== existingSvelteMetadata;
1822
- }
1823
- function generateSvelteMetadata(options) {
1824
- const metadata = {};
1825
- for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1826
- metadata[key] = options[key];
1827
- }
1828
- return metadata;
1829
- }
1830
-
1831
- // src/ui/inspector/plugin.ts
1832
- var import_vite5 = require("vite");
1833
- var import_path9 = __toESM(require("path"), 1);
1834
- var import_url2 = require("url");
1835
- var import_fs6 = __toESM(require("fs"), 1);
1836
-
1837
- // src/ui/inspector/utils.ts
1838
- var FS_PREFIX = `/@fs/`;
1839
- var IS_WINDOWS2 = process.platform === "win32";
1840
- var queryRE = /\?.*$/s;
1841
- var hashRE = /#.*$/s;
1842
- function idToFile(id) {
1843
- if (id.startsWith(FS_PREFIX)) {
1844
- id = id = id.slice(IS_WINDOWS2 ? FS_PREFIX.length : FS_PREFIX.length - 1);
1845
- }
1846
- return id.replace(hashRE, "").replace(queryRE, "");
1847
- }
1848
-
1849
- // src/ui/inspector/plugin.ts
1850
- var defaultInspectorOptions = {
1851
- toggleKeyCombo: process.platform === "win32" ? "control-shift" : "meta-shift",
1852
- navKeys: { parent: "ArrowUp", child: "ArrowDown", next: "ArrowRight", prev: "ArrowLeft" },
1853
- openKey: "Enter",
1854
- holdMode: false,
1855
- showToggleButton: "active",
1856
- toggleButtonPos: "top-right",
1857
- customStyles: true
1858
- };
1859
- function getInspectorPath() {
1860
- const pluginPath = (0, import_vite5.normalizePath)(import_path9.default.dirname((0, import_url2.fileURLToPath)(importMetaUrl)));
1861
- return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, "/vite-plugin-svelte/src/ui/inspector/");
1862
- }
1863
- function svelteInspector() {
1864
- const inspectorPath = getInspectorPath();
1865
- log.debug.enabled && log.debug(`svelte inspector path: ${inspectorPath}`);
1866
- let inspectorOptions;
1867
- let appendTo;
1868
- let disabled = false;
1869
- return {
1870
- name: "vite-plugin-svelte:inspector",
1871
- apply: "serve",
1872
- enforce: "pre",
1873
- configResolved(config) {
1874
- const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte");
1875
- if (vps?.api?.options?.experimental?.inspector) {
1876
- inspectorOptions = {
1877
- ...defaultInspectorOptions,
1878
- ...vps.api.options.experimental.inspector
1879
- };
1880
- }
1881
- if (!vps || !inspectorOptions) {
1882
- log.debug("inspector disabled, could not find config");
1883
- disabled = true;
1884
- } else {
1885
- if (vps.api.options.kit && !inspectorOptions.appendTo) {
1886
- const out_dir = import_path9.default.basename(vps.api.options.kit.outDir || ".svelte-kit");
1887
- inspectorOptions.appendTo = `${out_dir}/generated/root.svelte`;
1888
- }
1889
- appendTo = inspectorOptions.appendTo;
1890
- }
1891
- },
1892
- async resolveId(importee, importer, options) {
1893
- if (options?.ssr || disabled) {
1894
- return;
1895
- }
1896
- if (importee.startsWith("virtual:svelte-inspector-options")) {
1897
- return importee;
1898
- } else if (importee.startsWith("virtual:svelte-inspector-path:")) {
1899
- const resolved = importee.replace("virtual:svelte-inspector-path:", inspectorPath);
1900
- log.debug.enabled && log.debug(`resolved ${importee} with ${resolved}`);
1901
- return resolved;
1902
- }
1903
- },
1904
- async load(id, options) {
1905
- if (options?.ssr || disabled) {
1906
- return;
1907
- }
1908
- if (id === "virtual:svelte-inspector-options") {
1909
- return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1910
- } else if (id.startsWith(inspectorPath)) {
1911
- const file = idToFile(id);
1912
- if (import_fs6.default.existsSync(file)) {
1913
- return await import_fs6.default.promises.readFile(file, "utf-8");
1914
- } else {
1915
- log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1916
- }
1917
- }
1918
- },
1919
- transform(code, id, options) {
1920
- if (options?.ssr || disabled || !appendTo) {
1921
- return;
1922
- }
1923
- if (id.endsWith(appendTo)) {
1924
- return { code: `${code}
1925
- import 'virtual:svelte-inspector-path:load-inspector.js'` };
1926
- }
1927
- },
1928
- transformIndexHtml(html) {
1929
- if (disabled || appendTo) {
1930
- return;
1931
- }
1932
- return {
1933
- html,
1934
- tags: [
1935
- {
1936
- tag: "script",
1937
- injectTo: "body",
1938
- attrs: {
1939
- type: "module",
1940
- src: "/@id/virtual:svelte-inspector-path:load-inspector.js"
1941
- }
1942
- }
1943
- ]
1944
- };
1945
- }
1946
- };
1947
- }
1948
-
1949
- // src/utils/vite-plugin-svelte-cache.ts
1950
- var VitePluginSvelteCache = class {
1951
- constructor() {
1952
- this._css = /* @__PURE__ */ new Map();
1953
- this._js = /* @__PURE__ */ new Map();
1954
- this._dependencies = /* @__PURE__ */ new Map();
1955
- this._dependants = /* @__PURE__ */ new Map();
1956
- this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1957
- this._errors = /* @__PURE__ */ new Map();
1958
- }
1959
- update(compileData) {
1960
- this._errors.delete(compileData.normalizedFilename);
1961
- this.updateCSS(compileData);
1962
- this.updateJS(compileData);
1963
- this.updateDependencies(compileData);
1964
- }
1965
- has(svelteRequest) {
1966
- const id = svelteRequest.normalizedFilename;
1967
- return this._errors.has(id) || this._js.has(id) || this._css.has(id);
1968
- }
1969
- setError(svelteRequest, error) {
1970
- this.remove(svelteRequest, true);
1971
- this._errors.set(svelteRequest.normalizedFilename, error);
1972
- }
1973
- updateCSS(compileData) {
1974
- this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1975
- }
1976
- updateJS(compileData) {
1977
- if (!compileData.ssr) {
1978
- this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1979
- }
1980
- }
1981
- updateDependencies(compileData) {
1982
- const id = compileData.normalizedFilename;
1983
- const prevDependencies = this._dependencies.get(id) || [];
1984
- const dependencies = compileData.dependencies;
1985
- this._dependencies.set(id, dependencies);
1986
- const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1987
- const added = dependencies.filter((d) => !prevDependencies.includes(d));
1988
- added.forEach((d) => {
1989
- if (!this._dependants.has(d)) {
1990
- this._dependants.set(d, /* @__PURE__ */ new Set());
1991
- }
1992
- this._dependants.get(d).add(compileData.filename);
1993
- });
1994
- removed.forEach((d) => {
1995
- this._dependants.get(d).delete(compileData.filename);
1996
- });
1997
- }
1998
- remove(svelteRequest, keepDependencies = false) {
1999
- const id = svelteRequest.normalizedFilename;
2000
- let removed = false;
2001
- if (this._errors.delete(id)) {
2002
- removed = true;
2003
- }
2004
- if (this._js.delete(id)) {
2005
- removed = true;
2006
- }
2007
- if (this._css.delete(id)) {
2008
- removed = true;
2009
- }
2010
- if (!keepDependencies) {
2011
- const dependencies = this._dependencies.get(id);
2012
- if (dependencies) {
2013
- removed = true;
2014
- dependencies.forEach((d) => {
2015
- const dependants = this._dependants.get(d);
2016
- if (dependants && dependants.has(svelteRequest.filename)) {
2017
- dependants.delete(svelteRequest.filename);
2018
- }
2019
- });
2020
- this._dependencies.delete(id);
2021
- }
2022
- }
2023
- return removed;
2024
- }
2025
- getCSS(svelteRequest) {
2026
- return this._css.get(svelteRequest.normalizedFilename);
2027
- }
2028
- getJS(svelteRequest) {
2029
- if (!svelteRequest.ssr) {
2030
- return this._js.get(svelteRequest.normalizedFilename);
2031
- }
2032
- }
2033
- getError(svelteRequest) {
2034
- return this._errors.get(svelteRequest.normalizedFilename);
2035
- }
2036
- getDependants(path9) {
2037
- const dependants = this._dependants.get(path9);
2038
- return dependants ? [...dependants] : [];
2039
- }
2040
- getResolvedSvelteField(name, importer) {
2041
- return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
2042
- }
2043
- setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
2044
- this._resolvedSvelteFields.set(
2045
- this._getResolvedSvelteFieldKey(importee, importer),
2046
- resolvedSvelte
2047
- );
2048
- }
2049
- _getResolvedSvelteFieldKey(importee, importer) {
2050
- return importer ? `${importer} > ${importee}` : importee;
2051
- }
2052
- };
2053
-
2054
- // src/index.ts
2055
- function svelte(inlineOptions) {
2056
- if (process.env.DEBUG != null) {
2057
- log.setLevel("debug");
2058
- }
2059
- validateInlineOptions(inlineOptions);
2060
- const cache = new VitePluginSvelteCache();
2061
- let requestParser;
2062
- let options;
2063
- let viteConfig;
2064
- let compileSvelte2;
2065
- let resolvedSvelteSSR;
2066
- const api = {};
2067
- const plugins = [
2068
- {
2069
- name: "vite-plugin-svelte",
2070
- enforce: "pre",
2071
- api,
2072
- async config(config, configEnv) {
2073
- if (process.env.DEBUG) {
2074
- log.setLevel("debug");
2075
- } else if (config.logLevel) {
2076
- log.setLevel(config.logLevel);
2077
- }
2078
- options = await preResolveOptions(inlineOptions, config, configEnv);
2079
- const extraViteConfig = await buildExtraViteConfig(options, config);
2080
- log.debug("additional vite config", extraViteConfig);
2081
- return extraViteConfig;
2082
- },
2083
- async configResolved(config) {
2084
- options = resolveOptions(options, config);
2085
- patchResolvedViteConfig(config, options);
2086
- requestParser = buildIdParser(options);
2087
- compileSvelte2 = createCompileSvelte(options);
2088
- viteConfig = config;
2089
- api.options = options;
2090
- log.debug("resolved options", options);
2091
- },
2092
- async buildStart() {
2093
- if (!options.prebundleSvelteLibraries)
2094
- return;
2095
- const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options);
2096
- if (isSvelteMetadataChanged) {
2097
- viteConfig.optimizeDeps.force = true;
2098
- }
2099
- },
2100
- configureServer(server) {
2101
- options.server = server;
2102
- setupWatchers(options, cache, requestParser);
2103
- },
2104
- load(id, opts) {
2105
- const ssr = !!opts?.ssr;
2106
- const svelteRequest = requestParser(id, !!ssr);
2107
- if (svelteRequest) {
2108
- const { filename, query } = svelteRequest;
2109
- if (query.svelte && query.type === "style") {
2110
- const css = cache.getCSS(svelteRequest);
2111
- if (css) {
2112
- log.debug(`load returns css for ${filename}`);
2113
- return css;
2114
- }
2115
- }
2116
- if (viteConfig.assetsInclude(filename)) {
2117
- log.debug(`load returns raw content for ${filename}`);
2118
- return import_fs7.default.readFileSync(filename, "utf-8");
2119
- }
2120
- }
2121
- },
2122
- async resolveId(importee, importer, opts) {
2123
- const ssr = !!opts?.ssr;
2124
- const svelteRequest = requestParser(importee, ssr);
2125
- if (svelteRequest?.query.svelte) {
2126
- if (svelteRequest.query.type === "style") {
2127
- log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
2128
- return svelteRequest.cssId;
2129
- }
2130
- log.debug(`resolveId resolved ${importee}`);
2131
- return importee;
2132
- }
2133
- if (ssr && importee === "svelte") {
2134
- if (!resolvedSvelteSSR) {
2135
- resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then(
2136
- (svelteSSR) => {
2137
- log.debug("resolved svelte to svelte/ssr");
2138
- return svelteSSR;
2139
- },
2140
- (err) => {
2141
- log.debug(
2142
- "failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it",
2143
- err
2144
- );
2145
- return null;
2146
- }
2147
- );
2148
- }
2149
- return resolvedSvelteSSR;
2150
- }
2151
- const scan = !!opts?.scan;
2152
- const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !(0, import_vitefu4.isDepExcluded)(importee, viteConfig.optimizeDeps?.exclude ?? []);
2153
- if (ssr || scan || !isPrebundled) {
2154
- try {
2155
- const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
2156
- if (resolved) {
2157
- log.debug(
2158
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2159
- );
2160
- return resolved;
2161
- }
2162
- } catch (e) {
2163
- log.debug.once(
2164
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
2165
- e
2166
- );
2167
- }
2168
- }
2169
- },
2170
- async transform(code, id, opts) {
2171
- const ssr = !!opts?.ssr;
2172
- const svelteRequest = requestParser(id, ssr);
2173
- if (!svelteRequest || svelteRequest.query.svelte) {
2174
- return;
2175
- }
2176
- let compileData;
2177
- try {
2178
- compileData = await compileSvelte2(svelteRequest, code, options);
2179
- } catch (e) {
2180
- cache.setError(svelteRequest, e);
2181
- throw toRollupError(e, options);
2182
- }
2183
- logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
2184
- cache.update(compileData);
2185
- if (compileData.dependencies?.length && options.server) {
2186
- compileData.dependencies.forEach((d) => {
2187
- ensureWatchedFile(options.server.watcher, d, options.root);
2188
- });
2189
- }
2190
- log.debug(`transform returns compiled js for ${svelteRequest.filename}`);
2191
- return {
2192
- ...compileData.compiled.js,
2193
- meta: {
2194
- vite: {
2195
- lang: compileData.lang
2196
- }
2197
- }
2198
- };
2199
- },
2200
- handleHotUpdate(ctx) {
2201
- if (!options.hot || !options.emitCss) {
2202
- return;
2203
- }
2204
- const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
2205
- if (svelteRequest) {
2206
- try {
2207
- return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
2208
- } catch (e) {
2209
- throw toRollupError(e, options);
2210
- }
2211
- }
2212
- },
2213
- async buildEnd() {
2214
- await options.stats?.finishAll();
2215
- }
2216
- }
2217
- ];
2218
- plugins.push(svelteInspector());
2219
- return plugins.filter(Boolean);
2220
- }
2221
- // Annotate the CommonJS export names for ESM import in node:
2222
- 0 && (module.exports = {
2223
- loadSvelteConfig,
2224
- svelte
2225
- });
2226
- //# sourceMappingURL=index.cjs.map