@sveltejs/vite-plugin-svelte
Advanced tools
| <svg xmlns="http://www.w3.org/2000/svg" width="21" height="25" viewBox="0 0 107 128"> | ||
| <title>svelte-inspector-logo</title> | ||
| <path d="M94.1566,22.8189c-10.4-14.8851-30.94-19.2971-45.7914-9.8348L22.2825,29.6078A29.9234,29.9234,0,0,0,8.7639,49.6506a31.5136,31.5136,0,0,0,3.1076,20.2318A30.0061,30.0061,0,0,0,7.3953,81.0653a31.8886,31.8886,0,0,0,5.4473,24.1157c10.4022,14.8865,30.9423,19.2966,45.7914,9.8348L84.7167,98.3921A29.9177,29.9177,0,0,0,98.2353,78.3493,31.5263,31.5263,0,0,0,95.13,58.117a30,30,0,0,0,4.4743-11.1824,31.88,31.88,0,0,0-5.4473-24.1157" style="fill:#ff3e00"/><path d="M45.8171,106.5815A20.7182,20.7182,0,0,1,23.58,98.3389a19.1739,19.1739,0,0,1-3.2766-14.5025,18.1886,18.1886,0,0,1,.6233-2.4357l.4912-1.4978,1.3363.9815a33.6443,33.6443,0,0,0,10.203,5.0978l.9694.2941-.0893.9675a5.8474,5.8474,0,0,0,1.052,3.8781,6.2389,6.2389,0,0,0,6.6952,2.485,5.7449,5.7449,0,0,0,1.6021-.7041L69.27,76.281a5.4306,5.4306,0,0,0,2.4506-3.631,5.7948,5.7948,0,0,0-.9875-4.3712,6.2436,6.2436,0,0,0-6.6978-2.4864,5.7427,5.7427,0,0,0-1.6.7036l-9.9532,6.3449a19.0329,19.0329,0,0,1-5.2965,2.3259,20.7181,20.7181,0,0,1-22.2368-8.2427,19.1725,19.1725,0,0,1-3.2766-14.5024,17.9885,17.9885,0,0,1,8.13-12.0513L55.8833,23.7472a19.0038,19.0038,0,0,1,5.3-2.3287A20.7182,20.7182,0,0,1,83.42,29.6611a19.1739,19.1739,0,0,1,3.2766,14.5025,18.4,18.4,0,0,1-.6233,2.4357l-.4912,1.4978-1.3356-.98a33.6175,33.6175,0,0,0-10.2037-5.1l-.9694-.2942.0893-.9675a5.8588,5.8588,0,0,0-1.052-3.878,6.2389,6.2389,0,0,0-6.6952-2.485,5.7449,5.7449,0,0,0-1.6021.7041L37.73,51.719a5.4218,5.4218,0,0,0-2.4487,3.63,5.7862,5.7862,0,0,0,.9856,4.3717,6.2437,6.2437,0,0,0,6.6978,2.4864,5.7652,5.7652,0,0,0,1.602-.7041l9.9519-6.3425a18.978,18.978,0,0,1,5.2959-2.3278,20.7181,20.7181,0,0,1,22.2368,8.2427,19.1725,19.1725,0,0,1,3.2766,14.5024,17.9977,17.9977,0,0,1-8.13,12.0532L51.1167,104.2528a19.0038,19.0038,0,0,1-5.3,2.3287" style="fill:#fff"/> | ||
| <polygon points="0,0 15,40 40,20" stroke="#ff3e00" fill="#ff3e00"></polygon> | ||
| </svg> |
| <script> | ||
| // do not use TS here so that this component works in non-ts projects too | ||
| import { onMount } from 'svelte'; | ||
| // @ts-expect-error virtual import is resolved by vite-plugin-svelte-inspector | ||
| // eslint-disable-next-line node/no-missing-import | ||
| import icon from 'virtual:svelte-inspector:icon.svg'; | ||
| // @ts-expect-error virtual import is resolved by vite-plugin-svelte-inspector | ||
| // eslint-disable-next-line node/no-missing-import | ||
| import options from 'virtual:svelte-inspector-options'; | ||
| const toggle_combo = options.toggleKeyCombo?.toLowerCase().split('-'); | ||
| let enabled = false; | ||
| // location of code in file | ||
| let file_loc; | ||
| // cursor pos and width for file_loc overlay positioning | ||
| let x, y, w; | ||
| let active_el; | ||
| let toggle_el; | ||
| let enabled_ts; | ||
| $: show_toggle = | ||
| options.showToggleButton === 'always' || (options.showToggleButton === 'active' && enabled); | ||
| function mousemove(event) { | ||
| x = event.x; | ||
| y = event.y; | ||
| } | ||
| function findMetaEl(el) { | ||
| while (el) { | ||
| const file = el.__svelte_meta?.loc?.file; | ||
| if (el !== toggle_el && file && !file.includes('node_modules/')) { | ||
| return el; | ||
| } | ||
| el = el.parentNode; | ||
| } | ||
| } | ||
| function mouseover(event) { | ||
| const el = findMetaEl(event.target); | ||
| if (options.customStyles && el !== active_el) { | ||
| if (active_el) { | ||
| active_el.classList.remove('svelte-inspector-active-target'); | ||
| } | ||
| if (el) { | ||
| el.classList.add('svelte-inspector-active-target'); | ||
| } | ||
| } | ||
| if (el) { | ||
| const { file, line, column } = el.__svelte_meta.loc; | ||
| file_loc = `${file}:${line + 1}:${column + 1}`; | ||
| } else { | ||
| file_loc = null; | ||
| } | ||
| active_el = el; | ||
| } | ||
| function click(event) { | ||
| if (file_loc) { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| event.stopImmediatePropagation(); | ||
| fetch(`/__open-in-editor?file=${encodeURIComponent(file_loc)}`); | ||
| if (options.holdMode && is_holding()) { | ||
| disable(); | ||
| } | ||
| } | ||
| } | ||
| function is_key_active(key, event) { | ||
| switch (key) { | ||
| case 'shift': | ||
| case 'control': | ||
| case 'alt': | ||
| case 'meta': | ||
| return event.getModifierState(key.charAt(0).toUpperCase() + key.slice(1)); | ||
| default: | ||
| return key === event.key.toLowerCase(); | ||
| } | ||
| } | ||
| function is_combo(event) { | ||
| return toggle_combo?.every((key) => is_key_active(key, event)); | ||
| } | ||
| function is_holding() { | ||
| return enabled_ts && Date.now() - enabled_ts > 250; | ||
| } | ||
| function keydown(event) { | ||
| if (event.repeat) { | ||
| return; | ||
| } | ||
| if (is_combo(event)) { | ||
| toggle(); | ||
| if (options.holdMode && enabled) { | ||
| enabled_ts = Date.now(); | ||
| } | ||
| } | ||
| } | ||
| function keyup(event) { | ||
| if (event.repeat) { | ||
| return; | ||
| } | ||
| const k = event.key.toLowerCase(); | ||
| if (enabled && is_holding() && toggle_combo.includes(k)) { | ||
| disable(); | ||
| } else { | ||
| enabled_ts = null; | ||
| } | ||
| } | ||
| function toggle() { | ||
| enabled ? disable() : enable(); | ||
| } | ||
| function listeners(body, enabled) { | ||
| const l = enabled ? body.addEventListener : body.removeEventListener; | ||
| l('mousemove', mousemove); | ||
| l('mouseover', mouseover); | ||
| l('click', click, true); | ||
| } | ||
| function enable() { | ||
| enabled = true; | ||
| const b = document.body; | ||
| if (options.customStyles) { | ||
| b.classList.add('svelte-inspector-enabled'); | ||
| b.style.setProperty('--svelte-inspector-cursor', `url(${JSON.stringify(icon)})`); | ||
| } | ||
| listeners(b, enabled); | ||
| } | ||
| function disable() { | ||
| enabled = false; | ||
| enabled_ts = null; | ||
| const b = document.body; | ||
| listeners(b, enabled); | ||
| if (options.customStyles) { | ||
| b.classList.remove('svelte-inspector-enabled'); | ||
| b.style.removeProperty('--svelte-inspector-cursor'); | ||
| active_el?.classList.remove('svelte-inspector-active-target'); | ||
| } | ||
| } | ||
| onMount(() => { | ||
| if (toggle_combo) { | ||
| document.body.addEventListener('keydown', keydown); | ||
| if (options.holdMode) { | ||
| document.body.addEventListener('keyup', keyup); | ||
| } | ||
| } | ||
| return () => { | ||
| // make sure we get rid of everything | ||
| disable(); | ||
| if (toggle_combo) { | ||
| document.body.removeEventListener('keydown', keydown); | ||
| if (options.holdMode) { | ||
| document.body.addEventListener('keyup', keyup); | ||
| } | ||
| } | ||
| }; | ||
| }); | ||
| </script> | ||
| {#if show_toggle} | ||
| <div | ||
| class="svelte-inspector-toggle" | ||
| class:enabled | ||
| style={`background-image:url(${icon});${options.toggleButtonPos | ||
| .split('-') | ||
| .map((p) => `${p}: 8px;`) | ||
| .join('')}`} | ||
| on:click={() => toggle()} | ||
| bind:this={toggle_el} | ||
| /> | ||
| {/if} | ||
| {#if enabled && file_loc} | ||
| <div | ||
| class="svelte-inspector-overlay" | ||
| style:left="{Math.min(x + 3, document.body.clientWidth - w - 10)}px" | ||
| style:top="{y + 30}px" | ||
| bind:offsetWidth={w} | ||
| > | ||
| {file_loc} | ||
| </div> | ||
| {/if} | ||
| <style> | ||
| :global(body.svelte-inspector-enabled *) { | ||
| cursor: var(--svelte-inspector-cursor), crosshair !important; | ||
| } | ||
| :global(.svelte-inspector-active-target) { | ||
| outline: 2px dashed #ff3e00 !important; | ||
| } | ||
| .svelte-inspector-overlay { | ||
| position: fixed; | ||
| background-color: rgba(0, 0, 0, 0.8); | ||
| color: #fff; | ||
| padding: 2px 4px; | ||
| border-radius: 5px; | ||
| z-index: 999999; | ||
| } | ||
| .svelte-inspector-toggle { | ||
| border: 1px solid #ff3e00; | ||
| border-radius: 8px; | ||
| position: fixed; | ||
| height: 32px; | ||
| width: 32px; | ||
| background-color: white; | ||
| background-position: center; | ||
| background-repeat: no-repeat; | ||
| cursor: pointer; | ||
| } | ||
| .svelte-inspector-toggle:not(.enabled) { | ||
| filter: grayscale(1); | ||
| } | ||
| .svelte-inspector-toggle:hover { | ||
| background-color: #facece; | ||
| } | ||
| </style> |
| // @ts-expect-error virtual import is resolved by vite-plugin-svelte-inspector | ||
| // eslint-disable-next-line node/no-missing-import | ||
| import Inspector from 'virtual:svelte-inspector:Inspector.svelte'; | ||
| function create_inspector_host() { | ||
| const id = 'svelte-inspector-host'; | ||
| if (document.getElementById(id) != null) { | ||
| throw new Error('svelte-inspector-host element already exists'); | ||
| } | ||
| const el = document.createElement('div'); | ||
| el.setAttribute('id', id); | ||
| document.getElementsByTagName('body')[0].appendChild(el); | ||
| return el; | ||
| } | ||
| new Inspector({ target: create_inspector_host() }); |
| import { createRequire } from 'module'; | ||
| import { Plugin } from 'vite'; | ||
| import { log } from '../../utils/log'; | ||
| import { InspectorOptions } from '../../utils/options'; | ||
| const defaultInspectorOptions: InspectorOptions = { | ||
| toggleKeyCombo: process.platform === 'win32' ? 'control-shift' : 'meta-shift', | ||
| holdMode: false, | ||
| showToggleButton: 'active', | ||
| toggleButtonPos: 'top-right', | ||
| customStyles: true | ||
| }; | ||
| export function svelteInspector(): Plugin { | ||
| let root: string; | ||
| let rootRequire: NodeRequire; | ||
| let inspectorOptions: InspectorOptions; | ||
| let append_to: string | undefined; | ||
| return { | ||
| name: 'vite-plugin-svelte:inspector', | ||
| apply: 'serve', | ||
| enforce: 'pre', | ||
| configResolved(config) { | ||
| const vps = config.plugins.find((p) => p.name === 'vite-plugin-svelte'); | ||
| if (vps?.api?.options?.experimental?.inspector) { | ||
| inspectorOptions = { | ||
| ...defaultInspectorOptions, | ||
| ...vps.api.options.experimental.inspector | ||
| }; | ||
| } | ||
| if (!vps || !inspectorOptions) { | ||
| // disabled, turn all hooks into noops | ||
| this.resolveId = this.load = this.transformIndexHtml = this.transform = () => {}; | ||
| } else { | ||
| root = config.root || process.cwd(); | ||
| rootRequire = createRequire(root); | ||
| if (vps.api.options.kit && !inspectorOptions.appendTo) { | ||
| const out_dir = vps.api.options.kit.outDir || '.svelte-kit'; | ||
| inspectorOptions.appendTo = `${out_dir}/runtime/client/start.js`; | ||
| } | ||
| append_to = inspectorOptions.appendTo; | ||
| } | ||
| }, | ||
| async resolveId(importee: string, importer, options) { | ||
| if (options?.ssr) { | ||
| return; | ||
| } | ||
| if (importee === 'virtual:svelte-inspector-options') { | ||
| return importee; | ||
| } | ||
| if (importee.startsWith('virtual:svelte-inspector:')) { | ||
| // this is needed because the plugin itself is not a dependency of the app so regular resolve may not find it | ||
| const file = importee.replace( | ||
| 'virtual:svelte-inspector:', | ||
| '@sveltejs/vite-plugin-svelte/src/ui/inspector/' | ||
| ); | ||
| const path = rootRequire.resolve(file); | ||
| if (path) { | ||
| return path; | ||
| } else { | ||
| log.error.once(`failed to resolve ${file} for ${importee} from ${root}`); | ||
| } | ||
| } | ||
| }, | ||
| load(id) { | ||
| if (id === 'virtual:svelte-inspector-options') { | ||
| return `export default ${JSON.stringify(inspectorOptions ?? {})}`; | ||
| } | ||
| }, | ||
| transform(code: string, id: string, options?: { ssr?: boolean }) { | ||
| if (options?.ssr || !append_to) { | ||
| return; | ||
| } | ||
| if (id.endsWith(append_to)) { | ||
| return { code: `${code}\nimport 'virtual:svelte-inspector:load-inspector.ts'` }; | ||
| } | ||
| }, | ||
| transformIndexHtml(html) { | ||
| if (append_to) { | ||
| return; | ||
| } | ||
| return { | ||
| html, | ||
| tags: [ | ||
| { | ||
| tag: 'script', | ||
| injectTo: 'body', | ||
| attrs: { | ||
| type: 'module', | ||
| // /@id/ is needed, otherwise the virtual: is seen as protocol by browser and cors error happens | ||
| src: '/@id/virtual:svelte-inspector:load-inspector.ts' | ||
| } | ||
| } | ||
| ] | ||
| }; | ||
| } | ||
| }; | ||
| } |
+259
-140
@@ -297,4 +297,5 @@ var __create = Object.create; | ||
| // src/utils/compile.ts | ||
| var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/; | ||
| var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) { | ||
| var _a, _b; | ||
| var _a, _b, _c; | ||
| const { filename, normalizedFilename, cssId, ssr } = svelteRequest; | ||
@@ -362,2 +363,3 @@ const { emitCss = true } = options; | ||
| normalizedFilename, | ||
| lang: ((_c = code.match(scriptLangRE)) == null ? void 0 : _c[1]) || "js", | ||
| compiled, | ||
@@ -1076,2 +1078,3 @@ ssr, | ||
| // src/utils/options.ts | ||
| var import_deepmerge = __toESM(require("deepmerge"), 1); | ||
| var knownOptions = /* @__PURE__ */ new Set([ | ||
@@ -1089,3 +1092,4 @@ "configFile", | ||
| "disableDependencyReinclusion", | ||
| "experimental" | ||
| "experimental", | ||
| "kit" | ||
| ]); | ||
@@ -1110,5 +1114,3 @@ function validateInlineOptions(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), | ||
| const extraOptions = { | ||
| root: viteConfigWithResolvedRoot.root, | ||
@@ -1118,3 +1120,4 @@ isBuild: viteEnv.command === "build", | ||
| isDebug: process.env.DEBUG != null | ||
| }); | ||
| }; | ||
| const merged = mergeConfigs(defaultOptions, svelteConfig, inlineOptions, extraOptions); | ||
| if (svelteConfig == null ? void 0 : svelteConfig.configFile) { | ||
@@ -1125,2 +1128,11 @@ merged.configFile = svelteConfig.configFile; | ||
| } | ||
| function mergeConfigs(...configs) { | ||
| let result = {}; | ||
| for (const config of configs.filter(Boolean)) { | ||
| result = (0, import_deepmerge.default)(result, config, { | ||
| arrayMerge: (target, source) => source ?? target | ||
| }); | ||
| } | ||
| return result; | ||
| } | ||
| function resolveOptions(preResolveOptions2, viteConfig) { | ||
@@ -1134,7 +1146,7 @@ const defaultOptions = { | ||
| }; | ||
| const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), { | ||
| compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions), | ||
| const extraOptions = { | ||
| root: viteConfig.root, | ||
| isProduction: viteConfig.isProduction | ||
| }); | ||
| }; | ||
| const merged = mergeConfigs(defaultOptions, preResolveOptions2, extraOptions); | ||
| addExtraPreprocessors(merged, viteConfig); | ||
@@ -1192,2 +1204,3 @@ enforceOptionsForHmr(merged); | ||
| function buildExtraViteConfig(options, config) { | ||
| var _a; | ||
| const svelteDeps = findRootSvelteDependencies(options.root); | ||
@@ -1203,3 +1216,3 @@ const extraViteConfig = { | ||
| } | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) { | ||
| extraViteConfig.optimizeDeps = __spreadProps(__spreadValues({}, extraViteConfig.optimizeDeps), { | ||
@@ -1217,11 +1230,12 @@ extensions: options.extensions ?? [".svelte"], | ||
| function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) { | ||
| var _a; | ||
| const include = []; | ||
| const exclude = ["svelte-hmr"]; | ||
| const isIncluded = (dep) => { | ||
| var _a; | ||
| return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep)); | ||
| var _a2; | ||
| return include.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a2.includes(dep)); | ||
| }; | ||
| const isExcluded = (dep) => { | ||
| var _a; | ||
| return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`))); | ||
| var _a2; | ||
| return exclude.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a2.some((id) => dep === id || id.startsWith(`${dep}/`))); | ||
| }; | ||
@@ -1235,3 +1249,3 @@ if (!isExcluded("svelte")) { | ||
| } | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) { | ||
| return { include, exclude }; | ||
@@ -1415,13 +1429,2 @@ } | ||
| }; | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path5.default.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const listenerCollection = { | ||
@@ -1432,7 +1435,20 @@ add: [], | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| if (svelteConfigFile !== false) { | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path5.default.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| } | ||
| } | ||
@@ -1524,2 +1540,91 @@ Object.entries(listenerCollection).forEach(([evt, listeners]) => { | ||
| // src/ui/inspector/plugin.ts | ||
| var import_module5 = require("module"); | ||
| var defaultInspectorOptions = { | ||
| toggleKeyCombo: process.platform === "win32" ? "control-shift" : "meta-shift", | ||
| holdMode: false, | ||
| showToggleButton: "active", | ||
| toggleButtonPos: "top-right", | ||
| customStyles: true | ||
| }; | ||
| function svelteInspector() { | ||
| let root; | ||
| let rootRequire; | ||
| let inspectorOptions; | ||
| let append_to; | ||
| return { | ||
| name: "vite-plugin-svelte:inspector", | ||
| apply: "serve", | ||
| enforce: "pre", | ||
| configResolved(config) { | ||
| var _a, _b, _c; | ||
| const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte"); | ||
| if ((_c = (_b = (_a = vps == null ? void 0 : vps.api) == null ? void 0 : _a.options) == null ? void 0 : _b.experimental) == null ? void 0 : _c.inspector) { | ||
| inspectorOptions = __spreadValues(__spreadValues({}, defaultInspectorOptions), vps.api.options.experimental.inspector); | ||
| } | ||
| if (!vps || !inspectorOptions) { | ||
| this.resolveId = this.load = this.transformIndexHtml = this.transform = () => { | ||
| }; | ||
| } else { | ||
| root = config.root || process.cwd(); | ||
| rootRequire = (0, import_module5.createRequire)(root); | ||
| if (vps.api.options.kit && !inspectorOptions.appendTo) { | ||
| const out_dir = vps.api.options.kit.outDir || ".svelte-kit"; | ||
| inspectorOptions.appendTo = `${out_dir}/runtime/client/start.js`; | ||
| } | ||
| append_to = inspectorOptions.appendTo; | ||
| } | ||
| }, | ||
| async resolveId(importee, importer, options) { | ||
| if (options == null ? void 0 : options.ssr) { | ||
| return; | ||
| } | ||
| if (importee === "virtual:svelte-inspector-options") { | ||
| return importee; | ||
| } | ||
| if (importee.startsWith("virtual:svelte-inspector:")) { | ||
| const file = importee.replace("virtual:svelte-inspector:", "@sveltejs/vite-plugin-svelte/src/ui/inspector/"); | ||
| const path8 = rootRequire.resolve(file); | ||
| if (path8) { | ||
| return path8; | ||
| } else { | ||
| log.error.once(`failed to resolve ${file} for ${importee} from ${root}`); | ||
| } | ||
| } | ||
| }, | ||
| load(id) { | ||
| if (id === "virtual:svelte-inspector-options") { | ||
| return `export default ${JSON.stringify(inspectorOptions ?? {})}`; | ||
| } | ||
| }, | ||
| transform(code, id, options) { | ||
| if ((options == null ? void 0 : options.ssr) || !append_to) { | ||
| return; | ||
| } | ||
| if (id.endsWith(append_to)) { | ||
| return { code: `${code} | ||
| import 'virtual:svelte-inspector:load-inspector.ts'` }; | ||
| } | ||
| }, | ||
| transformIndexHtml(html) { | ||
| if (append_to) { | ||
| return; | ||
| } | ||
| return { | ||
| html, | ||
| tags: [ | ||
| { | ||
| tag: "script", | ||
| injectTo: "body", | ||
| attrs: { | ||
| type: "module", | ||
| src: "/@id/virtual:svelte-inspector:load-inspector.ts" | ||
| } | ||
| } | ||
| ] | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| // src/index.ts | ||
@@ -1537,120 +1642,134 @@ function svelte(inlineOptions) { | ||
| 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 preResolveOptions(inlineOptions, config, configEnv); | ||
| const extraViteConfig = buildExtraViteConfig(options, config); | ||
| log.debug("additional vite config", extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte2 = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| log.debug("resolved options", options); | ||
| }, | ||
| async buildStart() { | ||
| if (!options.experimental.prebundleSvelteLibraries) | ||
| return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| configureServer(server) { | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| load(id, opts) { | ||
| const ssr = opts === true || (opts == null ? void 0 : opts.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; | ||
| const api = {}; | ||
| const plugins = [ | ||
| { | ||
| name: "vite-plugin-svelte", | ||
| enforce: "pre", | ||
| api, | ||
| async config(config, configEnv) { | ||
| if (process.env.DEBUG) { | ||
| log.setLevel("debug"); | ||
| } else if (config.logLevel) { | ||
| log.setLevel(config.logLevel); | ||
| } | ||
| options = await preResolveOptions(inlineOptions, config, configEnv); | ||
| const extraViteConfig = buildExtraViteConfig(options, config); | ||
| log.debug("additional vite config", extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte2 = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| api.options = options; | ||
| log.debug("resolved options", options); | ||
| }, | ||
| async buildStart() { | ||
| var _a; | ||
| if (!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries)) | ||
| return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| configureServer(server) { | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| load(id, opts) { | ||
| const ssr = opts === true || (opts == null ? void 0 : opts.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_fs6.default.readFileSync(filename, "utf-8"); | ||
| } | ||
| } | ||
| if (viteConfig.assetsInclude(filename)) { | ||
| log.debug(`load returns raw content for ${filename}`); | ||
| return import_fs6.default.readFileSync(filename, "utf-8"); | ||
| }, | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!(opts == null ? void 0 : opts.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; | ||
| } | ||
| } | ||
| }, | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!(opts == null ? void 0 : opts.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; | ||
| 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; | ||
| } | ||
| 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; | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
| return resolved; | ||
| } | ||
| } catch (e) { | ||
| log.debug.once(`error trying to resolve ${importee} from ${importer} via package.json svelte field `, e); | ||
| } | ||
| }, | ||
| async transform(code, id, opts) { | ||
| var _a; | ||
| const ssr = !!(opts == null ? void 0 : opts.ssr); | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte2(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server.watcher, d, options.root); | ||
| }); | ||
| } | ||
| return resolvedSvelteSSR; | ||
| } | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
| return resolved; | ||
| log.debug(`transform returns compiled js for ${svelteRequest.filename}`); | ||
| return __spreadProps(__spreadValues({}, compileData.compiled.js), { | ||
| meta: { | ||
| vite: { | ||
| lang: compileData.lang | ||
| } | ||
| } | ||
| }); | ||
| }, | ||
| handleHotUpdate(ctx) { | ||
| if (!options.hot || !options.emitCss) { | ||
| return; | ||
| } | ||
| } catch (e) { | ||
| log.debug.once(`error trying to resolve ${importee} from ${importer} via package.json svelte field `, e); | ||
| const svelteRequest = requestParser(ctx.file, false, ctx.timestamp); | ||
| if (svelteRequest) { | ||
| return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options); | ||
| } | ||
| } | ||
| }, | ||
| async transform(code, id, opts) { | ||
| var _a; | ||
| const ssr = !!(opts == null ? void 0 : opts.ssr); | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte2(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server.watcher, d, options.root); | ||
| }); | ||
| } | ||
| log.debug(`transform returns compiled js for ${svelteRequest.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(compileSvelte2, ctx, svelteRequest, cache, options); | ||
| } | ||
| } | ||
| }; | ||
| ]; | ||
| plugins.push(svelteInspector()); | ||
| return plugins.filter(Boolean); | ||
| } | ||
@@ -1657,0 +1776,0 @@ // Annotate the CommonJS export names for ESM import in node: |
+45
-2
@@ -11,3 +11,3 @@ import { Plugin } from 'vite'; | ||
| * | ||
| * set to `false` to skip reading config from a file | ||
| * set to `false` to ignore the svelte config file | ||
| * | ||
@@ -154,3 +154,46 @@ * @see https://vitejs.dev/config/#root | ||
| }) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void; | ||
| /** | ||
| * enable svelte inspector | ||
| */ | ||
| inspector?: InspectorOptions | boolean; | ||
| } | ||
| interface InspectorOptions { | ||
| /** | ||
| * define a key combo to toggle inspector, | ||
| * @default 'control-shift' on windows, 'meta-shift' on other os | ||
| * | ||
| * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by - | ||
| * examples: control-shift, control-o, control-alt-s meta-x control-meta | ||
| * Some keys have native behavior (e.g. alt-s opens history menu on firefox). | ||
| * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended. | ||
| */ | ||
| toggleKeyCombo?: string; | ||
| /** | ||
| * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress | ||
| * @default false | ||
| */ | ||
| holdMode?: boolean; | ||
| /** | ||
| * when to show the toggle button | ||
| * @default 'active' | ||
| */ | ||
| showToggleButton?: 'always' | 'active' | 'never'; | ||
| /** | ||
| * where to display the toggle button | ||
| * @default top-right | ||
| */ | ||
| toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; | ||
| /** | ||
| * inject custom styles when inspector is active | ||
| */ | ||
| customStyles?: boolean; | ||
| /** | ||
| * append an import to the module id ending with `appendTo` instead of adding a script into body | ||
| * useful for frameworks that do not support trannsformIndexHtml hook | ||
| * | ||
| * WARNING: only set this if you know exactly what it does. | ||
| * Regular users of vite-plugin-svelte or SvelteKit do not need it | ||
| */ | ||
| appendTo?: string; | ||
| } | ||
| declare type ModuleFormat = NonNullable<CompileOptions['format']>; | ||
@@ -160,4 +203,4 @@ declare type CssHashGetter = NonNullable<CompileOptions['cssHash']>; | ||
| declare function svelte(inlineOptions?: Partial<Options>): Plugin; | ||
| declare function svelte(inlineOptions?: Partial<Options>): Plugin[]; | ||
| export { Arrayable, CssHashGetter, ModuleFormat, Options, svelte }; |
+259
-140
@@ -275,4 +275,5 @@ var __defProp = Object.defineProperty; | ||
| // src/utils/compile.ts | ||
| var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/; | ||
| var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) { | ||
| var _a, _b; | ||
| var _a, _b, _c; | ||
| const { filename, normalizedFilename, cssId, ssr } = svelteRequest; | ||
@@ -340,2 +341,3 @@ const { emitCss = true } = options; | ||
| normalizedFilename, | ||
| lang: ((_c = code.match(scriptLangRE)) == null ? void 0 : _c[1]) || "js", | ||
| compiled, | ||
@@ -1058,2 +1060,3 @@ ssr, | ||
| // src/utils/options.ts | ||
| import deepmerge from "deepmerge"; | ||
| var knownOptions = /* @__PURE__ */ new Set([ | ||
@@ -1071,3 +1074,4 @@ "configFile", | ||
| "disableDependencyReinclusion", | ||
| "experimental" | ||
| "experimental", | ||
| "kit" | ||
| ]); | ||
@@ -1092,5 +1096,3 @@ function validateInlineOptions(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), | ||
| const extraOptions = { | ||
| root: viteConfigWithResolvedRoot.root, | ||
@@ -1100,3 +1102,4 @@ isBuild: viteEnv.command === "build", | ||
| isDebug: process.env.DEBUG != null | ||
| }); | ||
| }; | ||
| const merged = mergeConfigs(defaultOptions, svelteConfig, inlineOptions, extraOptions); | ||
| if (svelteConfig == null ? void 0 : svelteConfig.configFile) { | ||
@@ -1107,2 +1110,11 @@ merged.configFile = svelteConfig.configFile; | ||
| } | ||
| function mergeConfigs(...configs) { | ||
| let result = {}; | ||
| for (const config of configs.filter(Boolean)) { | ||
| result = deepmerge(result, config, { | ||
| arrayMerge: (target, source) => source ?? target | ||
| }); | ||
| } | ||
| return result; | ||
| } | ||
| function resolveOptions(preResolveOptions2, viteConfig) { | ||
@@ -1116,7 +1128,7 @@ const defaultOptions = { | ||
| }; | ||
| const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), { | ||
| compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions), | ||
| const extraOptions = { | ||
| root: viteConfig.root, | ||
| isProduction: viteConfig.isProduction | ||
| }); | ||
| }; | ||
| const merged = mergeConfigs(defaultOptions, preResolveOptions2, extraOptions); | ||
| addExtraPreprocessors(merged, viteConfig); | ||
@@ -1174,2 +1186,3 @@ enforceOptionsForHmr(merged); | ||
| function buildExtraViteConfig(options, config) { | ||
| var _a; | ||
| const svelteDeps = findRootSvelteDependencies(options.root); | ||
@@ -1185,3 +1198,3 @@ const extraViteConfig = { | ||
| } | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) { | ||
| extraViteConfig.optimizeDeps = __spreadProps(__spreadValues({}, extraViteConfig.optimizeDeps), { | ||
@@ -1199,11 +1212,12 @@ extensions: options.extensions ?? [".svelte"], | ||
| function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) { | ||
| var _a; | ||
| const include = []; | ||
| const exclude = ["svelte-hmr"]; | ||
| const isIncluded = (dep) => { | ||
| var _a; | ||
| return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep)); | ||
| var _a2; | ||
| return include.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a2.includes(dep)); | ||
| }; | ||
| const isExcluded = (dep) => { | ||
| var _a; | ||
| return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`))); | ||
| var _a2; | ||
| return exclude.includes(dep) || ((_a2 = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a2.some((id) => dep === id || id.startsWith(`${dep}/`))); | ||
| }; | ||
@@ -1217,3 +1231,3 @@ if (!isExcluded("svelte")) { | ||
| } | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) { | ||
| return { include, exclude }; | ||
@@ -1397,13 +1411,2 @@ } | ||
| }; | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path5.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const listenerCollection = { | ||
@@ -1414,7 +1417,20 @@ add: [], | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| if (svelteConfigFile !== false) { | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path5.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| } | ||
| } | ||
@@ -1506,2 +1522,91 @@ Object.entries(listenerCollection).forEach(([evt, listeners]) => { | ||
| // src/ui/inspector/plugin.ts | ||
| import { createRequire as createRequire5 } from "module"; | ||
| var defaultInspectorOptions = { | ||
| toggleKeyCombo: process.platform === "win32" ? "control-shift" : "meta-shift", | ||
| holdMode: false, | ||
| showToggleButton: "active", | ||
| toggleButtonPos: "top-right", | ||
| customStyles: true | ||
| }; | ||
| function svelteInspector() { | ||
| let root; | ||
| let rootRequire; | ||
| let inspectorOptions; | ||
| let append_to; | ||
| return { | ||
| name: "vite-plugin-svelte:inspector", | ||
| apply: "serve", | ||
| enforce: "pre", | ||
| configResolved(config) { | ||
| var _a, _b, _c; | ||
| const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte"); | ||
| if ((_c = (_b = (_a = vps == null ? void 0 : vps.api) == null ? void 0 : _a.options) == null ? void 0 : _b.experimental) == null ? void 0 : _c.inspector) { | ||
| inspectorOptions = __spreadValues(__spreadValues({}, defaultInspectorOptions), vps.api.options.experimental.inspector); | ||
| } | ||
| if (!vps || !inspectorOptions) { | ||
| this.resolveId = this.load = this.transformIndexHtml = this.transform = () => { | ||
| }; | ||
| } else { | ||
| root = config.root || process.cwd(); | ||
| rootRequire = createRequire5(root); | ||
| if (vps.api.options.kit && !inspectorOptions.appendTo) { | ||
| const out_dir = vps.api.options.kit.outDir || ".svelte-kit"; | ||
| inspectorOptions.appendTo = `${out_dir}/runtime/client/start.js`; | ||
| } | ||
| append_to = inspectorOptions.appendTo; | ||
| } | ||
| }, | ||
| async resolveId(importee, importer, options) { | ||
| if (options == null ? void 0 : options.ssr) { | ||
| return; | ||
| } | ||
| if (importee === "virtual:svelte-inspector-options") { | ||
| return importee; | ||
| } | ||
| if (importee.startsWith("virtual:svelte-inspector:")) { | ||
| const file = importee.replace("virtual:svelte-inspector:", "@sveltejs/vite-plugin-svelte/src/ui/inspector/"); | ||
| const path8 = rootRequire.resolve(file); | ||
| if (path8) { | ||
| return path8; | ||
| } else { | ||
| log.error.once(`failed to resolve ${file} for ${importee} from ${root}`); | ||
| } | ||
| } | ||
| }, | ||
| load(id) { | ||
| if (id === "virtual:svelte-inspector-options") { | ||
| return `export default ${JSON.stringify(inspectorOptions ?? {})}`; | ||
| } | ||
| }, | ||
| transform(code, id, options) { | ||
| if ((options == null ? void 0 : options.ssr) || !append_to) { | ||
| return; | ||
| } | ||
| if (id.endsWith(append_to)) { | ||
| return { code: `${code} | ||
| import 'virtual:svelte-inspector:load-inspector.ts'` }; | ||
| } | ||
| }, | ||
| transformIndexHtml(html) { | ||
| if (append_to) { | ||
| return; | ||
| } | ||
| return { | ||
| html, | ||
| tags: [ | ||
| { | ||
| tag: "script", | ||
| injectTo: "body", | ||
| attrs: { | ||
| type: "module", | ||
| src: "/@id/virtual:svelte-inspector:load-inspector.ts" | ||
| } | ||
| } | ||
| ] | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| // src/index.ts | ||
@@ -1519,120 +1624,134 @@ function svelte(inlineOptions) { | ||
| 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 preResolveOptions(inlineOptions, config, configEnv); | ||
| const extraViteConfig = buildExtraViteConfig(options, config); | ||
| log.debug("additional vite config", extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte2 = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| log.debug("resolved options", options); | ||
| }, | ||
| async buildStart() { | ||
| if (!options.experimental.prebundleSvelteLibraries) | ||
| return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| configureServer(server) { | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| load(id, opts) { | ||
| const ssr = opts === true || (opts == null ? void 0 : opts.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; | ||
| const api = {}; | ||
| const plugins = [ | ||
| { | ||
| name: "vite-plugin-svelte", | ||
| enforce: "pre", | ||
| api, | ||
| async config(config, configEnv) { | ||
| if (process.env.DEBUG) { | ||
| log.setLevel("debug"); | ||
| } else if (config.logLevel) { | ||
| log.setLevel(config.logLevel); | ||
| } | ||
| options = await preResolveOptions(inlineOptions, config, configEnv); | ||
| const extraViteConfig = buildExtraViteConfig(options, config); | ||
| log.debug("additional vite config", extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte2 = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| api.options = options; | ||
| log.debug("resolved options", options); | ||
| }, | ||
| async buildStart() { | ||
| var _a; | ||
| if (!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries)) | ||
| return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| configureServer(server) { | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| load(id, opts) { | ||
| const ssr = opts === true || (opts == null ? void 0 : opts.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 fs7.readFileSync(filename, "utf-8"); | ||
| } | ||
| } | ||
| if (viteConfig.assetsInclude(filename)) { | ||
| log.debug(`load returns raw content for ${filename}`); | ||
| return fs7.readFileSync(filename, "utf-8"); | ||
| }, | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!(opts == null ? void 0 : opts.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; | ||
| } | ||
| } | ||
| }, | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!(opts == null ? void 0 : opts.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; | ||
| 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; | ||
| } | ||
| 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; | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
| return resolved; | ||
| } | ||
| } catch (e) { | ||
| log.debug.once(`error trying to resolve ${importee} from ${importer} via package.json svelte field `, e); | ||
| } | ||
| }, | ||
| async transform(code, id, opts) { | ||
| var _a; | ||
| const ssr = !!(opts == null ? void 0 : opts.ssr); | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte2(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server.watcher, d, options.root); | ||
| }); | ||
| } | ||
| return resolvedSvelteSSR; | ||
| } | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
| return resolved; | ||
| log.debug(`transform returns compiled js for ${svelteRequest.filename}`); | ||
| return __spreadProps(__spreadValues({}, compileData.compiled.js), { | ||
| meta: { | ||
| vite: { | ||
| lang: compileData.lang | ||
| } | ||
| } | ||
| }); | ||
| }, | ||
| handleHotUpdate(ctx) { | ||
| if (!options.hot || !options.emitCss) { | ||
| return; | ||
| } | ||
| } catch (e) { | ||
| log.debug.once(`error trying to resolve ${importee} from ${importer} via package.json svelte field `, e); | ||
| const svelteRequest = requestParser(ctx.file, false, ctx.timestamp); | ||
| if (svelteRequest) { | ||
| return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options); | ||
| } | ||
| } | ||
| }, | ||
| async transform(code, id, opts) { | ||
| var _a; | ||
| const ssr = !!(opts == null ? void 0 : opts.ssr); | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte2(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server.watcher, d, options.root); | ||
| }); | ||
| } | ||
| log.debug(`transform returns compiled js for ${svelteRequest.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(compileSvelte2, ctx, svelteRequest, cache, options); | ||
| } | ||
| } | ||
| }; | ||
| ]; | ||
| plugins.push(svelteInspector()); | ||
| return plugins.filter(Boolean); | ||
| } | ||
@@ -1639,0 +1758,0 @@ export { |
+5
-3
| { | ||
| "name": "@sveltejs/vite-plugin-svelte", | ||
| "version": "1.0.0-next.42", | ||
| "version": "1.0.0-next.43", | ||
| "license": "MIT", | ||
@@ -22,3 +22,4 @@ "author": "dominikg", | ||
| }, | ||
| "./package.json": "./package.json" | ||
| "./package.json": "./package.json", | ||
| "./src/ui/*": "./src/ui/*" | ||
| }, | ||
@@ -46,2 +47,3 @@ "engines": { | ||
| "debug": "^4.3.4", | ||
| "deepmerge": "^4.2.2", | ||
| "kleur": "^4.1.4", | ||
@@ -69,3 +71,3 @@ "magic-string": "^0.26.1", | ||
| "tsup": "^5.12.5", | ||
| "vite": "^2.9.5" | ||
| "vite": "^2.9.8" | ||
| }, | ||
@@ -72,0 +74,0 @@ "scripts": { |
+162
-135
@@ -23,4 +23,15 @@ import fs from 'fs'; | ||
| import { saveSvelteMetadata } from './utils/optimizer'; | ||
| import { svelteInspector } from './ui/inspector/plugin'; | ||
| export function svelte(inlineOptions?: Partial<Options>): Plugin { | ||
| interface PluginAPI { | ||
| /** | ||
| * must not be modified, should not be used outside of vite-plugin-svelte repo | ||
| * @internal | ||
| * @experimental | ||
| */ | ||
| options?: ResolvedOptions; | ||
| // TODO expose compile cache here so other utility plugins can use it | ||
| } | ||
| export function svelte(inlineOptions?: Partial<Options>): Plugin[] { | ||
| if (process.env.DEBUG != null) { | ||
@@ -44,151 +55,167 @@ log.setLevel('debug'); | ||
| let resolvedSvelteSSR: Promise<PartialResolvedId | null>; | ||
| const api: PluginAPI = {}; | ||
| const plugins: Plugin[] = [ | ||
| { | ||
| name: 'vite-plugin-svelte', | ||
| // make sure our resolver runs before vite internal resolver to resolve svelte field correctly | ||
| enforce: 'pre', | ||
| api, | ||
| async config(config, configEnv): Promise<Partial<UserConfig>> { | ||
| // setup logger | ||
| if (process.env.DEBUG) { | ||
| log.setLevel('debug'); | ||
| } else if (config.logLevel) { | ||
| log.setLevel(config.logLevel); | ||
| } | ||
| // @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); | ||
| log.debug('additional vite config', extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| return { | ||
| name: 'vite-plugin-svelte', | ||
| // make sure our resolver runs before vite internal resolver to resolve svelte field correctly | ||
| enforce: 'pre', | ||
| async config(config, configEnv): Promise<Partial<UserConfig>> { | ||
| // setup logger | ||
| if (process.env.DEBUG) { | ||
| log.setLevel('debug'); | ||
| } else if (config.logLevel) { | ||
| log.setLevel(config.logLevel); | ||
| } | ||
| // @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); | ||
| log.debug('additional vite config', extraViteConfig); | ||
| return extraViteConfig; | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| // TODO deep clone to avoid mutability from outside? | ||
| api.options = options; | ||
| log.debug('resolved options', options); | ||
| }, | ||
| async configResolved(config) { | ||
| options = resolveOptions(options, config); | ||
| patchResolvedViteConfig(config, options); | ||
| requestParser = buildIdParser(options); | ||
| compileSvelte = createCompileSvelte(options); | ||
| viteConfig = config; | ||
| log.debug('resolved options', options); | ||
| }, | ||
| async buildStart() { | ||
| if (!options.experimental?.prebundleSvelteLibraries) return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| // Force Vite to optimize again. Although we mutate the config here, it works because | ||
| // Vite's optimizer runs after `buildStart()`. | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| async buildStart() { | ||
| if (!options.experimental.prebundleSvelteLibraries) return; | ||
| const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options); | ||
| if (isSvelteMetadataChanged) { | ||
| // Force Vite to optimize again. Although we mutate the config here, it works because | ||
| // Vite's optimizer runs after `buildStart()`. | ||
| viteConfig.server.force = true; | ||
| } | ||
| }, | ||
| configureServer(server) { | ||
| // eslint-disable-next-line no-unused-vars | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| configureServer(server) { | ||
| // eslint-disable-next-line no-unused-vars | ||
| options.server = server; | ||
| setupWatchers(options, cache, requestParser); | ||
| }, | ||
| load(id, opts) { | ||
| // @ts-expect-error anticipate vite changing second parameter as options object | ||
| // see https://github.com/vitejs/vite/discussions/5109 | ||
| const ssr: boolean = opts === true || opts?.ssr; | ||
| const svelteRequest = requestParser(id, !!ssr); | ||
| if (svelteRequest) { | ||
| const { filename, query } = svelteRequest; | ||
| // virtual css module | ||
| if (query.svelte && query.type === 'style') { | ||
| const css = cache.getCSS(svelteRequest); | ||
| if (css) { | ||
| log.debug(`load returns css for ${filename}`); | ||
| return css; | ||
| } | ||
| } | ||
| // prevent vite asset plugin from loading files as url that should be compiled in transform | ||
| if (viteConfig.assetsInclude(filename)) { | ||
| log.debug(`load returns raw content for ${filename}`); | ||
| return fs.readFileSync(filename, 'utf-8'); | ||
| } | ||
| } | ||
| }, | ||
| load(id, opts) { | ||
| // @ts-expect-error anticipate vite changing second parameter as options object | ||
| // see https://github.com/vitejs/vite/discussions/5109 | ||
| const ssr: boolean = opts === true || opts?.ssr; | ||
| const svelteRequest = requestParser(id, !!ssr); | ||
| if (svelteRequest) { | ||
| const { filename, query } = svelteRequest; | ||
| // virtual css module | ||
| if (query.svelte && query.type === 'style') { | ||
| const css = cache.getCSS(svelteRequest); | ||
| if (css) { | ||
| log.debug(`load returns css for ${filename}`); | ||
| return css; | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!opts?.ssr; | ||
| const svelteRequest = requestParser(importee, ssr); | ||
| if (svelteRequest?.query.svelte) { | ||
| if (svelteRequest.query.type === 'style') { | ||
| // return cssId with root prefix so postcss pipeline of vite finds the directory correctly | ||
| // see https://github.com/sveltejs/vite-plugin-svelte/issues/14 | ||
| log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`); | ||
| return svelteRequest.cssId; | ||
| } | ||
| log.debug(`resolveId resolved ${importee}`); | ||
| return importee; // query with svelte tag, an id we generated, no need for further analysis | ||
| } | ||
| // prevent vite asset plugin from loading files as url that should be compiled in transform | ||
| if (viteConfig.assetsInclude(filename)) { | ||
| log.debug(`load returns raw content for ${filename}`); | ||
| return fs.readFileSync(filename, 'utf-8'); | ||
| if (ssr && importee === 'svelte') { | ||
| if (!resolvedSvelteSSR) { | ||
| resolvedSvelteSSR = this.resolve('svelte/ssr', undefined, { 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; // returning null here leads to svelte getting resolved regularly | ||
| } | ||
| ); | ||
| } | ||
| return resolvedSvelteSSR; | ||
| } | ||
| } | ||
| }, | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug( | ||
| `resolveId resolved ${resolved} via package.json svelte field of ${importee}` | ||
| ); | ||
| return resolved; | ||
| } | ||
| } catch (e) { | ||
| log.debug.once( | ||
| `error trying to resolve ${importee} from ${importer} via package.json svelte field `, | ||
| e | ||
| ); | ||
| // this error most likely happens due to non-svelte related importee/importers so swallow it here | ||
| // in case it really way a svelte library, users will notice anyway. (lib not working due to failed resolve) | ||
| } | ||
| }, | ||
| async resolveId(importee, importer, opts) { | ||
| const ssr = !!opts?.ssr; | ||
| const svelteRequest = requestParser(importee, ssr); | ||
| if (svelteRequest?.query.svelte) { | ||
| if (svelteRequest.query.type === 'style') { | ||
| // return cssId with root prefix so postcss pipeline of vite finds the directory correctly | ||
| // see https://github.com/sveltejs/vite-plugin-svelte/issues/14 | ||
| log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`); | ||
| return svelteRequest.cssId; | ||
| async transform(code, id, opts) { | ||
| const ssr = !!opts?.ssr; | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| log.debug(`resolveId resolved ${importee}`); | ||
| return importee; // query with svelte tag, an id we generated, no need for further analysis | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (compileData.dependencies?.length && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server!.watcher, d, options.root); | ||
| }); | ||
| } | ||
| log.debug(`transform returns compiled js for ${svelteRequest.filename}`); | ||
| return { | ||
| ...compileData.compiled.js, | ||
| meta: { | ||
| vite: { | ||
| lang: compileData.lang | ||
| } | ||
| } | ||
| }; | ||
| }, | ||
| if (ssr && importee === 'svelte') { | ||
| if (!resolvedSvelteSSR) { | ||
| resolvedSvelteSSR = this.resolve('svelte/ssr', undefined, { 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; // returning null here leads to svelte getting resolved regularly | ||
| } | ||
| ); | ||
| handleHotUpdate(ctx: HmrContext): void | Promise<Array<ModuleNode> | void> { | ||
| if (!options.hot || !options.emitCss) { | ||
| return; | ||
| } | ||
| return resolvedSvelteSSR; | ||
| } | ||
| try { | ||
| const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); | ||
| if (resolved) { | ||
| log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
| return resolved; | ||
| const svelteRequest = requestParser(ctx.file, false, ctx.timestamp); | ||
| if (svelteRequest) { | ||
| return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options); | ||
| } | ||
| } catch (e) { | ||
| log.debug.once( | ||
| `error trying to resolve ${importee} from ${importer} via package.json svelte field `, | ||
| e | ||
| ); | ||
| // this error most likely happens due to non-svelte related importee/importers so swallow it here | ||
| // in case it really way a svelte library, users will notice anyway. (lib not working due to failed resolve) | ||
| } | ||
| }, | ||
| async transform(code, id, opts) { | ||
| const ssr = !!opts?.ssr; | ||
| const svelteRequest = requestParser(id, ssr); | ||
| if (!svelteRequest || svelteRequest.query.svelte) { | ||
| return; | ||
| } | ||
| let compileData; | ||
| try { | ||
| compileData = await compileSvelte(svelteRequest, code, options); | ||
| } catch (e) { | ||
| throw toRollupError(e, options); | ||
| } | ||
| logCompilerWarnings(compileData.compiled.warnings, options); | ||
| cache.update(compileData); | ||
| if (compileData.dependencies?.length && options.server) { | ||
| compileData.dependencies.forEach((d) => { | ||
| ensureWatchedFile(options.server!.watcher, d, options.root); | ||
| }); | ||
| } | ||
| log.debug(`transform returns compiled js for ${svelteRequest.filename}`); | ||
| return compileData.compiled.js; | ||
| }, | ||
| handleHotUpdate(ctx: HmrContext): void | Promise<Array<ModuleNode> | void> { | ||
| if (!options.hot || !options.emitCss) { | ||
| return; | ||
| } | ||
| const svelteRequest = requestParser(ctx.file, false, ctx.timestamp); | ||
| if (svelteRequest) { | ||
| return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options); | ||
| } | ||
| } | ||
| }; | ||
| ]; | ||
| plugins.push(svelteInspector()); | ||
| return plugins.filter(Boolean); | ||
| } | ||
@@ -195,0 +222,0 @@ |
@@ -9,2 +9,4 @@ import { CompileOptions, ResolvedOptions } from './options'; | ||
| const scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/; | ||
| const _createCompileSvelte = (makeHot: Function) => | ||
@@ -92,2 +94,3 @@ async function compileSvelte( | ||
| normalizedFilename, | ||
| lang: code.match(scriptLangRE)?.[1] || 'js', | ||
| // @ts-ignore | ||
@@ -153,2 +156,3 @@ compiled, | ||
| normalizedFilename: string; | ||
| lang: string; | ||
| compiled: Compiled; | ||
@@ -155,0 +159,0 @@ ssr: boolean | undefined; |
+77
-26
@@ -27,2 +27,3 @@ /* eslint-disable no-unused-vars */ | ||
| import { addExtraPreprocessors } from './preprocess'; | ||
| import deepmerge from 'deepmerge'; | ||
@@ -41,3 +42,4 @@ const knownOptions = new Set([ | ||
| 'disableDependencyReinclusion', | ||
| 'experimental' | ||
| 'experimental', | ||
| 'kit' | ||
| ]); | ||
@@ -70,17 +72,3 @@ | ||
| 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 | ||
| const extraOptions: Partial<PreResolvedOptions> = { | ||
| root: viteConfigWithResolvedRoot.root!, | ||
@@ -91,2 +79,9 @@ isBuild: viteEnv.command === 'build', | ||
| }; | ||
| const merged = mergeConfigs<Partial<PreResolvedOptions> | undefined>( | ||
| defaultOptions, | ||
| svelteConfig, | ||
| inlineOptions, | ||
| extraOptions | ||
| ); | ||
| // configFile of svelteConfig contains the absolute path it was loaded from, | ||
@@ -100,2 +95,13 @@ // prefer it over the possibly relative inline path | ||
| function mergeConfigs<T>(...configs: T[]): ResolvedOptions { | ||
| let result = {}; | ||
| for (const config of configs.filter(Boolean)) { | ||
| result = deepmerge<T>(result, config, { | ||
| // replace arrays | ||
| arrayMerge: (target: any[], source: any[]) => source ?? target | ||
| }); | ||
| } | ||
| return result as ResolvedOptions; | ||
| } | ||
| // used in configResolved phase, merges a contextual default config, pre-resolved options, and some preprocessors. | ||
@@ -114,12 +120,8 @@ // also validates the final config. | ||
| }; | ||
| const merged: ResolvedOptions = { | ||
| ...defaultOptions, | ||
| ...preResolveOptions, | ||
| compilerOptions: { | ||
| ...defaultOptions.compilerOptions, | ||
| ...preResolveOptions.compilerOptions | ||
| }, | ||
| const extraOptions: Partial<ResolvedOptions> = { | ||
| root: viteConfig.root, | ||
| isProduction: viteConfig.isProduction | ||
| }; | ||
| const merged: ResolvedOptions = mergeConfigs(defaultOptions, preResolveOptions, extraOptions); | ||
| addExtraPreprocessors(merged, viteConfig); | ||
@@ -216,3 +218,3 @@ enforceOptionsForHmr(merged); | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if (options.experimental?.prebundleSvelteLibraries) { | ||
| extraViteConfig.optimizeDeps = { | ||
@@ -266,3 +268,3 @@ ...extraViteConfig.optimizeDeps, | ||
| // If we prebundle svelte libraries, we can skip the whole prebundling dance below | ||
| if (options.experimental.prebundleSvelteLibraries) { | ||
| if (options.experimental?.prebundleSvelteLibraries) { | ||
| return { include, exclude }; | ||
@@ -366,3 +368,3 @@ } | ||
| * | ||
| * set to `false` to skip reading config from a file | ||
| * set to `false` to ignore the svelte config file | ||
| * | ||
@@ -521,4 +523,53 @@ * @see https://vitejs.dev/config/#root | ||
| }) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void; | ||
| /** | ||
| * enable svelte inspector | ||
| */ | ||
| inspector?: InspectorOptions | boolean; | ||
| } | ||
| export interface InspectorOptions { | ||
| /** | ||
| * define a key combo to toggle inspector, | ||
| * @default 'control-shift' on windows, 'meta-shift' on other os | ||
| * | ||
| * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by - | ||
| * examples: control-shift, control-o, control-alt-s meta-x control-meta | ||
| * Some keys have native behavior (e.g. alt-s opens history menu on firefox). | ||
| * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended. | ||
| */ | ||
| toggleKeyCombo?: string; | ||
| /** | ||
| * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress | ||
| * @default false | ||
| */ | ||
| holdMode?: boolean; | ||
| /** | ||
| * when to show the toggle button | ||
| * @default 'active' | ||
| */ | ||
| showToggleButton?: 'always' | 'active' | 'never'; | ||
| /** | ||
| * where to display the toggle button | ||
| * @default top-right | ||
| */ | ||
| toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; | ||
| /** | ||
| * inject custom styles when inspector is active | ||
| */ | ||
| customStyles?: boolean; | ||
| /** | ||
| * append an import to the module id ending with `appendTo` instead of adding a script into body | ||
| * useful for frameworks that do not support trannsformIndexHtml hook | ||
| * | ||
| * WARNING: only set this if you know exactly what it does. | ||
| * Regular users of vite-plugin-svelte or SvelteKit do not need it | ||
| */ | ||
| appendTo?: string; | ||
| } | ||
| export interface PreResolvedOptions extends Options { | ||
@@ -525,0 +576,0 @@ // these options are non-nullable after resolve |
+22
-18
@@ -61,15 +61,2 @@ import { VitePluginSvelteCache } from './vite-plugin-svelte-cache'; | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename: string) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename: string) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| // collection of watcher listeners by event | ||
@@ -81,7 +68,24 @@ const listenerCollection = { | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| if (svelteConfigFile !== false) { | ||
| // configFile false means we ignore the file and external process is responsible | ||
| const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path.join(root, cfg)); | ||
| const restartOnConfigAdd = (filename: string) => { | ||
| if (possibleSvelteConfigs.includes(filename)) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| const restartOnConfigChange = (filename: string) => { | ||
| if (filename === svelteConfigFile) { | ||
| triggerViteRestart(filename); | ||
| } | ||
| }; | ||
| if (svelteConfigFile) { | ||
| listenerCollection.change.push(restartOnConfigChange); | ||
| listenerCollection.unlink.push(restartOnConfigChange); | ||
| } else { | ||
| listenerCollection.add.push(restartOnConfigAdd); | ||
| } | ||
| } | ||
@@ -88,0 +92,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
479689
8.78%32
14.29%6210
8.08%9
12.5%74
25.42%+ Added
+ Added