Refactor buildProject, copy public files

This commit is contained in:
Alex Gleason committed 2025-09-12 13:35:52 -05:00
1 parent e8e2b28504
commit d33fa36591
5 files changed
+374 -99

No files matched your search

+29 -32
View File
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { BuildProjectTool } from './BuildProjectTool';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock the buildProject function
// Mock the build functions
vi.mock('../build', () => ({
buildProject: vi.fn(),
}));
@@ -32,36 +32,39 @@ describe('BuildProjectTool', () => {
});
it('should fail if package.json does not exist', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
vi.mocked(buildProject).mockRejectedValue(
new Error('❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.')
);
await expect(tool.execute()).rejects.toThrow(
'❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.'
'❌ Build failed: Error: ❌ 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
vi.mocked(buildProject).mockRejectedValue(
new Error('❌ Could not find index.html at /test/project. This is required for building the project.')
);
await expect(tool.execute()).rejects.toThrow(
'❌ Could not find index.html at /test/project. This is required for building the project.'
'❌ Build failed: Error: ❌ Could not find index.html at /test/project. This is required for building the project.'
);
});
it('should successfully build project', async () => {
const mockDist = {
const mockFiles = {
'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('<html></html>'); // index.html
const mockResult = {
files: mockFiles,
outputPath: '/test/project/dist',
projectId: 'project',
};
vi.mocked(mockFS.readdir).mockRejectedValue(new Error('Directory not found'));
vi.mocked(buildProject).mockResolvedValue(mockDist);
vi.mocked(buildProject).mockResolvedValue(mockResult);
const result = await tool.execute();
@@ -71,13 +74,8 @@ describe('BuildProjectTool', () => {
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('📁 Output: /test/project/dist');
expect(result).toContain('📦 Files generated: 3');
expect(result).toContain('📄 index.html');
expect(result).toContain('📄 main.js');
@@ -87,29 +85,28 @@ describe('BuildProjectTool', () => {
it('should clean existing dist directory before building', async () => {
const mockDist = {
const mockFiles = {
'index.html': new Uint8Array([1, 2, 3]),
};
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json
.mockResolvedValueOnce('<html></html>'); // index.html
const mockResult = {
files: mockFiles,
outputPath: '/test/project/dist',
projectId: 'project',
};
vi.mocked(mockFS.readdir).mockResolvedValue(['old-file.js', 'old-style.css']);
vi.mocked(buildProject).mockResolvedValue(mockDist);
vi.mocked(buildProject).mockResolvedValue(mockResult);
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');
expect(buildProject).toHaveBeenCalledWith({
fs: mockFS,
projectPath: '/test/project',
domParser: expect.any(DOMParser),
});
});
it('should handle build errors gracefully', async () => {
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json
.mockResolvedValueOnce('<html></html>'); // index.html
vi.mocked(buildProject).mockRejectedValue(new Error('Build compilation failed'));
await expect(tool.execute()).rejects.toThrow(
+5 -49
View File
@@ -15,61 +15,17 @@ export class BuildProjectTool implements Tool<void> {
async execute(): Promise<string> {
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({
// Build and write the project files
const result = 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)
}
const fileCount = Object.keys(result.files).length;
const fileList = Object.keys(result.files).map(file => ` 📄 ${file}`).join('\n');
// 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');
// Extract project ID from the current working directory path
// Expected format: /projects/{projectId}
const projectId = this.cwd.split('/').pop();
// Emit build completion event for PreviewPane to listen to
if (projectId && typeof window !== 'undefined') {
const buildCompleteEvent = new CustomEvent('buildComplete', {
detail: { projectId }
});
window.dispatchEvent(buildCompleteEvent);
}
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!`;
return `✅ Successfully built project!\n\n📁 Output: ${result.outputPath}\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`;
} catch (error) {
throw new Error(`❌ Build failed: ${String(error)}`);
}