1180 lines
41 KiB
JavaScript
1180 lines
41 KiB
JavaScript
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __defProps = Object.defineProperties;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
var __spreadValues = (a, b) => {
|
|
for (var prop in b || (b = {}))
|
|
if (__hasOwnProp.call(b, prop))
|
|
__defNormalProp(a, prop, b[prop]);
|
|
if (__getOwnPropSymbols)
|
|
for (var prop of __getOwnPropSymbols(b)) {
|
|
if (__propIsEnum.call(b, prop))
|
|
__defNormalProp(a, prop, b[prop]);
|
|
}
|
|
return a;
|
|
};
|
|
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
|
|
var __export = (target, all) => {
|
|
__markAsModule(target);
|
|
for (var name in all)
|
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
};
|
|
var __reExport = (target, module2, desc) => {
|
|
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
|
|
for (let key of __getOwnPropNames(module2))
|
|
if (!__hasOwnProp.call(target, key) && key !== "default")
|
|
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
|
|
}
|
|
return target;
|
|
};
|
|
var __toModule = (module2) => {
|
|
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
|
|
};
|
|
|
|
// src/index.ts
|
|
__export(exports, {
|
|
svelte: () => svelte
|
|
});
|
|
var import_fs4 = __toModule(require("fs"));
|
|
|
|
// src/utils/log.ts
|
|
var import_colors = __toModule(require("kleur/colors"));
|
|
var import_debug = __toModule(require("debug"));
|
|
var levels = ["debug", "info", "warn", "error", "silent"];
|
|
var prefix = "vite-plugin-svelte";
|
|
var loggers = {
|
|
debug: {
|
|
log: (0, import_debug.default)(`vite:${prefix}`),
|
|
enabled: false,
|
|
isDebug: true
|
|
},
|
|
info: {
|
|
color: import_colors.cyan,
|
|
log: console.log,
|
|
enabled: true
|
|
},
|
|
warn: {
|
|
color: import_colors.yellow,
|
|
log: console.warn,
|
|
enabled: true
|
|
},
|
|
error: {
|
|
color: import_colors.red,
|
|
log: console.error,
|
|
enabled: true
|
|
},
|
|
silent: {
|
|
enabled: false
|
|
}
|
|
};
|
|
var _level = "info";
|
|
function setLevel(level) {
|
|
if (level === _level) {
|
|
return;
|
|
}
|
|
const levelIndex = levels.indexOf(level);
|
|
if (levelIndex > -1) {
|
|
_level = level;
|
|
for (let i = 0; i < levels.length; i++) {
|
|
loggers[levels[i]].enabled = i >= levelIndex;
|
|
}
|
|
} else {
|
|
_log(loggers.error, `invalid log level: ${level} `);
|
|
}
|
|
}
|
|
function _log(logger, message, payload) {
|
|
if (!logger.enabled) {
|
|
return;
|
|
}
|
|
if (logger.isDebug) {
|
|
payload !== void 0 ? logger.log(message, payload) : logger.log(message);
|
|
} else {
|
|
logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
|
|
if (payload) {
|
|
logger.log(payload);
|
|
}
|
|
}
|
|
}
|
|
function createLogger(level) {
|
|
const logger = loggers[level];
|
|
const logFn = _log.bind(null, logger);
|
|
const logged = new Set();
|
|
const once = function(message, payload) {
|
|
if (logged.has(message)) {
|
|
return;
|
|
}
|
|
logged.add(message);
|
|
logFn.apply(null, [message, payload]);
|
|
};
|
|
Object.defineProperty(logFn, "enabled", {
|
|
get() {
|
|
return logger.enabled;
|
|
}
|
|
});
|
|
Object.defineProperty(logFn, "once", {
|
|
get() {
|
|
return once;
|
|
}
|
|
});
|
|
return logFn;
|
|
}
|
|
var log = {
|
|
debug: createLogger("debug"),
|
|
info: createLogger("info"),
|
|
warn: createLogger("warn"),
|
|
error: createLogger("error"),
|
|
setLevel
|
|
};
|
|
function logCompilerWarnings(warnings, options) {
|
|
const { emitCss, onwarn, isBuild } = options;
|
|
const warn = isBuild ? warnBuild : warnDev;
|
|
warnings == null ? void 0 : warnings.forEach((warning) => {
|
|
if (!emitCss && warning.code === "css-unused-selector") {
|
|
return;
|
|
}
|
|
if (onwarn) {
|
|
onwarn(warning, warn);
|
|
} else {
|
|
warn(warning);
|
|
}
|
|
});
|
|
}
|
|
function warnDev(w) {
|
|
log.info.enabled && log.info(buildExtendedLogMessage(w));
|
|
}
|
|
function warnBuild(w) {
|
|
log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
|
|
}
|
|
function buildExtendedLogMessage(w) {
|
|
const parts = [];
|
|
if (w.filename) {
|
|
parts.push(w.filename);
|
|
}
|
|
if (w.start) {
|
|
parts.push(":", w.start.line, ":", w.start.column);
|
|
}
|
|
if (w.message) {
|
|
parts.push(" ", w.message);
|
|
}
|
|
return parts.join("");
|
|
}
|
|
|
|
// src/handle-hot-update.ts
|
|
async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) {
|
|
const { read, server } = ctx;
|
|
const cachedJS = cache.getJS(svelteRequest);
|
|
if (!cachedJS) {
|
|
log.debug(`handleHotUpdate first call ${svelteRequest.id}`);
|
|
return;
|
|
}
|
|
const cachedCss = cache.getCSS(svelteRequest);
|
|
const content = await read();
|
|
const compileData = await compileSvelte(svelteRequest, content, options);
|
|
cache.update(compileData);
|
|
const affectedModules = new Set();
|
|
const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
|
|
const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
|
|
const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
|
|
if (cssUpdated) {
|
|
log.debug("handleHotUpdate css changed");
|
|
affectedModules.add(cssModule);
|
|
}
|
|
const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
|
|
if (jsUpdated) {
|
|
log.debug("handleHotUpdate js changed");
|
|
affectedModules.add(mainModule);
|
|
}
|
|
if (!jsUpdated) {
|
|
logCompilerWarnings(compileData.compiled.warnings, options);
|
|
}
|
|
const result = [...affectedModules].filter(Boolean);
|
|
const ssrModulesToInvalidate = result.filter((m) => !!m.ssrTransformResult);
|
|
if (ssrModulesToInvalidate.length > 0) {
|
|
log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
|
|
ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
|
|
}
|
|
if (result.length > 0) {
|
|
log.debug(`handleHotUpdate for ${svelteRequest.id} result: ${result.map((m) => m.id).join(", ")}`);
|
|
}
|
|
return result;
|
|
}
|
|
function cssChanged(prev, next) {
|
|
return !isCodeEqual(prev == null ? void 0 : prev.code, next == null ? void 0 : next.code);
|
|
}
|
|
function jsChanged(prev, next, filename) {
|
|
const prevJs = prev == null ? void 0 : prev.code;
|
|
const nextJs = next == null ? void 0 : next.code;
|
|
const isStrictEqual = isCodeEqual(prevJs, nextJs);
|
|
if (isStrictEqual) {
|
|
return false;
|
|
}
|
|
const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
|
|
if (!isStrictEqual && isLooseEqual) {
|
|
log.warn(`ignoring compiler output js change for ${filename} as it is equal to previous output after normalization`);
|
|
}
|
|
return !isLooseEqual;
|
|
}
|
|
function isCodeEqual(prev, next) {
|
|
if (!prev && !next) {
|
|
return true;
|
|
}
|
|
if (!prev && next || prev && !next) {
|
|
return false;
|
|
}
|
|
return prev === next;
|
|
}
|
|
function normalizeJsCode(code) {
|
|
if (!code) {
|
|
return code;
|
|
}
|
|
return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, "");
|
|
}
|
|
|
|
// src/utils/compile.ts
|
|
var import_compiler = __toModule(require("svelte/compiler"));
|
|
var import_svelte_hmr = __toModule(require("svelte-hmr"));
|
|
|
|
// src/utils/hash.ts
|
|
var crypto = __toModule(require("crypto"));
|
|
var hashes = Object.create(null);
|
|
var hash_length = 12;
|
|
function safeBase64Hash(input) {
|
|
if (hashes[input]) {
|
|
return hashes[input];
|
|
}
|
|
const md5 = crypto.createHash("md5");
|
|
md5.update(input);
|
|
const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
|
|
hashes[input] = hash;
|
|
return hash;
|
|
}
|
|
var replacements = {
|
|
"+": "-",
|
|
"/": "_",
|
|
"=": ""
|
|
};
|
|
var replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
|
|
function toSafe(base64) {
|
|
return base64.replace(replaceRE, (x) => replacements[x]);
|
|
}
|
|
|
|
// src/utils/compile.ts
|
|
var _createCompileSvelte = (makeHot) => async function compileSvelte(svelteRequest, code, options) {
|
|
var _a, _b;
|
|
const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
|
|
const { emitCss = true } = options;
|
|
const dependencies = [];
|
|
const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
|
|
filename,
|
|
generate: ssr ? "ssr" : "dom"
|
|
});
|
|
if (options.hot && options.emitCss) {
|
|
const hash = `s-${safeBase64Hash(normalizedFilename)}`;
|
|
log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
|
|
compileOptions.cssHash = () => hash;
|
|
}
|
|
let preprocessed;
|
|
if (options.preprocess) {
|
|
preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
|
|
if (preprocessed.dependencies)
|
|
dependencies.push(...preprocessed.dependencies);
|
|
if (preprocessed.map)
|
|
compileOptions.sourcemap = preprocessed.map;
|
|
}
|
|
const finalCode = preprocessed ? preprocessed.code : code;
|
|
const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
|
|
filename,
|
|
code: finalCode,
|
|
compileOptions
|
|
}));
|
|
if (dynamicCompileOptions && log.debug.enabled) {
|
|
log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
|
|
}
|
|
const finalCompileOptions = dynamicCompileOptions ? __spreadValues(__spreadValues({}, compileOptions), dynamicCompileOptions) : compileOptions;
|
|
const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
|
|
if (emitCss && compiled.css.code) {
|
|
compiled.js.code += `
|
|
import ${JSON.stringify(cssId)};
|
|
`;
|
|
}
|
|
if (!ssr && makeHot) {
|
|
compiled.js.code = makeHot({
|
|
id: filename,
|
|
compiledCode: compiled.js.code,
|
|
hotOptions: options.hot,
|
|
compiled,
|
|
originalCode: code,
|
|
compileOptions: finalCompileOptions
|
|
});
|
|
}
|
|
compiled.js.dependencies = dependencies;
|
|
return {
|
|
filename,
|
|
normalizedFilename,
|
|
compiled,
|
|
ssr,
|
|
dependencies
|
|
};
|
|
};
|
|
function buildMakeHot(options) {
|
|
var _a, _b;
|
|
const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
|
|
if (needsMakeHot) {
|
|
const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
|
|
const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
|
|
return (0, import_svelte_hmr.createMakeHot)({
|
|
walk: import_compiler.walk,
|
|
hotApi,
|
|
adapter,
|
|
hotOptions: __spreadValues({ noOverlay: true }, options.hot)
|
|
});
|
|
}
|
|
}
|
|
function createCompileSvelte(options) {
|
|
const makeHot = buildMakeHot(options);
|
|
return _createCompileSvelte(makeHot);
|
|
}
|
|
|
|
// src/utils/id.ts
|
|
var import_pluginutils = __toModule(require("@rollup/pluginutils"));
|
|
var import_vite = __toModule(require("vite"));
|
|
var fs = __toModule(require("fs"));
|
|
var VITE_FS_PREFIX = "/@fs/";
|
|
var IS_WINDOWS = process.platform === "win32";
|
|
function splitId(id) {
|
|
const parts = id.split(`?`, 2);
|
|
const filename = parts[0];
|
|
const rawQuery = parts[1];
|
|
return { filename, rawQuery };
|
|
}
|
|
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
|
|
const query = parseRequestQuery(rawQuery);
|
|
if (query.url || query.raw) {
|
|
return;
|
|
}
|
|
const normalizedFilename = normalize(filename, root);
|
|
const cssId = createVirtualImportId(filename, root, "style");
|
|
return {
|
|
id,
|
|
filename,
|
|
normalizedFilename,
|
|
cssId,
|
|
query,
|
|
timestamp,
|
|
ssr
|
|
};
|
|
}
|
|
function createVirtualImportId(filename, root, type) {
|
|
const parts = ["svelte", `type=${type}`];
|
|
if (type === "style") {
|
|
parts.push("lang.css");
|
|
}
|
|
if (existsInRoot(filename, root)) {
|
|
filename = root + filename;
|
|
} else if (filename.startsWith(VITE_FS_PREFIX)) {
|
|
filename = IS_WINDOWS ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
|
|
}
|
|
return `${filename}?${parts.join("&")}`;
|
|
}
|
|
function parseRequestQuery(rawQuery) {
|
|
const query = Object.fromEntries(new URLSearchParams(rawQuery));
|
|
for (const key in query) {
|
|
if (query[key] === "") {
|
|
query[key] = true;
|
|
}
|
|
}
|
|
return query;
|
|
}
|
|
function normalize(filename, normalizedRoot) {
|
|
return stripRoot((0, import_vite.normalizePath)(filename), normalizedRoot);
|
|
}
|
|
function existsInRoot(filename, root) {
|
|
if (filename.startsWith(VITE_FS_PREFIX)) {
|
|
return false;
|
|
}
|
|
return fs.existsSync(root + filename);
|
|
}
|
|
function stripRoot(normalizedFilename, normalizedRoot) {
|
|
return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
|
|
}
|
|
function buildFilter(include, exclude, extensions) {
|
|
const rollupFilter = (0, import_pluginutils.createFilter)(include, exclude);
|
|
return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
|
|
}
|
|
function buildIdParser(options) {
|
|
const { include, exclude, extensions, root } = options;
|
|
const normalizedRoot = (0, import_vite.normalizePath)(root);
|
|
const filter = buildFilter(include, exclude, extensions);
|
|
return (id, ssr, timestamp = Date.now()) => {
|
|
const { filename, rawQuery } = splitId(id);
|
|
if (filter(filename)) {
|
|
return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
|
|
}
|
|
};
|
|
}
|
|
|
|
// src/utils/options.ts
|
|
var import_vite2 = __toModule(require("vite"));
|
|
|
|
// src/utils/load-svelte-config.ts
|
|
var import_path = __toModule(require("path"));
|
|
var import_fs = __toModule(require("fs"));
|
|
var import_url = __toModule(require("url"));
|
|
var knownSvelteConfigNames = [
|
|
"svelte.config.js",
|
|
"svelte.config.cjs",
|
|
"svelte.config.mjs"
|
|
];
|
|
var dynamicImportDefault = new Function("path", 'return import(path + "?t=" + Date.now()).then(m => m.default)');
|
|
async function loadSvelteConfig(viteConfig, inlineOptions) {
|
|
const configFile = findConfigToLoad(viteConfig, inlineOptions);
|
|
if (configFile) {
|
|
let err;
|
|
if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
|
|
try {
|
|
const result = await dynamicImportDefault((0, import_url.pathToFileURL)(configFile).href);
|
|
if (result != null) {
|
|
return __spreadProps(__spreadValues({}, result), {
|
|
configFile
|
|
});
|
|
} else {
|
|
throw new Error(`invalid export in ${configFile}`);
|
|
}
|
|
} catch (e) {
|
|
log.error(`failed to import config ${configFile}`, e);
|
|
err = e;
|
|
}
|
|
}
|
|
if (!configFile.endsWith(".mjs")) {
|
|
try {
|
|
delete require.cache[require.resolve(configFile)];
|
|
const result = require(configFile);
|
|
if (result != null) {
|
|
return __spreadProps(__spreadValues({}, result), {
|
|
configFile
|
|
});
|
|
} else {
|
|
throw new Error(`invalid export in ${configFile}`);
|
|
}
|
|
} catch (e) {
|
|
log.error(`failed to require config ${configFile}`, e);
|
|
if (!err) {
|
|
err = e;
|
|
}
|
|
}
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
function findConfigToLoad(viteConfig, inlineOptions) {
|
|
const root = viteConfig.root || process.cwd();
|
|
if (inlineOptions.configFile) {
|
|
const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile);
|
|
if (!import_fs.default.existsSync(abolutePath)) {
|
|
throw new Error(`failed to find svelte config file ${abolutePath}.`);
|
|
}
|
|
return abolutePath;
|
|
} else {
|
|
const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file));
|
|
if (existingKnownConfigFiles.length === 0) {
|
|
log.debug(`no svelte config found at ${root}`);
|
|
return;
|
|
} else if (existingKnownConfigFiles.length > 1) {
|
|
log.warn(`found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`, existingKnownConfigFiles);
|
|
}
|
|
return existingKnownConfigFiles[0];
|
|
}
|
|
}
|
|
|
|
// src/utils/constants.ts
|
|
var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
|
|
var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
|
|
var SVELTE_IMPORTS = [
|
|
"svelte/animate",
|
|
"svelte/easing",
|
|
"svelte/internal",
|
|
"svelte/motion",
|
|
"svelte/store",
|
|
"svelte/transition",
|
|
"svelte"
|
|
];
|
|
var SVELTE_HMR_IMPORTS = [
|
|
"svelte-hmr/runtime/hot-api-esm.js",
|
|
"svelte-hmr/runtime/proxy-adapter-dom.js",
|
|
"svelte-hmr"
|
|
];
|
|
|
|
// src/utils/options.ts
|
|
var import_path2 = __toModule(require("path"));
|
|
var knownOptions = new Set([
|
|
"configFile",
|
|
"include",
|
|
"exclude",
|
|
"extensions",
|
|
"emitCss",
|
|
"compilerOptions",
|
|
"onwarn",
|
|
"preprocess",
|
|
"hot",
|
|
"ignorePluginPreprocessors",
|
|
"experimental"
|
|
]);
|
|
function buildDefaultOptions(isProduction, options) {
|
|
const emitCss = (options == null ? void 0 : options.emitCss) != null ? options.emitCss : true;
|
|
const hot = isProduction ? false : {
|
|
injectCss: !emitCss
|
|
};
|
|
const defaultOptions = {
|
|
extensions: [".svelte"],
|
|
hot,
|
|
emitCss,
|
|
compilerOptions: {
|
|
format: "esm",
|
|
css: !emitCss,
|
|
dev: !isProduction
|
|
}
|
|
};
|
|
log.debug(`default options for ${isProduction ? "production" : "development"}`, defaultOptions);
|
|
return defaultOptions;
|
|
}
|
|
function validateInlineOptions(inlineOptions) {
|
|
const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
|
|
if (invalidKeys.length) {
|
|
log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
|
|
}
|
|
}
|
|
function enforceOptionsForHmr(options) {
|
|
if (options.hot) {
|
|
if (!options.compilerOptions.dev) {
|
|
log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
|
|
options.compilerOptions.dev = true;
|
|
}
|
|
if (options.emitCss) {
|
|
if (options.hot !== true && options.hot.injectCss) {
|
|
log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
|
|
options.hot.injectCss = false;
|
|
}
|
|
if (options.compilerOptions.css) {
|
|
log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
|
|
options.compilerOptions.css = false;
|
|
}
|
|
} else {
|
|
if (options.hot === true || !options.hot.injectCss) {
|
|
log.warn("hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true");
|
|
if (options.hot === true) {
|
|
options.hot = { injectCss: true };
|
|
} else {
|
|
options.hot.injectCss = true;
|
|
}
|
|
}
|
|
if (!options.compilerOptions.css) {
|
|
log.warn("hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true");
|
|
options.compilerOptions.css = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function enforceOptionsForProduction(options) {
|
|
if (options.isProduction) {
|
|
if (options.hot) {
|
|
log.warn("options.hot is enabled but does not work on production build, forcing it to false");
|
|
options.hot = false;
|
|
}
|
|
if (options.compilerOptions.dev) {
|
|
log.warn("you are building for production but compilerOptions.dev is true, forcing it to false");
|
|
options.compilerOptions.dev = false;
|
|
}
|
|
}
|
|
}
|
|
function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig, viteEnv) {
|
|
const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
|
|
compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
|
|
experimental: __spreadValues(__spreadValues({}, (svelteConfig == null ? void 0 : svelteConfig.experimental) || {}), (inlineOptions == null ? void 0 : inlineOptions.experimental) || {}),
|
|
root: viteConfig.root,
|
|
isProduction: viteEnv.mode === "production",
|
|
isBuild: viteEnv.command === "build",
|
|
isServe: viteEnv.command === "serve"
|
|
});
|
|
if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
|
|
merged.configFile = svelteConfig.configFile;
|
|
}
|
|
return merged;
|
|
}
|
|
async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
|
|
const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
|
|
root: resolveViteRoot(viteConfig)
|
|
});
|
|
const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", inlineOptions);
|
|
const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
|
|
const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
|
|
enforceOptionsForProduction(resolvedOptions);
|
|
enforceOptionsForHmr(resolvedOptions);
|
|
return resolvedOptions;
|
|
}
|
|
function resolveViteRoot(viteConfig) {
|
|
return (0, import_vite2.normalizePath)(viteConfig.root ? import_path2.default.resolve(viteConfig.root) : process.cwd());
|
|
}
|
|
function buildExtraViteConfig(options, config) {
|
|
var _a, _b, _c, _d;
|
|
const allSvelteImports = [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS];
|
|
const excludeFromOptimize = allSvelteImports.filter((x) => {
|
|
var _a2, _b2;
|
|
return !((_b2 = (_a2 = config.optimizeDeps) == null ? void 0 : _a2.include) == null ? void 0 : _b2.includes(x));
|
|
});
|
|
const extraViteConfig = {
|
|
optimizeDeps: {
|
|
exclude: excludeFromOptimize
|
|
},
|
|
resolve: {
|
|
mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
|
|
dedupe: allSvelteImports
|
|
}
|
|
};
|
|
if (options.isBuild && ((_a = config.build) == null ? void 0 : _a.ssr)) {
|
|
if (!((_c = (_b = config.ssr) == null ? void 0 : _b.external) == null ? void 0 : _c.includes("svelte"))) {
|
|
extraViteConfig.ssr = {
|
|
noExternal: ["svelte"]
|
|
};
|
|
}
|
|
}
|
|
if ((_d = options.experimental) == null ? void 0 : _d.useVitePreprocess) {
|
|
extraViteConfig.esbuild = {
|
|
tsconfigRaw: {
|
|
compilerOptions: {
|
|
importsNotUsedAsValues: "preserve"
|
|
}
|
|
}
|
|
};
|
|
}
|
|
return extraViteConfig;
|
|
}
|
|
|
|
// src/utils/vite-plugin-svelte-cache.ts
|
|
var VitePluginSvelteCache = class {
|
|
constructor() {
|
|
this._css = new Map();
|
|
this._js = new Map();
|
|
this._dependencies = new Map();
|
|
this._dependants = new Map();
|
|
}
|
|
update(compileData) {
|
|
this.updateCSS(compileData);
|
|
this.updateJS(compileData);
|
|
this.updateDependencies(compileData);
|
|
}
|
|
updateCSS(compileData) {
|
|
this._css.set(compileData.normalizedFilename, compileData.compiled.css);
|
|
}
|
|
updateJS(compileData) {
|
|
if (!compileData.ssr) {
|
|
this._js.set(compileData.normalizedFilename, compileData.compiled.js);
|
|
}
|
|
}
|
|
updateDependencies(compileData) {
|
|
const id = compileData.normalizedFilename;
|
|
const prevDependencies = this._dependencies.get(id) || [];
|
|
const dependencies = compileData.dependencies;
|
|
this._dependencies.set(id, dependencies);
|
|
const removed = prevDependencies.filter((d) => !dependencies.includes(d));
|
|
const added = dependencies.filter((d) => !prevDependencies.includes(d));
|
|
added.forEach((d) => {
|
|
if (!this._dependants.has(d)) {
|
|
this._dependants.set(d, new Set());
|
|
}
|
|
this._dependants.get(d).add(compileData.filename);
|
|
});
|
|
removed.forEach((d) => {
|
|
this._dependants.get(d).delete(compileData.filename);
|
|
});
|
|
}
|
|
remove(svelteRequest) {
|
|
const id = svelteRequest.normalizedFilename;
|
|
let removed = false;
|
|
if (this._js.delete(id)) {
|
|
removed = true;
|
|
}
|
|
if (this._css.delete(id)) {
|
|
removed = true;
|
|
}
|
|
const dependencies = this._dependencies.get(id);
|
|
if (dependencies) {
|
|
removed = true;
|
|
dependencies.forEach((d) => {
|
|
const dependants = this._dependants.get(d);
|
|
if (dependants && dependants.has(svelteRequest.filename)) {
|
|
dependants.delete(svelteRequest.filename);
|
|
}
|
|
});
|
|
this._dependencies.delete(id);
|
|
}
|
|
return removed;
|
|
}
|
|
getCSS(svelteRequest) {
|
|
return this._css.get(svelteRequest.normalizedFilename);
|
|
}
|
|
getJS(svelteRequest) {
|
|
if (!svelteRequest.ssr) {
|
|
return this._js.get(svelteRequest.normalizedFilename);
|
|
}
|
|
}
|
|
getDependants(path5) {
|
|
const dependants = this._dependants.get(path5);
|
|
return dependants ? [...dependants] : [];
|
|
}
|
|
};
|
|
|
|
// src/utils/watch.ts
|
|
var import_fs2 = __toModule(require("fs"));
|
|
var import_path3 = __toModule(require("path"));
|
|
function setupWatchers(options, cache, requestParser) {
|
|
const { server, configFile: svelteConfigFile } = options;
|
|
if (!server) {
|
|
return;
|
|
}
|
|
const { watcher, ws } = server;
|
|
const { configFile: viteConfigFile, root, server: serverConfig } = server.config;
|
|
const emitChangeEventOnDependants = (filename) => {
|
|
const dependants = cache.getDependants(filename);
|
|
dependants.forEach((dependant) => {
|
|
if (import_fs2.default.existsSync(dependant)) {
|
|
log.debug(`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`);
|
|
watcher.emit("change", dependant);
|
|
}
|
|
});
|
|
};
|
|
const removeUnlinkedFromCache = (filename) => {
|
|
const svelteRequest = requestParser(filename, false);
|
|
if (svelteRequest) {
|
|
const removedFromCache = cache.remove(svelteRequest);
|
|
if (removedFromCache) {
|
|
log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
|
|
}
|
|
}
|
|
};
|
|
const triggerViteRestart = (filename) => {
|
|
if (!!viteConfigFile && !serverConfig.middlewareMode) {
|
|
log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
|
|
watcher.emit("change", viteConfigFile);
|
|
} else {
|
|
const message = "Svelte config change detected, restart your dev process to apply the changes.";
|
|
log.info(message, filename);
|
|
ws.send({
|
|
type: "error",
|
|
err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
|
|
});
|
|
}
|
|
};
|
|
const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path3.default.join(root, cfg));
|
|
const restartOnConfigAdd = (filename) => {
|
|
if (possibleSvelteConfigs.includes(filename)) {
|
|
triggerViteRestart(filename);
|
|
}
|
|
};
|
|
const restartOnConfigChange = (filename) => {
|
|
if (filename === svelteConfigFile) {
|
|
triggerViteRestart(filename);
|
|
}
|
|
};
|
|
const listeners = {
|
|
add: [],
|
|
change: [emitChangeEventOnDependants],
|
|
unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
|
|
};
|
|
if (svelteConfigFile) {
|
|
listeners.change.push(restartOnConfigChange);
|
|
listeners.unlink.push(restartOnConfigChange);
|
|
} else {
|
|
listeners.add.push(restartOnConfigAdd);
|
|
}
|
|
Object.entries(listeners).forEach(([evt, listeners2]) => {
|
|
if (listeners2.length > 0) {
|
|
watcher.on(evt, (filename) => listeners2.forEach((listener) => listener(filename)));
|
|
}
|
|
});
|
|
}
|
|
|
|
// src/utils/resolve.ts
|
|
var import_path4 = __toModule(require("path"));
|
|
var import_fs3 = __toModule(require("fs"));
|
|
var import_require_relative = __toModule(require("require-relative"));
|
|
function resolveViaPackageJsonSvelte(importee, importer) {
|
|
if (importer && isBareImport(importee)) {
|
|
const importeePkgFile = import_require_relative.default.resolve(`${importee}/package.json`, import_path4.default.dirname(importer));
|
|
const importeePkg = JSON.parse(import_fs3.default.readFileSync(importeePkgFile, { encoding: "utf-8" }));
|
|
if (importeePkg.svelte) {
|
|
return import_path4.default.resolve(import_path4.default.dirname(importeePkgFile), importeePkg.svelte);
|
|
}
|
|
}
|
|
}
|
|
function isBareImport(importee) {
|
|
if (!importee || importee[0] === "." || importee[0] === "\0" || import_path4.default.isAbsolute(importee)) {
|
|
return false;
|
|
}
|
|
const parts = importee.split("/");
|
|
switch (parts.length) {
|
|
case 1:
|
|
return true;
|
|
case 2:
|
|
return parts[0].startsWith("@");
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// src/utils/preprocess.ts
|
|
var import_magic_string2 = __toModule(require("magic-string"));
|
|
|
|
// src/utils/sourcemap.ts
|
|
var import_magic_string = __toModule(require("magic-string"));
|
|
async function buildMagicString(from, to, options) {
|
|
let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
|
|
try {
|
|
const dmpPkg = await Promise.resolve().then(() => __toModule(require("diff-match-patch")));
|
|
diff_match_patch = dmpPkg.diff_match_patch;
|
|
DIFF_INSERT = dmpPkg.DIFF_INSERT;
|
|
DIFF_DELETE = dmpPkg.DIFF_DELETE;
|
|
} catch (e) {
|
|
log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
|
|
return null;
|
|
}
|
|
const dmp = new diff_match_patch();
|
|
const diffs = dmp.diff_main(from, to);
|
|
dmp.diff_cleanupSemantic(diffs);
|
|
const m = new import_magic_string.default(from, options);
|
|
let pos = 0;
|
|
for (let i = 0; i < diffs.length; i++) {
|
|
const diff = diffs[i];
|
|
const nextDiff = diffs[i + 1];
|
|
if (diff[0] === DIFF_DELETE) {
|
|
if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
|
|
m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
|
|
i++;
|
|
} else {
|
|
m.remove(pos, pos + diff[1].length);
|
|
}
|
|
pos += diff[1].length;
|
|
} else if (diff[0] === DIFF_INSERT) {
|
|
if (nextDiff) {
|
|
m.appendRight(pos, diff[1]);
|
|
} else {
|
|
m.append(diff[1]);
|
|
}
|
|
} else {
|
|
pos += diff[1].length;
|
|
}
|
|
}
|
|
return m;
|
|
}
|
|
async function buildSourceMap(from, to, filename) {
|
|
const m = await buildMagicString(from, to, { filename });
|
|
return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
|
|
}
|
|
|
|
// src/utils/preprocess.ts
|
|
var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
|
|
var supportedScriptLangs = ["ts"];
|
|
function createPreprocessorFromVitePlugin(config, options, pluginName, supportedLangs) {
|
|
const plugin = config.plugins.find((p) => p.name === pluginName);
|
|
if (!plugin) {
|
|
throw new Error(`failed to find plugin ${pluginName}`);
|
|
}
|
|
if (!plugin.transform) {
|
|
throw new Error(`plugin ${pluginName} has no transform`);
|
|
}
|
|
const pluginTransform = plugin.transform.bind(null);
|
|
return async ({ attributes, content, filename }) => {
|
|
var _a, _b, _c, _d;
|
|
const lang = attributes.lang;
|
|
if (!supportedLangs.includes(lang)) {
|
|
return { code: content };
|
|
}
|
|
const moduleId = `${filename}.${lang}`;
|
|
const moduleGraph = (_a = options.server) == null ? void 0 : _a.moduleGraph;
|
|
if (moduleGraph && !moduleGraph.getModuleById(moduleId)) {
|
|
await moduleGraph.ensureEntryFromUrl(moduleId);
|
|
}
|
|
const transformResult = await pluginTransform(content, moduleId);
|
|
const hasMap = transformResult.map && ((_b = transformResult.map) == null ? void 0 : _b.mappings) !== "";
|
|
if (((_d = (_c = transformResult.map) == null ? void 0 : _c.sources) == null ? void 0 : _d[0]) === moduleId) {
|
|
transformResult.map.sources[0] = filename;
|
|
}
|
|
return {
|
|
code: transformResult.code,
|
|
map: hasMap ? transformResult.map : void 0,
|
|
dependencies: transformResult.deps
|
|
};
|
|
};
|
|
}
|
|
function createVitePreprocessorGroup(config, options) {
|
|
return {
|
|
script: createPreprocessorFromVitePlugin(config, options, "vite:esbuild", supportedScriptLangs),
|
|
style: createPreprocessorFromVitePlugin(config, options, "vite:css", supportedStyleLangs)
|
|
};
|
|
}
|
|
function createInjectScopeEverythingRulePreprocessorGroup() {
|
|
return {
|
|
style({ content, filename }) {
|
|
const s = new import_magic_string2.default(content);
|
|
s.append(" *{}");
|
|
return {
|
|
code: s.toString(),
|
|
map: s.generateDecodedMap({ source: filename, hires: true })
|
|
};
|
|
}
|
|
};
|
|
}
|
|
function buildExtraPreprocessors(options, config) {
|
|
var _a, _b;
|
|
const extraPreprocessors = [];
|
|
if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
|
|
log.debug("adding vite preprocessor");
|
|
extraPreprocessors.push(createVitePreprocessorGroup(config, options));
|
|
}
|
|
const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
|
|
if (pluginsWithPreprocessorsDeprecated.length > 0) {
|
|
log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
|
|
pluginsWithPreprocessorsDeprecated.forEach((p) => {
|
|
if (!p.api) {
|
|
p.api = {};
|
|
}
|
|
if (p.api.sveltePreprocess === void 0) {
|
|
p.api.sveltePreprocess = p.sveltePreprocess;
|
|
} else {
|
|
log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
|
|
}
|
|
});
|
|
}
|
|
const pluginsWithPreprocessors = config.plugins.filter((p) => {
|
|
var _a2;
|
|
return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
|
|
});
|
|
const ignored = [], included = [];
|
|
for (const p of pluginsWithPreprocessors) {
|
|
if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
|
|
ignored.push(p);
|
|
} else {
|
|
included.push(p);
|
|
}
|
|
}
|
|
if (ignored.length > 0) {
|
|
log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
|
|
}
|
|
if (included.length > 0) {
|
|
log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
|
|
extraPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
|
|
}
|
|
if (options.hot && options.emitCss) {
|
|
extraPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
|
|
}
|
|
return extraPreprocessors;
|
|
}
|
|
function addExtraPreprocessors(options, config) {
|
|
var _a;
|
|
const extra = buildExtraPreprocessors(options, config);
|
|
if ((extra == null ? void 0 : extra.length) > 0) {
|
|
if (!options.preprocess) {
|
|
options.preprocess = extra;
|
|
} else if (Array.isArray(options.preprocess)) {
|
|
options.preprocess.push(...extra);
|
|
} else {
|
|
options.preprocess = [options.preprocess, ...extra];
|
|
}
|
|
}
|
|
const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
|
|
if (options.preprocess && generateMissingSourceMaps) {
|
|
options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
|
|
}
|
|
}
|
|
function validateSourceMapOutputWrapper(group, i) {
|
|
const wrapper = {};
|
|
for (const [processorType, processorFn] of Object.entries(group)) {
|
|
wrapper[processorType] = async (options) => {
|
|
var _a;
|
|
const result = await processorFn(options);
|
|
if (result && result.code !== options.content) {
|
|
let invalidMap = false;
|
|
if (!result.map) {
|
|
invalidMap = true;
|
|
log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
|
|
filename: options.filename,
|
|
type: processorType,
|
|
processor: processorFn.toString()
|
|
});
|
|
} else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
|
|
invalidMap = true;
|
|
log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
|
|
filename: options.filename,
|
|
type: processorType,
|
|
processor: processorFn.toString()
|
|
});
|
|
}
|
|
if (invalidMap) {
|
|
try {
|
|
const map = await buildSourceMap(options.content, result.code, options.filename);
|
|
if (map) {
|
|
log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
|
|
result.map = map;
|
|
}
|
|
} catch (e) {
|
|
log.error(`failed to build sourcemap`, e);
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
};
|
|
}
|
|
return wrapper;
|
|
}
|
|
|
|
// src/index.ts
|
|
function svelte(inlineOptions) {
|
|
if (process.env.DEBUG != null) {
|
|
log.setLevel("debug");
|
|
}
|
|
validateInlineOptions(inlineOptions);
|
|
const cache = new VitePluginSvelteCache();
|
|
const pkg_export_errors = new Set();
|
|
let requestParser;
|
|
let options;
|
|
let viteConfig;
|
|
let compileSvelte;
|
|
let resolvedSvelteSSR;
|
|
return {
|
|
name: "vite-plugin-svelte",
|
|
enforce: "pre",
|
|
async config(config, configEnv) {
|
|
if (process.env.DEBUG) {
|
|
log.setLevel("debug");
|
|
} else if (config.logLevel) {
|
|
log.setLevel(config.logLevel);
|
|
}
|
|
options = await resolveOptions(inlineOptions, config, configEnv);
|
|
const extraViteConfig = buildExtraViteConfig(options, config);
|
|
log.debug("additional vite config", extraViteConfig);
|
|
return extraViteConfig;
|
|
},
|
|
async configResolved(config) {
|
|
addExtraPreprocessors(options, config);
|
|
requestParser = buildIdParser(options);
|
|
compileSvelte = createCompileSvelte(options);
|
|
viteConfig = config;
|
|
log.debug("resolved options", options);
|
|
},
|
|
configureServer(server) {
|
|
options.server = server;
|
|
setupWatchers(options, cache, requestParser);
|
|
},
|
|
load(id, ssr) {
|
|
const svelteRequest = requestParser(id, !!ssr);
|
|
if (svelteRequest) {
|
|
const { filename, query } = svelteRequest;
|
|
if (query.svelte && query.type === "style") {
|
|
const css = cache.getCSS(svelteRequest);
|
|
if (css) {
|
|
log.debug(`load returns css for ${filename}`);
|
|
return css;
|
|
}
|
|
}
|
|
if (viteConfig.assetsInclude(filename)) {
|
|
log.debug(`load returns raw content for ${filename}`);
|
|
return import_fs4.default.readFileSync(filename, "utf-8");
|
|
}
|
|
}
|
|
},
|
|
async resolveId(importee, importer, customOptions, ssr) {
|
|
const svelteRequest = requestParser(importee, !!ssr);
|
|
if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
|
|
if (svelteRequest.query.type === "style") {
|
|
log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
|
|
return svelteRequest.cssId;
|
|
}
|
|
log.debug(`resolveId resolved ${importee}`);
|
|
return importee;
|
|
}
|
|
if (ssr && importee === "svelte") {
|
|
if (!resolvedSvelteSSR) {
|
|
resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then((svelteSSR) => {
|
|
log.debug("resolved svelte to svelte/ssr");
|
|
return svelteSSR;
|
|
}, (err) => {
|
|
log.debug("failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it", err);
|
|
return null;
|
|
});
|
|
}
|
|
return resolvedSvelteSSR;
|
|
}
|
|
try {
|
|
const resolved = resolveViaPackageJsonSvelte(importee, importer);
|
|
if (resolved) {
|
|
log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
|
|
return resolved;
|
|
}
|
|
} catch (err) {
|
|
switch (err.code) {
|
|
case "ERR_PACKAGE_PATH_NOT_EXPORTED":
|
|
pkg_export_errors.add(importee);
|
|
return null;
|
|
case "MODULE_NOT_FOUND":
|
|
return null;
|
|
default:
|
|
throw err;
|
|
}
|
|
}
|
|
},
|
|
async transform(code, id, ssr) {
|
|
var _a;
|
|
const svelteRequest = requestParser(id, !!ssr);
|
|
if (!svelteRequest) {
|
|
return;
|
|
}
|
|
const { filename, query } = svelteRequest;
|
|
if (query.svelte) {
|
|
if (query.type === "style") {
|
|
const css = cache.getCSS(svelteRequest);
|
|
if (css) {
|
|
log.debug(`transform returns css for ${filename}`);
|
|
return css;
|
|
}
|
|
}
|
|
log.error("failed to transform tagged svelte request", svelteRequest);
|
|
throw new Error(`failed to transform tagged svelte request for id ${id}`);
|
|
}
|
|
const compileData = await compileSvelte(svelteRequest, code, options);
|
|
logCompilerWarnings(compileData.compiled.warnings, options);
|
|
cache.update(compileData);
|
|
if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
|
|
compileData.dependencies.forEach((d) => this.addWatchFile(d));
|
|
}
|
|
log.debug(`transform returns compiled js for ${filename}`);
|
|
return compileData.compiled.js;
|
|
},
|
|
handleHotUpdate(ctx) {
|
|
if (!options.hot || !options.emitCss) {
|
|
return;
|
|
}
|
|
const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
|
|
if (svelteRequest) {
|
|
return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options);
|
|
}
|
|
},
|
|
buildEnd() {
|
|
if (pkg_export_errors.size > 0) {
|
|
log.warn(`The following packages did not export their \`package.json\` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.`, Array.from(pkg_export_errors, (s) => `- ${s}`).join("\n"));
|
|
}
|
|
}
|
|
};
|
|
}
|
|
// Annotate the CommonJS export names for ESM import in node:
|
|
0 && (module.exports = {
|
|
svelte
|
|
});
|
|
//# sourceMappingURL=index.cjs.map
|