Elffuss BraidHub

kikocis/continue public

main · 5.3 KiBRawPermalink
1import { logger } from "../../util/logger.js";
2
3/**
4 * Dynamically import Sharp without using eval
5 */
6async function loadSharp(): Promise<any> {
7 try {
8 // Use Function constructor to avoid bundler issues with dynamic imports
9 const importSharp = new Function('return import("sharp")');
10 const sharpModule = await importSharp().catch(() => null);
11 return sharpModule ? sharpModule.default || sharpModule : null;
12 } catch {
13 return null;
14 }
15}
16
17/**
18 * Process image buffer to JPEG with resizing using Sharp (if available)
19 */
20async function processImageWithSharp(
21 imageBuffer: Buffer,
22 maxWidth = 1024,
23 maxHeight = 1024,
24): Promise<{ buffer: Buffer; isJpeg: boolean }> {
25 try {
26 // Try to load Sharp - it's an optional dependency
27 const sharp = await loadSharp();
28 if (!sharp) {
29 logger.debug("Sharp not available, using original image buffer");
30 return { buffer: imageBuffer, isJpeg: false };
31 }
32
33 logger.debug("Processing image with Sharp...");
34
35 // Process image: convert to JPEG and resize if needed
36 const processedBuffer = await sharp(imageBuffer)
37 .resize(maxWidth, maxHeight, {
38 fit: "inside",
39 withoutEnlargement: true,
40 })
41 .jpeg({
42 quality: 85,
43 progressive: true,
44 })
45 .toBuffer();
46
47 logger.debug(
48 `Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`,
49 );
50 return { buffer: processedBuffer, isJpeg: true };
51 } catch (error) {
52 logger.warn("Failed to process image with Sharp, using original:", error);
53 return { buffer: imageBuffer, isJpeg: false };
54 }
55}
56
57/**
58 * Detect image format from buffer header - simplified to reduce complexity
59 */
60function detectImageFormat(buffer: Buffer): string {
61 if (buffer.length < 4) return "image/png";
62
63 const signature = buffer.subarray(0, 4);
64
65 // JPEG: FF D8 FF
66 if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) {
67 return "image/jpeg";
68 }
69
70 // PNG: 89 50 4E 47
71 if (
72 signature[0] === 0x89 &&
73 signature[1] === 0x50 &&
74 signature[2] === 0x4e &&
75 signature[3] === 0x47
76 ) {
77 return "image/png";
78 }
79
80 // GIF: 47 49 46 38
81 if (
82 signature[0] === 0x47 &&
83 signature[1] === 0x49 &&
84 signature[2] === 0x46 &&
85 signature[3] === 0x38
86 ) {
87 return "image/gif";
88 }
89
90 // WebP: RIFF + WEBP at offset 8
91 if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) {
92 const webpSig = buffer.subarray(8, 12);
93 if (
94 webpSig[0] === 0x57 &&
95 webpSig[1] === 0x45 &&
96 webpSig[2] === 0x42 &&
97 webpSig[3] === 0x50
98 ) {
99 return "image/webp";
100 }
101 }
102
103 return "image/png"; // Default fallback
104}
105
106/**
107 * Process a single image placeholder - extracted to reduce nesting depth
108 */
109export async function processImagePlaceholder(
110 placeholder: string,
111 originalImageBuffer: Buffer,
112 textContent: string,
113 messageParts: import("core/index.js").MessagePart[],
114): Promise<{ textContent: string }> {
115 logger.debug(
116 `Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`,
117 );
118
119 try {
120 // Process image with Sharp (convert to JPEG and resize)
121 const processResult = await processImageWithSharp(originalImageBuffer);
122 const processedImageBuffer = processResult.buffer;
123 const isProcessedJpeg = processResult.isJpeg;
124
125 // Check processed image size
126 const maxSize = 10 * 1024 * 1024; // 10MB limit
127 if (processedImageBuffer.length > maxSize) {
128 logger.warn(
129 `Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`,
130 );
131 return {
132 textContent: textContent.replace(
133 placeholder,
134 "[Large image skipped - reduce image size and try again]",
135 ),
136 };
137 }
138
139 // Convert processed buffer to base64 data URL asynchronously to avoid blocking
140 logger.debug("Converting processed image to base64...");
141 const base64Image = await new Promise<string>((resolve) => {
142 // Use setImmediate to yield to event loop
143 setImmediate(() => {
144 const result = processedImageBuffer.toString("base64");
145 resolve(result);
146 });
147 });
148
149 // Use correct MIME type based on whether Sharp processing was successful
150 const mimeType = isProcessedJpeg
151 ? "image/jpeg"
152 : detectImageFormat(processedImageBuffer);
153 const dataUrl = `data:${mimeType};base64,${base64Image}`;
154 logger.debug(
155 `Image converted to base64 with MIME type ${mimeType}, dataUrl length: ${dataUrl.length}`,
156 );
157
158 // Split text around the placeholder
159 const parts = textContent.split(placeholder);
160 if (parts.length > 1) {
161 // Add text before placeholder
162 if (parts[0]) {
163 messageParts.push({
164 type: "text",
165 text: parts[0],
166 });
167 }
168
169 // Add image part
170 messageParts.push({
171 type: "imageUrl",
172 imageUrl: { url: dataUrl },
173 });
174
175 // Continue with remaining text
176 return { textContent: parts.slice(1).join(placeholder) };
177 }
178
179 return { textContent };
180 } catch (error) {
181 logger.error(`Failed to process image ${placeholder}:`, error);
182 return {
183 textContent: textContent.replace(
184 placeholder,
185 "[Image processing failed]",
186 ),
187 };
188 }
189}