Support building svelvekit projects

This commit is contained in:
Alex Gleason committed 2025-10-15 20:49:26 -05:00
1 parent 0bd7ee94fd
commit d87700e731
6 files changed
+696 -28

No files matched your search

+64 -1
View File
@@ -33,9 +33,12 @@ describe('useIsProjectPreviewable', () => {
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json');
});
it('returns false when index.html is missing', async () => {
it('returns false when index.html is missing and not a SvelteKit project', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'src/app.html') return Promise.resolve(false);
if (filePath === 'svelte.config.js') return Promise.resolve(false);
if (filePath === 'svelte.config.ts') return Promise.resolve(false);
return Promise.resolve(true);
});
@@ -51,6 +54,66 @@ describe('useIsProjectPreviewable', () => {
expect(result.current.data).toBe(false);
});
it('returns true for SvelteKit project with src/app.html', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'src/app.html') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns true for SvelteKit project with svelte.config.js', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'svelte.config.js') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns true for SvelteKit project with svelte.config.ts', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'svelte.config.ts') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns false when package.json is missing', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(false);
+19 -6
View File
@@ -3,7 +3,9 @@ import { useProjectsManager } from './useProjectsManager';
/**
* Hook to check if a project is previewable
* A project is previewable if it has index.html and package.json
* A project is previewable if it's either:
* 1. A React/Vite project (has index.html and package.json)
* 2. A SvelteKit project (has src/app.html or svelte.config.js/ts and package.json)
*/
export function useIsProjectPreviewable(projectId: string) {
const projectsManager = useProjectsManager();
@@ -12,13 +14,24 @@ export function useIsProjectPreviewable(projectId: string) {
queryKey: ['project-previewable', projectId],
queryFn: async () => {
try {
// Check for required files
const [hasIndexHtml, hasPackageJson] = await Promise.all([
projectsManager.fileExists(projectId, 'index.html'),
projectsManager.fileExists(projectId, 'package.json'),
// Check for package.json (required for all projects)
const hasPackageJson = await projectsManager.fileExists(projectId, 'package.json');
if (!hasPackageJson) return false;
// Check for React/Vite project (index.html at root)
const hasIndexHtml = await projectsManager.fileExists(projectId, 'index.html');
if (hasIndexHtml) return true;
// Check for SvelteKit project
const [hasAppHtml, hasSvelteConfigJs, hasSvelteConfigTs] = await Promise.all([
projectsManager.fileExists(projectId, 'src/app.html'),
projectsManager.fileExists(projectId, 'svelte.config.js'),
projectsManager.fileExists(projectId, 'svelte.config.ts'),
]);
return hasIndexHtml && hasPackageJson;
// SvelteKit project if it has app.html or svelte.config
const isSvelteKit = hasAppHtml || hasSvelteConfigJs || hasSvelteConfigTs;
return isSvelteKit;
} catch (error) {
console.error('Failed to check if project is previewable:', error);
return false;
+1
View File
@@ -222,6 +222,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
switch (moduleName) {
case "buffer":
case "events":
return {
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
+58 -5
View File
@@ -35,16 +35,69 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
return;
}
let resolved: string;
let resolved: string | undefined;
// 1. Absolute paths from CSS files should be treated as external (public assets)
if (args.path.startsWith("/")) {
// Check if the importer is a CSS file
const importerExt = args.importer ? extname(args.importer).slice(1) : '';
if (importerExt === 'css') {
// CSS imports of absolute paths are public assets (fonts, images, etc.)
return {
path: args.path,
external: true,
};
}
resolved = args.path;
} else if (args.path.startsWith("@/")) {
}
// 2. Built-in @/ alias (always points to src/)
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
}
// 3. Relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
}
// 4. Try tsconfig paths
else if (tsconfig?.compilerOptions?.paths) {
const paths = tsconfig.compilerOptions.paths;
const baseUrl = tsconfig.compilerOptions.baseUrl || ".";
// Try to match against tsconfig paths
for (const [pattern, mappings] of Object.entries(paths)) {
// Handle exact matches
if (pattern === args.path) {
const mapping = mappings[0];
if (mapping) {
resolved = join(cwd, baseUrl, mapping);
break;
}
}
// Handle wildcard patterns (e.g., "$lib/*": ["src/lib/*"])
if (pattern.endsWith('/*')) {
const prefix = pattern.slice(0, -2);
if (args.path.startsWith(prefix + '/') || args.path === prefix) {
const suffix = args.path.slice(prefix.length);
const mapping = mappings[0];
if (mapping) {
// Replace the * in the mapping with the suffix
const resolvedMapping = mapping.replace('*', suffix.slice(1) || '');
resolved = join(cwd, baseUrl, resolvedMapping);
break;
}
}
}
}
}
// 5. Try baseUrl as fallback
if (!resolved && args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else {
}
// If still not resolved, let other plugins handle it
if (!resolved) {
return;
}
+331 -16
View File
@@ -7,6 +7,7 @@ import { addDomainToCSP } from "@/lib/csp";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
import { sveltePlugin } from "./sveltePlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -20,6 +21,237 @@ export interface BuildProjectOptions {
esmUrl: string;
}
/**
* Bundle a SvelteKit project
*/
async function bundleSvelteKit(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
const esbuild = await getEsbuild(esmUrl);
// Read app.html template
const appHtmlText = await fs.readFile(
`${projectPath}/src/app.html`,
"utf8",
);
// Read package.json
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
const packageJson = JSON.parse(packageJsonText);
// Try to read tsconfig.json
let tsconfig;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
tsconfig = undefined;
}
// Extract aliases from svelte.config.js and merge with tsconfig paths
const svelteAliases = await extractSvelteAliases(fs, projectPath);
// Always add default SvelteKit $lib alias
const defaultSvelteAliases: Record<string, string> = {
'$lib': 'src/lib',
'$lib/*': 'src/lib/*',
};
const allSvelteAliases = { ...defaultSvelteAliases, ...svelteAliases };
if (Object.keys(allSvelteAliases).length > 0) {
// Convert Svelte aliases to tsconfig paths format
const pathsFromAliases: Record<string, string[]> = {};
for (const [alias, path] of Object.entries(allSvelteAliases)) {
// Handle different alias formats:
// 'my-file' -> 'path/to/file.js' becomes 'my-file': ['path/to/file.js']
// 'my-dir' -> 'path/to/dir' becomes 'my-dir/*': ['path/to/dir/*']
// 'my-dir/*' -> 'path/to/dir/*' stays as is
if (alias.endsWith('/*')) {
pathsFromAliases[alias] = [path];
} else if (path.includes('.')) {
// Likely a file
pathsFromAliases[alias] = [path];
} else {
// Likely a directory - add /* for directory resolution
pathsFromAliases[`${alias}/*`] = [`${path}/*`];
// Also add exact match for the directory itself
pathsFromAliases[alias] = [path];
}
}
// Merge with existing tsconfig paths
if (!tsconfig) {
tsconfig = { compilerOptions: {} };
}
if (!tsconfig.compilerOptions) {
tsconfig.compilerOptions = {};
}
tsconfig.compilerOptions.paths = {
...pathsFromAliases,
...tsconfig.compilerOptions.paths, // tsconfig paths take precedence
};
console.log('Merged Svelte aliases into tsconfig paths:', tsconfig.compilerOptions.paths);
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
console.log(`Building SvelteKit project with ${buildMode}`);
// Find entry point - typically src/routes/+page.svelte or a layout
const entryPoints: string[] = [];
// Check for common SvelteKit entry points
const possibleEntries = [
join(projectPath, "src", "routes", "+layout.svelte"),
join(projectPath, "src", "routes", "+page.svelte"),
];
for (const entry of possibleEntries) {
if (await fileExists(fs, entry)) {
entryPoints.push(entry);
break; // Use the first one found
}
}
// If no entry found, scan the routes directory
if (entryPoints.length === 0) {
try {
const routesPath = join(projectPath, "src", "routes");
const routes = await fs.readdir(routesPath);
for (const route of routes) {
if (route.endsWith(".svelte")) {
entryPoints.push(join(routesPath, route));
break;
}
}
} catch {
throw new Error("Could not find SvelteKit entry point in src/routes/");
}
}
// Build with esbuild
const results = await esbuild.build({
entryPoints,
bundle: true,
write: false,
format: "esm",
target,
outdir: "/",
metafile: true,
sourcemap: true,
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
sveltePlugin({ fs, projectPath }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
define: {
"import.meta.env": JSON.stringify({}),
},
});
const dist: Record<string, Uint8Array> = {};
const doc = domParser.parseFromString(appHtmlText, "text/html");
// Process output files
for (const file of results.outputFiles) {
const ext = file.path.split('.').pop();
const filename = `${file.path.slice(1)}`;
if (ext === "js") {
const script = document.createElement("script");
script.type = "module";
script.src = "/" + filename;
// Insert before %sveltekit.head% placeholder or in head
const head = doc.head;
if (head.textContent?.includes("%sveltekit.head%")) {
head.innerHTML = head.innerHTML.replace("%sveltekit.head%", script.outerHTML);
} else {
head.appendChild(script);
}
dist[filename] = file.contents;
} else if (ext === "css") {
const style = doc.createElement("link");
style.rel = "stylesheet";
style.href = "/" + filename;
if (doc.head.textContent?.includes("%sveltekit.head%")) {
doc.head.innerHTML = doc.head.innerHTML.replace("%sveltekit.head%", style.outerHTML);
} else {
doc.head.appendChild(style);
}
dist[filename] = file.contents;
} else {
dist[filename] = file.contents;
}
}
// Replace SvelteKit placeholders
let htmlContent = doc.documentElement.outerHTML;
// Replace common placeholders
htmlContent = htmlContent.replace(/%sveltekit\.head%/g, "");
htmlContent = htmlContent.replace(/%sveltekit\.body%/g, '<div id="svelte"></div>');
htmlContent = htmlContent.replace(/%sveltekit\.assets%/g, "");
htmlContent = htmlContent.replace(/%sveltekit\.nonce%/g, "");
// Parse CSP and ensure ESM CDN is allowed
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
htmlContent = htmlContent.replace(cspContent, updatedCSP);
}
}
const updatedHtml = "<!DOCTYPE html>\n" + htmlContent;
dist["index.html"] = new TextEncoder().encode(updatedHtml);
return dist;
}
async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
@@ -194,15 +426,32 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
throw new Error(`❌ Could not find package.json at ${projectPath}. Make sure you're in a valid project directory.`);
}
// Check if index.html exists
try {
await fs.readFile(`${projectPath}/index.html`, "utf8");
} catch {
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
}
// Detect if this is a SvelteKit project
const isSvelteKit = await isSvelteKitProject(fs, projectPath);
// Run the build
const dist = await bundle(options);
let dist: Record<string, Uint8Array>;
if (isSvelteKit) {
// Check for src/app.html (required for SvelteKit)
try {
await fs.readFile(`${projectPath}/src/app.html`, "utf8");
} catch {
throw new Error(`❌ Could not find src/app.html at ${projectPath}. This is required for building SvelteKit projects.`);
}
console.log("🎭 Detected SvelteKit project");
dist = await bundleSvelteKit(options);
} else {
// Check if index.html exists (required for React/Vite projects)
try {
await fs.readFile(`${projectPath}/index.html`, "utf8");
} catch {
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
}
// Run the standard build
dist = await bundle(options);
}
// Delete all existing files in output directory
try {
@@ -222,15 +471,19 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
await fs.writeFile(`${outputPath}/${path}`, contents);
}
// Copy files from public directory if it exists
try {
const publicPath = `${projectPath}/public`;
const stat = await fs.stat(publicPath);
if (stat.isDirectory()) {
await copyFiles(fs, fs, publicPath, outputPath);
// Copy files from public directory (React/Vite) or static directory (SvelteKit)
const staticDirs = isSvelteKit ? ["static"] : ["public"];
for (const dirName of staticDirs) {
try {
const staticPath = `${projectPath}/${dirName}`;
const stat = await fs.stat(staticPath);
if (stat.isDirectory()) {
await copyFiles(fs, fs, staticPath, outputPath);
}
} catch {
// Static directory doesn't exist, which is fine
}
} catch {
// Public directory doesn't exist, which is fine
}
// Extract project ID from the project path
@@ -261,6 +514,68 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
}
}
/**
* Extract aliases from svelte.config.js
*/
async function extractSvelteAliases(fs: JSRuntimeFS, projectPath: string): Promise<Record<string, string> | undefined> {
try {
// Try to read svelte.config.js
let configPath: string | undefined;
if (await fileExists(fs, join(projectPath, "svelte.config.js"))) {
configPath = join(projectPath, "svelte.config.js");
} else if (await fileExists(fs, join(projectPath, "svelte.config.ts"))) {
configPath = join(projectPath, "svelte.config.ts");
}
if (!configPath) return undefined;
const configText = await fs.readFile(configPath, "utf8");
// Try to extract alias object using regex
// Look for: alias: { ... }
const aliasMatch = configText.match(/alias\s*:\s*\{([^}]+)\}/s);
if (!aliasMatch) return undefined;
const aliasContent = aliasMatch[1];
const aliases: Record<string, string> = {};
// Parse each alias line: 'key': 'value' or "key": "value"
const aliasPattern = /['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/g;
let match;
while ((match = aliasPattern.exec(aliasContent)) !== null) {
const [, key, value] = match;
aliases[key] = value;
}
return Object.keys(aliases).length > 0 ? aliases : undefined;
} catch (error) {
console.warn('Failed to extract Svelte aliases:', error);
return undefined;
}
}
/**
* Detect if a project is a SvelteKit project
*/
async function isSvelteKitProject(fs: JSRuntimeFS, projectPath: string): Promise<boolean> {
// Check for src/app.html (required for SvelteKit)
const hasAppHtml = await fileExists(fs, join(projectPath, "src", "app.html"));
// Check for svelte.config.js or svelte.config.ts
const hasSvelteConfig =
await fileExists(fs, join(projectPath, "svelte.config.js")) ||
await fileExists(fs, join(projectPath, "svelte.config.ts"));
// Check if index.html exists at root (indicates React/Vite project, not SvelteKit)
const hasRootIndexHtml = await fileExists(fs, join(projectPath, "index.html"));
// A project is considered SvelteKit if:
// 1. It has app.html or svelte.config, AND
// 2. It does NOT have a root index.html (which would indicate React/Vite)
return (hasAppHtml || hasSvelteConfig) && !hasRootIndexHtml;
}
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
const esmDirectives = [
+223
View File
@@ -0,0 +1,223 @@
import type { Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from "@/lib/JSRuntime";
import { compile } from "svelte/compiler";
interface SveltePluginOptions {
fs: JSRuntimeFS;
projectPath: string;
}
/**
* Svelte plugin for esbuild to compile .svelte files in the browser.
* This is a basic implementation that transforms Svelte components to JavaScript.
*/
export function sveltePlugin(options: SveltePluginOptions): Plugin {
const { fs } = options;
return {
name: "svelte",
setup(build) {
// Stub SvelteKit $app modules
build.onResolve({ filter: /^\$app\// }, (args) => {
return {
path: args.path,
namespace: "sveltekit-stub",
};
});
build.onLoad({ filter: /.*/, namespace: "sveltekit-stub" }, (args) => {
const module = args.path;
// $app/environment
if (module === "$app/environment") {
return {
contents: `
export const browser = true;
export const building = false;
export const dev = true;
export const version = "stub";
`,
loader: "js",
};
}
// $app/navigation
if (module === "$app/navigation") {
return {
contents: `
export function afterNavigate(callback) {
// Stub: no-op in browser build
}
export function beforeNavigate(callback) {
// Stub: no-op in browser build
}
export function disableScrollHandling() {
// Stub: no-op in browser build
}
export function goto(url, opts) {
console.warn('[SvelteKit Stub] goto() called with:', url, opts);
window.location.href = typeof url === 'string' ? url : url.toString();
return Promise.resolve();
}
export function invalidate(url) {
console.warn('[SvelteKit Stub] invalidate() called');
return Promise.resolve();
}
export function invalidateAll() {
console.warn('[SvelteKit Stub] invalidateAll() called');
return Promise.resolve();
}
export function onNavigate(callback) {
// Stub: no-op in browser build
}
export function preloadCode(...args) {
console.warn('[SvelteKit Stub] preloadCode() called');
return Promise.resolve();
}
export function preloadData(url) {
console.warn('[SvelteKit Stub] preloadData() called');
return Promise.resolve();
}
export function pushState(url, state) {
console.warn('[SvelteKit Stub] pushState() called');
window.history.pushState(state, '', url);
}
export function replaceState(url, state) {
console.warn('[SvelteKit Stub] replaceState() called');
window.history.replaceState(state, '', url);
}
export function refreshAll() {
console.warn('[SvelteKit Stub] refreshAll() called');
window.location.reload();
return Promise.resolve();
}
`,
loader: "js",
};
}
// $app/stores
if (module === "$app/stores") {
return {
contents: `
import { writable, readable } from 'svelte/store';
export const page = readable({
url: new URL(window.location.href),
params: {},
route: { id: null },
status: 200,
error: null,
data: {},
form: null,
state: {}
});
export const navigating = readable(null);
export const updated = Object.assign(
readable(false),
{ check: () => Promise.resolve(false) }
);
export function getStores() {
return { page, navigating, updated };
}
`,
loader: "js",
};
}
// $app/paths
if (module === "$app/paths") {
return {
contents: `
export const base = '';
export const assets = '';
`,
loader: "js",
};
}
// $app/forms (for form actions)
if (module === "$app/forms") {
return {
contents: `
export function enhance(form, submit) {
console.warn('[SvelteKit Stub] enhance() called - form actions not supported in browser build');
return { destroy() {} };
}
export function applyAction(result) {
console.warn('[SvelteKit Stub] applyAction() called');
return Promise.resolve();
}
export function deserialize(result) {
console.warn('[SvelteKit Stub] deserialize() called');
return result;
}
`,
loader: "js",
};
}
// Unknown $app module
return {
contents: `
console.error('[SvelteKit Stub] Unknown module: ${module}');
export default {};
`,
loader: "js",
};
});
// Handle .svelte file imports
build.onLoad({ filter: /\.svelte$/ }, async (args) => {
try {
const source = await fs.readFile(args.path, "utf8");
// Compile the Svelte component
const result = compile(source, {
filename: args.path,
generate: "client", // Svelte 5 uses "client" instead of "dom"
css: "injected", // Inject CSS into the component
});
// Return the compiled JavaScript
return {
contents: result.js.code,
loader: "js",
warnings: result.warnings?.map((warning) => ({
text: warning.message,
location: warning.start ? {
file: args.path,
line: warning.start.line,
column: warning.start.column,
} : undefined,
})) || [],
};
} catch (error) {
return {
errors: [{
text: error instanceof Error ? error.message : String(error),
location: { file: args.path },
}],
};
}
});
},
};
}