@sveltejs/vite-plugin-svelte 2.2.0 → 2.4.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/package.json +12 -17
- package/src/{handle-hot-update.ts → handle-hot-update.js} +35 -20
- package/src/index.d.ts +215 -0
- package/src/{index.ts → index.js} +50 -71
- package/src/{preprocess.ts → preprocess.js} +37 -28
- package/src/types/compile.d.ts +48 -0
- package/src/types/id.d.ts +31 -0
- package/src/types/log.d.ts +24 -0
- package/src/types/options.d.ts +20 -0
- package/src/types/plugin-api.d.ts +11 -0
- package/src/types/vite-plugin-svelte-stats.d.ts +30 -0
- package/src/utils/{compile.ts → compile.js} +32 -66
- package/src/utils/{dependencies.ts → dependencies.js} +14 -11
- package/src/utils/{error.ts → error.js} +21 -14
- package/src/utils/{esbuild.ts → esbuild.js} +23 -17
- package/src/utils/{hash.ts → hash.js} +14 -3
- package/src/utils/{id.ts → id.js} +59 -60
- package/src/utils/{load-raw.ts → load-raw.js} +16 -16
- package/src/utils/{load-svelte-config.ts → load-svelte-config.js} +12 -10
- package/src/utils/{log.ts → log.js} +81 -48
- package/src/utils/{optimizer.ts → optimizer.js} +15 -7
- package/src/utils/{options.ts → options.js} +146 -295
- package/src/utils/{preprocess.ts → preprocess.js} +28 -12
- package/src/utils/{resolve.ts → resolve.js} +18 -9
- package/src/utils/{sourcemaps.ts → sourcemaps.js} +22 -14
- package/src/utils/{svelte-version.ts → svelte-version.js} +15 -7
- package/src/utils/vite-plugin-svelte-cache.js +253 -0
- package/src/utils/{vite-plugin-svelte-stats.ts → vite-plugin-svelte-stats.js} +66 -62
- package/src/utils/{watch.ts → watch.js} +30 -22
- package/dist/index.d.ts +0 -259
- package/dist/index.js +0 -2428
- package/dist/index.js.map +0 -1
- package/src/__tests__/fixtures/preprocess/foo.scss +0 -3
- package/src/__tests__/preprocess.spec.ts +0 -51
- package/src/ui/inspector/Inspector.svelte +0 -384
- package/src/ui/inspector/load-inspector.js +0 -15
- package/src/ui/inspector/options.ts +0 -131
- package/src/ui/inspector/plugin.ts +0 -97
- package/src/ui/inspector/utils.ts +0 -13
- package/src/utils/__tests__/compile.spec.ts +0 -49
- package/src/utils/__tests__/sourcemaps.spec.ts +0 -79
- package/src/utils/__tests__/svelte-version.spec.ts +0 -102
- package/src/utils/vite-plugin-svelte-cache.ts +0 -182
- /package/src/utils/{constants.ts → constants.js} +0 -0
package/dist/index.js
DELETED
|
@@ -1,2428 +0,0 @@
|
|
|
1
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
-
}) : x)(function(x) {
|
|
4
|
-
if (typeof require !== "undefined")
|
|
5
|
-
return require.apply(this, arguments);
|
|
6
|
-
throw new Error('Dynamic require of "' + x + '" is not supported');
|
|
7
|
-
});
|
|
8
|
-
|
|
9
|
-
// src/index.ts
|
|
10
|
-
import fs8 from "fs";
|
|
11
|
-
import { VERSION as svelteVersion } from "svelte/compiler";
|
|
12
|
-
import {
|
|
13
|
-
version as viteVersion
|
|
14
|
-
} from "vite";
|
|
15
|
-
import { isDepExcluded as isDepExcluded2 } from "vitefu";
|
|
16
|
-
|
|
17
|
-
// src/utils/log.ts
|
|
18
|
-
import { cyan, yellow, red } from "kleur/colors";
|
|
19
|
-
import debug from "debug";
|
|
20
|
-
var levels = ["debug", "info", "warn", "error", "silent"];
|
|
21
|
-
var prefix = "vite-plugin-svelte";
|
|
22
|
-
var loggers = {
|
|
23
|
-
debug: {
|
|
24
|
-
log: debug(`vite:${prefix}`),
|
|
25
|
-
enabled: false,
|
|
26
|
-
isDebug: true
|
|
27
|
-
},
|
|
28
|
-
info: {
|
|
29
|
-
color: cyan,
|
|
30
|
-
log: console.log,
|
|
31
|
-
enabled: true
|
|
32
|
-
},
|
|
33
|
-
warn: {
|
|
34
|
-
color: yellow,
|
|
35
|
-
log: console.warn,
|
|
36
|
-
enabled: true
|
|
37
|
-
},
|
|
38
|
-
error: {
|
|
39
|
-
color: red,
|
|
40
|
-
log: console.error,
|
|
41
|
-
enabled: true
|
|
42
|
-
},
|
|
43
|
-
silent: {
|
|
44
|
-
enabled: false
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
var _level = "info";
|
|
48
|
-
function setLevel(level) {
|
|
49
|
-
if (level === _level) {
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
const levelIndex = levels.indexOf(level);
|
|
53
|
-
if (levelIndex > -1) {
|
|
54
|
-
_level = level;
|
|
55
|
-
for (let i = 0; i < levels.length; i++) {
|
|
56
|
-
loggers[levels[i]].enabled = i >= levelIndex;
|
|
57
|
-
}
|
|
58
|
-
} else {
|
|
59
|
-
_log(loggers.error, `invalid log level: ${level} `);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
function _log(logger, message, payload, namespace) {
|
|
63
|
-
if (!logger.enabled) {
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
if (logger.isDebug) {
|
|
67
|
-
const log2 = namespace ? logger.log.extend(namespace) : logger.log;
|
|
68
|
-
payload !== void 0 ? log2(message, payload) : log2(message);
|
|
69
|
-
} else {
|
|
70
|
-
logger.log(
|
|
71
|
-
logger.color(
|
|
72
|
-
`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} [${prefix}${namespace ? `:${namespace}` : ""}] ${message}`
|
|
73
|
-
)
|
|
74
|
-
);
|
|
75
|
-
if (payload) {
|
|
76
|
-
logger.log(payload);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
function createLogger(level) {
|
|
81
|
-
const logger = loggers[level];
|
|
82
|
-
const logFn = _log.bind(null, logger);
|
|
83
|
-
const logged = /* @__PURE__ */ new Set();
|
|
84
|
-
const once = function(message, payload, namespace) {
|
|
85
|
-
if (!logger.enabled || logged.has(message)) {
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
logged.add(message);
|
|
89
|
-
logFn.apply(null, [message, payload, namespace]);
|
|
90
|
-
};
|
|
91
|
-
Object.defineProperty(logFn, "enabled", {
|
|
92
|
-
get() {
|
|
93
|
-
return logger.enabled;
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
Object.defineProperty(logFn, "once", {
|
|
97
|
-
get() {
|
|
98
|
-
return once;
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
return logFn;
|
|
102
|
-
}
|
|
103
|
-
var log = {
|
|
104
|
-
debug: createLogger("debug"),
|
|
105
|
-
info: createLogger("info"),
|
|
106
|
-
warn: createLogger("warn"),
|
|
107
|
-
error: createLogger("error"),
|
|
108
|
-
setLevel
|
|
109
|
-
};
|
|
110
|
-
function logCompilerWarnings(svelteRequest, warnings, options) {
|
|
111
|
-
const { emitCss, onwarn, isBuild } = options;
|
|
112
|
-
const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser;
|
|
113
|
-
let warn = isBuild ? warnBuild : warnDev;
|
|
114
|
-
const handledByDefaultWarn = [];
|
|
115
|
-
const notIgnored = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
|
|
116
|
-
const extra = buildExtraWarnings(warnings, isBuild);
|
|
117
|
-
const allWarnings = [...notIgnored, ...extra];
|
|
118
|
-
if (sendViaWS) {
|
|
119
|
-
const _warn = warn;
|
|
120
|
-
warn = (w) => {
|
|
121
|
-
handledByDefaultWarn.push(w);
|
|
122
|
-
_warn(w);
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
allWarnings.forEach((warning) => {
|
|
126
|
-
if (onwarn) {
|
|
127
|
-
onwarn(warning, warn);
|
|
128
|
-
} else {
|
|
129
|
-
warn(warning);
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
if (sendViaWS) {
|
|
133
|
-
const message = {
|
|
134
|
-
id: svelteRequest.id,
|
|
135
|
-
filename: svelteRequest.filename,
|
|
136
|
-
normalizedFilename: svelteRequest.normalizedFilename,
|
|
137
|
-
timestamp: svelteRequest.timestamp,
|
|
138
|
-
warnings: handledByDefaultWarn,
|
|
139
|
-
// allWarnings filtered by warnings where onwarn did not call the default handler
|
|
140
|
-
allWarnings,
|
|
141
|
-
// includes warnings filtered by onwarn and our extra vite plugin svelte warnings
|
|
142
|
-
rawWarnings: warnings
|
|
143
|
-
// raw compiler output
|
|
144
|
-
};
|
|
145
|
-
log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`);
|
|
146
|
-
options.server?.ws?.send("svelte:warnings", message);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
function ignoreCompilerWarning(warning, isBuild, emitCss) {
|
|
150
|
-
return !emitCss && warning.code === "css-unused-selector" || // same as rollup-plugin-svelte
|
|
151
|
-
!isBuild && isNoScopableElementWarning(warning);
|
|
152
|
-
}
|
|
153
|
-
function isNoScopableElementWarning(warning) {
|
|
154
|
-
return warning.code === "css-unused-selector" && warning.message.includes('"*"');
|
|
155
|
-
}
|
|
156
|
-
function buildExtraWarnings(warnings, isBuild) {
|
|
157
|
-
const extraWarnings = [];
|
|
158
|
-
if (!isBuild) {
|
|
159
|
-
const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w));
|
|
160
|
-
if (noScopableElementWarnings.length > 0) {
|
|
161
|
-
const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1];
|
|
162
|
-
extraWarnings.push({
|
|
163
|
-
...noScopableElementWarning,
|
|
164
|
-
code: "vite-plugin-svelte-css-no-scopable-elements",
|
|
165
|
-
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.`
|
|
166
|
-
});
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return extraWarnings;
|
|
170
|
-
}
|
|
171
|
-
function warnDev(w) {
|
|
172
|
-
log.info.enabled && log.info(buildExtendedLogMessage(w));
|
|
173
|
-
}
|
|
174
|
-
function warnBuild(w) {
|
|
175
|
-
log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
|
|
176
|
-
}
|
|
177
|
-
function buildExtendedLogMessage(w) {
|
|
178
|
-
const parts = [];
|
|
179
|
-
if (w.filename) {
|
|
180
|
-
parts.push(w.filename);
|
|
181
|
-
}
|
|
182
|
-
if (w.start) {
|
|
183
|
-
parts.push(":", w.start.line, ":", w.start.column);
|
|
184
|
-
}
|
|
185
|
-
if (w.message) {
|
|
186
|
-
if (parts.length > 0) {
|
|
187
|
-
parts.push(" ");
|
|
188
|
-
}
|
|
189
|
-
parts.push(w.message);
|
|
190
|
-
}
|
|
191
|
-
return parts.join("");
|
|
192
|
-
}
|
|
193
|
-
function isDebugNamespaceEnabled(namespace) {
|
|
194
|
-
return debug.enabled(`vite:${prefix}:${namespace}`);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// src/utils/error.ts
|
|
198
|
-
function toRollupError(error, options) {
|
|
199
|
-
const { filename, frame, start, code, name, stack } = error;
|
|
200
|
-
const rollupError = {
|
|
201
|
-
name,
|
|
202
|
-
// needed otherwise sveltekit coalesce_to_error turns it into a string
|
|
203
|
-
id: filename,
|
|
204
|
-
message: buildExtendedLogMessage(error),
|
|
205
|
-
// include filename:line:column so that it's clickable
|
|
206
|
-
frame: formatFrameForVite(frame),
|
|
207
|
-
code,
|
|
208
|
-
stack: options.isBuild || options.isDebug || !frame ? stack : ""
|
|
209
|
-
};
|
|
210
|
-
if (start) {
|
|
211
|
-
rollupError.loc = {
|
|
212
|
-
line: start.line,
|
|
213
|
-
column: start.column,
|
|
214
|
-
file: filename
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
return rollupError;
|
|
218
|
-
}
|
|
219
|
-
function toESBuildError(error, options) {
|
|
220
|
-
const { filename, frame, start, stack } = error;
|
|
221
|
-
const partialMessage = {
|
|
222
|
-
text: buildExtendedLogMessage(error)
|
|
223
|
-
};
|
|
224
|
-
if (start) {
|
|
225
|
-
partialMessage.location = {
|
|
226
|
-
line: start.line,
|
|
227
|
-
column: start.column,
|
|
228
|
-
file: filename,
|
|
229
|
-
lineText: lineFromFrame(start.line, frame)
|
|
230
|
-
// needed to get a meaningful error message on cli
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
if (options.isBuild || options.isDebug || !frame) {
|
|
234
|
-
partialMessage.detail = stack;
|
|
235
|
-
}
|
|
236
|
-
return partialMessage;
|
|
237
|
-
}
|
|
238
|
-
function lineFromFrame(lineNo, frame) {
|
|
239
|
-
if (!frame) {
|
|
240
|
-
return "";
|
|
241
|
-
}
|
|
242
|
-
const lines = frame.split("\n");
|
|
243
|
-
const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
|
|
244
|
-
return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
|
|
245
|
-
}
|
|
246
|
-
function formatFrameForVite(frame) {
|
|
247
|
-
if (!frame) {
|
|
248
|
-
return "";
|
|
249
|
-
}
|
|
250
|
-
return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// src/handle-hot-update.ts
|
|
254
|
-
async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) {
|
|
255
|
-
if (!cache.has(svelteRequest)) {
|
|
256
|
-
log.debug(`handleHotUpdate called before initial transform for ${svelteRequest.id}`);
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
const { read, server, modules } = ctx;
|
|
260
|
-
const cachedJS = cache.getJS(svelteRequest);
|
|
261
|
-
const cachedCss = cache.getCSS(svelteRequest);
|
|
262
|
-
const content = await read();
|
|
263
|
-
let compileData;
|
|
264
|
-
try {
|
|
265
|
-
compileData = await compileSvelte2(svelteRequest, content, options);
|
|
266
|
-
cache.update(compileData);
|
|
267
|
-
} catch (e) {
|
|
268
|
-
cache.setError(svelteRequest, e);
|
|
269
|
-
throw toRollupError(e, options);
|
|
270
|
-
}
|
|
271
|
-
const affectedModules = [...modules];
|
|
272
|
-
const cssIdx = modules.findIndex((m) => m.id === svelteRequest.cssId);
|
|
273
|
-
if (cssIdx > -1) {
|
|
274
|
-
const cssUpdated = cssChanged(cachedCss, compileData.compiled.css);
|
|
275
|
-
if (!cssUpdated) {
|
|
276
|
-
log.debug(`skipping unchanged css for ${svelteRequest.cssId}`);
|
|
277
|
-
affectedModules.splice(cssIdx, 1);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
const jsIdx = modules.findIndex((m) => m.id === svelteRequest.id);
|
|
281
|
-
if (jsIdx > -1) {
|
|
282
|
-
const jsUpdated = jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
|
|
283
|
-
if (!jsUpdated) {
|
|
284
|
-
log.debug(`skipping unchanged js for ${svelteRequest.id}`);
|
|
285
|
-
affectedModules.splice(jsIdx, 1);
|
|
286
|
-
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
const ssrModulesToInvalidate = affectedModules.filter((m) => !!m.ssrTransformResult);
|
|
290
|
-
if (ssrModulesToInvalidate.length > 0) {
|
|
291
|
-
log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
|
|
292
|
-
ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
|
|
293
|
-
}
|
|
294
|
-
if (affectedModules.length > 0) {
|
|
295
|
-
log.debug(
|
|
296
|
-
`handleHotUpdate for ${svelteRequest.id} result: ${affectedModules.map((m) => m.id).join(", ")}`
|
|
297
|
-
);
|
|
298
|
-
}
|
|
299
|
-
return affectedModules;
|
|
300
|
-
}
|
|
301
|
-
function cssChanged(prev, next) {
|
|
302
|
-
return !isCodeEqual(prev?.code, next?.code);
|
|
303
|
-
}
|
|
304
|
-
function jsChanged(prev, next, filename) {
|
|
305
|
-
const prevJs = prev?.code;
|
|
306
|
-
const nextJs = next?.code;
|
|
307
|
-
const isStrictEqual = isCodeEqual(prevJs, nextJs);
|
|
308
|
-
if (isStrictEqual) {
|
|
309
|
-
return false;
|
|
310
|
-
}
|
|
311
|
-
const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
|
|
312
|
-
if (!isStrictEqual && isLooseEqual) {
|
|
313
|
-
log.warn(
|
|
314
|
-
`ignoring compiler output js change for ${filename} as it is equal to previous output after normalization`
|
|
315
|
-
);
|
|
316
|
-
}
|
|
317
|
-
return !isLooseEqual;
|
|
318
|
-
}
|
|
319
|
-
function isCodeEqual(prev, next) {
|
|
320
|
-
if (!prev && !next) {
|
|
321
|
-
return true;
|
|
322
|
-
}
|
|
323
|
-
if (!prev && next || prev && !next) {
|
|
324
|
-
return false;
|
|
325
|
-
}
|
|
326
|
-
return prev === next;
|
|
327
|
-
}
|
|
328
|
-
function normalizeJsCode(code) {
|
|
329
|
-
if (!code) {
|
|
330
|
-
return code;
|
|
331
|
-
}
|
|
332
|
-
return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, "");
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// src/utils/compile.ts
|
|
336
|
-
import { compile, preprocess, walk } from "svelte/compiler";
|
|
337
|
-
import { createMakeHot } from "svelte-hmr";
|
|
338
|
-
|
|
339
|
-
// src/utils/hash.ts
|
|
340
|
-
import * as crypto from "crypto";
|
|
341
|
-
var hashes = /* @__PURE__ */ Object.create(null);
|
|
342
|
-
var hash_length = 12;
|
|
343
|
-
function safeBase64Hash(input) {
|
|
344
|
-
if (hashes[input]) {
|
|
345
|
-
return hashes[input];
|
|
346
|
-
}
|
|
347
|
-
const md5 = crypto.createHash("md5");
|
|
348
|
-
md5.update(input);
|
|
349
|
-
const hash = toSafe(md5.digest("base64")).slice(0, hash_length);
|
|
350
|
-
hashes[input] = hash;
|
|
351
|
-
return hash;
|
|
352
|
-
}
|
|
353
|
-
var replacements = {
|
|
354
|
-
"+": "-",
|
|
355
|
-
"/": "_",
|
|
356
|
-
"=": ""
|
|
357
|
-
};
|
|
358
|
-
var replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
|
|
359
|
-
function toSafe(base64) {
|
|
360
|
-
return base64.replace(replaceRE, (x) => replacements[x]);
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// src/utils/preprocess.ts
|
|
364
|
-
import MagicString from "magic-string";
|
|
365
|
-
import path from "path";
|
|
366
|
-
function createInjectScopeEverythingRulePreprocessorGroup() {
|
|
367
|
-
return {
|
|
368
|
-
style({ content, filename }) {
|
|
369
|
-
const s = new MagicString(content);
|
|
370
|
-
s.append(" *{}");
|
|
371
|
-
return {
|
|
372
|
-
code: s.toString(),
|
|
373
|
-
map: s.generateDecodedMap({
|
|
374
|
-
source: filename ? path.basename(filename) : void 0,
|
|
375
|
-
hires: true
|
|
376
|
-
})
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
function buildExtraPreprocessors(options, config) {
|
|
382
|
-
const prependPreprocessors = [];
|
|
383
|
-
const appendPreprocessors = [];
|
|
384
|
-
const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p?.sveltePreprocess);
|
|
385
|
-
if (pluginsWithPreprocessorsDeprecated.length > 0) {
|
|
386
|
-
log.warn(
|
|
387
|
-
`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(", ")}`
|
|
388
|
-
);
|
|
389
|
-
pluginsWithPreprocessorsDeprecated.forEach((p) => {
|
|
390
|
-
if (!p.api) {
|
|
391
|
-
p.api = {};
|
|
392
|
-
}
|
|
393
|
-
if (p.api.sveltePreprocess === void 0) {
|
|
394
|
-
p.api.sveltePreprocess = p.sveltePreprocess;
|
|
395
|
-
} else {
|
|
396
|
-
log.error(
|
|
397
|
-
`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`
|
|
398
|
-
);
|
|
399
|
-
}
|
|
400
|
-
});
|
|
401
|
-
}
|
|
402
|
-
const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess);
|
|
403
|
-
const ignored = [], included = [];
|
|
404
|
-
for (const p of pluginsWithPreprocessors) {
|
|
405
|
-
if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && options.ignorePluginPreprocessors?.includes(p.name)) {
|
|
406
|
-
ignored.push(p);
|
|
407
|
-
} else {
|
|
408
|
-
included.push(p);
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
if (ignored.length > 0) {
|
|
412
|
-
log.debug(
|
|
413
|
-
`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`
|
|
414
|
-
);
|
|
415
|
-
}
|
|
416
|
-
if (included.length > 0) {
|
|
417
|
-
log.debug(
|
|
418
|
-
`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`
|
|
419
|
-
);
|
|
420
|
-
appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
|
|
421
|
-
}
|
|
422
|
-
return { prependPreprocessors, appendPreprocessors };
|
|
423
|
-
}
|
|
424
|
-
function addExtraPreprocessors(options, config) {
|
|
425
|
-
const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
|
|
426
|
-
if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
|
|
427
|
-
if (!options.preprocess) {
|
|
428
|
-
options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
|
|
429
|
-
} else if (Array.isArray(options.preprocess)) {
|
|
430
|
-
options.preprocess.unshift(...prependPreprocessors);
|
|
431
|
-
options.preprocess.push(...appendPreprocessors);
|
|
432
|
-
} else {
|
|
433
|
-
options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
// src/utils/sourcemaps.ts
|
|
439
|
-
import path2 from "path";
|
|
440
|
-
var IS_WINDOWS = process.platform === "win32";
|
|
441
|
-
function mapToRelative(map, filename) {
|
|
442
|
-
if (!map) {
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
const sourceRoot = map.sourceRoot;
|
|
446
|
-
const dirname2 = path2.dirname(filename);
|
|
447
|
-
const toRelative = (s) => {
|
|
448
|
-
if (!s) {
|
|
449
|
-
return s;
|
|
450
|
-
}
|
|
451
|
-
let sourcePath;
|
|
452
|
-
if (s.startsWith("file:///")) {
|
|
453
|
-
sourcePath = s.slice(IS_WINDOWS ? 8 : 7);
|
|
454
|
-
} else if (sourceRoot) {
|
|
455
|
-
const sep = sourceRoot[sourceRoot.length - 1] === "/" || s[0] === "/" ? "" : "/";
|
|
456
|
-
sourcePath = `${sourceRoot}${sep}${s}`;
|
|
457
|
-
} else {
|
|
458
|
-
sourcePath = s;
|
|
459
|
-
}
|
|
460
|
-
return path2.isAbsolute(sourcePath) ? path2.relative(dirname2, sourcePath) : sourcePath;
|
|
461
|
-
};
|
|
462
|
-
if (map.file) {
|
|
463
|
-
map.file = path2.basename(filename);
|
|
464
|
-
}
|
|
465
|
-
if (map.sources) {
|
|
466
|
-
map.sources = map.sources.map(toRelative);
|
|
467
|
-
}
|
|
468
|
-
if (map.sourceRoot) {
|
|
469
|
-
delete map.sourceRoot;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
function removeLangSuffix(map, suffix) {
|
|
473
|
-
if (!map) {
|
|
474
|
-
return;
|
|
475
|
-
}
|
|
476
|
-
const removeSuffix = (s) => s?.endsWith(suffix) ? s.slice(0, -1 * suffix.length) : s;
|
|
477
|
-
if (map.file) {
|
|
478
|
-
map.file = removeSuffix(map.file);
|
|
479
|
-
}
|
|
480
|
-
if (map.sources) {
|
|
481
|
-
map.sources = map.sources.map(removeSuffix);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// src/utils/compile.ts
|
|
486
|
-
var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
|
|
487
|
-
var _createCompileSvelte = (makeHot) => {
|
|
488
|
-
let stats;
|
|
489
|
-
const devStylePreprocessor = createInjectScopeEverythingRulePreprocessorGroup();
|
|
490
|
-
return async function compileSvelte2(svelteRequest, code, options) {
|
|
491
|
-
const { filename, normalizedFilename, cssId, ssr, raw } = svelteRequest;
|
|
492
|
-
const { emitCss = true } = options;
|
|
493
|
-
const dependencies = [];
|
|
494
|
-
if (options.stats) {
|
|
495
|
-
if (options.isBuild) {
|
|
496
|
-
if (!stats) {
|
|
497
|
-
stats = options.stats.startCollection(`${ssr ? "ssr" : "dom"} compile`, {
|
|
498
|
-
logInProgress: () => false
|
|
499
|
-
});
|
|
500
|
-
}
|
|
501
|
-
} else {
|
|
502
|
-
if (ssr && !stats) {
|
|
503
|
-
stats = options.stats.startCollection("ssr compile");
|
|
504
|
-
}
|
|
505
|
-
if (!ssr && stats) {
|
|
506
|
-
stats.finish();
|
|
507
|
-
stats = void 0;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
const compileOptions = {
|
|
512
|
-
...options.compilerOptions,
|
|
513
|
-
filename: normalizedFilename,
|
|
514
|
-
// use normalized here to avoid bleeding absolute fs path
|
|
515
|
-
generate: ssr ? "ssr" : "dom",
|
|
516
|
-
format: "esm"
|
|
517
|
-
};
|
|
518
|
-
if (options.hot && options.emitCss) {
|
|
519
|
-
const hash = `s-${safeBase64Hash(normalizedFilename)}`;
|
|
520
|
-
log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
|
|
521
|
-
compileOptions.cssHash = () => hash;
|
|
522
|
-
}
|
|
523
|
-
if (ssr && compileOptions.enableSourcemap !== false) {
|
|
524
|
-
if (typeof compileOptions.enableSourcemap === "object") {
|
|
525
|
-
compileOptions.enableSourcemap.css = false;
|
|
526
|
-
} else {
|
|
527
|
-
compileOptions.enableSourcemap = { js: true, css: false };
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
let preprocessed;
|
|
531
|
-
let preprocessors = options.preprocess;
|
|
532
|
-
if (!options.isBuild && options.emitCss && options.hot) {
|
|
533
|
-
if (!Array.isArray(preprocessors)) {
|
|
534
|
-
preprocessors = preprocessors ? [preprocessors, devStylePreprocessor] : [devStylePreprocessor];
|
|
535
|
-
} else {
|
|
536
|
-
preprocessors = preprocessors.concat(devStylePreprocessor);
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
if (preprocessors) {
|
|
540
|
-
try {
|
|
541
|
-
preprocessed = await preprocess(code, preprocessors, { filename });
|
|
542
|
-
} catch (e) {
|
|
543
|
-
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
|
|
544
|
-
throw e;
|
|
545
|
-
}
|
|
546
|
-
if (preprocessed.dependencies)
|
|
547
|
-
dependencies.push(...preprocessed.dependencies);
|
|
548
|
-
if (preprocessed.map)
|
|
549
|
-
compileOptions.sourcemap = preprocessed.map;
|
|
550
|
-
}
|
|
551
|
-
if (typeof preprocessed?.map === "object") {
|
|
552
|
-
mapToRelative(preprocessed?.map, filename);
|
|
553
|
-
}
|
|
554
|
-
if (raw && svelteRequest.query.type === "preprocessed") {
|
|
555
|
-
return { preprocessed: preprocessed ?? { code } };
|
|
556
|
-
}
|
|
557
|
-
const finalCode = preprocessed ? preprocessed.code : code;
|
|
558
|
-
const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
|
|
559
|
-
filename,
|
|
560
|
-
code: finalCode,
|
|
561
|
-
compileOptions
|
|
562
|
-
});
|
|
563
|
-
if (dynamicCompileOptions && log.debug.enabled) {
|
|
564
|
-
log.debug(
|
|
565
|
-
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
|
|
566
|
-
);
|
|
567
|
-
}
|
|
568
|
-
const finalCompileOptions = dynamicCompileOptions ? {
|
|
569
|
-
...compileOptions,
|
|
570
|
-
...dynamicCompileOptions
|
|
571
|
-
} : compileOptions;
|
|
572
|
-
const endStat = stats?.start(filename);
|
|
573
|
-
const compiled = compile(finalCode, finalCompileOptions);
|
|
574
|
-
compiled.js.code = compiled.js.code.replace(
|
|
575
|
-
/\/\* [@#]__PURE__ \*\/(\s*)$/gm,
|
|
576
|
-
" $1"
|
|
577
|
-
);
|
|
578
|
-
if (endStat) {
|
|
579
|
-
endStat();
|
|
580
|
-
}
|
|
581
|
-
mapToRelative(compiled.js?.map, filename);
|
|
582
|
-
mapToRelative(compiled.css?.map, filename);
|
|
583
|
-
if (!raw) {
|
|
584
|
-
const hasCss = compiled.css?.code?.trim().length > 0;
|
|
585
|
-
if (emitCss && hasCss) {
|
|
586
|
-
compiled.js.code += `
|
|
587
|
-
import ${JSON.stringify(cssId)};
|
|
588
|
-
`;
|
|
589
|
-
}
|
|
590
|
-
if (!ssr && makeHot) {
|
|
591
|
-
compiled.js.code = makeHot({
|
|
592
|
-
id: filename,
|
|
593
|
-
compiledCode: compiled.js.code,
|
|
594
|
-
//@ts-expect-error hot isn't a boolean at this point
|
|
595
|
-
hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
|
|
596
|
-
compiled,
|
|
597
|
-
originalCode: code,
|
|
598
|
-
compileOptions: finalCompileOptions
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
compiled.js.dependencies = dependencies;
|
|
603
|
-
return {
|
|
604
|
-
filename,
|
|
605
|
-
normalizedFilename,
|
|
606
|
-
lang: code.match(scriptLangRE)?.[1] || "js",
|
|
607
|
-
// @ts-ignore
|
|
608
|
-
compiled,
|
|
609
|
-
ssr,
|
|
610
|
-
dependencies,
|
|
611
|
-
preprocessed: preprocessed ?? { code }
|
|
612
|
-
};
|
|
613
|
-
};
|
|
614
|
-
};
|
|
615
|
-
function buildMakeHot(options) {
|
|
616
|
-
const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
|
|
617
|
-
if (needsMakeHot) {
|
|
618
|
-
const hotApi = options?.hot?.hotApi;
|
|
619
|
-
const adapter = options?.hot?.adapter;
|
|
620
|
-
return createMakeHot({
|
|
621
|
-
walk,
|
|
622
|
-
hotApi,
|
|
623
|
-
adapter,
|
|
624
|
-
hotOptions: { noOverlay: true, ...options.hot }
|
|
625
|
-
});
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
function createCompileSvelte(options) {
|
|
629
|
-
const makeHot = buildMakeHot(options);
|
|
630
|
-
return _createCompileSvelte(makeHot);
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
// src/utils/id.ts
|
|
634
|
-
import { createFilter } from "vite";
|
|
635
|
-
import { normalizePath } from "vite";
|
|
636
|
-
import * as fs from "fs";
|
|
637
|
-
var VITE_FS_PREFIX = "/@fs/";
|
|
638
|
-
var IS_WINDOWS2 = process.platform === "win32";
|
|
639
|
-
var SUPPORTED_COMPILER_OPTIONS = [
|
|
640
|
-
"generate",
|
|
641
|
-
"dev",
|
|
642
|
-
"css",
|
|
643
|
-
"hydratable",
|
|
644
|
-
"customElement",
|
|
645
|
-
"immutable",
|
|
646
|
-
"enableSourcemap"
|
|
647
|
-
];
|
|
648
|
-
var TYPES_WITH_COMPILER_OPTIONS = ["style", "script", "all"];
|
|
649
|
-
function splitId(id) {
|
|
650
|
-
const parts = id.split(`?`, 2);
|
|
651
|
-
const filename = parts[0];
|
|
652
|
-
const rawQuery = parts[1];
|
|
653
|
-
return { filename, rawQuery };
|
|
654
|
-
}
|
|
655
|
-
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
|
|
656
|
-
const query = parseRequestQuery(rawQuery);
|
|
657
|
-
const rawOrDirect = !!(query.raw || query.direct);
|
|
658
|
-
if (query.url || !query.svelte && rawOrDirect) {
|
|
659
|
-
return;
|
|
660
|
-
}
|
|
661
|
-
const raw = rawOrDirect;
|
|
662
|
-
const normalizedFilename = normalize(filename, root);
|
|
663
|
-
const cssId = createVirtualImportId(filename, root, "style");
|
|
664
|
-
return {
|
|
665
|
-
id,
|
|
666
|
-
filename,
|
|
667
|
-
normalizedFilename,
|
|
668
|
-
cssId,
|
|
669
|
-
query,
|
|
670
|
-
timestamp,
|
|
671
|
-
ssr,
|
|
672
|
-
raw
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
function createVirtualImportId(filename, root, type) {
|
|
676
|
-
const parts = ["svelte", `type=${type}`];
|
|
677
|
-
if (type === "style") {
|
|
678
|
-
parts.push("lang.css");
|
|
679
|
-
}
|
|
680
|
-
if (existsInRoot(filename, root)) {
|
|
681
|
-
filename = root + filename;
|
|
682
|
-
} else if (filename.startsWith(VITE_FS_PREFIX)) {
|
|
683
|
-
filename = IS_WINDOWS2 ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
|
|
684
|
-
}
|
|
685
|
-
return `${filename}?${parts.join("&")}`;
|
|
686
|
-
}
|
|
687
|
-
function parseRequestQuery(rawQuery) {
|
|
688
|
-
const query = Object.fromEntries(new URLSearchParams(rawQuery));
|
|
689
|
-
for (const key in query) {
|
|
690
|
-
if (query[key] === "") {
|
|
691
|
-
query[key] = true;
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
const compilerOptions = query.compilerOptions;
|
|
695
|
-
if (compilerOptions) {
|
|
696
|
-
if (!((query.raw || query.direct) && TYPES_WITH_COMPILER_OPTIONS.includes(query.type))) {
|
|
697
|
-
throw new Error(
|
|
698
|
-
`Invalid compilerOptions in query ${rawQuery}. CompilerOptions are only supported for raw or direct queries with type in "${TYPES_WITH_COMPILER_OPTIONS.join(
|
|
699
|
-
", "
|
|
700
|
-
)}" e.g. '?svelte&raw&type=script&compilerOptions={"generate":"ssr","dev":false}`
|
|
701
|
-
);
|
|
702
|
-
}
|
|
703
|
-
try {
|
|
704
|
-
const parsed = JSON.parse(compilerOptions);
|
|
705
|
-
const invalid = Object.keys(parsed).filter(
|
|
706
|
-
(key) => !SUPPORTED_COMPILER_OPTIONS.includes(key)
|
|
707
|
-
);
|
|
708
|
-
if (invalid.length) {
|
|
709
|
-
throw new Error(
|
|
710
|
-
`Invalid compilerOptions in query ${rawQuery}: ${invalid.join(
|
|
711
|
-
", "
|
|
712
|
-
)}. Supported: ${SUPPORTED_COMPILER_OPTIONS.join(", ")}`
|
|
713
|
-
);
|
|
714
|
-
}
|
|
715
|
-
query.compilerOptions = parsed;
|
|
716
|
-
} catch (e) {
|
|
717
|
-
log.error("failed to parse request query compilerOptions", e);
|
|
718
|
-
throw e;
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
return query;
|
|
722
|
-
}
|
|
723
|
-
function normalize(filename, normalizedRoot) {
|
|
724
|
-
return stripRoot(normalizePath(filename), normalizedRoot);
|
|
725
|
-
}
|
|
726
|
-
function existsInRoot(filename, root) {
|
|
727
|
-
if (filename.startsWith(VITE_FS_PREFIX)) {
|
|
728
|
-
return false;
|
|
729
|
-
}
|
|
730
|
-
return fs.existsSync(root + filename);
|
|
731
|
-
}
|
|
732
|
-
function stripRoot(normalizedFilename, normalizedRoot) {
|
|
733
|
-
return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
|
|
734
|
-
}
|
|
735
|
-
function buildFilter(include, exclude, extensions) {
|
|
736
|
-
const rollupFilter = createFilter(include, exclude);
|
|
737
|
-
return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
|
|
738
|
-
}
|
|
739
|
-
function buildIdParser(options) {
|
|
740
|
-
const { include, exclude, extensions, root } = options;
|
|
741
|
-
const normalizedRoot = normalizePath(root);
|
|
742
|
-
const filter = buildFilter(include, exclude, extensions);
|
|
743
|
-
return (id, ssr, timestamp = Date.now()) => {
|
|
744
|
-
const { filename, rawQuery } = splitId(id);
|
|
745
|
-
if (filter(filename)) {
|
|
746
|
-
return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
|
|
747
|
-
}
|
|
748
|
-
};
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
// src/utils/options.ts
|
|
752
|
-
import { normalizePath as normalizePath3 } from "vite";
|
|
753
|
-
|
|
754
|
-
// src/utils/load-svelte-config.ts
|
|
755
|
-
import { createRequire } from "module";
|
|
756
|
-
import path3 from "path";
|
|
757
|
-
import fs2 from "fs";
|
|
758
|
-
import { pathToFileURL } from "url";
|
|
759
|
-
var esmRequire;
|
|
760
|
-
var knownSvelteConfigNames = [
|
|
761
|
-
"svelte.config.js",
|
|
762
|
-
"svelte.config.cjs",
|
|
763
|
-
"svelte.config.mjs"
|
|
764
|
-
];
|
|
765
|
-
var dynamicImportDefault = new Function(
|
|
766
|
-
"path",
|
|
767
|
-
"timestamp",
|
|
768
|
-
'return import(path + "?t=" + timestamp).then(m => m.default)'
|
|
769
|
-
);
|
|
770
|
-
async function loadSvelteConfig(viteConfig, inlineOptions) {
|
|
771
|
-
if (inlineOptions?.configFile === false) {
|
|
772
|
-
return;
|
|
773
|
-
}
|
|
774
|
-
const configFile = findConfigToLoad(viteConfig, inlineOptions);
|
|
775
|
-
if (configFile) {
|
|
776
|
-
let err;
|
|
777
|
-
if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
|
|
778
|
-
try {
|
|
779
|
-
const result = await dynamicImportDefault(
|
|
780
|
-
pathToFileURL(configFile).href,
|
|
781
|
-
fs2.statSync(configFile).mtimeMs
|
|
782
|
-
);
|
|
783
|
-
if (result != null) {
|
|
784
|
-
return {
|
|
785
|
-
...result,
|
|
786
|
-
configFile
|
|
787
|
-
};
|
|
788
|
-
} else {
|
|
789
|
-
throw new Error(`invalid export in ${configFile}`);
|
|
790
|
-
}
|
|
791
|
-
} catch (e) {
|
|
792
|
-
log.error(`failed to import config ${configFile}`, e);
|
|
793
|
-
err = e;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
if (!configFile.endsWith(".mjs")) {
|
|
797
|
-
try {
|
|
798
|
-
const _require = import.meta.url ? esmRequire ?? (esmRequire = createRequire(import.meta.url)) : __require;
|
|
799
|
-
delete _require.cache[_require.resolve(configFile)];
|
|
800
|
-
const result = _require(configFile);
|
|
801
|
-
if (result != null) {
|
|
802
|
-
return {
|
|
803
|
-
...result,
|
|
804
|
-
configFile
|
|
805
|
-
};
|
|
806
|
-
} else {
|
|
807
|
-
throw new Error(`invalid export in ${configFile}`);
|
|
808
|
-
}
|
|
809
|
-
} catch (e) {
|
|
810
|
-
log.error(`failed to require config ${configFile}`, e);
|
|
811
|
-
if (!err) {
|
|
812
|
-
err = e;
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
throw err;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
function findConfigToLoad(viteConfig, inlineOptions) {
|
|
820
|
-
const root = viteConfig?.root || process.cwd();
|
|
821
|
-
if (inlineOptions?.configFile) {
|
|
822
|
-
const abolutePath = path3.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : path3.resolve(root, inlineOptions.configFile);
|
|
823
|
-
if (!fs2.existsSync(abolutePath)) {
|
|
824
|
-
throw new Error(`failed to find svelte config file ${abolutePath}.`);
|
|
825
|
-
}
|
|
826
|
-
return abolutePath;
|
|
827
|
-
} else {
|
|
828
|
-
const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => path3.resolve(root, candidate)).filter((file) => fs2.existsSync(file));
|
|
829
|
-
if (existingKnownConfigFiles.length === 0) {
|
|
830
|
-
log.debug(`no svelte config found at ${root}`);
|
|
831
|
-
return;
|
|
832
|
-
} else if (existingKnownConfigFiles.length > 1) {
|
|
833
|
-
log.warn(
|
|
834
|
-
`found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`,
|
|
835
|
-
existingKnownConfigFiles
|
|
836
|
-
);
|
|
837
|
-
}
|
|
838
|
-
return existingKnownConfigFiles[0];
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
// src/utils/constants.ts
|
|
843
|
-
var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
|
|
844
|
-
var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte"];
|
|
845
|
-
var SVELTE_IMPORTS = [
|
|
846
|
-
"svelte/animate",
|
|
847
|
-
"svelte/easing",
|
|
848
|
-
"svelte/internal",
|
|
849
|
-
"svelte/motion",
|
|
850
|
-
"svelte/ssr",
|
|
851
|
-
"svelte/store",
|
|
852
|
-
"svelte/transition",
|
|
853
|
-
"svelte"
|
|
854
|
-
];
|
|
855
|
-
var SVELTE_HMR_IMPORTS = [
|
|
856
|
-
"svelte-hmr/runtime/hot-api-esm.js",
|
|
857
|
-
"svelte-hmr/runtime/proxy-adapter-dom.js",
|
|
858
|
-
"svelte-hmr"
|
|
859
|
-
];
|
|
860
|
-
var SVELTE_EXPORT_CONDITIONS = ["svelte"];
|
|
861
|
-
var FAQ_LINK_CONFLICTS_IN_SVELTE_RESOLVE = "https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#conflicts-in-svelte-resolve";
|
|
862
|
-
|
|
863
|
-
// src/utils/options.ts
|
|
864
|
-
import path5 from "path";
|
|
865
|
-
|
|
866
|
-
// src/utils/esbuild.ts
|
|
867
|
-
import { readFileSync } from "fs";
|
|
868
|
-
import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
|
|
869
|
-
var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
|
|
870
|
-
function esbuildSveltePlugin(options) {
|
|
871
|
-
return {
|
|
872
|
-
name: "vite-plugin-svelte:optimize-svelte",
|
|
873
|
-
setup(build) {
|
|
874
|
-
if (build.initialOptions.plugins?.some((v) => v.name === "vite:dep-scan"))
|
|
875
|
-
return;
|
|
876
|
-
const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
|
|
877
|
-
const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
|
|
878
|
-
let statsCollection;
|
|
879
|
-
build.onStart(() => {
|
|
880
|
-
statsCollection = options.stats?.startCollection("prebundle libraries", {
|
|
881
|
-
logResult: (c) => c.stats.length > 1
|
|
882
|
-
});
|
|
883
|
-
});
|
|
884
|
-
build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
|
|
885
|
-
const code = readFileSync(filename, "utf8");
|
|
886
|
-
try {
|
|
887
|
-
const contents = await compileSvelte(options, { filename, code }, statsCollection);
|
|
888
|
-
return { contents };
|
|
889
|
-
} catch (e) {
|
|
890
|
-
return { errors: [toESBuildError(e, options)] };
|
|
891
|
-
}
|
|
892
|
-
});
|
|
893
|
-
build.onEnd(() => {
|
|
894
|
-
statsCollection?.finish();
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
};
|
|
898
|
-
}
|
|
899
|
-
async function compileSvelte(options, { filename, code }, statsCollection) {
|
|
900
|
-
let css = options.compilerOptions.css;
|
|
901
|
-
if (css !== "none") {
|
|
902
|
-
css = "injected";
|
|
903
|
-
}
|
|
904
|
-
const compileOptions = {
|
|
905
|
-
...options.compilerOptions,
|
|
906
|
-
css,
|
|
907
|
-
filename,
|
|
908
|
-
format: "esm",
|
|
909
|
-
generate: "dom"
|
|
910
|
-
};
|
|
911
|
-
let preprocessed;
|
|
912
|
-
if (options.preprocess) {
|
|
913
|
-
try {
|
|
914
|
-
preprocessed = await preprocess2(code, options.preprocess, { filename });
|
|
915
|
-
} catch (e) {
|
|
916
|
-
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
|
|
917
|
-
throw e;
|
|
918
|
-
}
|
|
919
|
-
if (preprocessed.map)
|
|
920
|
-
compileOptions.sourcemap = preprocessed.map;
|
|
921
|
-
}
|
|
922
|
-
const finalCode = preprocessed ? preprocessed.code : code;
|
|
923
|
-
const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
|
|
924
|
-
filename,
|
|
925
|
-
code: finalCode,
|
|
926
|
-
compileOptions
|
|
927
|
-
});
|
|
928
|
-
if (dynamicCompileOptions && log.debug.enabled) {
|
|
929
|
-
log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
|
|
930
|
-
}
|
|
931
|
-
const finalCompileOptions = dynamicCompileOptions ? {
|
|
932
|
-
...compileOptions,
|
|
933
|
-
...dynamicCompileOptions
|
|
934
|
-
} : compileOptions;
|
|
935
|
-
const endStat = statsCollection?.start(filename);
|
|
936
|
-
const compiled = compile2(finalCode, finalCompileOptions);
|
|
937
|
-
if (endStat) {
|
|
938
|
-
endStat();
|
|
939
|
-
}
|
|
940
|
-
return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// src/utils/options.ts
|
|
944
|
-
import deepmerge from "deepmerge";
|
|
945
|
-
import {
|
|
946
|
-
crawlFrameworkPkgs,
|
|
947
|
-
isDepExcluded,
|
|
948
|
-
isDepExternaled,
|
|
949
|
-
isDepIncluded,
|
|
950
|
-
isDepNoExternaled
|
|
951
|
-
} from "vitefu";
|
|
952
|
-
|
|
953
|
-
// src/utils/dependencies.ts
|
|
954
|
-
import path4 from "path";
|
|
955
|
-
import fs3 from "fs/promises";
|
|
956
|
-
import { findDepPkgJsonPath } from "vitefu";
|
|
957
|
-
async function resolveDependencyData(dep, parent) {
|
|
958
|
-
const depDataPath = await findDepPkgJsonPath(dep, parent);
|
|
959
|
-
if (!depDataPath)
|
|
960
|
-
return void 0;
|
|
961
|
-
try {
|
|
962
|
-
return {
|
|
963
|
-
dir: path4.dirname(depDataPath),
|
|
964
|
-
pkg: JSON.parse(await fs3.readFile(depDataPath, "utf-8"))
|
|
965
|
-
};
|
|
966
|
-
} catch {
|
|
967
|
-
return void 0;
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
|
|
971
|
-
"@lukeed/uuid",
|
|
972
|
-
"@playwright/test",
|
|
973
|
-
"@sveltejs/vite-plugin-svelte",
|
|
974
|
-
"@sveltejs/kit",
|
|
975
|
-
"autoprefixer",
|
|
976
|
-
"cookie",
|
|
977
|
-
"dotenv",
|
|
978
|
-
"esbuild",
|
|
979
|
-
"eslint",
|
|
980
|
-
"jest",
|
|
981
|
-
"mdsvex",
|
|
982
|
-
"playwright",
|
|
983
|
-
"postcss",
|
|
984
|
-
"prettier",
|
|
985
|
-
"svelte",
|
|
986
|
-
"svelte-check",
|
|
987
|
-
"svelte-hmr",
|
|
988
|
-
"svelte-preprocess",
|
|
989
|
-
"tslib",
|
|
990
|
-
"typescript",
|
|
991
|
-
"vite",
|
|
992
|
-
"vitest",
|
|
993
|
-
"__vite-browser-external"
|
|
994
|
-
// see https://github.com/sveltejs/vite-plugin-svelte/issues/362
|
|
995
|
-
];
|
|
996
|
-
var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
|
|
997
|
-
"@fontsource/",
|
|
998
|
-
"@postcss-plugins/",
|
|
999
|
-
"@rollup/",
|
|
1000
|
-
"@sveltejs/adapter-",
|
|
1001
|
-
"@types/",
|
|
1002
|
-
"@typescript-eslint/",
|
|
1003
|
-
"eslint-",
|
|
1004
|
-
"jest-",
|
|
1005
|
-
"postcss-plugin-",
|
|
1006
|
-
"prettier-plugin-",
|
|
1007
|
-
"rollup-plugin-",
|
|
1008
|
-
"vite-plugin-"
|
|
1009
|
-
];
|
|
1010
|
-
function isCommonDepWithoutSvelteField(dependency) {
|
|
1011
|
-
return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
|
|
1012
|
-
(prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
|
|
1013
|
-
// check prefix omitting @scope/
|
|
1014
|
-
);
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
// src/utils/vite-plugin-svelte-stats.ts
|
|
1018
|
-
import { performance } from "perf_hooks";
|
|
1019
|
-
import { normalizePath as normalizePath2 } from "vite";
|
|
1020
|
-
var defaultCollectionOptions = {
|
|
1021
|
-
// log after 500ms and more than one file processed
|
|
1022
|
-
logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
|
|
1023
|
-
// always log results
|
|
1024
|
-
logResult: () => true
|
|
1025
|
-
};
|
|
1026
|
-
function humanDuration(n) {
|
|
1027
|
-
return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1e3).toFixed(2)}s`;
|
|
1028
|
-
}
|
|
1029
|
-
function formatPackageStats(pkgStats) {
|
|
1030
|
-
const statLines = pkgStats.map((pkgStat) => {
|
|
1031
|
-
const duration = pkgStat.duration;
|
|
1032
|
-
const avg = duration / pkgStat.files;
|
|
1033
|
-
return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
|
|
1034
|
-
});
|
|
1035
|
-
statLines.unshift(["package", "files", "time", "avg"]);
|
|
1036
|
-
const columnWidths = statLines.reduce(
|
|
1037
|
-
(widths, row) => {
|
|
1038
|
-
for (let i = 0; i < row.length; i++) {
|
|
1039
|
-
const cell = row[i];
|
|
1040
|
-
if (widths[i] < cell.length) {
|
|
1041
|
-
widths[i] = cell.length;
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
return widths;
|
|
1045
|
-
},
|
|
1046
|
-
statLines[0].map(() => 0)
|
|
1047
|
-
);
|
|
1048
|
-
const table = statLines.map(
|
|
1049
|
-
(row) => row.map((cell, i) => {
|
|
1050
|
-
if (i === 0) {
|
|
1051
|
-
return cell.padEnd(columnWidths[i], " ");
|
|
1052
|
-
} else {
|
|
1053
|
-
return cell.padStart(columnWidths[i], " ");
|
|
1054
|
-
}
|
|
1055
|
-
}).join(" ")
|
|
1056
|
-
).join("\n");
|
|
1057
|
-
return table;
|
|
1058
|
-
}
|
|
1059
|
-
var VitePluginSvelteStats = class {
|
|
1060
|
-
constructor(cache) {
|
|
1061
|
-
this._collections = [];
|
|
1062
|
-
this._cache = cache;
|
|
1063
|
-
}
|
|
1064
|
-
startCollection(name, opts) {
|
|
1065
|
-
const options = {
|
|
1066
|
-
...defaultCollectionOptions,
|
|
1067
|
-
...opts
|
|
1068
|
-
};
|
|
1069
|
-
const stats = [];
|
|
1070
|
-
const collectionStart = performance.now();
|
|
1071
|
-
const _this = this;
|
|
1072
|
-
let hasLoggedProgress = false;
|
|
1073
|
-
const collection = {
|
|
1074
|
-
name,
|
|
1075
|
-
options,
|
|
1076
|
-
stats,
|
|
1077
|
-
collectionStart,
|
|
1078
|
-
finished: false,
|
|
1079
|
-
start(file) {
|
|
1080
|
-
if (collection.finished) {
|
|
1081
|
-
throw new Error("called after finish() has been used");
|
|
1082
|
-
}
|
|
1083
|
-
file = normalizePath2(file);
|
|
1084
|
-
const start = performance.now();
|
|
1085
|
-
const stat = { file, start, end: start };
|
|
1086
|
-
return () => {
|
|
1087
|
-
const now = performance.now();
|
|
1088
|
-
stat.end = now;
|
|
1089
|
-
stats.push(stat);
|
|
1090
|
-
if (!hasLoggedProgress && options.logInProgress(collection, now)) {
|
|
1091
|
-
hasLoggedProgress = true;
|
|
1092
|
-
log.debug(`${name} in progress ...`, void 0, "stats");
|
|
1093
|
-
}
|
|
1094
|
-
};
|
|
1095
|
-
},
|
|
1096
|
-
async finish() {
|
|
1097
|
-
await _this._finish(collection);
|
|
1098
|
-
}
|
|
1099
|
-
};
|
|
1100
|
-
_this._collections.push(collection);
|
|
1101
|
-
return collection;
|
|
1102
|
-
}
|
|
1103
|
-
async finishAll() {
|
|
1104
|
-
await Promise.all(this._collections.map((c) => c.finish()));
|
|
1105
|
-
}
|
|
1106
|
-
async _finish(collection) {
|
|
1107
|
-
try {
|
|
1108
|
-
collection.finished = true;
|
|
1109
|
-
const now = performance.now();
|
|
1110
|
-
collection.duration = now - collection.collectionStart;
|
|
1111
|
-
const logResult = collection.options.logResult(collection);
|
|
1112
|
-
if (logResult) {
|
|
1113
|
-
await this._aggregateStatsResult(collection);
|
|
1114
|
-
log.debug(
|
|
1115
|
-
`${collection.name} done.
|
|
1116
|
-
${formatPackageStats(collection.packageStats)}`,
|
|
1117
|
-
void 0,
|
|
1118
|
-
"stats"
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1121
|
-
const index = this._collections.indexOf(collection);
|
|
1122
|
-
this._collections.splice(index, 1);
|
|
1123
|
-
collection.stats.length = 0;
|
|
1124
|
-
collection.stats = [];
|
|
1125
|
-
if (collection.packageStats) {
|
|
1126
|
-
collection.packageStats.length = 0;
|
|
1127
|
-
collection.packageStats = [];
|
|
1128
|
-
}
|
|
1129
|
-
collection.start = () => () => {
|
|
1130
|
-
};
|
|
1131
|
-
collection.finish = () => {
|
|
1132
|
-
};
|
|
1133
|
-
} catch (e) {
|
|
1134
|
-
log.debug.once(`failed to finish stats for ${collection.name}
|
|
1135
|
-
`, e, "stats");
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
async _aggregateStatsResult(collection) {
|
|
1139
|
-
const stats = collection.stats;
|
|
1140
|
-
for (const stat of stats) {
|
|
1141
|
-
stat.pkg = (await this._cache.getPackageInfo(stat.file)).name;
|
|
1142
|
-
}
|
|
1143
|
-
const grouped = {};
|
|
1144
|
-
stats.forEach((stat) => {
|
|
1145
|
-
const pkg = stat.pkg;
|
|
1146
|
-
let group = grouped[pkg];
|
|
1147
|
-
if (!group) {
|
|
1148
|
-
group = grouped[pkg] = {
|
|
1149
|
-
files: 0,
|
|
1150
|
-
duration: 0,
|
|
1151
|
-
pkg
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
group.files += 1;
|
|
1155
|
-
group.duration += stat.end - stat.start;
|
|
1156
|
-
});
|
|
1157
|
-
const groups = Object.values(grouped);
|
|
1158
|
-
groups.sort((a, b) => b.duration - a.duration);
|
|
1159
|
-
collection.packageStats = groups;
|
|
1160
|
-
}
|
|
1161
|
-
};
|
|
1162
|
-
|
|
1163
|
-
// src/utils/options.ts
|
|
1164
|
-
var allowedPluginOptions = /* @__PURE__ */ new Set([
|
|
1165
|
-
"include",
|
|
1166
|
-
"exclude",
|
|
1167
|
-
"emitCss",
|
|
1168
|
-
"hot",
|
|
1169
|
-
"ignorePluginPreprocessors",
|
|
1170
|
-
"disableDependencyReinclusion",
|
|
1171
|
-
"prebundleSvelteLibraries",
|
|
1172
|
-
"inspector",
|
|
1173
|
-
"experimental"
|
|
1174
|
-
]);
|
|
1175
|
-
var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions", "preprocess", "onwarn"]);
|
|
1176
|
-
var allowedInlineOptions = /* @__PURE__ */ new Set(["configFile", ...allowedPluginOptions, ...knownRootOptions]);
|
|
1177
|
-
function validateInlineOptions(inlineOptions) {
|
|
1178
|
-
const invalidKeys = Object.keys(inlineOptions || {}).filter(
|
|
1179
|
-
(key) => !allowedInlineOptions.has(key)
|
|
1180
|
-
);
|
|
1181
|
-
if (invalidKeys.length) {
|
|
1182
|
-
log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in inline config`, inlineOptions);
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
function convertPluginOptions(config) {
|
|
1186
|
-
if (!config) {
|
|
1187
|
-
return;
|
|
1188
|
-
}
|
|
1189
|
-
const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
|
|
1190
|
-
if (invalidRootOptions.length > 0) {
|
|
1191
|
-
throw new Error(
|
|
1192
|
-
`Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(
|
|
1193
|
-
", "
|
|
1194
|
-
)}`
|
|
1195
|
-
);
|
|
1196
|
-
}
|
|
1197
|
-
if (!config.vitePlugin) {
|
|
1198
|
-
return config;
|
|
1199
|
-
}
|
|
1200
|
-
const pluginOptions = config.vitePlugin;
|
|
1201
|
-
const pluginOptionKeys = Object.keys(pluginOptions);
|
|
1202
|
-
const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
|
|
1203
|
-
if (rootOptionsInPluginOptions.length > 0) {
|
|
1204
|
-
throw new Error(
|
|
1205
|
-
`Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(
|
|
1206
|
-
", "
|
|
1207
|
-
)}`
|
|
1208
|
-
);
|
|
1209
|
-
}
|
|
1210
|
-
const duplicateOptions = pluginOptionKeys.filter(
|
|
1211
|
-
(key) => Object.prototype.hasOwnProperty.call(config, key)
|
|
1212
|
-
);
|
|
1213
|
-
if (duplicateOptions.length > 0) {
|
|
1214
|
-
throw new Error(
|
|
1215
|
-
`Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(
|
|
1216
|
-
", "
|
|
1217
|
-
)}`
|
|
1218
|
-
);
|
|
1219
|
-
}
|
|
1220
|
-
const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
|
|
1221
|
-
if (unknownPluginOptions.length > 0) {
|
|
1222
|
-
log.warn(
|
|
1223
|
-
`ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(
|
|
1224
|
-
", "
|
|
1225
|
-
)}`
|
|
1226
|
-
);
|
|
1227
|
-
unknownPluginOptions.forEach((unkownOption) => {
|
|
1228
|
-
delete pluginOptions[unkownOption];
|
|
1229
|
-
});
|
|
1230
|
-
}
|
|
1231
|
-
const result = {
|
|
1232
|
-
...config,
|
|
1233
|
-
...pluginOptions
|
|
1234
|
-
};
|
|
1235
|
-
delete result.vitePlugin;
|
|
1236
|
-
return result;
|
|
1237
|
-
}
|
|
1238
|
-
async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
|
|
1239
|
-
const viteConfigWithResolvedRoot = {
|
|
1240
|
-
...viteUserConfig,
|
|
1241
|
-
root: resolveViteRoot(viteUserConfig)
|
|
1242
|
-
};
|
|
1243
|
-
const isBuild = viteEnv.command === "build";
|
|
1244
|
-
const defaultOptions = {
|
|
1245
|
-
extensions: [".svelte"],
|
|
1246
|
-
emitCss: true,
|
|
1247
|
-
prebundleSvelteLibraries: !isBuild
|
|
1248
|
-
};
|
|
1249
|
-
const svelteConfig = convertPluginOptions(
|
|
1250
|
-
await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
|
|
1251
|
-
);
|
|
1252
|
-
const extraOptions = {
|
|
1253
|
-
root: viteConfigWithResolvedRoot.root,
|
|
1254
|
-
isBuild,
|
|
1255
|
-
isServe: viteEnv.command === "serve",
|
|
1256
|
-
isDebug: process.env.DEBUG != null
|
|
1257
|
-
};
|
|
1258
|
-
const merged = mergeConfigs(
|
|
1259
|
-
defaultOptions,
|
|
1260
|
-
svelteConfig,
|
|
1261
|
-
inlineOptions,
|
|
1262
|
-
extraOptions
|
|
1263
|
-
);
|
|
1264
|
-
if (svelteConfig?.configFile) {
|
|
1265
|
-
merged.configFile = svelteConfig.configFile;
|
|
1266
|
-
}
|
|
1267
|
-
return merged;
|
|
1268
|
-
}
|
|
1269
|
-
function mergeConfigs(...configs) {
|
|
1270
|
-
let result = {};
|
|
1271
|
-
for (const config of configs.filter((x) => x != null)) {
|
|
1272
|
-
result = deepmerge(result, config, {
|
|
1273
|
-
// replace arrays
|
|
1274
|
-
arrayMerge: (target, source) => source ?? target
|
|
1275
|
-
});
|
|
1276
|
-
}
|
|
1277
|
-
return result;
|
|
1278
|
-
}
|
|
1279
|
-
function resolveOptions(preResolveOptions2, viteConfig, cache) {
|
|
1280
|
-
const css = preResolveOptions2.emitCss ? "external" : "injected";
|
|
1281
|
-
const defaultOptions = {
|
|
1282
|
-
hot: viteConfig.isProduction ? false : {
|
|
1283
|
-
injectCss: css === "injected",
|
|
1284
|
-
partialAccept: !!viteConfig.experimental?.hmrPartialAccept
|
|
1285
|
-
},
|
|
1286
|
-
compilerOptions: {
|
|
1287
|
-
css,
|
|
1288
|
-
dev: !viteConfig.isProduction
|
|
1289
|
-
}
|
|
1290
|
-
};
|
|
1291
|
-
const extraOptions = {
|
|
1292
|
-
root: viteConfig.root,
|
|
1293
|
-
isProduction: viteConfig.isProduction
|
|
1294
|
-
};
|
|
1295
|
-
const merged = mergeConfigs(defaultOptions, preResolveOptions2, extraOptions);
|
|
1296
|
-
removeIgnoredOptions(merged);
|
|
1297
|
-
handleDeprecatedOptions(merged);
|
|
1298
|
-
addExtraPreprocessors(merged, viteConfig);
|
|
1299
|
-
enforceOptionsForHmr(merged);
|
|
1300
|
-
enforceOptionsForProduction(merged);
|
|
1301
|
-
if (log.debug.enabled && isDebugNamespaceEnabled("stats")) {
|
|
1302
|
-
merged.stats = new VitePluginSvelteStats(cache);
|
|
1303
|
-
}
|
|
1304
|
-
return merged;
|
|
1305
|
-
}
|
|
1306
|
-
function enforceOptionsForHmr(options) {
|
|
1307
|
-
if (options.hot) {
|
|
1308
|
-
if (!options.compilerOptions.dev) {
|
|
1309
|
-
log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
|
|
1310
|
-
options.compilerOptions.dev = true;
|
|
1311
|
-
}
|
|
1312
|
-
if (options.emitCss) {
|
|
1313
|
-
if (options.hot !== true && options.hot.injectCss) {
|
|
1314
|
-
log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
|
|
1315
|
-
options.hot.injectCss = false;
|
|
1316
|
-
}
|
|
1317
|
-
const css = options.compilerOptions.css;
|
|
1318
|
-
if (css === true || css === "injected") {
|
|
1319
|
-
const forcedCss = "external";
|
|
1320
|
-
log.warn(
|
|
1321
|
-
`hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
|
|
1322
|
-
);
|
|
1323
|
-
options.compilerOptions.css = forcedCss;
|
|
1324
|
-
}
|
|
1325
|
-
} else {
|
|
1326
|
-
if (options.hot === true || !options.hot.injectCss) {
|
|
1327
|
-
log.warn(
|
|
1328
|
-
"hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true"
|
|
1329
|
-
);
|
|
1330
|
-
if (options.hot === true) {
|
|
1331
|
-
options.hot = { injectCss: true };
|
|
1332
|
-
} else {
|
|
1333
|
-
options.hot.injectCss = true;
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
const css = options.compilerOptions.css;
|
|
1337
|
-
if (!(css === true || css === "injected")) {
|
|
1338
|
-
const forcedCss = "injected";
|
|
1339
|
-
log.warn(
|
|
1340
|
-
`hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
|
|
1341
|
-
);
|
|
1342
|
-
options.compilerOptions.css = forcedCss;
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
function enforceOptionsForProduction(options) {
|
|
1348
|
-
if (options.isProduction) {
|
|
1349
|
-
if (options.hot) {
|
|
1350
|
-
log.warn("options.hot is enabled but does not work on production build, forcing it to false");
|
|
1351
|
-
options.hot = false;
|
|
1352
|
-
}
|
|
1353
|
-
if (options.compilerOptions.dev) {
|
|
1354
|
-
log.warn(
|
|
1355
|
-
"you are building for production but compilerOptions.dev is true, forcing it to false"
|
|
1356
|
-
);
|
|
1357
|
-
options.compilerOptions.dev = false;
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
function removeIgnoredOptions(options) {
|
|
1362
|
-
const ignoredCompilerOptions = ["generate", "format", "filename"];
|
|
1363
|
-
if (options.hot && options.emitCss) {
|
|
1364
|
-
ignoredCompilerOptions.push("cssHash");
|
|
1365
|
-
}
|
|
1366
|
-
const passedCompilerOptions = Object.keys(options.compilerOptions || {});
|
|
1367
|
-
const passedIgnored = passedCompilerOptions.filter((o) => ignoredCompilerOptions.includes(o));
|
|
1368
|
-
if (passedIgnored.length) {
|
|
1369
|
-
log.warn(
|
|
1370
|
-
`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(
|
|
1371
|
-
", "
|
|
1372
|
-
)}`
|
|
1373
|
-
);
|
|
1374
|
-
passedIgnored.forEach((ignored) => {
|
|
1375
|
-
delete options.compilerOptions[ignored];
|
|
1376
|
-
});
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
function handleDeprecatedOptions(options) {
|
|
1380
|
-
const experimental = options.experimental;
|
|
1381
|
-
if (experimental) {
|
|
1382
|
-
for (const promoted of ["prebundleSvelteLibraries", "inspector"]) {
|
|
1383
|
-
if (experimental[promoted]) {
|
|
1384
|
-
options[promoted] = experimental[promoted];
|
|
1385
|
-
delete experimental[promoted];
|
|
1386
|
-
log.warn(
|
|
1387
|
-
`Option "vitePlugin.experimental.${promoted}" is no longer experimental and has moved to "vitePlugin.${promoted}". Please update your svelte config.`
|
|
1388
|
-
);
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
if (experimental.generateMissingPreprocessorSourcemaps) {
|
|
1392
|
-
log.warn("experimental.generateMissingPreprocessorSourcemaps has been removed.");
|
|
1393
|
-
}
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
function resolveViteRoot(viteConfig) {
|
|
1397
|
-
return normalizePath3(viteConfig.root ? path5.resolve(viteConfig.root) : process.cwd());
|
|
1398
|
-
}
|
|
1399
|
-
async function buildExtraViteConfig(options, config) {
|
|
1400
|
-
if (!config.resolve) {
|
|
1401
|
-
config.resolve = {};
|
|
1402
|
-
}
|
|
1403
|
-
config.resolve.mainFields = [
|
|
1404
|
-
...SVELTE_RESOLVE_MAIN_FIELDS,
|
|
1405
|
-
...config.resolve.mainFields ?? VITE_RESOLVE_MAIN_FIELDS
|
|
1406
|
-
];
|
|
1407
|
-
const extraViteConfig = {
|
|
1408
|
-
resolve: {
|
|
1409
|
-
dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
|
|
1410
|
-
conditions: [...SVELTE_EXPORT_CONDITIONS]
|
|
1411
|
-
}
|
|
1412
|
-
// this option is still awaiting a PR in vite to be supported
|
|
1413
|
-
// see https://github.com/sveltejs/vite-plugin-svelte/issues/60
|
|
1414
|
-
// @ts-ignore
|
|
1415
|
-
// knownJsSrcExtensions: options.extensions
|
|
1416
|
-
};
|
|
1417
|
-
const extraSvelteConfig = buildExtraConfigForSvelte(config);
|
|
1418
|
-
const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
|
|
1419
|
-
extraViteConfig.optimizeDeps = {
|
|
1420
|
-
include: [
|
|
1421
|
-
...extraSvelteConfig.optimizeDeps.include,
|
|
1422
|
-
...extraDepsConfig.optimizeDeps.include.filter(
|
|
1423
|
-
(dep) => !isDepExcluded(dep, extraSvelteConfig.optimizeDeps.exclude)
|
|
1424
|
-
)
|
|
1425
|
-
],
|
|
1426
|
-
exclude: [
|
|
1427
|
-
...extraSvelteConfig.optimizeDeps.exclude,
|
|
1428
|
-
...extraDepsConfig.optimizeDeps.exclude.filter(
|
|
1429
|
-
(dep) => !isDepIncluded(dep, extraSvelteConfig.optimizeDeps.include)
|
|
1430
|
-
)
|
|
1431
|
-
]
|
|
1432
|
-
};
|
|
1433
|
-
extraViteConfig.ssr = {
|
|
1434
|
-
external: [
|
|
1435
|
-
...extraSvelteConfig.ssr.external,
|
|
1436
|
-
...extraDepsConfig.ssr.external.filter(
|
|
1437
|
-
(dep) => !isDepNoExternaled(dep, extraSvelteConfig.ssr.noExternal)
|
|
1438
|
-
)
|
|
1439
|
-
],
|
|
1440
|
-
noExternal: [
|
|
1441
|
-
...extraSvelteConfig.ssr.noExternal,
|
|
1442
|
-
...extraDepsConfig.ssr.noExternal.filter(
|
|
1443
|
-
(dep) => !isDepExternaled(dep, extraSvelteConfig.ssr.external)
|
|
1444
|
-
)
|
|
1445
|
-
]
|
|
1446
|
-
};
|
|
1447
|
-
if (options.prebundleSvelteLibraries) {
|
|
1448
|
-
extraViteConfig.optimizeDeps = {
|
|
1449
|
-
...extraViteConfig.optimizeDeps,
|
|
1450
|
-
// Experimental Vite API to allow these extensions to be scanned and prebundled
|
|
1451
|
-
// @ts-ignore
|
|
1452
|
-
extensions: options.extensions ?? [".svelte"],
|
|
1453
|
-
// Add esbuild plugin to prebundle Svelte files.
|
|
1454
|
-
// Currently a placeholder as more information is needed after Vite config is resolved,
|
|
1455
|
-
// the real Svelte plugin is added in `patchResolvedViteConfig()`
|
|
1456
|
-
esbuildOptions: {
|
|
1457
|
-
plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
|
|
1458
|
-
} }]
|
|
1459
|
-
}
|
|
1460
|
-
};
|
|
1461
|
-
}
|
|
1462
|
-
if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && // deviate from svelte-hmr, default to true
|
|
1463
|
-
config.experimental?.hmrPartialAccept !== false) {
|
|
1464
|
-
log.debug('enabling "experimental.hmrPartialAccept" in vite config');
|
|
1465
|
-
extraViteConfig.experimental = { hmrPartialAccept: true };
|
|
1466
|
-
}
|
|
1467
|
-
validateViteConfig(extraViteConfig, config, options);
|
|
1468
|
-
return extraViteConfig;
|
|
1469
|
-
}
|
|
1470
|
-
function validateViteConfig(extraViteConfig, config, options) {
|
|
1471
|
-
const { prebundleSvelteLibraries, isBuild } = options;
|
|
1472
|
-
if (prebundleSvelteLibraries) {
|
|
1473
|
-
const isEnabled = (option) => option !== true && option !== (isBuild ? "build" : "dev");
|
|
1474
|
-
const logWarning = (name, value, recommendation) => log.warn.once(
|
|
1475
|
-
`Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
|
|
1476
|
-
value
|
|
1477
|
-
)}\` ${isBuild ? "during build." : "."} ${recommendation}`
|
|
1478
|
-
);
|
|
1479
|
-
const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? "build";
|
|
1480
|
-
const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
|
|
1481
|
-
if (!isBuild && !isOptimizeDepsEnabled) {
|
|
1482
|
-
logWarning(
|
|
1483
|
-
"optimizeDeps.disabled",
|
|
1484
|
-
viteOptimizeDepsDisabled,
|
|
1485
|
-
'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
|
|
1486
|
-
);
|
|
1487
|
-
extraViteConfig.optimizeDeps.disabled = "build";
|
|
1488
|
-
} else if (isBuild && isOptimizeDepsEnabled) {
|
|
1489
|
-
logWarning(
|
|
1490
|
-
"optimizeDeps.disabled",
|
|
1491
|
-
viteOptimizeDepsDisabled,
|
|
1492
|
-
"Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors."
|
|
1493
|
-
);
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
}
|
|
1497
|
-
async function buildExtraConfigForDependencies(options, config) {
|
|
1498
|
-
const depsConfig = await crawlFrameworkPkgs({
|
|
1499
|
-
root: options.root,
|
|
1500
|
-
isBuild: options.isBuild,
|
|
1501
|
-
viteUserConfig: config,
|
|
1502
|
-
isFrameworkPkgByJson(pkgJson) {
|
|
1503
|
-
let hasSvelteCondition = false;
|
|
1504
|
-
if (typeof pkgJson.exports === "object") {
|
|
1505
|
-
JSON.stringify(pkgJson.exports, (key, value) => {
|
|
1506
|
-
if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
|
|
1507
|
-
hasSvelteCondition = true;
|
|
1508
|
-
}
|
|
1509
|
-
return value;
|
|
1510
|
-
});
|
|
1511
|
-
}
|
|
1512
|
-
return hasSvelteCondition || !!pkgJson.svelte;
|
|
1513
|
-
},
|
|
1514
|
-
isSemiFrameworkPkgByJson(pkgJson) {
|
|
1515
|
-
return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
|
|
1516
|
-
},
|
|
1517
|
-
isFrameworkPkgByName(pkgName) {
|
|
1518
|
-
const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
|
|
1519
|
-
if (isNotSveltePackage) {
|
|
1520
|
-
return false;
|
|
1521
|
-
} else {
|
|
1522
|
-
return void 0;
|
|
1523
|
-
}
|
|
1524
|
-
}
|
|
1525
|
-
});
|
|
1526
|
-
log.debug("extra config for dependencies generated by vitefu", depsConfig);
|
|
1527
|
-
if (options.prebundleSvelteLibraries) {
|
|
1528
|
-
depsConfig.optimizeDeps.exclude = [];
|
|
1529
|
-
const userExclude = config.optimizeDeps?.exclude;
|
|
1530
|
-
depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
|
|
1531
|
-
return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => isDepExcluded(d.trim(), userExclude));
|
|
1532
|
-
});
|
|
1533
|
-
}
|
|
1534
|
-
if (options.disableDependencyReinclusion === true) {
|
|
1535
|
-
depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
|
|
1536
|
-
(dep) => !dep.includes(">")
|
|
1537
|
-
);
|
|
1538
|
-
} else if (Array.isArray(options.disableDependencyReinclusion)) {
|
|
1539
|
-
const disabledDeps = options.disableDependencyReinclusion;
|
|
1540
|
-
depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
|
|
1541
|
-
if (!dep.includes(">"))
|
|
1542
|
-
return true;
|
|
1543
|
-
const trimDep = dep.replace(/\s+/g, "");
|
|
1544
|
-
return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
|
|
1545
|
-
});
|
|
1546
|
-
}
|
|
1547
|
-
log.debug("post-processed extra config for dependencies", depsConfig);
|
|
1548
|
-
return depsConfig;
|
|
1549
|
-
}
|
|
1550
|
-
function buildExtraConfigForSvelte(config) {
|
|
1551
|
-
const include = [];
|
|
1552
|
-
const exclude = ["svelte-hmr"];
|
|
1553
|
-
if (!isDepExcluded("svelte", config.optimizeDeps?.exclude ?? [])) {
|
|
1554
|
-
const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
|
|
1555
|
-
log.debug(
|
|
1556
|
-
`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
|
|
1557
|
-
);
|
|
1558
|
-
include.push(...svelteImportsToInclude);
|
|
1559
|
-
} else {
|
|
1560
|
-
log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
|
|
1561
|
-
}
|
|
1562
|
-
const noExternal = [];
|
|
1563
|
-
const external = [];
|
|
1564
|
-
if (!isDepExternaled("svelte", config.ssr?.external ?? [])) {
|
|
1565
|
-
noExternal.push("svelte", /^svelte\//);
|
|
1566
|
-
}
|
|
1567
|
-
return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
|
|
1568
|
-
}
|
|
1569
|
-
function patchResolvedViteConfig(viteConfig, options) {
|
|
1570
|
-
if (options.preprocess) {
|
|
1571
|
-
for (const preprocessor of arraify(options.preprocess)) {
|
|
1572
|
-
if (preprocessor.style && "__resolvedConfig" in preprocessor.style) {
|
|
1573
|
-
preprocessor.style.__resolvedConfig = viteConfig;
|
|
1574
|
-
}
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
|
|
1578
|
-
(plugin) => plugin.name === facadeEsbuildSveltePluginName
|
|
1579
|
-
);
|
|
1580
|
-
if (facadeEsbuildSveltePlugin) {
|
|
1581
|
-
Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
function arraify(value) {
|
|
1585
|
-
return Array.isArray(value) ? value : [value];
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
// src/utils/watch.ts
|
|
1589
|
-
import fs4 from "fs";
|
|
1590
|
-
import path6 from "path";
|
|
1591
|
-
function setupWatchers(options, cache, requestParser) {
|
|
1592
|
-
const { server, configFile: svelteConfigFile } = options;
|
|
1593
|
-
if (!server) {
|
|
1594
|
-
return;
|
|
1595
|
-
}
|
|
1596
|
-
const { watcher, ws } = server;
|
|
1597
|
-
const { root, server: serverConfig } = server.config;
|
|
1598
|
-
const emitChangeEventOnDependants = (filename) => {
|
|
1599
|
-
const dependants = cache.getDependants(filename);
|
|
1600
|
-
dependants.forEach((dependant) => {
|
|
1601
|
-
if (fs4.existsSync(dependant)) {
|
|
1602
|
-
log.debug(
|
|
1603
|
-
`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
|
|
1604
|
-
);
|
|
1605
|
-
watcher.emit("change", dependant);
|
|
1606
|
-
}
|
|
1607
|
-
});
|
|
1608
|
-
};
|
|
1609
|
-
const removeUnlinkedFromCache = (filename) => {
|
|
1610
|
-
const svelteRequest = requestParser(filename, false);
|
|
1611
|
-
if (svelteRequest) {
|
|
1612
|
-
const removedFromCache = cache.remove(svelteRequest);
|
|
1613
|
-
if (removedFromCache) {
|
|
1614
|
-
log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
|
|
1615
|
-
}
|
|
1616
|
-
}
|
|
1617
|
-
};
|
|
1618
|
-
const triggerViteRestart = (filename) => {
|
|
1619
|
-
if (serverConfig.middlewareMode) {
|
|
1620
|
-
const message = "Svelte config change detected, restart your dev process to apply the changes.";
|
|
1621
|
-
log.info(message, filename);
|
|
1622
|
-
ws.send({
|
|
1623
|
-
type: "error",
|
|
1624
|
-
err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
|
|
1625
|
-
});
|
|
1626
|
-
} else {
|
|
1627
|
-
log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
|
|
1628
|
-
server.restart();
|
|
1629
|
-
}
|
|
1630
|
-
};
|
|
1631
|
-
const listenerCollection = {
|
|
1632
|
-
add: [],
|
|
1633
|
-
change: [emitChangeEventOnDependants],
|
|
1634
|
-
unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
|
|
1635
|
-
};
|
|
1636
|
-
if (svelteConfigFile !== false) {
|
|
1637
|
-
const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path6.join(root, cfg));
|
|
1638
|
-
const restartOnConfigAdd = (filename) => {
|
|
1639
|
-
if (possibleSvelteConfigs.includes(filename)) {
|
|
1640
|
-
triggerViteRestart(filename);
|
|
1641
|
-
}
|
|
1642
|
-
};
|
|
1643
|
-
const restartOnConfigChange = (filename) => {
|
|
1644
|
-
if (filename === svelteConfigFile) {
|
|
1645
|
-
triggerViteRestart(filename);
|
|
1646
|
-
}
|
|
1647
|
-
};
|
|
1648
|
-
if (svelteConfigFile) {
|
|
1649
|
-
listenerCollection.change.push(restartOnConfigChange);
|
|
1650
|
-
listenerCollection.unlink.push(restartOnConfigChange);
|
|
1651
|
-
} else {
|
|
1652
|
-
listenerCollection.add.push(restartOnConfigAdd);
|
|
1653
|
-
}
|
|
1654
|
-
}
|
|
1655
|
-
Object.entries(listenerCollection).forEach(([evt, listeners]) => {
|
|
1656
|
-
if (listeners.length > 0) {
|
|
1657
|
-
watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
|
|
1658
|
-
}
|
|
1659
|
-
});
|
|
1660
|
-
}
|
|
1661
|
-
function ensureWatchedFile(watcher, file, root) {
|
|
1662
|
-
if (file && // only need to watch if out of root
|
|
1663
|
-
!file.startsWith(root + "/") && // some rollup plugins use null bytes for private resolved Ids
|
|
1664
|
-
!file.includes("\0") && fs4.existsSync(file)) {
|
|
1665
|
-
watcher.add(path6.resolve(file));
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
|
-
|
|
1669
|
-
// src/utils/resolve.ts
|
|
1670
|
-
import path7 from "path";
|
|
1671
|
-
import { builtinModules } from "module";
|
|
1672
|
-
import { normalizePath as normalizePath4 } from "vite";
|
|
1673
|
-
async function resolveViaPackageJsonSvelte(importee, importer, cache) {
|
|
1674
|
-
if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
|
|
1675
|
-
const cached = cache.getResolvedSvelteField(importee, importer);
|
|
1676
|
-
if (cached) {
|
|
1677
|
-
return cached;
|
|
1678
|
-
}
|
|
1679
|
-
const pkgData = await resolveDependencyData(importee, importer);
|
|
1680
|
-
if (pkgData) {
|
|
1681
|
-
const { pkg, dir } = pkgData;
|
|
1682
|
-
if (pkg.svelte) {
|
|
1683
|
-
const result = normalizePath4(path7.resolve(dir, pkg.svelte));
|
|
1684
|
-
cache.setResolvedSvelteField(importee, importer, result);
|
|
1685
|
-
return result;
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
function isNodeInternal(importee) {
|
|
1691
|
-
return importee.startsWith("node:") || builtinModules.includes(importee);
|
|
1692
|
-
}
|
|
1693
|
-
function isBareImport(importee) {
|
|
1694
|
-
if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || path7.isAbsolute(importee)) {
|
|
1695
|
-
return false;
|
|
1696
|
-
}
|
|
1697
|
-
const parts = importee.split("/");
|
|
1698
|
-
switch (parts.length) {
|
|
1699
|
-
case 1:
|
|
1700
|
-
return true;
|
|
1701
|
-
case 2:
|
|
1702
|
-
return parts[0].startsWith("@");
|
|
1703
|
-
default:
|
|
1704
|
-
return false;
|
|
1705
|
-
}
|
|
1706
|
-
}
|
|
1707
|
-
|
|
1708
|
-
// src/utils/optimizer.ts
|
|
1709
|
-
import { promises as fs5 } from "fs";
|
|
1710
|
-
import path8 from "path";
|
|
1711
|
-
var PREBUNDLE_SENSITIVE_OPTIONS = [
|
|
1712
|
-
"compilerOptions",
|
|
1713
|
-
"configFile",
|
|
1714
|
-
"experimental",
|
|
1715
|
-
"extensions",
|
|
1716
|
-
"ignorePluginPreprocessors",
|
|
1717
|
-
"preprocess"
|
|
1718
|
-
];
|
|
1719
|
-
async function saveSvelteMetadata(cacheDir, options) {
|
|
1720
|
-
const svelteMetadata = generateSvelteMetadata(options);
|
|
1721
|
-
const svelteMetadataPath = path8.resolve(cacheDir, "_svelte_metadata.json");
|
|
1722
|
-
const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => {
|
|
1723
|
-
return typeof value === "function" ? value.toString() : value;
|
|
1724
|
-
});
|
|
1725
|
-
let existingSvelteMetadata;
|
|
1726
|
-
try {
|
|
1727
|
-
existingSvelteMetadata = await fs5.readFile(svelteMetadataPath, "utf8");
|
|
1728
|
-
} catch {
|
|
1729
|
-
}
|
|
1730
|
-
await fs5.mkdir(cacheDir, { recursive: true });
|
|
1731
|
-
await fs5.writeFile(svelteMetadataPath, currentSvelteMetadata);
|
|
1732
|
-
return currentSvelteMetadata !== existingSvelteMetadata;
|
|
1733
|
-
}
|
|
1734
|
-
function generateSvelteMetadata(options) {
|
|
1735
|
-
const metadata = {};
|
|
1736
|
-
for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
|
|
1737
|
-
metadata[key] = options[key];
|
|
1738
|
-
}
|
|
1739
|
-
return metadata;
|
|
1740
|
-
}
|
|
1741
|
-
|
|
1742
|
-
// src/ui/inspector/plugin.ts
|
|
1743
|
-
import { normalizePath as normalizePath5 } from "vite";
|
|
1744
|
-
import path9 from "path";
|
|
1745
|
-
import { fileURLToPath } from "url";
|
|
1746
|
-
import fs6 from "fs";
|
|
1747
|
-
|
|
1748
|
-
// src/ui/inspector/utils.ts
|
|
1749
|
-
var FS_PREFIX = `/@fs/`;
|
|
1750
|
-
var IS_WINDOWS3 = process.platform === "win32";
|
|
1751
|
-
var queryRE = /\?.*$/s;
|
|
1752
|
-
var hashRE = /#.*$/s;
|
|
1753
|
-
function idToFile(id) {
|
|
1754
|
-
if (id.startsWith(FS_PREFIX)) {
|
|
1755
|
-
id = id = id.slice(IS_WINDOWS3 ? FS_PREFIX.length : FS_PREFIX.length - 1);
|
|
1756
|
-
}
|
|
1757
|
-
return id.replace(hashRE, "").replace(queryRE, "");
|
|
1758
|
-
}
|
|
1759
|
-
|
|
1760
|
-
// src/ui/inspector/options.ts
|
|
1761
|
-
import * as process2 from "process";
|
|
1762
|
-
import { loadEnv } from "vite";
|
|
1763
|
-
var defaultInspectorOptions = {
|
|
1764
|
-
toggleKeyCombo: process2.platform === "darwin" ? "meta-shift" : "control-shift",
|
|
1765
|
-
navKeys: { parent: "ArrowUp", child: "ArrowDown", next: "ArrowRight", prev: "ArrowLeft" },
|
|
1766
|
-
openKey: "Enter",
|
|
1767
|
-
holdMode: true,
|
|
1768
|
-
showToggleButton: "active",
|
|
1769
|
-
toggleButtonPos: "top-right",
|
|
1770
|
-
customStyles: true
|
|
1771
|
-
};
|
|
1772
|
-
function parseEnvironmentOptions(config) {
|
|
1773
|
-
const env = loadEnv(config.mode, config.envDir ?? process2.cwd(), "SVELTE_INSPECTOR");
|
|
1774
|
-
const options = env?.SVELTE_INSPECTOR_OPTIONS;
|
|
1775
|
-
const toggle = env?.SVELTE_INSPECTOR_TOGGLE;
|
|
1776
|
-
if (options) {
|
|
1777
|
-
try {
|
|
1778
|
-
const parsed = JSON.parse(options);
|
|
1779
|
-
const parsedType = typeof parsed;
|
|
1780
|
-
if (parsedType === "boolean") {
|
|
1781
|
-
return parsed;
|
|
1782
|
-
} else if (parsedType === "object") {
|
|
1783
|
-
if (Array.isArray(parsed)) {
|
|
1784
|
-
throw new Error("invalid type, expected object map but got array");
|
|
1785
|
-
}
|
|
1786
|
-
const parsedKeys = Object.keys(parsed);
|
|
1787
|
-
const defaultKeys = Object.keys(defaultInspectorOptions);
|
|
1788
|
-
const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k));
|
|
1789
|
-
if (unknownKeys.length) {
|
|
1790
|
-
log.warn(
|
|
1791
|
-
`ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join(
|
|
1792
|
-
", "
|
|
1793
|
-
)}.`,
|
|
1794
|
-
void 0,
|
|
1795
|
-
"inspector"
|
|
1796
|
-
);
|
|
1797
|
-
for (const key of unknownKeys) {
|
|
1798
|
-
delete parsed[key];
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
log.debug("loaded environment config", parsed, "inspector");
|
|
1802
|
-
return parsed;
|
|
1803
|
-
}
|
|
1804
|
-
} catch (e) {
|
|
1805
|
-
log.error(
|
|
1806
|
-
`failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"`,
|
|
1807
|
-
e,
|
|
1808
|
-
"inspector"
|
|
1809
|
-
);
|
|
1810
|
-
}
|
|
1811
|
-
} else if (toggle) {
|
|
1812
|
-
const keyConfig = {
|
|
1813
|
-
toggleKeyCombo: toggle
|
|
1814
|
-
};
|
|
1815
|
-
log.debug("loaded environment config", keyConfig, "inspector");
|
|
1816
|
-
return keyConfig;
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
|
|
1820
|
-
// src/ui/inspector/plugin.ts
|
|
1821
|
-
function getInspectorPath() {
|
|
1822
|
-
const pluginPath = normalizePath5(path9.dirname(fileURLToPath(import.meta.url)));
|
|
1823
|
-
return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, "/vite-plugin-svelte/src/ui/inspector/");
|
|
1824
|
-
}
|
|
1825
|
-
function svelteInspector() {
|
|
1826
|
-
const inspectorPath = getInspectorPath();
|
|
1827
|
-
log.debug.enabled && log.debug(`svelte inspector path: ${inspectorPath}`);
|
|
1828
|
-
let inspectorOptions;
|
|
1829
|
-
let disabled = false;
|
|
1830
|
-
return {
|
|
1831
|
-
name: "vite-plugin-svelte:inspector",
|
|
1832
|
-
apply: "serve",
|
|
1833
|
-
enforce: "pre",
|
|
1834
|
-
configResolved(config) {
|
|
1835
|
-
const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte");
|
|
1836
|
-
if (!vps) {
|
|
1837
|
-
log.warn("vite-plugin-svelte is missing, inspector disabled", void 0, "inspector");
|
|
1838
|
-
disabled = true;
|
|
1839
|
-
return;
|
|
1840
|
-
}
|
|
1841
|
-
const configFileOptions = vps?.api?.options?.inspector;
|
|
1842
|
-
const environmentOptions = parseEnvironmentOptions(config);
|
|
1843
|
-
if (!configFileOptions && !environmentOptions) {
|
|
1844
|
-
log.debug("no options found, inspector disabled", void 0, "inspector");
|
|
1845
|
-
disabled = true;
|
|
1846
|
-
return;
|
|
1847
|
-
}
|
|
1848
|
-
if (environmentOptions === true) {
|
|
1849
|
-
inspectorOptions = defaultInspectorOptions;
|
|
1850
|
-
} else {
|
|
1851
|
-
inspectorOptions = {
|
|
1852
|
-
...defaultInspectorOptions,
|
|
1853
|
-
...configFileOptions,
|
|
1854
|
-
...environmentOptions || {}
|
|
1855
|
-
};
|
|
1856
|
-
}
|
|
1857
|
-
inspectorOptions.__internal = {
|
|
1858
|
-
base: config.base?.replace(/\/$/, "") || ""
|
|
1859
|
-
};
|
|
1860
|
-
},
|
|
1861
|
-
async resolveId(importee, importer, options) {
|
|
1862
|
-
if (options?.ssr || disabled) {
|
|
1863
|
-
return;
|
|
1864
|
-
}
|
|
1865
|
-
if (importee.startsWith("virtual:svelte-inspector-options")) {
|
|
1866
|
-
return importee;
|
|
1867
|
-
} else if (importee.startsWith("virtual:svelte-inspector-path:")) {
|
|
1868
|
-
const resolved = importee.replace("virtual:svelte-inspector-path:", inspectorPath);
|
|
1869
|
-
log.debug.enabled && log.debug(`resolved ${importee} with ${resolved}`, void 0, "inspector");
|
|
1870
|
-
return resolved;
|
|
1871
|
-
}
|
|
1872
|
-
},
|
|
1873
|
-
async load(id, options) {
|
|
1874
|
-
if (options?.ssr || disabled) {
|
|
1875
|
-
return;
|
|
1876
|
-
}
|
|
1877
|
-
if (id === "virtual:svelte-inspector-options") {
|
|
1878
|
-
return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
|
|
1879
|
-
} else if (id.startsWith(inspectorPath)) {
|
|
1880
|
-
const file = idToFile(id);
|
|
1881
|
-
if (fs6.existsSync(file)) {
|
|
1882
|
-
return await fs6.promises.readFile(file, "utf-8");
|
|
1883
|
-
} else {
|
|
1884
|
-
log.error(
|
|
1885
|
-
`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`,
|
|
1886
|
-
void 0,
|
|
1887
|
-
"inspector"
|
|
1888
|
-
);
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
},
|
|
1892
|
-
transform(code, id, options) {
|
|
1893
|
-
if (options?.ssr || disabled) {
|
|
1894
|
-
return;
|
|
1895
|
-
}
|
|
1896
|
-
if (id.includes("vite/dist/client/client.mjs")) {
|
|
1897
|
-
return { code: `${code}
|
|
1898
|
-
import('virtual:svelte-inspector-path:load-inspector.js')` };
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
};
|
|
1902
|
-
}
|
|
1903
|
-
|
|
1904
|
-
// src/utils/vite-plugin-svelte-cache.ts
|
|
1905
|
-
import { readFileSync as readFileSync2 } from "fs";
|
|
1906
|
-
import { dirname } from "path";
|
|
1907
|
-
import { findClosestPkgJsonPath } from "vitefu";
|
|
1908
|
-
import { normalizePath as normalizePath6 } from "vite";
|
|
1909
|
-
var VitePluginSvelteCache = class {
|
|
1910
|
-
constructor() {
|
|
1911
|
-
this._css = /* @__PURE__ */ new Map();
|
|
1912
|
-
this._js = /* @__PURE__ */ new Map();
|
|
1913
|
-
this._dependencies = /* @__PURE__ */ new Map();
|
|
1914
|
-
this._dependants = /* @__PURE__ */ new Map();
|
|
1915
|
-
this._resolvedSvelteFields = /* @__PURE__ */ new Map();
|
|
1916
|
-
this._errors = /* @__PURE__ */ new Map();
|
|
1917
|
-
this._packageInfos = [];
|
|
1918
|
-
}
|
|
1919
|
-
update(compileData) {
|
|
1920
|
-
this._errors.delete(compileData.normalizedFilename);
|
|
1921
|
-
this.updateCSS(compileData);
|
|
1922
|
-
this.updateJS(compileData);
|
|
1923
|
-
this.updateDependencies(compileData);
|
|
1924
|
-
}
|
|
1925
|
-
has(svelteRequest) {
|
|
1926
|
-
const id = svelteRequest.normalizedFilename;
|
|
1927
|
-
return this._errors.has(id) || this._js.has(id) || this._css.has(id);
|
|
1928
|
-
}
|
|
1929
|
-
setError(svelteRequest, error) {
|
|
1930
|
-
this.remove(svelteRequest, true);
|
|
1931
|
-
this._errors.set(svelteRequest.normalizedFilename, error);
|
|
1932
|
-
}
|
|
1933
|
-
updateCSS(compileData) {
|
|
1934
|
-
this._css.set(compileData.normalizedFilename, compileData.compiled.css);
|
|
1935
|
-
}
|
|
1936
|
-
updateJS(compileData) {
|
|
1937
|
-
if (!compileData.ssr) {
|
|
1938
|
-
this._js.set(compileData.normalizedFilename, compileData.compiled.js);
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
1941
|
-
updateDependencies(compileData) {
|
|
1942
|
-
const id = compileData.normalizedFilename;
|
|
1943
|
-
const prevDependencies = this._dependencies.get(id) || [];
|
|
1944
|
-
const dependencies = compileData.dependencies;
|
|
1945
|
-
this._dependencies.set(id, dependencies);
|
|
1946
|
-
const removed = prevDependencies.filter((d) => !dependencies.includes(d));
|
|
1947
|
-
const added = dependencies.filter((d) => !prevDependencies.includes(d));
|
|
1948
|
-
added.forEach((d) => {
|
|
1949
|
-
if (!this._dependants.has(d)) {
|
|
1950
|
-
this._dependants.set(d, /* @__PURE__ */ new Set());
|
|
1951
|
-
}
|
|
1952
|
-
this._dependants.get(d).add(compileData.filename);
|
|
1953
|
-
});
|
|
1954
|
-
removed.forEach((d) => {
|
|
1955
|
-
this._dependants.get(d).delete(compileData.filename);
|
|
1956
|
-
});
|
|
1957
|
-
}
|
|
1958
|
-
remove(svelteRequest, keepDependencies = false) {
|
|
1959
|
-
const id = svelteRequest.normalizedFilename;
|
|
1960
|
-
let removed = false;
|
|
1961
|
-
if (this._errors.delete(id)) {
|
|
1962
|
-
removed = true;
|
|
1963
|
-
}
|
|
1964
|
-
if (this._js.delete(id)) {
|
|
1965
|
-
removed = true;
|
|
1966
|
-
}
|
|
1967
|
-
if (this._css.delete(id)) {
|
|
1968
|
-
removed = true;
|
|
1969
|
-
}
|
|
1970
|
-
if (!keepDependencies) {
|
|
1971
|
-
const dependencies = this._dependencies.get(id);
|
|
1972
|
-
if (dependencies) {
|
|
1973
|
-
removed = true;
|
|
1974
|
-
dependencies.forEach((d) => {
|
|
1975
|
-
const dependants = this._dependants.get(d);
|
|
1976
|
-
if (dependants && dependants.has(svelteRequest.filename)) {
|
|
1977
|
-
dependants.delete(svelteRequest.filename);
|
|
1978
|
-
}
|
|
1979
|
-
});
|
|
1980
|
-
this._dependencies.delete(id);
|
|
1981
|
-
}
|
|
1982
|
-
}
|
|
1983
|
-
return removed;
|
|
1984
|
-
}
|
|
1985
|
-
getCSS(svelteRequest) {
|
|
1986
|
-
return this._css.get(svelteRequest.normalizedFilename);
|
|
1987
|
-
}
|
|
1988
|
-
getJS(svelteRequest) {
|
|
1989
|
-
if (!svelteRequest.ssr) {
|
|
1990
|
-
return this._js.get(svelteRequest.normalizedFilename);
|
|
1991
|
-
}
|
|
1992
|
-
}
|
|
1993
|
-
getError(svelteRequest) {
|
|
1994
|
-
return this._errors.get(svelteRequest.normalizedFilename);
|
|
1995
|
-
}
|
|
1996
|
-
getDependants(path10) {
|
|
1997
|
-
const dependants = this._dependants.get(path10);
|
|
1998
|
-
return dependants ? [...dependants] : [];
|
|
1999
|
-
}
|
|
2000
|
-
getResolvedSvelteField(name, importer) {
|
|
2001
|
-
return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
|
|
2002
|
-
}
|
|
2003
|
-
hasResolvedSvelteField(name, importer) {
|
|
2004
|
-
return this._resolvedSvelteFields.has(this._getResolvedSvelteFieldKey(name, importer));
|
|
2005
|
-
}
|
|
2006
|
-
setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
|
|
2007
|
-
this._resolvedSvelteFields.set(
|
|
2008
|
-
this._getResolvedSvelteFieldKey(importee, importer),
|
|
2009
|
-
resolvedSvelte
|
|
2010
|
-
);
|
|
2011
|
-
}
|
|
2012
|
-
_getResolvedSvelteFieldKey(importee, importer) {
|
|
2013
|
-
return importer ? `${importer} > ${importee}` : importee;
|
|
2014
|
-
}
|
|
2015
|
-
async getPackageInfo(file) {
|
|
2016
|
-
let info = this._packageInfos.find((pi) => file.startsWith(pi.path));
|
|
2017
|
-
if (!info) {
|
|
2018
|
-
info = await findPackageInfo(file);
|
|
2019
|
-
this._packageInfos.push(info);
|
|
2020
|
-
}
|
|
2021
|
-
return info;
|
|
2022
|
-
}
|
|
2023
|
-
};
|
|
2024
|
-
async function findPackageInfo(file) {
|
|
2025
|
-
const info = {
|
|
2026
|
-
name: "$unknown",
|
|
2027
|
-
version: "0.0.0-unknown",
|
|
2028
|
-
path: "$unknown"
|
|
2029
|
-
};
|
|
2030
|
-
let path10 = await findClosestPkgJsonPath(file, (pkgPath) => {
|
|
2031
|
-
const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
|
|
2032
|
-
if (pkg.name != null) {
|
|
2033
|
-
info.name = pkg.name;
|
|
2034
|
-
if (pkg.version != null) {
|
|
2035
|
-
info.version = pkg.version;
|
|
2036
|
-
}
|
|
2037
|
-
info.svelte = pkg.svelte;
|
|
2038
|
-
return true;
|
|
2039
|
-
}
|
|
2040
|
-
return false;
|
|
2041
|
-
});
|
|
2042
|
-
path10 = normalizePath6(dirname(path10 ?? file)) + "/";
|
|
2043
|
-
info.path = path10;
|
|
2044
|
-
return info;
|
|
2045
|
-
}
|
|
2046
|
-
|
|
2047
|
-
// src/utils/load-raw.ts
|
|
2048
|
-
import fs7 from "fs";
|
|
2049
|
-
async function loadRaw(svelteRequest, compileSvelte2, options) {
|
|
2050
|
-
const { id, filename, query } = svelteRequest;
|
|
2051
|
-
let compileData;
|
|
2052
|
-
const source = fs7.readFileSync(filename, "utf-8");
|
|
2053
|
-
try {
|
|
2054
|
-
svelteRequest.ssr = query.compilerOptions?.generate === "ssr";
|
|
2055
|
-
const type = query.type;
|
|
2056
|
-
compileData = await compileSvelte2(svelteRequest, source, {
|
|
2057
|
-
...options,
|
|
2058
|
-
// don't use dynamic vite-plugin-svelte defaults here to ensure stable result between ssr,dev and build
|
|
2059
|
-
compilerOptions: {
|
|
2060
|
-
dev: false,
|
|
2061
|
-
css: false,
|
|
2062
|
-
hydratable: false,
|
|
2063
|
-
enableSourcemap: query.sourcemap ? {
|
|
2064
|
-
js: type === "script" || type === "all",
|
|
2065
|
-
css: type === "style" || type === "all"
|
|
2066
|
-
} : false,
|
|
2067
|
-
...svelteRequest.query.compilerOptions
|
|
2068
|
-
},
|
|
2069
|
-
hot: false,
|
|
2070
|
-
emitCss: true
|
|
2071
|
-
});
|
|
2072
|
-
} catch (e) {
|
|
2073
|
-
throw toRollupError(e, options);
|
|
2074
|
-
}
|
|
2075
|
-
let result;
|
|
2076
|
-
if (query.type === "style") {
|
|
2077
|
-
result = compileData.compiled.css;
|
|
2078
|
-
} else if (query.type === "script") {
|
|
2079
|
-
result = compileData.compiled.js;
|
|
2080
|
-
} else if (query.type === "preprocessed") {
|
|
2081
|
-
result = compileData.preprocessed;
|
|
2082
|
-
} else if (query.type === "all" && query.raw) {
|
|
2083
|
-
return allToRawExports(compileData, source);
|
|
2084
|
-
} else {
|
|
2085
|
-
throw new Error(
|
|
2086
|
-
`invalid "type=${query.type}" in ${id}. supported are script, style, preprocessed, all`
|
|
2087
|
-
);
|
|
2088
|
-
}
|
|
2089
|
-
if (query.direct) {
|
|
2090
|
-
const supportedDirectTypes = ["script", "style"];
|
|
2091
|
-
if (!supportedDirectTypes.includes(query.type)) {
|
|
2092
|
-
throw new Error(
|
|
2093
|
-
`invalid "type=${query.type}" combined with direct in ${id}. supported are: ${supportedDirectTypes.join(", ")}`
|
|
2094
|
-
);
|
|
2095
|
-
}
|
|
2096
|
-
log.debug(`load returns direct result for ${id}`);
|
|
2097
|
-
let directOutput = result.code;
|
|
2098
|
-
if (query.sourcemap && result.map?.toUrl) {
|
|
2099
|
-
const map = `sourceMappingURL=${result.map.toUrl()}`;
|
|
2100
|
-
if (query.type === "style") {
|
|
2101
|
-
directOutput += `
|
|
2102
|
-
|
|
2103
|
-
/*# ${map} */
|
|
2104
|
-
`;
|
|
2105
|
-
} else if (query.type === "script") {
|
|
2106
|
-
directOutput += `
|
|
2107
|
-
|
|
2108
|
-
//# ${map}
|
|
2109
|
-
`;
|
|
2110
|
-
}
|
|
2111
|
-
}
|
|
2112
|
-
return directOutput;
|
|
2113
|
-
} else if (query.raw) {
|
|
2114
|
-
log.debug(`load returns raw result for ${id}`);
|
|
2115
|
-
return toRawExports(result);
|
|
2116
|
-
} else {
|
|
2117
|
-
throw new Error(`invalid raw mode in ${id}, supported are raw, direct`);
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
function allToRawExports(compileData, source) {
|
|
2121
|
-
const exports = {
|
|
2122
|
-
...compileData,
|
|
2123
|
-
...compileData.compiled,
|
|
2124
|
-
source
|
|
2125
|
-
};
|
|
2126
|
-
delete exports.compiled;
|
|
2127
|
-
delete exports.filename;
|
|
2128
|
-
return toRawExports(exports);
|
|
2129
|
-
}
|
|
2130
|
-
function toRawExports(object) {
|
|
2131
|
-
let exports = Object.entries(object).filter(([key, value]) => typeof value !== "function").sort(([a], [b]) => a < b ? -1 : a === b ? 0 : 1).map(([key, value]) => `export const ${key}=${JSON.stringify(value)}`).join("\n") + "\n";
|
|
2132
|
-
if (Object.prototype.hasOwnProperty.call(object, "code")) {
|
|
2133
|
-
exports += `export default code
|
|
2134
|
-
`;
|
|
2135
|
-
}
|
|
2136
|
-
return exports;
|
|
2137
|
-
}
|
|
2138
|
-
|
|
2139
|
-
// src/preprocess.ts
|
|
2140
|
-
import { preprocessCSS, resolveConfig, transformWithEsbuild } from "vite";
|
|
2141
|
-
var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss", "sss"];
|
|
2142
|
-
var supportedScriptLangs = ["ts"];
|
|
2143
|
-
var lang_sep = ".vite-preprocess.";
|
|
2144
|
-
function vitePreprocess(opts) {
|
|
2145
|
-
const preprocessor = {};
|
|
2146
|
-
if (opts?.script !== false) {
|
|
2147
|
-
preprocessor.script = viteScript().script;
|
|
2148
|
-
}
|
|
2149
|
-
if (opts?.style !== false) {
|
|
2150
|
-
const styleOpts = typeof opts?.style == "object" ? opts?.style : void 0;
|
|
2151
|
-
preprocessor.style = viteStyle(styleOpts).style;
|
|
2152
|
-
}
|
|
2153
|
-
return preprocessor;
|
|
2154
|
-
}
|
|
2155
|
-
function viteScript() {
|
|
2156
|
-
return {
|
|
2157
|
-
async script({ attributes, content, filename = "" }) {
|
|
2158
|
-
const lang = attributes.lang;
|
|
2159
|
-
if (!supportedScriptLangs.includes(lang))
|
|
2160
|
-
return;
|
|
2161
|
-
const { code, map } = await transformWithEsbuild(content, filename, {
|
|
2162
|
-
loader: lang,
|
|
2163
|
-
target: "esnext",
|
|
2164
|
-
tsconfigRaw: {
|
|
2165
|
-
compilerOptions: {
|
|
2166
|
-
// svelte typescript needs this flag to work with type imports
|
|
2167
|
-
importsNotUsedAsValues: "preserve",
|
|
2168
|
-
preserveValueImports: true
|
|
2169
|
-
}
|
|
2170
|
-
}
|
|
2171
|
-
});
|
|
2172
|
-
mapToRelative(map, filename);
|
|
2173
|
-
return {
|
|
2174
|
-
code,
|
|
2175
|
-
map
|
|
2176
|
-
};
|
|
2177
|
-
}
|
|
2178
|
-
};
|
|
2179
|
-
}
|
|
2180
|
-
function viteStyle(config = {}) {
|
|
2181
|
-
let transform;
|
|
2182
|
-
const style = async ({ attributes, content, filename = "" }) => {
|
|
2183
|
-
const lang = attributes.lang;
|
|
2184
|
-
if (!supportedStyleLangs.includes(lang))
|
|
2185
|
-
return;
|
|
2186
|
-
if (!transform) {
|
|
2187
|
-
let resolvedConfig;
|
|
2188
|
-
if (style.__resolvedConfig) {
|
|
2189
|
-
resolvedConfig = style.__resolvedConfig;
|
|
2190
|
-
} else if (isResolvedConfig(config)) {
|
|
2191
|
-
resolvedConfig = config;
|
|
2192
|
-
} else {
|
|
2193
|
-
resolvedConfig = await resolveConfig(
|
|
2194
|
-
config,
|
|
2195
|
-
process.env.NODE_ENV === "production" ? "build" : "serve"
|
|
2196
|
-
);
|
|
2197
|
-
}
|
|
2198
|
-
transform = getCssTransformFn(resolvedConfig);
|
|
2199
|
-
}
|
|
2200
|
-
const suffix = `${lang_sep}${lang}`;
|
|
2201
|
-
const moduleId = `${filename}${suffix}`;
|
|
2202
|
-
const { code, map, deps } = await transform(content, moduleId);
|
|
2203
|
-
removeLangSuffix(map, suffix);
|
|
2204
|
-
mapToRelative(map, filename);
|
|
2205
|
-
const dependencies = deps ? Array.from(deps).filter((d) => !d.endsWith(suffix)) : void 0;
|
|
2206
|
-
return {
|
|
2207
|
-
code,
|
|
2208
|
-
map: map ?? void 0,
|
|
2209
|
-
dependencies
|
|
2210
|
-
};
|
|
2211
|
-
};
|
|
2212
|
-
style.__resolvedConfig = null;
|
|
2213
|
-
return { style };
|
|
2214
|
-
}
|
|
2215
|
-
function getCssTransformFn(config) {
|
|
2216
|
-
return async (code, filename) => {
|
|
2217
|
-
return preprocessCSS(code, filename, config);
|
|
2218
|
-
};
|
|
2219
|
-
}
|
|
2220
|
-
function isResolvedConfig(config) {
|
|
2221
|
-
return !!config.inlineConfig;
|
|
2222
|
-
}
|
|
2223
|
-
|
|
2224
|
-
// src/index.ts
|
|
2225
|
-
var isVite4_0 = viteVersion.startsWith("4.0");
|
|
2226
|
-
var isSvelte3 = svelteVersion.startsWith("3");
|
|
2227
|
-
function svelte(inlineOptions) {
|
|
2228
|
-
if (process.env.DEBUG != null) {
|
|
2229
|
-
log.setLevel("debug");
|
|
2230
|
-
}
|
|
2231
|
-
validateInlineOptions(inlineOptions);
|
|
2232
|
-
const cache = new VitePluginSvelteCache();
|
|
2233
|
-
let requestParser;
|
|
2234
|
-
let options;
|
|
2235
|
-
let viteConfig;
|
|
2236
|
-
let compileSvelte2;
|
|
2237
|
-
let resolvedSvelteSSR;
|
|
2238
|
-
let packagesWithResolveWarnings;
|
|
2239
|
-
const api = {};
|
|
2240
|
-
const plugins = [
|
|
2241
|
-
{
|
|
2242
|
-
name: "vite-plugin-svelte",
|
|
2243
|
-
// make sure our resolver runs before vite internal resolver to resolve svelte field correctly
|
|
2244
|
-
enforce: "pre",
|
|
2245
|
-
api,
|
|
2246
|
-
async config(config, configEnv) {
|
|
2247
|
-
if (process.env.DEBUG) {
|
|
2248
|
-
log.setLevel("debug");
|
|
2249
|
-
} else if (config.logLevel) {
|
|
2250
|
-
log.setLevel(config.logLevel);
|
|
2251
|
-
}
|
|
2252
|
-
options = await preResolveOptions(inlineOptions, config, configEnv);
|
|
2253
|
-
const extraViteConfig = await buildExtraViteConfig(options, config);
|
|
2254
|
-
log.debug("additional vite config", extraViteConfig);
|
|
2255
|
-
return extraViteConfig;
|
|
2256
|
-
},
|
|
2257
|
-
async configResolved(config) {
|
|
2258
|
-
options = resolveOptions(options, config, cache);
|
|
2259
|
-
patchResolvedViteConfig(config, options);
|
|
2260
|
-
requestParser = buildIdParser(options);
|
|
2261
|
-
compileSvelte2 = createCompileSvelte(options);
|
|
2262
|
-
viteConfig = config;
|
|
2263
|
-
api.options = options;
|
|
2264
|
-
log.debug("resolved options", options);
|
|
2265
|
-
},
|
|
2266
|
-
async buildStart() {
|
|
2267
|
-
packagesWithResolveWarnings = /* @__PURE__ */ new Set();
|
|
2268
|
-
if (!options.prebundleSvelteLibraries)
|
|
2269
|
-
return;
|
|
2270
|
-
const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options);
|
|
2271
|
-
if (isSvelteMetadataChanged) {
|
|
2272
|
-
viteConfig.optimizeDeps.force = true;
|
|
2273
|
-
}
|
|
2274
|
-
},
|
|
2275
|
-
configureServer(server) {
|
|
2276
|
-
options.server = server;
|
|
2277
|
-
setupWatchers(options, cache, requestParser);
|
|
2278
|
-
},
|
|
2279
|
-
async load(id, opts) {
|
|
2280
|
-
const ssr = !!opts?.ssr;
|
|
2281
|
-
const svelteRequest = requestParser(id, !!ssr);
|
|
2282
|
-
if (svelteRequest) {
|
|
2283
|
-
const { filename, query, raw } = svelteRequest;
|
|
2284
|
-
if (raw) {
|
|
2285
|
-
return loadRaw(svelteRequest, compileSvelte2, options);
|
|
2286
|
-
} else {
|
|
2287
|
-
if (query.svelte && query.type === "style") {
|
|
2288
|
-
const css = cache.getCSS(svelteRequest);
|
|
2289
|
-
if (css) {
|
|
2290
|
-
log.debug(`load returns css for ${filename}`);
|
|
2291
|
-
return css;
|
|
2292
|
-
}
|
|
2293
|
-
}
|
|
2294
|
-
if (viteConfig.assetsInclude(filename)) {
|
|
2295
|
-
log.debug(`load returns raw content for ${filename}`);
|
|
2296
|
-
return fs8.readFileSync(filename, "utf-8");
|
|
2297
|
-
}
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
|
-
},
|
|
2301
|
-
async resolveId(importee, importer, opts) {
|
|
2302
|
-
const ssr = !!opts?.ssr;
|
|
2303
|
-
const svelteRequest = requestParser(importee, ssr);
|
|
2304
|
-
if (svelteRequest?.query.svelte) {
|
|
2305
|
-
if (svelteRequest.query.type === "style" && !svelteRequest.raw) {
|
|
2306
|
-
log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
|
|
2307
|
-
return svelteRequest.cssId;
|
|
2308
|
-
}
|
|
2309
|
-
}
|
|
2310
|
-
if (isVite4_0 && isSvelte3 && ssr && importee === "svelte") {
|
|
2311
|
-
if (!resolvedSvelteSSR) {
|
|
2312
|
-
resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then(
|
|
2313
|
-
(svelteSSR) => {
|
|
2314
|
-
log.debug("resolved svelte to svelte/ssr");
|
|
2315
|
-
return svelteSSR;
|
|
2316
|
-
},
|
|
2317
|
-
(err) => {
|
|
2318
|
-
log.debug(
|
|
2319
|
-
"failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it",
|
|
2320
|
-
err
|
|
2321
|
-
);
|
|
2322
|
-
return null;
|
|
2323
|
-
}
|
|
2324
|
-
);
|
|
2325
|
-
}
|
|
2326
|
-
return resolvedSvelteSSR;
|
|
2327
|
-
}
|
|
2328
|
-
const scan = !!opts?.scan;
|
|
2329
|
-
const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !isDepExcluded2(importee, viteConfig.optimizeDeps?.exclude ?? []);
|
|
2330
|
-
if (ssr || scan || !isPrebundled) {
|
|
2331
|
-
try {
|
|
2332
|
-
const isFirstResolve = !cache.hasResolvedSvelteField(importee, importer);
|
|
2333
|
-
const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
|
|
2334
|
-
if (isFirstResolve && resolved) {
|
|
2335
|
-
const packageInfo = await cache.getPackageInfo(resolved);
|
|
2336
|
-
const packageVersion = `${packageInfo.name}@${packageInfo.version}`;
|
|
2337
|
-
log.debug.once(
|
|
2338
|
-
`resolveId resolved ${importee} to ${resolved} via package.json svelte field of ${packageVersion}`
|
|
2339
|
-
);
|
|
2340
|
-
try {
|
|
2341
|
-
const viteResolved = (await this.resolve(importee, importer, { ...opts, skipSelf: true }))?.id;
|
|
2342
|
-
if (resolved !== viteResolved) {
|
|
2343
|
-
packagesWithResolveWarnings.add(packageVersion);
|
|
2344
|
-
log.debug.enabled && log.debug.once(
|
|
2345
|
-
`resolve difference for ${packageVersion} ${importee} - svelte: "${resolved}", vite: "${viteResolved}"`
|
|
2346
|
-
);
|
|
2347
|
-
}
|
|
2348
|
-
} catch (e) {
|
|
2349
|
-
packagesWithResolveWarnings.add(packageVersion);
|
|
2350
|
-
log.debug.enabled && log.debug.once(
|
|
2351
|
-
`resolve error for ${packageVersion} ${importee} - svelte: "${resolved}", vite: ERROR`,
|
|
2352
|
-
e
|
|
2353
|
-
);
|
|
2354
|
-
}
|
|
2355
|
-
}
|
|
2356
|
-
return resolved;
|
|
2357
|
-
} catch (e) {
|
|
2358
|
-
log.debug.once(
|
|
2359
|
-
`error trying to resolve ${importee} from ${importer} via package.json svelte field `,
|
|
2360
|
-
e
|
|
2361
|
-
);
|
|
2362
|
-
}
|
|
2363
|
-
}
|
|
2364
|
-
},
|
|
2365
|
-
async transform(code, id, opts) {
|
|
2366
|
-
const ssr = !!opts?.ssr;
|
|
2367
|
-
const svelteRequest = requestParser(id, ssr);
|
|
2368
|
-
if (!svelteRequest || svelteRequest.query.type === "style" || svelteRequest.raw) {
|
|
2369
|
-
return;
|
|
2370
|
-
}
|
|
2371
|
-
let compileData;
|
|
2372
|
-
try {
|
|
2373
|
-
compileData = await compileSvelte2(svelteRequest, code, options);
|
|
2374
|
-
} catch (e) {
|
|
2375
|
-
cache.setError(svelteRequest, e);
|
|
2376
|
-
throw toRollupError(e, options);
|
|
2377
|
-
}
|
|
2378
|
-
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
|
|
2379
|
-
cache.update(compileData);
|
|
2380
|
-
if (compileData.dependencies?.length && options.server) {
|
|
2381
|
-
compileData.dependencies.forEach((d) => {
|
|
2382
|
-
ensureWatchedFile(options.server.watcher, d, options.root);
|
|
2383
|
-
});
|
|
2384
|
-
}
|
|
2385
|
-
log.debug(`transform returns compiled js for ${svelteRequest.filename}`);
|
|
2386
|
-
return {
|
|
2387
|
-
...compileData.compiled.js,
|
|
2388
|
-
meta: {
|
|
2389
|
-
vite: {
|
|
2390
|
-
lang: compileData.lang
|
|
2391
|
-
}
|
|
2392
|
-
}
|
|
2393
|
-
};
|
|
2394
|
-
},
|
|
2395
|
-
handleHotUpdate(ctx) {
|
|
2396
|
-
if (!options.hot || !options.emitCss) {
|
|
2397
|
-
return;
|
|
2398
|
-
}
|
|
2399
|
-
const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
|
|
2400
|
-
if (svelteRequest) {
|
|
2401
|
-
return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
|
|
2402
|
-
}
|
|
2403
|
-
},
|
|
2404
|
-
async buildEnd() {
|
|
2405
|
-
await options.stats?.finishAll();
|
|
2406
|
-
if (!options.experimental?.disableSvelteResolveWarnings && packagesWithResolveWarnings?.size > 0) {
|
|
2407
|
-
log.warn(
|
|
2408
|
-
`WARNING: The following packages use a svelte resolve configuration in package.json that has conflicting results and is going to cause problems future.
|
|
2409
|
-
|
|
2410
|
-
${[
|
|
2411
|
-
...packagesWithResolveWarnings
|
|
2412
|
-
].join("\n")}
|
|
2413
|
-
|
|
2414
|
-
Please see ${FAQ_LINK_CONFLICTS_IN_SVELTE_RESOLVE} for details.`
|
|
2415
|
-
);
|
|
2416
|
-
}
|
|
2417
|
-
}
|
|
2418
|
-
},
|
|
2419
|
-
svelteInspector()
|
|
2420
|
-
];
|
|
2421
|
-
return plugins;
|
|
2422
|
-
}
|
|
2423
|
-
export {
|
|
2424
|
-
loadSvelteConfig,
|
|
2425
|
-
svelte,
|
|
2426
|
-
vitePreprocess
|
|
2427
|
-
};
|
|
2428
|
-
//# sourceMappingURL=index.js.map
|