Socket
Socket
Sign inDemoInstall

@sveltejs/vite-plugin-svelte

Package Overview
Dependencies
6
Maintainers
4
Versions
102
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.0-next.32 to 1.0.0-next.33

570

dist/index.js

@@ -438,3 +438,5 @@ var __defProp = Object.defineProperty;

// src/utils/options.ts
import { normalizePath as normalizePath2 } from "vite";
import {
normalizePath as normalizePath2
} from "vite";

@@ -682,3 +684,7 @@ // src/utils/load-svelte-config.ts

const pkg = depData.pkg;
return pkg.main && !pkg.module && !pkg.exports;
const isCjs = pkg.main && !pkg.module && !pkg.exports;
if (!isCjs)
return false;
const entryExt = path2.extname(pkg.main);
return !entryExt || entryExt === ".js" || entryExt === ".cjs";
}

@@ -744,2 +750,3 @@

// src/utils/esbuild.ts
var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
function esbuildSveltePlugin(options) {

@@ -786,2 +793,3 @@ return {

filename,
format: "esm",
generate: "dom"

@@ -809,2 +817,230 @@ });

// src/utils/preprocess.ts
import {
transformWithEsbuild
} from "vite";
import MagicString2 from "magic-string";
import { preprocess as preprocess3 } from "svelte/compiler";
// src/utils/sourcemap.ts
import MagicString from "magic-string";
async function buildMagicString(from, to, options) {
let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
try {
const dmpPkg = await import("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 MagicString(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 createViteScriptPreprocessor() {
return async ({ attributes, content, filename = "" }) => {
const lang = attributes.lang;
if (!supportedScriptLangs.includes(lang))
return;
const transformResult = await transformWithEsbuild(content, filename, {
loader: lang,
tsconfigRaw: {
compilerOptions: {
importsNotUsedAsValues: "preserve"
}
}
});
return {
code: transformResult.code,
map: transformResult.map
};
};
}
function createViteStylePreprocessor(config) {
const pluginName = "vite:css";
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;
const lang = attributes.lang;
if (!supportedStyleLangs.includes(lang))
return;
const moduleId = `${filename}.${lang}`;
const transformResult = await pluginTransform(content, moduleId);
if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
transformResult.map.sources[0] = filename;
}
return {
code: transformResult.code,
map: transformResult.map ?? void 0
};
};
}
function createVitePreprocessorGroup(config) {
return {
markup({ content, filename }) {
return preprocess3(content, {
script: createViteScriptPreprocessor(),
style: createViteStylePreprocessor(config)
}, { filename });
}
};
}
function createInjectScopeEverythingRulePreprocessorGroup() {
return {
style({ content, filename }) {
const s = new MagicString2(content);
s.append(" *{}");
return {
code: s.toString(),
map: s.generateDecodedMap({ source: filename, hires: true })
};
}
};
}
function buildExtraPreprocessors(options, config) {
var _a, _b;
const prependPreprocessors = [];
const appendPreprocessors = [];
if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
log.debug("adding vite preprocessor");
prependPreprocessors.push(createVitePreprocessorGroup(config));
}
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(", ")}`);
appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
}
if (options.hot && options.emitCss) {
appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
}
return { prependPreprocessors, appendPreprocessors };
}
function addExtraPreprocessors(options, config) {
var _a;
const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
if (!options.preprocess) {
options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
} else if (Array.isArray(options.preprocess)) {
options.preprocess.unshift(...prependPreprocessors);
options.preprocess.push(...appendPreprocessors);
} else {
options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
}
}
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/utils/options.ts

@@ -825,25 +1061,49 @@ var knownOptions = new Set([

]);
function buildDefaultOptions(isProduction, emitCss = true) {
const hot = isProduction ? false : {
injectCss: !emitCss
};
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);
}
}
async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
root: resolveViteRoot(viteUserConfig)
});
const defaultOptions = {
extensions: [".svelte"],
hot,
emitCss,
emitCss: true,
compilerOptions: {
format: "esm",
css: !emitCss,
dev: !isProduction
format: "esm"
}
};
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);
const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
root: viteConfigWithResolvedRoot.root,
isBuild: viteEnv.command === "build",
isServe: viteEnv.command === "serve"
});
if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
merged.configFile = svelteConfig.configFile;
}
return merged;
}
function resolveOptions(preResolveOptions2, viteConfig) {
const defaultOptions = {
hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
compilerOptions: {
css: !preResolveOptions2.emitCss,
dev: !viteConfig.isProduction
}
};
const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
isProduction: viteConfig.isProduction
});
addExtraPreprocessors(merged, viteConfig);
enforceOptionsForHmr(merged);
enforceOptionsForProduction(merged);
return merged;
}
function enforceOptionsForHmr(options) {

@@ -892,28 +1152,2 @@ if (options.hot) {

}
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",
isSvelteKit: !!(svelteConfig == null ? void 0 : svelteConfig.kit)
});
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 svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", inlineOptions.emitCss ?? svelteConfig.emitCss);
const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
enforceOptionsForProduction(resolvedOptions);
enforceOptionsForHmr(resolvedOptions);
return resolvedOptions;
}
function resolveViteRoot(viteConfig) {

@@ -959,3 +1193,4 @@ return normalizePath2(viteConfig.root ? path3.resolve(viteConfig.root) : process.cwd());

esbuildOptions: {
plugins: [esbuildSveltePlugin(options)]
plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
} }]
}

@@ -1000,2 +1235,9 @@ };

}
function patchResolvedViteConfig(viteConfig, options) {
var _a, _b;
const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
if (facadeEsbuildSveltePlugin) {
Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
}
}

@@ -1106,3 +1348,3 @@ // src/utils/vite-plugin-svelte-cache.ts

var _a;
if (serverConfig.middlewareMode || options.isSvelteKit) {
if (serverConfig.middlewareMode) {
const message = "Svelte config change detected, restart your dev process to apply the changes.";

@@ -1181,231 +1423,2 @@ log.info(message, filename);

// src/utils/preprocess.ts
import {
transformWithEsbuild
} from "vite";
import MagicString2 from "magic-string";
import { preprocess as preprocess3 } from "svelte/compiler";
// src/utils/sourcemap.ts
import MagicString from "magic-string";
async function buildMagicString(from, to, options) {
let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
try {
const dmpPkg = await import("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 MagicString(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 createViteScriptPreprocessor() {
return async ({ attributes, content, filename = "" }) => {
const lang = attributes.lang;
if (!supportedScriptLangs.includes(lang))
return;
const transformResult = await transformWithEsbuild(content, filename, {
loader: lang,
tsconfigRaw: {
compilerOptions: {
importsNotUsedAsValues: "preserve"
}
}
});
return {
code: transformResult.code,
map: transformResult.map
};
};
}
function createViteStylePreprocessor(config) {
const pluginName = "vite:css";
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;
const lang = attributes.lang;
if (!supportedStyleLangs.includes(lang))
return;
const moduleId = `${filename}.${lang}`;
const transformResult = await pluginTransform(content, moduleId);
const hasMap = transformResult.map && transformResult.map.mappings !== "";
if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
transformResult.map.sources[0] = filename;
}
return {
code: transformResult.code,
map: hasMap ? transformResult.map : void 0
};
};
}
function createVitePreprocessorGroup(config) {
return {
markup({ content, filename }) {
return preprocess3(content, {
script: createViteScriptPreprocessor(),
style: createViteStylePreprocessor(config)
}, { filename });
}
};
}
function createInjectScopeEverythingRulePreprocessorGroup() {
return {
style({ content, filename }) {
const s = new MagicString2(content);
s.append(" *{}");
return {
code: s.toString(),
map: s.generateDecodedMap({ source: filename, hires: true })
};
}
};
}
function buildExtraPreprocessors(options, config) {
var _a, _b;
const prependPreprocessors = [];
const appendPreprocessors = [];
if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
log.debug("adding vite preprocessor");
prependPreprocessors.push(createVitePreprocessorGroup(config));
}
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(", ")}`);
appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
}
if (options.hot && options.emitCss) {
appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
}
return { prependPreprocessors, appendPreprocessors };
}
function addExtraPreprocessors(options, config) {
var _a;
const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
if (!options.preprocess) {
options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
} else if (Array.isArray(options.preprocess)) {
options.preprocess.unshift(...prependPreprocessors);
options.preprocess.push(...appendPreprocessors);
} else {
options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
}
}
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

@@ -1433,3 +1446,3 @@ function svelte(inlineOptions) {

}
options = await resolveOptions(inlineOptions, config, configEnv);
options = await preResolveOptions(inlineOptions, config, configEnv);
const extraViteConfig = buildExtraViteConfig(options, config, configEnv);

@@ -1440,3 +1453,4 @@ log.debug("additional vite config", extraViteConfig);

async configResolved(config) {
addExtraPreprocessors(options, config);
options = resolveOptions(options, config);
patchResolvedViteConfig(config, options);
requestParser = buildIdParser(options);

@@ -1564,2 +1578,2 @@ compileSvelte2 = createCompileSvelte(options);

};
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map
{
"name": "@sveltejs/vite-plugin-svelte",
"version": "1.0.0-next.32",
"version": "1.0.0-next.33",
"license": "MIT",

@@ -43,3 +43,3 @@ "author": "dominikg",

"dependencies": {
"@rollup/pluginutils": "^4.1.1",
"@rollup/pluginutils": "^4.1.2",
"debug": "^4.3.3",

@@ -49,3 +49,3 @@ "kleur": "^4.1.4",

"require-relative": "^0.8.7",
"svelte-hmr": "^0.14.7"
"svelte-hmr": "^0.14.9"
},

@@ -67,6 +67,6 @@ "peerDependencies": {

"esbuild": "^0.13.15",
"rollup": "^2.60.2",
"svelte": "^3.44.2",
"tsup": "^5.10.1",
"vite": "^2.7.0"
"rollup": "^2.62.0",
"svelte": "^3.44.3",
"tsup": "^5.11.9",
"vite": "^2.7.7"
},

@@ -77,3 +77,4 @@ "scripts": {

"build": "pnpm run build:ci -- --dts --sourcemap"
}
},
"readme": "# @sveltejs/vite-plugin-svelte\n\nThe official [Svelte](https://svelte.dev) plugin for [Vite](https://vitejs.dev).\n\n## Usage\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport { svelte } from '@sveltejs/vite-plugin-svelte';\n\nexport default defineConfig({\n\tplugins: [\n\t\tsvelte({\n\t\t\t/* plugin options */\n\t\t})\n\t]\n});\n```\n\n## Documentation\n\n- [Plugin options](../../docs/config.md)\n- [FAQ](../../docs/faq.md)\n\n## License\n\n[MIT](./LICENSE)\n"
}

@@ -12,3 +12,5 @@ import fs from 'fs';

ResolvedOptions,
resolveOptions
resolveOptions,
patchResolvedViteConfig,
preResolveOptions
} from './utils/options';

@@ -19,3 +21,2 @@ import { VitePluginSvelteCache } from './utils/vite-plugin-svelte-cache';

import { resolveViaPackageJsonSvelte } from './utils/resolve';
import { addExtraPreprocessors } from './utils/preprocess';
import { PartialResolvedId } from 'rollup';

@@ -56,11 +57,13 @@ import { toRollupError } from './utils/error';

}
options = await resolveOptions(inlineOptions, config, configEnv);
// @ts-expect-error temporarily lend the options variable until fixed in configResolved
options = await preResolveOptions(inlineOptions, config, configEnv);
// extra vite config
const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
log.debug('additional vite config', extraViteConfig);
return extraViteConfig as Partial<UserConfig>;
return extraViteConfig;
},
async configResolved(config) {
addExtraPreprocessors(options, config);
options = resolveOptions(options, config);
patchResolvedViteConfig(config, options);
requestParser = buildIdParser(options);

@@ -67,0 +70,0 @@ compileSvelte = createCompileSvelte(options);

@@ -187,3 +187,8 @@ import { log } from './log';

// see https://github.com/sveltejs/vite-plugin-svelte/issues/162
return pkg.main && !pkg.module && !pkg.exports;
const isCjs = pkg.main && !pkg.module && !pkg.exports;
if (!isCjs) return false;
// ensure entry is js so vite can prebundle it
// see https://github.com/sveltejs/vite-plugin-svelte/issues/233
const entryExt = path.extname(pkg.main);
return !entryExt || entryExt === '.js' || entryExt === '.cjs';
}

@@ -190,0 +195,0 @@

@@ -13,2 +13,4 @@ import { promises as fs } from 'fs';

export const facadeEsbuildSveltePluginName = 'vite-plugin-svelte:facade';
export function esbuildSveltePlugin(options: ResolvedOptions): EsbuildPlugin {

@@ -68,2 +70,3 @@ return {

filename,
format: 'esm',
generate: 'dom'

@@ -70,0 +73,0 @@ };

/* eslint-disable no-unused-vars */
import { ConfigEnv, DepOptimizationOptions, UserConfig, ViteDevServer, normalizePath } from 'vite';
import {
ConfigEnv,
DepOptimizationOptions,
ResolvedConfig,
UserConfig,
ViteDevServer,
normalizePath
} from 'vite';
import { log } from './log';

@@ -18,3 +25,4 @@ import { loadSvelteConfig } from './load-svelte-config';

import { createRequire } from 'module';
import { esbuildSveltePlugin } from './esbuild';
import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild';
import { addExtraPreprocessors } from './preprocess';

@@ -36,29 +44,80 @@ const knownOptions = new Set([

function buildDefaultOptions(isProduction: boolean, emitCss = true): Partial<Options> {
// no hmr in prod, only inject css in dev if emitCss is false
const hot = isProduction
? false
: {
// emit for prod, emit in dev unless css hmr is disabled
injectCss: !emitCss
};
export function validateInlineOptions(inlineOptions?: Partial<Options>) {
const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
if (invalidKeys.length) {
log.warn(`invalid plugin options "${invalidKeys.join(', ')}" in config`, inlineOptions);
}
}
// used in config phase, merges the default options, svelte config, and inline options
export async function preResolveOptions(
inlineOptions: Partial<Options> = {},
viteUserConfig: UserConfig,
viteEnv: ConfigEnv
): Promise<PreResolvedOptions> {
const viteConfigWithResolvedRoot: UserConfig = {
...viteUserConfig,
root: resolveViteRoot(viteUserConfig)
};
const defaultOptions: Partial<Options> = {
extensions: ['.svelte'],
hot,
emitCss,
emitCss: true,
compilerOptions: {
format: 'esm',
css: !emitCss,
dev: !isProduction
format: 'esm'
}
};
log.debug(`default options for ${isProduction ? 'production' : 'development'}`, defaultOptions);
return defaultOptions;
const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
const merged = {
...defaultOptions,
...svelteConfig,
...inlineOptions,
compilerOptions: {
...defaultOptions?.compilerOptions,
...svelteConfig?.compilerOptions,
...inlineOptions?.compilerOptions
},
experimental: {
...defaultOptions?.experimental,
...svelteConfig?.experimental,
...inlineOptions?.experimental
},
// extras
root: viteConfigWithResolvedRoot.root!,
isBuild: viteEnv.command === 'build',
isServe: viteEnv.command === 'serve'
};
// configFile of svelteConfig contains the absolute path it was loaded from,
// prefer it over the possibly relative inline path
if (svelteConfig?.configFile) {
merged.configFile = svelteConfig.configFile;
}
return merged;
}
export function validateInlineOptions(inlineOptions?: Partial<Options>) {
const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
if (invalidKeys.length) {
log.warn(`invalid plugin options "${invalidKeys.join(', ')}" in config`, inlineOptions);
}
// used in configResolved phase, merges a contextual default config, pre-resolved options, and some preprocessors.
// also validates the final config.
export function resolveOptions(
preResolveOptions: PreResolvedOptions,
viteConfig: ResolvedConfig
): ResolvedOptions {
const defaultOptions: Partial<Options> = {
hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions.emitCss },
compilerOptions: {
css: !preResolveOptions.emitCss,
dev: !viteConfig.isProduction
}
};
const merged: ResolvedOptions = {
...defaultOptions,
...preResolveOptions,
compilerOptions: {
...defaultOptions.compilerOptions,
...preResolveOptions.compilerOptions
},
isProduction: viteConfig.isProduction
};
addExtraPreprocessors(merged, viteConfig);
enforceOptionsForHmr(merged);
enforceOptionsForProduction(merged);
return merged;
}

@@ -119,65 +178,2 @@

function mergeOptions(
defaultOptions: Partial<Options>,
svelteConfig: Partial<Options>,
inlineOptions: Partial<Options>,
viteConfig: UserConfig,
viteEnv: ConfigEnv
): ResolvedOptions {
// @ts-ignore
const merged = {
...defaultOptions,
...svelteConfig,
...inlineOptions,
compilerOptions: {
...defaultOptions.compilerOptions,
...(svelteConfig?.compilerOptions || {}),
...(inlineOptions?.compilerOptions || {})
},
experimental: {
...(svelteConfig?.experimental || {}),
...(inlineOptions?.experimental || {})
},
root: viteConfig.root!,
isProduction: viteEnv.mode === 'production',
isBuild: viteEnv.command === 'build',
isServe: viteEnv.command === 'serve',
// @ts-expect-error we don't declare kit property of svelte config but read it once here to identify kit projects
isSvelteKit: !!svelteConfig?.kit
};
// configFile of svelteConfig contains the absolute path it was loaded from,
// prefer it over the possibly relative inline path
if (svelteConfig?.configFile) {
merged.configFile = svelteConfig.configFile;
}
return merged;
}
export async function resolveOptions(
inlineOptions: Partial<Options> = {},
viteConfig: UserConfig,
viteEnv: ConfigEnv
): Promise<ResolvedOptions> {
const viteConfigWithResolvedRoot = {
...viteConfig,
root: resolveViteRoot(viteConfig)
};
const svelteConfig = (await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)) || {};
const defaultOptions = buildDefaultOptions(
viteEnv.mode === 'production',
inlineOptions.emitCss ?? svelteConfig.emitCss
);
const resolvedOptions = mergeOptions(
defaultOptions,
svelteConfig,
inlineOptions,
viteConfigWithResolvedRoot,
viteEnv
);
enforceOptionsForProduction(resolvedOptions);
enforceOptionsForHmr(resolvedOptions);
return resolvedOptions;
}
// vite passes unresolved `root`option to config hook but we need the resolved value, so do it here

@@ -191,3 +187,3 @@ // https://github.com/sveltejs/vite-plugin-svelte/issues/113

export function buildExtraViteConfig(
options: ResolvedOptions,
options: PreResolvedOptions,
config: UserConfig,

@@ -225,3 +221,3 @@ configEnv: ConfigEnv

svelteDeps: SvelteDependency[],
options: ResolvedOptions,
options: PreResolvedOptions,
optimizeDeps?: DepOptimizationOptions

@@ -257,3 +253,3 @@ ): DepOptimizationOptions {

esbuildOptions: {
plugins: [esbuildSveltePlugin(options)]
plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {} }]
}

@@ -329,2 +325,10 @@ };

export function patchResolvedViteConfig(viteConfig: ResolvedConfig, options: ResolvedOptions) {
const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
(plugin) => plugin.name === facadeEsbuildSveltePluginName
);
if (facadeEsbuildSveltePlugin) {
Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
}
}
export interface Options {

@@ -488,3 +492,3 @@ /**

export interface ResolvedOptions extends Options {
export interface PreResolvedOptions extends Options {
// these options are non-nullable after resolve

@@ -495,7 +499,9 @@ compilerOptions: CompileOptions;

root: string;
isProduction: boolean;
isBuild: boolean;
isServe: boolean;
}
export interface ResolvedOptions extends PreResolvedOptions {
isProduction: boolean;
server?: ViteDevServer;
isSvelteKit?: boolean;
}

@@ -502,0 +508,0 @@

@@ -20,3 +20,2 @@ import {

function createViteScriptPreprocessor(): Preprocessor {
// @ts-expect-error - allow return void
return async ({ attributes, content, filename = '' }) => {

@@ -51,3 +50,2 @@ const lang = attributes.lang as string;

const pluginTransform = plugin.transform!.bind(null as unknown as TransformPluginContext);
// @ts-expect-error - allow return void
return async ({ attributes, content, filename = '' }) => {

@@ -61,6 +59,4 @@ const lang = attributes.lang as string;

)) as TransformResult;
// vite returns empty mappings that would kill svelte compiler before 3.43.0
const hasMap = transformResult.map && transformResult.map.mappings !== '';
// patch sourcemap source to point back to original filename
if (hasMap && transformResult.map?.sources?.[0] === moduleId) {
if (transformResult.map?.sources?.[0] === moduleId) {
transformResult.map.sources[0] = filename;

@@ -70,3 +66,3 @@ }

code: transformResult.code,
map: hasMap ? transformResult.map : undefined
map: transformResult.map ?? undefined
};

@@ -76,3 +72,3 @@ };

export function createVitePreprocessorGroup(config: ResolvedConfig): PreprocessorGroup {
function createVitePreprocessorGroup(config: ResolvedConfig): PreprocessorGroup {
return {

@@ -79,0 +75,0 @@ markup({ content, filename }) {

@@ -45,4 +45,4 @@ import { VitePluginSvelteCache } from './vite-plugin-svelte-cache';

const triggerViteRestart = (filename: string) => {
if (serverConfig.middlewareMode || options.isSvelteKit) {
// in middlewareMode or for sveltekit we can't restart the server automatically
if (serverConfig.middlewareMode) {
// in middlewareMode we can't restart the server automatically
// show the user an overlay instead

@@ -49,0 +49,0 @@ const message =

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc