From 1ab976330246eac5821e56c7bf3288c89dc35d75 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 20 Jul 2025 16:16:02 -0500 Subject: [PATCH] Abstract WebContainer into "JSRuntime" type --- src/App.tsx | 37 ++++---- src/components/JSRuntimeProvider.tsx | 18 ++++ src/components/Shakespeare/ChatPane.tsx | 107 +++++------------------ src/contexts/JSRuntimeContext.ts | 8 ++ src/hooks/useJSRuntime.ts | 14 +++ src/lib/JSRuntime.ts | 40 +++++++++ src/lib/WebContainerAdapter.ts | 109 ++++++++++++++++++++++++ src/lib/copyFiles.ts | 85 ++++++++++++++++++ 8 files changed, 316 insertions(+), 102 deletions(-) create mode 100644 src/components/JSRuntimeProvider.tsx create mode 100644 src/contexts/JSRuntimeContext.ts create mode 100644 src/hooks/useJSRuntime.ts create mode 100644 src/lib/JSRuntime.ts create mode 100644 src/lib/WebContainerAdapter.ts create mode 100644 src/lib/copyFiles.ts diff --git a/src/App.tsx b/src/App.tsx index a912a268..efd59a76 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,8 @@ import { AppProvider } from '@/components/AppProvider'; import { AppConfig } from '@/contexts/AppContext'; import { AISettingsProvider } from '@/components/AISettingsProvider'; import { FSProvider } from '@/components/FSProvider'; +import { JSRuntimeProvider } from '@/components/JSRuntimeProvider'; +import { WebContainerAdapter } from '@/lib/WebContainerAdapter'; import AppRouter from './AppRouter'; const head = createHead({ @@ -49,26 +51,31 @@ const presetRelays = [ const lightningFS = new LightningFS('shakespeare-fs'); const fs = lightningFS.promises; +// Initialize JSRuntime with WebContainer adapter +const jsRuntime = new WebContainerAdapter(); + export function App() { return ( - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/src/components/JSRuntimeProvider.tsx b/src/components/JSRuntimeProvider.tsx new file mode 100644 index 00000000..e9f9c984 --- /dev/null +++ b/src/components/JSRuntimeProvider.tsx @@ -0,0 +1,18 @@ +import { ReactNode } from 'react'; +import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext'; +import type { JSRuntime } from '@/lib/JSRuntime'; + +interface JSRuntimeProviderProps { + children: ReactNode; + runtime: JSRuntime; +} + +export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) { + const contextValue: JSRuntimeContextType = { runtime }; + + return ( + + {children} + + ); +} \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 34372add..df5b1250 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,4 +1,4 @@ -import { FileSystemTree, WebContainer } from '@webcontainer/api'; +import { FileSystemTree } from '@webcontainer/api'; import { useState, useRef, useEffect } from 'react'; import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai'; import { Button } from '@/components/ui/button'; @@ -10,8 +10,9 @@ import { cn } from '@/lib/utils'; import { useAISettings } from '@/hooks/useAISettings'; import { FsToolSet } from '@/lib/FsToolSet'; import { useFS } from '@/hooks/useFS'; - -const webcontainerPromise = WebContainer.boot(); +import { useJSRuntime } from '@/hooks/useJSRuntime'; +import { copyDirectory } from '@/lib/copyFiles'; +import type { WebContainerAdapter } from '@/lib/WebContainerAdapter'; interface ChatPaneProps { projectId: string; @@ -27,6 +28,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const scrollAreaRef = useRef(null); const { settings, isConfigured } = useAISettings(); const { fs } = useFS(); + const { runtime } = useJSRuntime(); const addMessage = (message: AIMessage) => { setMessages((prev) => { @@ -44,8 +46,6 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { }; const runBuild = async () => { - const webcontainer = await webcontainerPromise; - const buildFileTree = async (dirPath: string): Promise => { const tree: FileSystemTree = {}; const items = await fs.readdir(dirPath); @@ -71,95 +71,28 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { return tree; }; + // Build file tree and mount to WebContainer const fsTree = await buildFileTree(`/projects/${projectId}`); - await webcontainer.mount(fsTree); + + // Mount the file tree (this will boot the container if needed) + const webcontainerAdapter = runtime as WebContainerAdapter; + await webcontainerAdapter.mount(fsTree); // Install dependencies and build - const proc = await webcontainer.spawn('npm', ['i']); + const proc = await runtime.spawn('npm', ['i']); await proc.exit; - const proc2 = await webcontainer.spawn('npm', ['run', 'build']); + const proc2 = await runtime.spawn('npm', ['run', 'build']); await proc2.exit; - // Copy "dist" out of the webcontainer back to the project directory - const copyDist = async () => { - try { - // Read the dist directory from webcontainer - const distContents = await webcontainer.fs.readdir('dist', { withFileTypes: true }); - - // Create dist directory in project if it doesn't exist - const distPath = `/projects/${projectId}/dist`; - try { - await fs.mkdir(distPath); - } catch { - // Directory might already exist, that's fine - } - - // Helper function to copy directory recursively - const copyDirectory = async (sourcePath: string, destPath: string) => { - try { - console.log(`Copying directory: ${sourcePath}`); - const items = await webcontainer.fs.readdir(sourcePath, { withFileTypes: true }); - console.log(`Found ${items.length} items in ${sourcePath}`); - - for (const item of items) { - const sourceItemPath = `${sourcePath}/${item.name}`; - const destItemPath = `${destPath}/${item.name}`; - - try { - if (item.isDirectory()) { - console.log(`Creating directory: ${destItemPath}`); - try { - await fs.mkdir(destItemPath); - } catch { - // Directory might already exist - } - await copyDirectory(sourceItemPath, destItemPath); - } else { - console.log(`Copying file: ${sourceItemPath} -> ${destItemPath}`); - const content = await webcontainer.fs.readFile(sourceItemPath); - await fs.writeFile(destItemPath, content); - } - } catch (itemError) { - console.warn(`Failed to copy item ${item.name}:`, itemError); - } - } - } catch (error) { - console.warn(`Failed to copy ${sourcePath}:`, error); - } - }; - - // Copy each package in dist - for (const item of distContents) { - const sourcePath = `dist/${item.name}`; - const destPath = `${distPath}/${item.name}`; - - try { - if (item.isDirectory()) { - console.log(`Processing directory: ${item.name}`); - try { - await fs.mkdir(destPath); - } catch { - // Directory might already exist - } - await copyDirectory(sourcePath, destPath); - } else { - console.log(`Processing file: ${item.name}`); - const content = await webcontainer.fs.readFile(sourcePath); - await fs.writeFile(destPath, content); - } - } catch (itemError) { - console.warn(`Failed to process ${item.name}:`, itemError); - } - } - - console.log('Successfully copied node_modules from webcontainer'); - } catch (error) { - console.error('Failed to copy node_modules:', error); - } - }; - - await copyDist(); + // Copy "dist" directory from runtime back to project filesystem + const distPath = `/projects/${projectId}/dist`; + try { + await copyDirectory(runtime.fs, fs, 'dist', distPath); + console.log('Successfully copied dist from runtime'); + } catch (error) { + console.error('Failed to copy dist:', error); + } }; useEffect(() => { diff --git a/src/contexts/JSRuntimeContext.ts b/src/contexts/JSRuntimeContext.ts new file mode 100644 index 00000000..8f8ec5c7 --- /dev/null +++ b/src/contexts/JSRuntimeContext.ts @@ -0,0 +1,8 @@ +import { createContext } from 'react'; +import type { JSRuntime } from '@/lib/JSRuntime'; + +export interface JSRuntimeContextType { + runtime: JSRuntime; +} + +export const JSRuntimeContext = createContext(undefined); \ No newline at end of file diff --git a/src/hooks/useJSRuntime.ts b/src/hooks/useJSRuntime.ts new file mode 100644 index 00000000..3d6b8771 --- /dev/null +++ b/src/hooks/useJSRuntime.ts @@ -0,0 +1,14 @@ +import { useContext } from 'react'; +import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext'; + +/** + * Hook to access the JavaScript runtime + * @returns JSRuntime context with runtime instance + */ +export function useJSRuntime(): JSRuntimeContextType { + const context = useContext(JSRuntimeContext); + if (context === undefined) { + throw new Error('useJSRuntime must be used within a JSRuntimeProvider'); + } + return context; +} \ No newline at end of file diff --git a/src/lib/JSRuntime.ts b/src/lib/JSRuntime.ts new file mode 100644 index 00000000..5dd51b5d --- /dev/null +++ b/src/lib/JSRuntime.ts @@ -0,0 +1,40 @@ +import type { WebContainerProcess } from '@webcontainer/api'; + +/** + * Directory entry with file type information + */ +export interface DirectoryEntry { + name: string; + isDirectory(): boolean; + isFile(): boolean; +} + +/** + * Filesystem interface compatible with both WebContainer and LightningFS + */ +export interface JSRuntimeFS { + readFile(path: string, encoding?: string): Promise; + writeFile(path: string, data: string | Uint8Array): Promise; + readdir(path: string, options?: { withFileTypes?: boolean }): Promise; + mkdir(path: string, options?: { recursive?: boolean }): Promise; + stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean }>; +} + +/** + * JavaScript runtime interface for executing code and managing files + */ +export interface JSRuntime { + /** + * Filesystem access + */ + readonly fs: JSRuntimeFS; + + /** + * Spawn a process in the runtime environment + * @param command Command to execute + * @param args Command arguments + * @param options Spawn options + * @returns Process handle + */ + spawn(command: string, args?: string[], options?: Record): Promise; +} \ No newline at end of file diff --git a/src/lib/WebContainerAdapter.ts b/src/lib/WebContainerAdapter.ts new file mode 100644 index 00000000..016a75a8 --- /dev/null +++ b/src/lib/WebContainerAdapter.ts @@ -0,0 +1,109 @@ +import { WebContainer, type WebContainerProcess, type FileSystemTree } from '@webcontainer/api'; +import type { JSRuntime, JSRuntimeFS, DirectoryEntry } from './JSRuntime'; + +/** + * WebContainer adapter that implements the JSRuntime interface + */ +export class WebContainerAdapter implements JSRuntime { + private webcontainer: WebContainer | null = null; + private bootPromise: Promise | null = null; + private _fs: JSRuntimeFS | null = null; + + /** + * Get the filesystem interface + */ + get fs(): JSRuntimeFS { + if (!this._fs) { + throw new Error('WebContainer not initialized. Call spawn() first to initialize.'); + } + return this._fs; + } + + /** + * Ensure WebContainer is booted + */ + private async ensureBooted(): Promise { + if (this.webcontainer) { + return this.webcontainer; + } + + if (!this.bootPromise) { + this.bootPromise = WebContainer.boot(); + } + + this.webcontainer = await this.bootPromise; + this._fs = new WebContainerFSAdapter(this.webcontainer); + return this.webcontainer; + } + + /** + * Spawn a process in the WebContainer + * Automatically boots the container on first call + */ + async spawn(command: string, args: string[] = [], options: Record = {}): Promise { + const webcontainer = await this.ensureBooted(); + return webcontainer.spawn(command, args, options); + } + + /** + * Mount a file tree in the WebContainer + * This is a convenience method for setting up the container + */ + async mount(tree: FileSystemTree): Promise { + const webcontainer = await this.ensureBooted(); + return webcontainer.mount(tree); + } +} + +/** + * WebContainer filesystem adapter that implements JSRuntimeFS + */ +class WebContainerFSAdapter implements JSRuntimeFS { + constructor(private webcontainer: WebContainer) {} + + async readFile(path: string, encoding?: string): Promise { + if (encoding) { + return this.webcontainer.fs.readFile(path, encoding as 'utf8'); + } else { + return this.webcontainer.fs.readFile(path); + } + } + + async writeFile(path: string, data: string | Uint8Array): Promise { + return this.webcontainer.fs.writeFile(path, data); + } + + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { + if (options?.withFileTypes) { + return this.webcontainer.fs.readdir(path, { withFileTypes: true }) as Promise; + } else { + return this.webcontainer.fs.readdir(path) as Promise; + } + } + + async mkdir(path: string, options?: { recursive?: boolean }): Promise { + if (options?.recursive) { + await this.webcontainer.fs.mkdir(path, { recursive: true }); + } else { + await this.webcontainer.fs.mkdir(path); + } + } + + async stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean }> { + // WebContainer doesn't have a stat method, so we'll implement a workaround + try { + // Try to read as directory first + await this.webcontainer.fs.readdir(path); + return { + isDirectory: () => true, + isFile: () => false, + }; + } catch { + // If readdir fails, assume it's a file + return { + isDirectory: () => false, + isFile: () => true, + }; + } + } +} \ No newline at end of file diff --git a/src/lib/copyFiles.ts b/src/lib/copyFiles.ts new file mode 100644 index 00000000..3b2a5d8b --- /dev/null +++ b/src/lib/copyFiles.ts @@ -0,0 +1,85 @@ +import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; +import type LightningFS from '@isomorphic-git/lightning-fs'; + +/** + * Copy files and directories between two filesystem instances + * @param sourceFS Source filesystem (e.g., WebContainer fs) + * @param targetFS Target filesystem (e.g., LightningFS) + * @param sourcePath Source directory path + * @param targetPath Target directory path + */ +export async function copyFiles( + sourceFS: JSRuntimeFS, + targetFS: LightningFS.PromisifiedFS, + sourcePath: string, + targetPath: string +): Promise { + try { + console.log(`Copying: ${sourcePath} -> ${targetPath}`); + + // Get source directory contents + const items = await sourceFS.readdir(sourcePath, { withFileTypes: true }) as DirectoryEntry[]; + console.log(`Found ${items.length} items in ${sourcePath}`); + + // Ensure target directory exists + try { + await targetFS.mkdir(targetPath); + } catch { + // Directory might already exist, that's fine + } + + // Copy each item + for (const item of items) { + const sourceItemPath = `${sourcePath}/${item.name}`; + const targetItemPath = `${targetPath}/${item.name}`; + + try { + if (item.isDirectory()) { + console.log(`Creating directory: ${targetItemPath}`); + try { + await targetFS.mkdir(targetItemPath); + } catch { + // Directory might already exist + } + // Recursively copy directory contents + await copyFiles(sourceFS, targetFS, sourceItemPath, targetItemPath); + } else { + console.log(`Copying file: ${sourceItemPath} -> ${targetItemPath}`); + const content = await sourceFS.readFile(sourceItemPath); + await targetFS.writeFile(targetItemPath, content); + } + } catch (itemError) { + console.warn(`Failed to copy item ${item.name}:`, itemError); + } + } + + console.log(`Successfully copied ${sourcePath} to ${targetPath}`); + } catch (error) { + console.error(`Failed to copy ${sourcePath}:`, error); + throw error; + } +} + +/** + * Copy a directory from JSRuntime filesystem to LightningFS + * Convenience wrapper for copyFiles with better error handling + */ +export async function copyDirectory( + sourceFS: JSRuntimeFS, + targetFS: LightningFS.PromisifiedFS, + sourcePath: string, + targetPath: string +): Promise { + try { + // Check if source exists and is a directory + const sourceStat = await sourceFS.stat(sourcePath); + if (!sourceStat.isDirectory()) { + throw new Error(`Source path ${sourcePath} is not a directory`); + } + + await copyFiles(sourceFS, targetFS, sourcePath, targetPath); + } catch (error) { + console.error(`Failed to copy directory ${sourcePath} to ${targetPath}:`, error); + throw error; + } +} \ No newline at end of file