fix: maybe

This commit is contained in:
2023-11-17 13:22:28 +00:00
parent b625ccd8d6
commit 999b1ae6fc
772 changed files with 3923 additions and 30947 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@sveltejs/kit",
"version": "1.27.5",
"version": "1.27.3",
"description": "The fastest way to build Svelte apps",
"repository": {
"type": "git",
@ -11,7 +11,7 @@
"homepage": "https://kit.svelte.dev",
"type": "module",
"dependencies": {
"@sveltejs/vite-plugin-svelte": "^2.5.0",
"@sveltejs/vite-plugin-svelte": "^2.4.1",
"@types/cookie": "^0.5.1",
"cookie": "^0.5.0",
"devalue": "^4.3.1",
@ -41,7 +41,7 @@
"vitest": "^0.34.5"
},
"peerDependencies": {
"svelte": "^3.54.0 || ^4.0.0-next.0 || ^5.0.0-next.0",
"svelte": "^3.54.0 || ^4.0.0-next.0",
"vite": "^4.0.0"
},
"bin": {

View File

@ -1,6 +1,6 @@
import { join } from 'node:path';
/** @typedef {import('./types.js').Validator} Validator */
/** @typedef {import('./types').Validator} Validator */
const directives = object({
'child-src': string_array(),

View File

@ -444,7 +444,7 @@ function create_routes_and_nodes(cwd, config, fallback) {
* @param {string} file
* @param {string[]} component_extensions
* @param {string[]} module_extensions
* @returns {import('./types.js').RouteFile}
* @returns {import('./types').RouteFile}
*/
function analyze(project_relative, file, component_extensions, module_extensions) {
const component_extension = component_extensions.find((ext) => file.endsWith(ext));

View File

@ -1,6 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import { VERSION } from 'svelte/compiler';
import { mkdirp } from '../../utils/filesystem.js';
/** @type {Map<string, string>} */
@ -69,7 +68,3 @@ export function dedent(strings, ...values) {
return str;
}
export function isSvelte5Plus() {
return Number(VERSION[0]) >= 5;
}

View File

@ -1,7 +1,7 @@
import path from 'node:path';
import { relative_path, resolve_entry } from '../../utils/filesystem.js';
import { s } from '../../utils/misc.js';
import { dedent, isSvelte5Plus, write_if_changed } from './utils.js';
import { dedent, write_if_changed } from './utils.js';
import colors from 'kleur';
/**
@ -143,7 +143,7 @@ export function write_client_manifest(kit, manifest_data, output, metadata) {
}(({ error }) => { console.error(error) }),
};
export { default as root } from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}';
export { default as root } from '../root.svelte';
`
);

View File

@ -1,4 +1,4 @@
import { dedent, isSvelte5Plus, write_if_changed } from './utils.js';
import { dedent, write_if_changed } from './utils.js';
/**
* @param {import('types').ManifestData} manifest_data
@ -89,15 +89,4 @@ export function write_root(manifest_data, output) {
{/if}
`
);
if (isSvelte5Plus()) {
write_if_changed(
`${output}/root.js`,
dedent`
import { asClassComponent } from 'svelte/legacy';
import Root from './root.svelte';
export default asClassComponent(Root);
`
);
}
}

View File

@ -4,7 +4,7 @@ import { posixify, resolve_entry } from '../../utils/filesystem.js';
import { s } from '../../utils/misc.js';
import { load_error_page, load_template } from '../config/index.js';
import { runtime_directory } from '../utils.js';
import { isSvelte5Plus, write_if_changed } from './utils.js';
import { write_if_changed } from './utils.js';
import colors from 'kleur';
/**
@ -25,7 +25,7 @@ const server_template = ({
template,
error_page
}) => `
import root from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}';
import root from '../root.svelte';
import { set_building } from '__sveltekit/environment';
import { set_assets } from '__sveltekit/paths';
import { set_private_env, set_public_env } from '${runtime_directory}/shared-server.js';

View File

@ -88,7 +88,6 @@ export function get_tsconfig(kit, include_base_url) {
const include = new Set([
'ambient.d.ts',
'./types/**/$types.d.ts',
config_relative('vite.config.js'),
config_relative('vite.config.ts')
]);
// TODO(v2): find a better way to include all src files. We can't just use routes/lib only because

View File

@ -10,7 +10,7 @@ import { normalizePath } from 'vite';
* @param {import('types').ManifestData} manifest_data
* @param {import('vite').Manifest} server_manifest
* @param {import('vite').Manifest | null} client_manifest
* @param {import('vite').Rollup.OutputAsset[] | null} css
* @param {import('rollup').OutputAsset[] | null} css
*/
export function build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css) {
mkdirp(`${out}/server/nodes`);

View File

@ -25,7 +25,7 @@ export function is_illegal(id, dirs) {
/**
* Creates a guard that checks that no id imports a module that is not allowed to be imported into client-side code.
* @param {import('vite').Rollup.PluginContext} context
* @param {import('rollup').PluginContext} context
* @param {{ cwd: string; lib: string }} paths
*/
export function module_guard(context, { cwd, lib }) {

View File

@ -24,13 +24,13 @@ import prerender from '../../core/postbuild/prerender.js';
import analyse from '../../core/postbuild/analyse.js';
import { s } from '../../utils/misc.js';
import { hash } from '../../runtime/hash.js';
import { dedent, isSvelte5Plus } from '../../core/sync/utils.js';
import { dedent } from '../../core/sync/utils.js';
export { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
const cwd = process.cwd();
/** @type {import('./types.js').EnforcedConfig} */
/** @type {import('./types').EnforcedConfig} */
const enforced_config = {
appType: true,
base: true,
@ -136,7 +136,7 @@ export async function sveltekit() {
onwarn: svelte_config.onwarn,
compilerOptions: {
// @ts-expect-error SvelteKit requires hydratable true by default
hydratable: isSvelte5Plus() ? undefined : true,
hydratable: true,
...svelte_config.compilerOptions
},
...svelte_config.vitePlugin
@ -702,7 +702,7 @@ function kit({ svelte_config }) {
secondary_build_started = true;
const { output } = /** @type {import('vite').Rollup.RollupOutput} */ (
const { output } = /** @type {import('rollup').RollupOutput} */ (
await vite.build({
configFile: vite_config.configFile,
// CLI args
@ -742,7 +742,7 @@ function kit({ svelte_config }) {
};
const css = output.filter(
/** @type {(value: any) => value is import('vite').Rollup.OutputAsset} */
/** @type {(value: any) => value is import('rollup').OutputAsset} */
(value) => value.type === 'asset' && value.fileName.endsWith('.css')
);
@ -863,7 +863,7 @@ function warn_overridden_config(config, resolved_config) {
/**
* @param {Record<string, any>} config
* @param {Record<string, any>} resolved_config
* @param {import('./types.js').EnforcedConfig} enforced_config
* @param {import('./types').EnforcedConfig} enforced_config
* @param {string} path
* @param {string[]} out used locally to compute the return value
*/

View File

@ -15,7 +15,10 @@ import { not_found } from '../utils.js';
/** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
/**
* @param {{ middlewares: import('connect').Server }} vite
* @param {{
* middlewares: import('connect').Server;
* httpServer: import('http').Server;
* }} vite
* @param {import('vite').ResolvedConfig} vite_config
* @param {import('types').ValidatedConfig} svelte_config
*/

View File

@ -22,8 +22,7 @@ import {
get_link_info,
get_router_options,
is_external_url,
scroll_state,
origin
scroll_state
} from './utils.js';
import { base } from '__sveltekit/paths';
@ -56,9 +55,9 @@ function update_scroll_positions(index) {
}
/**
* @param {import('./types.js').SvelteKitApp} app
* @param {import('./types').SvelteKitApp} app
* @param {HTMLElement} target
* @returns {import('./types.js').Client}
* @returns {import('./types').Client}
*/
export function create_client(app, target) {
const routes = parse(app);
@ -83,7 +82,7 @@ export function create_client(app, target) {
*/
const components = [];
/** @type {{id: string, promise: Promise<import('./types.js').NavigationResult>} | null} */
/** @type {{id: string, promise: Promise<import('./types').NavigationResult>} | null} */
let load_cache = null;
const callbacks = {
@ -97,7 +96,7 @@ export function create_client(app, target) {
after_navigate: []
};
/** @type {import('./types.js').NavigationState} */
/** @type {import('./types').NavigationState} */
let current = {
branch: [],
error: null,
@ -248,7 +247,7 @@ export function create_client(app, target) {
});
}
/** @param {import('./types.js').NavigationIntent} intent */
/** @param {import('./types').NavigationIntent} intent */
async function preload_data(intent) {
load_cache = {
id: intent.id,
@ -275,7 +274,7 @@ export function create_client(app, target) {
await Promise.all(promises);
}
/** @param {import('./types.js').NavigationFinished} result */
/** @param {import('./types').NavigationFinished} result */
function initialize(result) {
if (DEV && result.state.error && document.querySelector('vite-error-overlay')) return;
@ -316,7 +315,7 @@ export function create_client(app, target) {
* @param {{
* url: URL;
* params: Record<string, string>;
* branch: Array<import('./types.js').BranchNode | undefined>;
* branch: Array<import('./types').BranchNode | undefined>;
* status: number;
* error: App.Error | null;
* route: import('types').CSRRoute | null;
@ -341,7 +340,7 @@ export function create_client(app, target) {
// eslint-disable-next-line
url.search = url.search; // turn `/?` into `/`
/** @type {import('./types.js').NavigationFinished} */
/** @type {import('./types').NavigationFinished} */
const result = {
type: 'loaded',
state: {
@ -418,9 +417,9 @@ export function create_client(app, target) {
* url: URL;
* params: Record<string, string>;
* route: { id: string | null };
* server_data_node: import('./types.js').DataNode | null;
* server_data_node: import('./types').DataNode | null;
* }} options
* @returns {Promise<import('./types.js').BranchNode>}
* @returns {Promise<import('./types').BranchNode>}
*/
async function load_node({ loader, parent, url, params, route, server_data_node }) {
/** @type {Record<string, any> | null} */
@ -590,8 +589,8 @@ export function create_client(app, target) {
/**
* @param {import('types').ServerDataNode | import('types').ServerDataSkippedNode | null} node
* @param {import('./types.js').DataNode | null} [previous]
* @returns {import('./types.js').DataNode | null}
* @param {import('./types').DataNode | null} [previous]
* @returns {import('./types').DataNode | null}
*/
function create_data_node(node, previous) {
if (node?.type === 'data') return node;
@ -600,8 +599,8 @@ export function create_client(app, target) {
}
/**
* @param {import('./types.js').NavigationIntent} intent
* @returns {Promise<import('./types.js').NavigationResult>}
* @param {import('./types').NavigationIntent} intent
* @returns {Promise<import('./types').NavigationResult>}
*/
async function load_route({ id, invalidating, url, params, route }) {
if (load_cache?.id === id) {
@ -665,7 +664,7 @@ export function create_client(app, target) {
const branch_promises = loaders.map(async (loader, i) => {
if (!loader) return;
/** @type {import('./types.js').BranchNode | undefined} */
/** @type {import('./types').BranchNode | undefined} */
const previous = current.branch[i];
const server_data_node = server_data_nodes?.[i];
@ -708,7 +707,7 @@ export function create_client(app, target) {
// if we don't do this, rejections will be unhandled
for (const p of branch_promises) p.catch(() => {});
/** @type {Array<import('./types.js').BranchNode | undefined>} */
/** @type {Array<import('./types').BranchNode | undefined>} */
const branch = [];
for (let i = 0; i < loaders.length; i += 1) {
@ -782,9 +781,9 @@ export function create_client(app, target) {
/**
* @param {number} i Start index to backtrack from
* @param {Array<import('./types.js').BranchNode | undefined>} branch Branch to backtrack
* @param {Array<import('./types').BranchNode | undefined>} branch Branch to backtrack
* @param {Array<import('types').CSRPageNodeLoader | undefined>} errors All error pages for this branch
* @returns {Promise<{idx: number; node: import('./types.js').BranchNode} | undefined>}
* @returns {Promise<{idx: number; node: import('./types').BranchNode} | undefined>}
*/
async function load_nearest_error_page(i, branch, errors) {
while (i--) {
@ -816,7 +815,7 @@ export function create_client(app, target) {
* url: URL;
* route: { id: string | null }
* }} opts
* @returns {Promise<import('./types.js').NavigationFinished>}
* @returns {Promise<import('./types').NavigationFinished>}
*/
async function load_root_error_page({ status, error, url, route }) {
/** @type {Record<string, string>} */
@ -844,7 +843,7 @@ export function create_client(app, target) {
} catch {
// at this point we have no choice but to fall back to the server, if it wouldn't
// bring us right back here, turning this into an endless loop
if (url.origin !== origin || url.pathname !== location.pathname || hydrated) {
if (url.origin !== location.origin || url.pathname !== location.pathname || hydrated) {
await native_navigation(url);
}
}
@ -859,7 +858,7 @@ export function create_client(app, target) {
server_data_node: create_data_node(server_data_node)
});
/** @type {import('./types.js').BranchNode} */
/** @type {import('./types').BranchNode} */
const root_error = {
node: await default_error_loader(),
loader: default_error_loader,
@ -892,7 +891,7 @@ export function create_client(app, target) {
if (params) {
const id = url.pathname + url.search;
/** @type {import('./types.js').NavigationIntent} */
/** @type {import('./types').NavigationIntent} */
const intent = { id, invalidating, route, params: decode_params(params), url };
return intent;
}
@ -908,7 +907,7 @@ export function create_client(app, target) {
* @param {{
* url: URL;
* type: import('@sveltejs/kit').Navigation["type"];
* intent?: import('./types.js').NavigationIntent;
* intent?: import('./types').NavigationIntent;
* delta?: number;
* }} opts
*/
@ -1171,10 +1170,10 @@ export function create_client(app, target) {
* @param {{ id: string | null }} route
* @param {App.Error} error
* @param {number} status
* @returns {Promise<import('./types.js').NavigationFinished>}
* @returns {Promise<import('./types').NavigationFinished>}
*/
async function server_fallback(url, route, error, status) {
if (url.origin === origin && url.pathname === location.pathname && !hydrated) {
if (url.origin === location.origin && url.pathname === location.pathname && !hydrated) {
// We would reload the same page we're currently on, which isn't hydrated,
// which means no SSR, which means we would end up in an endless loop
return await load_root_error_page({
@ -1766,7 +1765,7 @@ export function create_client(app, target) {
({ params = {}, route = { id: null } } = get_navigation_intent(url, false) || {});
}
/** @type {import('./types.js').NavigationFinished | undefined} */
/** @type {import('./types').NavigationFinished | undefined} */
let result;
try {
@ -1793,7 +1792,7 @@ export function create_client(app, target) {
});
});
/** @type {Array<import('./types.js').BranchNode | undefined>} */
/** @type {Array<import('./types').BranchNode | undefined>} */
const branch = await Promise.all(branch_promises);
const parsed_route = routes.find(({ id }) => id === route.id);
@ -2019,8 +2018,8 @@ function reset_focus() {
}
/**
* @param {import('./types.js').NavigationState} current
* @param {import('./types.js').NavigationIntent | undefined} intent
* @param {import('./types').NavigationState} current
* @param {import('./types').NavigationIntent | undefined} intent
* @param {URL | null} url
* @param {Exclude<import('@sveltejs/kit').NavigationType, 'enter'>} type
*/

View File

@ -1,7 +1,7 @@
import { exec, parse_route_id } from '../../utils/routing.js';
/**
* @param {import('./types.js').SvelteKitApp} app
* @param {import('./types').SvelteKitApp} app
* @returns {import('types').CSRRoute[]}
*/
export function parse({ nodes, server_loads, dictionary, matchers }) {

View File

@ -2,12 +2,12 @@ import { writable } from 'svelte/store';
import { create_updated_store, notifiable_store } from './utils.js';
import { BROWSER } from 'esm-env';
/** @type {import('./types.js').Client} */
/** @type {import('./types').Client} */
export let client;
/**
* @param {{
* client: import('./types.js').Client;
* client: import('./types').Client;
* }} opts
*/
export function init(opts) {

View File

@ -3,9 +3,9 @@ import { create_client } from './client.js';
import { init } from './singletons.js';
/**
* @param {import('./types.js').SvelteKitApp} app
* @param {import('./types').SvelteKitApp} app
* @param {HTMLElement} target
* @param {Parameters<import('./types.js').Client['_hydrate']>[0]} [hydrate]
* @param {Parameters<import('./types').Client['_hydrate']>[0]} [hydrate]
*/
export async function start(app, target, hydrate) {
if (DEV && target === document.body) {

View File

@ -1,4 +1,4 @@
import { applyAction } from '../app/forms.js';
import { applyAction } from '../app/forms';
import {
afterNavigate,
beforeNavigate,
@ -8,7 +8,7 @@ import {
invalidateAll,
preloadCode,
preloadData
} from '../app/navigation.js';
} from '../app/navigation';
import { SvelteComponent } from 'svelte';
import { ClientHooks, CSRPageNode, CSRPageNodeLoader, CSRRoute, TrailingSlash, Uses } from 'types';
import { Page, ParamMatcher } from '@sveltejs/kit';
@ -90,8 +90,7 @@ export type NavigationFinished = {
type: 'loaded';
state: NavigationState;
props: {
constructors: Array<typeof SvelteComponent>;
components?: Array<SvelteComponent>;
components: Array<typeof SvelteComponent>;
page?: Page;
form?: Record<string, any> | null;
[key: `data_${number}`]: Record<string, any>;

View File

@ -6,8 +6,6 @@ import { PRELOAD_PRIORITIES } from './constants.js';
/* global __SVELTEKIT_APP_VERSION_FILE__, __SVELTEKIT_APP_VERSION_POLL_INTERVAL__ */
export const origin = BROWSER ? location.origin : '';
/** @param {HTMLDocument} doc */
export function get_base_uri(doc) {
let baseURI = doc.baseURI;
@ -137,7 +135,7 @@ export function get_link_info(a, base) {
is_external_url(url, base) ||
(a.getAttribute('rel') || '').split(/\s+/).includes('external');
const download = url?.origin === origin && a.hasAttribute('download');
const download = url?.origin === location.origin && a.hasAttribute('download');
return { url, external, target, download };
}
@ -292,5 +290,5 @@ export function create_updated_store() {
* @param {string} base
*/
export function is_external_url(url, base) {
return url.origin !== origin || !url.pathname.startsWith(base);
return url.origin !== location.origin || !url.pathname.startsWith(base);
}

View File

@ -27,7 +27,7 @@ export function get_cookies(request, url, trailing_slash) {
// Emulate browser-behavior: if the cookie is set at '/foo/bar', its path is '/foo'
const default_path = normalized_url.split('/').slice(0, -1).join('/') || '/';
/** @type {Record<string, import('./page/types.js').Cookie>} */
/** @type {Record<string, import('./page/types').Cookie>} */
const new_cookies = {};
/** @type {import('cookie').CookieSerializeOptions} */
@ -232,7 +232,7 @@ export function path_matches(path, constraint) {
/**
* @param {Headers} headers
* @param {import('./page/types.js').Cookie[]} cookies
* @param {import('./page/types').Cookie[]} cookies
*/
export function add_cookies_to_headers(headers, cookies) {
for (const new_cookie of cookies) {

View File

@ -223,8 +223,8 @@ export class Csp {
report_only_provider;
/**
* @param {import('./types.js').CspConfig} config
* @param {import('./types.js').CspOpts} opts
* @param {import('./types').CspConfig} config
* @param {import('./types').CspOpts} opts
*/
constructor({ mode, directives, reportOnly }, { prerender }) {
const use_hashes = mode === 'hash' || (mode === 'auto' && prerender);

View File

@ -96,10 +96,10 @@ export async function render_page(event, page, options, manifest, state, resolve
// inherit the prerender option of the page
state.prerender_default = should_prerender;
/** @type {import('./types.js').Fetched[]} */
/** @type {import('./types').Fetched[]} */
const fetched = [];
if (get_option(nodes, 'ssr') === false && !state.prerendering) {
if (get_option(nodes, 'ssr') === false) {
return await render_response({
branch: [],
fetched,

View File

@ -144,7 +144,7 @@ export async function load_server_data({
* Calls the user's `load` function.
* @param {{
* event: import('@sveltejs/kit').RequestEvent;
* fetched: import('./types.js').Fetched[];
* fetched: import('./types').Fetched[];
* node: import('types').SSRNode | undefined;
* parent: () => Promise<Record<string, any>>;
* resolve_opts: import('types').RequiredResolveOptions;
@ -192,7 +192,7 @@ export async function load_data({
/**
* @param {Pick<import('@sveltejs/kit').RequestEvent, 'fetch' | 'url' | 'request' | 'route'>} event
* @param {import('types').SSRState} state
* @param {import('./types.js').Fetched[]} fetched
* @param {import('./types').Fetched[]} fetched
* @param {boolean} csr
* @param {Pick<Required<import('@sveltejs/kit').ResolveOptions>, 'filterSerializedResponseHeaders'>} resolve_opts
*/

View File

@ -26,8 +26,8 @@ const encoder = new TextEncoder();
/**
* Creates the HTML response.
* @param {{
* branch: Array<import('./types.js').Loaded>;
* fetched: Array<import('./types.js').Fetched>;
* branch: Array<import('./types').Loaded>;
* fetched: Array<import('./types').Fetched>;
* options: import('types').SSROptions;
* manifest: import('@sveltejs/kit').SSRManifest;
* state: import('types').SSRState;

View File

@ -33,7 +33,7 @@ export async function respond_with_error({
return static_error_page(options, status, /** @type {Error} */ (error).message);
}
/** @type {import('./types.js').Fetched[]} */
/** @type {import('./types').Fetched[]} */
const fetched = [];
try {

View File

@ -134,7 +134,7 @@ export async function respond(request, options, manifest, state) {
/** @type {Record<string, string>} */
const headers = {};
/** @type {Record<string, import('./page/types.js').Cookie>} */
/** @type {Record<string, import('./page/types').Cookie>} */
let cookies_to_add = {};
/** @type {import('@sveltejs/kit').RequestEvent} */

View File

@ -414,5 +414,5 @@ export type ValidatedConfig = RecursiveRequired<Config>;
export type ValidatedKitConfig = RecursiveRequired<KitConfig>;
export * from '../exports/index.js';
export * from '../exports/index';
export * from './private.js';

View File

@ -1,4 +1,4 @@
// generated during release, do not modify
/** @type {string} */
export const VERSION = '1.27.5';
export const VERSION = '1.27.3';

View File

@ -1,6 +1,6 @@
{
"name": "@sveltejs/vite-plugin-svelte",
"version": "2.5.2",
"version": "2.4.6",
"license": "MIT",
"author": "dominikg",
"files": [
@ -43,7 +43,7 @@
"vitefu": "^0.2.4"
},
"peerDependencies": {
"svelte": "^3.54.0 || ^4.0.0 || ^5.0.0-next.0",
"svelte": "^3.54.0 || ^4.0.0",
"vite": "^4.0.0"
},
"devDependencies": {

View File

@ -170,16 +170,6 @@ interface ExperimentalOptions {
* @default false
*/
disableSvelteResolveWarnings?: boolean;
/**
* Options for compiling Svelte JS/TS modules
*/
compileModule?: CompileModuleOptions;
}
interface CompileModuleOptions {
extensions?: string[];
include?: Arrayable<string>;
exclude?: Arrayable<string>;
}
type ModuleFormat = NonNullable<'esm'>;

View File

@ -1,6 +1,5 @@
import fs from 'node:fs';
import { version as viteVersion } from 'vite';
import * as svelteCompiler from 'svelte/compiler';
import { svelteInspector } from '@sveltejs/vite-plugin-svelte-inspector';
@ -8,7 +7,7 @@ import { isDepExcluded } from 'vitefu';
import { handleHotUpdate } from './handle-hot-update.js';
import { log, logCompilerWarnings } from './utils/log.js';
import { createCompileSvelte } from './utils/compile.js';
import { buildIdParser, buildModuleIdParser } from './utils/id.js';
import { buildIdParser } from './utils/id.js';
import {
buildExtraViteConfig,
validateInlineOptions,
@ -25,7 +24,7 @@ import { saveSvelteMetadata } from './utils/optimizer.js';
import { VitePluginSvelteCache } from './utils/vite-plugin-svelte-cache.js';
import { loadRaw } from './utils/load-raw.js';
import { FAQ_LINK_CONFLICTS_IN_SVELTE_RESOLVE } from './utils/constants.js';
import { isSvelte3, isSvelte5 } from './utils/svelte-version.js';
import { isSvelte3 } from './utils/svelte-version.js';
const isVite4_0 = viteVersion.startsWith('4.0');
@ -39,8 +38,6 @@ export function svelte(inlineOptions) {
// updated in configResolved hook
/** @type {import('./types/id.d.ts').IdParser} */
let requestParser;
/** @type {import('./types/id.d.ts').ModuleIdParser} */
let moduleRequestParser;
/** @type {import('./types/options.d.ts').ResolvedOptions} */
let options;
/** @type {import('vite').ResolvedConfig} */
@ -271,45 +268,9 @@ export function svelte(inlineOptions) {
);
}
}
}
},
svelteInspector()
];
if (!isSvelte5) {
plugins.push(svelteInspector()); // TODO reenable once svelte5 has support
}
if (isSvelte5) {
log.warn(
'svelte 5 support in v-p-s is experimental, breaking changes can occur in any release until this notice is removed'
);
log.warn('svelte 5 does not support svelte-inspector yet, disabling it');
// TODO move to separate file
plugins.push({
name: 'vite-plugin-svelte-module',
enforce: 'post',
async configResolved() {
moduleRequestParser = buildModuleIdParser(options);
},
async transform(code, id, opts) {
const ssr = !!opts?.ssr;
const moduleRequest = moduleRequestParser(id, ssr);
if (!moduleRequest) {
return;
}
try {
// @ts-ignore doesn't exist in Svelte 4
const compileResult = await svelteCompiler.compileModule(code, {
generate: ssr ? 'server' : 'client',
filename: moduleRequest.filename
});
logCompilerWarnings(moduleRequest, compileResult.warnings, options);
return compileResult.js;
} catch (e) {
throw toRollupError(e, options);
}
}
});
}
return plugins;
}

View File

@ -28,19 +28,4 @@ export interface SvelteRequest {
raw: boolean;
}
export interface SvelteModuleRequest {
id: string;
filename: string;
normalizedFilename: string;
query: RequestQuery;
timestamp: number;
ssr: boolean;
}
export type IdParser = (id: string, ssr: boolean, timestamp?: number) => SvelteRequest | undefined;
export type ModuleIdParser = (
id: string,
ssr: boolean,
timestamp?: number
) => SvelteModuleRequest | undefined;

View File

@ -1,4 +1,4 @@
import * as svelte from 'svelte/compiler';
import { compile, preprocess, walk } from 'svelte/compiler';
// @ts-ignore
import { createMakeHot } from 'svelte-hmr';
import { safeBase64Hash } from './hash.js';
@ -9,7 +9,7 @@ import { mapToRelative } from './sourcemaps.js';
const scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
import { isSvelte3, isSvelte5 } from './svelte-version.js';
import { isSvelte3 } from './svelte-version.js';
/**
* @param {Function} [makeHot]
@ -53,8 +53,7 @@ export const _createCompileSvelte = (makeHot) => {
const compileOptions = {
...options.compilerOptions,
filename,
// @ts-expect-error generate type is different for svelte5
generate: isSvelte5 ? (ssr ? 'server' : 'client') : ssr ? 'ssr' : 'dom'
generate: ssr ? 'ssr' : 'dom'
};
if (isSvelte3) {
// @ts-ignore
@ -87,7 +86,7 @@ export const _createCompileSvelte = (makeHot) => {
}
if (preprocessors) {
try {
preprocessed = await svelte.preprocess(code, preprocessors, { filename }); // full filename here so postcss works
preprocessed = await preprocess(code, preprocessors, { filename }); // full filename here so postcss works
} catch (e) {
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ''}`;
throw e;
@ -124,7 +123,7 @@ export const _createCompileSvelte = (makeHot) => {
: compileOptions;
const endStat = stats?.start(filename);
const compiled = svelte.compile(finalCode, finalCompileOptions);
const compiled = compile(finalCode, finalCompileOptions);
if (isSvelte3) {
// prevent dangling pure comments
@ -188,8 +187,7 @@ function buildMakeHot(options) {
// @ts-ignore
const adapter = options?.hot?.adapter;
return createMakeHot({
// TODO Svelte 5 doesn't expose walk anymore. If we decide to make v-p-s 2 work with Svelte 5 HMR, we need to import walk from estree-walker
walk: svelte.walk,
walk,
hotApi,
adapter,
hotOptions: { noOverlay: true, .../** @type {object} */ (options.hot) }

View File

@ -1,8 +1,8 @@
import { readFileSync } from 'node:fs';
import * as svelte from 'svelte/compiler';
import { compile, preprocess } from 'svelte/compiler';
import { log } from './log.js';
import { toESBuildError } from './error.js';
import { isSvelte3, isSvelte5 } from './svelte-version.js';
import { isSvelte3 } from './svelte-version.js';
/**
* @typedef {NonNullable<import('vite').DepOptimizationOptions['esbuildOptions']>} EsbuildOptions
@ -11,8 +11,6 @@ import { isSvelte3, isSvelte5 } from './svelte-version.js';
export const facadeEsbuildSveltePluginName = 'vite-plugin-svelte:facade';
const svelteModuleExtension = '.svelte.js';
/**
* @param {import('../types/options.d.ts').ResolvedOptions} options
* @returns {EsbuildPlugin}
@ -26,9 +24,6 @@ export function esbuildSveltePlugin(options) {
if (build.initialOptions.plugins?.some((v) => v.name === 'vite:dep-scan')) return;
const svelteExtensions = (options.extensions ?? ['.svelte']).map((ext) => ext.slice(1));
if (isSvelte5) {
svelteExtensions.push(svelteModuleExtension.slice(1));
}
const svelteFilter = new RegExp('\\.(' + svelteExtensions.join('|') + ')(\\?.*)?$');
/** @type {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection | undefined} */
let statsCollection;
@ -60,21 +55,6 @@ export function esbuildSveltePlugin(options) {
* @returns {Promise<string>}
*/
async function compileSvelte(options, { filename, code }, statsCollection) {
if (isSvelte5 && filename.endsWith(svelteModuleExtension)) {
const endStat = statsCollection?.start(filename);
// @ts-ignore doesn't exist in Svelte 4
const compiled = svelte.compileModule(code, {
filename,
generate: 'client'
});
if (endStat) {
endStat();
}
return compiled.js.map
? compiled.js.code + '//# sourceMappingURL=' + compiled.js.map.toUrl()
: compiled.js.code;
}
let css = options.compilerOptions.css;
if (css !== 'none') {
// TODO ideally we'd be able to externalize prebundled styles too, but for now always put them in the js
@ -85,8 +65,7 @@ async function compileSvelte(options, { filename, code }, statsCollection) {
...options.compilerOptions,
css,
filename,
// @ts-expect-error generate type is different for svelte5
generate: isSvelte5 ? 'client' : 'dom'
generate: 'dom'
};
if (isSvelte3) {
// @ts-ignore
@ -96,7 +75,7 @@ async function compileSvelte(options, { filename, code }, statsCollection) {
if (options.preprocess) {
try {
preprocessed = await svelte.preprocess(code, options.preprocess, { filename });
preprocessed = await preprocess(code, options.preprocess, { filename });
} catch (e) {
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ''}`;
throw e;
@ -123,7 +102,7 @@ async function compileSvelte(options, { filename, code }, statsCollection) {
}
: compileOptions;
const endStat = statsCollection?.start(filename);
const compiled = svelte.compile(finalCode, finalCompileOptions);
const compiled = compile(finalCode, finalCompileOptions);
if (endStat) {
endStat();
}

View File

@ -184,48 +184,3 @@ export function buildIdParser(options) {
}
};
}
/**
* @param {import('../types/options.d.ts').ResolvedOptions} options
* @returns {import('../types/id.d.ts').ModuleIdParser}
*/
export function buildModuleIdParser(options) {
const { include, exclude, extensions } = options?.experimental?.compileModule ?? {};
const root = options.root;
const normalizedRoot = normalizePath(root);
const filter = buildFilter(include, exclude, extensions ?? ['.svelte.js', '.svelte.ts']);
return (id, ssr, timestamp = Date.now()) => {
const { filename, rawQuery } = splitId(id);
if (filter(filename)) {
return parseToSvelteModuleRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
}
};
}
/**
* @param {string} id
* @param {string} filename
* @param {string} rawQuery
* @param {string} root
* @param {number} timestamp
* @param {boolean} ssr
* @returns {import('../types/id.d.ts').SvelteModuleRequest | undefined}
*/
function parseToSvelteModuleRequest(id, filename, rawQuery, root, timestamp, ssr) {
const query = parseRequestQuery(rawQuery);
if (query.url || query.raw || query.direct) {
// skip requests with special vite tags
return;
}
const normalizedFilename = normalize(filename, root);
return {
id,
filename,
normalizedFilename,
query,
timestamp,
ssr
};
}

View File

@ -120,7 +120,7 @@ export const log = {
};
/**
* @param {import('../types/id.d.ts').SvelteRequest | import('../types/id.d.ts').SvelteModuleRequest} svelteRequest
* @param {import('../types/id.d.ts').SvelteRequest} svelteRequest
* @param {import('svelte/types/compiler/interfaces').Warning[]} warnings
* @param {import('../types/options.d.ts').ResolvedOptions} options
*/

View File

@ -25,7 +25,6 @@ import {
import { isCommonDepWithoutSvelteField } from './dependencies.js';
import { VitePluginSvelteStats } from './vite-plugin-svelte-stats.js';
import { VitePluginSvelteCache } from './vite-plugin-svelte-cache.js';
import { isSvelte5 } from './svelte-version.js';
const allowedPluginOptions = new Set([
'include',
@ -228,10 +227,6 @@ export function resolveOptions(preResolveOptions, viteConfig, cache) {
* @param {import('../types/options.d.ts').ResolvedOptions} options
*/
function enforceOptionsForHmr(options) {
if (isSvelte5) {
log.warn('svelte 5 does not support hmr api yet, disabling it for now');
options.hot = false;
}
if (options.hot) {
if (!options.compilerOptions.dev) {
log.warn('hmr is enabled but compilerOptions.dev is false, forcing it to true');

View File

@ -4,8 +4,3 @@ import { VERSION } from 'svelte/compiler';
* @type {boolean}
*/
export const isSvelte3 = VERSION.startsWith('3.');
/**
* @type {boolean}
*/
export const isSvelte5 = VERSION.startsWith('5.');