https://altly.madebydanny.uk

Fix stack overflow in edge function

Address "Maximum call stack size exceeded" error by chunking base64 image conversion and adding image size validation.

+18 -1
+18 -1
supabase/functions/generate-alt-text/index.ts
··· 116 116 } 117 117 118 118 const imageBuffer = await imageResponse.arrayBuffer(); 119 - const base64Image = btoa(String.fromCharCode(...new Uint8Array(imageBuffer))); 119 + 120 + // Check image size (max 10MB) 121 + if (imageBuffer.byteLength > 10 * 1024 * 1024) { 122 + return new Response( 123 + JSON.stringify({ error: 'Image too large. Maximum size is 10MB.' }), 124 + { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } 125 + ); 126 + } 127 + 128 + // Convert to base64 in chunks to avoid stack overflow 129 + const uint8Array = new Uint8Array(imageBuffer); 130 + let binaryString = ''; 131 + const chunkSize = 8192; 132 + for (let i = 0; i < uint8Array.length; i += chunkSize) { 133 + const chunk = uint8Array.slice(i, i + chunkSize); 134 + binaryString += String.fromCharCode(...chunk); 135 + } 136 + const base64Image = btoa(binaryString); 120 137 const contentType = imageResponse.headers.get('content-type') || 'image/jpeg'; 121 138 122 139 console.log('Calling Claude API...');