import { NextResponse } from 'next/server'; import { SandboxFactory } from '@/lib/sandbox/factory'; import { SandboxProvider } from '@/lib/sandbox/types'; import type { SandboxState } from '@/types/sandbox'; // Store active sandbox globally declare global { var activeSandboxProvider: any; var sandboxData: any; var existingFiles: Set; var sandboxState: SandboxState; } export async function POST() { try { console.log('[create-ai-sandbox-v2] Creating sandbox...'); // Clean up existing sandbox if any if (global.activeSandboxProvider) { console.log('[create-ai-sandbox-v2] Terminating existing sandbox...'); try { await global.activeSandboxProvider.terminate(); } catch (e) { console.error('Failed to terminate existing sandbox:', e); } global.activeSandboxProvider = null; } // Clear existing files tracking if (global.existingFiles) { global.existingFiles.clear(); } else { global.existingFiles = new Set(); } // Create new sandbox using factory const provider = SandboxFactory.create(); const sandboxInfo = await provider.createSandbox(); console.log('[create-ai-sandbox-v2] Setting up Vite React app...'); await provider.setupViteApp(); // Store provider globally global.activeSandboxProvider = provider; global.sandboxData = { sandboxId: sandboxInfo.sandboxId, url: sandboxInfo.url }; // Initialize sandbox state global.sandboxState = { fileCache: { files: {}, lastSync: Date.now(), sandboxId: sandboxInfo.sandboxId }, sandbox: provider, // Store the provider instead of raw sandbox sandboxData: { sandboxId: sandboxInfo.sandboxId, url: sandboxInfo.url } }; console.log('[create-ai-sandbox-v2] Sandbox ready at:', sandboxInfo.url); return NextResponse.json({ success: true, sandboxId: sandboxInfo.sandboxId, url: sandboxInfo.url, provider: sandboxInfo.provider, message: 'Sandbox created and Vite React app initialized' }); } catch (error) { console.error('[create-ai-sandbox-v2] Error:', error); // Clean up on error if (global.activeSandboxProvider) { try { await global.activeSandboxProvider.terminate(); } catch (e) { console.error('Failed to terminate sandbox on error:', e); } global.activeSandboxProvider = null; } return NextResponse.json( { error: error instanceof Error ? error.message : 'Failed to create sandbox', details: error instanceof Error ? error.stack : undefined }, { status: 500 } ); } }