diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f933aa82..c41eb466 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -19,6 +19,7 @@ import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool'; import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; import { GitCommitTool } from '@/lib/tools/GitCommitTool'; +import { BuildProjectTool } from '@/lib/tools/BuildProjectTool'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; @@ -47,6 +48,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), npm_add_package: new NpmAddPackageTool(browserFS, cwd), npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), + build_project: new BuildProjectTool(browserFS, cwd), }; // Convert tools to OpenAI format @@ -61,7 +63,7 @@ Key capabilities: - Read and write files in the project - List directory contents - Check if files exist -- Build the project using Vite +- Build the project using esbuild (use the build_project tool) - Get project structure overview - Search through files - Add and remove npm packages @@ -78,7 +80,7 @@ Guidelines: The project uses: - React 18 with TypeScript -- Vite for building +- esbuild for building - TailwindCSS for styling - Nostrify for Nostr integration - shadcn/ui components diff --git a/src/lib/tools/BuildProjectTool.test.ts b/src/lib/tools/BuildProjectTool.test.ts new file mode 100644 index 00000000..acf481ac --- /dev/null +++ b/src/lib/tools/BuildProjectTool.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { BuildProjectTool } from './BuildProjectTool'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock the buildProject function +vi.mock('../build', () => ({ + buildProject: vi.fn(), +})); + +import { buildProject } from '../build'; + +describe('BuildProjectTool', () => { + let mockFS: JSRuntimeFS; + let tool: BuildProjectTool; + + beforeEach(() => { + vi.clearAllMocks(); + + mockFS = { + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + unlink: vi.fn(), + mkdir: vi.fn(), + } as unknown as JSRuntimeFS; + + tool = new BuildProjectTool(mockFS, '/test/project'); + }); + + it('should have correct description and schema', () => { + expect(tool.description).toBe('Build the project using esbuild. Creates optimized production files in the dist directory.'); + expect(tool.inputSchema).toBeDefined(); + }); + + it('should validate input schema correctly', () => { + // Valid inputs (empty object only) + expect(() => tool.inputSchema.parse({})).not.toThrow(); + }); + + it('should fail if package.json does not exist', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + + await expect(tool.execute({})).rejects.toThrow( + 'āŒ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.' + ); + }); + + it('should fail if index.html does not exist', async () => { + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce('{"name": "test"}') // package.json exists + .mockRejectedValueOnce(new Error('File not found')); // index.html doesn't exist + + await expect(tool.execute({})).rejects.toThrow( + 'āŒ Could not find index.html at /test/project. This is required for building the project.' + ); + }); + + it('should successfully build project', async () => { + const mockDist = { + 'index.html': new Uint8Array([1, 2, 3]), + 'main.js': new Uint8Array([4, 5, 6]), + 'main.css': new Uint8Array([7, 8, 9]), + }; + + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce('{"name": "test"}') // package.json + .mockResolvedValueOnce(''); // index.html + + vi.mocked(mockFS.readdir).mockRejectedValue(new Error('Directory not found')); + vi.mocked(buildProject).mockResolvedValue(mockDist); + + const result = await tool.execute({}); + + expect(buildProject).toHaveBeenCalledWith({ + fs: mockFS, + projectPath: '/test/project', + domParser: expect.any(DOMParser), + }); + + expect(mockFS.mkdir).toHaveBeenCalledWith('/test/project/dist', { recursive: true }); + expect(mockFS.writeFile).toHaveBeenCalledTimes(3); + expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/index.html', mockDist['index.html']); + expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.js', mockDist['main.js']); + expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.css', mockDist['main.css']); + + expect(result).toContain('āœ… Successfully built project!'); + expect(result).toContain('šŸ“¦ Files generated: 3'); + expect(result).toContain('šŸ“„ index.html'); + expect(result).toContain('šŸ“„ main.js'); + expect(result).toContain('šŸ“„ main.css'); + }); + + + + it('should clean existing dist directory before building', async () => { + const mockDist = { + 'index.html': new Uint8Array([1, 2, 3]), + }; + + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce('{"name": "test"}') // package.json + .mockResolvedValueOnce(''); // index.html + + vi.mocked(mockFS.readdir).mockResolvedValue(['old-file.js', 'old-style.css']); + vi.mocked(buildProject).mockResolvedValue(mockDist); + + await tool.execute({}); + + expect(mockFS.readdir).toHaveBeenCalledWith('/test/project/dist'); + expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-file.js'); + expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-style.css'); + }); + + it('should handle build errors gracefully', async () => { + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce('{"name": "test"}') // package.json + .mockResolvedValueOnce(''); // index.html + + vi.mocked(buildProject).mockRejectedValue(new Error('Build compilation failed')); + + await expect(tool.execute({})).rejects.toThrow( + 'āŒ Build failed: Error: Build compilation failed' + ); + }); +}); \ No newline at end of file diff --git a/src/lib/tools/BuildProjectTool.ts b/src/lib/tools/BuildProjectTool.ts new file mode 100644 index 00000000..4907b0e8 --- /dev/null +++ b/src/lib/tools/BuildProjectTool.ts @@ -0,0 +1,71 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; +import { buildProject } from "../build"; + +type BuildProjectParams = Record; + +export class BuildProjectTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + + readonly description = "Build the project using esbuild. Creates optimized production files in the dist directory."; + + readonly inputSchema = z.object({}); + + constructor(fs: JSRuntimeFS, cwd: string) { + this.fs = fs; + this.cwd = cwd; + } + + async execute(_args: BuildProjectParams): Promise { + try { + // Check if we're in a valid project directory + try { + await this.fs.readFile(`${this.cwd}/package.json`, "utf8"); + } catch { + throw new Error(`āŒ Could not find package.json at ${this.cwd}. Make sure you're in a valid project directory.`); + } + + // Check if index.html exists + try { + await this.fs.readFile(`${this.cwd}/index.html`, "utf8"); + } catch { + throw new Error(`āŒ Could not find index.html at ${this.cwd}. This is required for building the project.`); + } + + // Run the build + const dist = await buildProject({ + fs: this.fs, + projectPath: this.cwd, + domParser: new DOMParser(), + }); + + // Delete all existing files in "dist" directory + try { + const distFiles = await this.fs.readdir(`${this.cwd}/dist`); + for (const file of distFiles) { + await this.fs.unlink(`${this.cwd}/dist/${file}`); + } + } catch { + // Ignore errors (e.g., directory doesn't exist) + } + + // Create dist directory if it doesn't exist + await this.fs.mkdir(`${this.cwd}/dist`, { recursive: true }); + + // Write all built files to dist directory + for (const [path, contents] of Object.entries(dist)) { + await this.fs.writeFile(`${this.cwd}/dist/${path}`, contents); + } + + const fileCount = Object.keys(dist).length; + const fileList = Object.keys(dist).map(file => ` šŸ“„ ${file}`).join('\n'); + + return `āœ… Successfully built project!\n\nšŸ“ Output: ${this.cwd}/dist\nšŸ“¦ Files generated: ${fileCount}\n\n${fileList}\n\nšŸš€ Your project is ready for deployment!`; + } catch (error) { + throw new Error(`āŒ Build failed: ${String(error)}`); + } + } +} \ No newline at end of file