File size: 7,987 Bytes
d7b37e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Page } from "@/types";
import {
  DIVIDER,
  NEW_FILE_END,
  NEW_FILE_START,
  REPLACE_END,
  SEARCH_START,
  UPDATE_FILE_END,
  UPDATE_FILE_START,
} from "./prompts";

/**
 * Escape special regex characters in a string
 */
export const escapeRegExp = (string: string): string => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

/**
 * Create a flexible HTML regex that accounts for whitespace variations
 */
export const createFlexibleHtmlRegex = (searchBlock: string): RegExp => {
  let searchRegex = escapeRegExp(searchBlock)
    .replace(/\s+/g, '\\s*')
    .replace(/>\s*</g, '>\\s*<')
    .replace(/\s*>/g, '\\s*>');
  
  return new RegExp(searchRegex, 'g');
};

/**
 * Process AI response chunk and apply updates to pages
 * Returns updated pages and updated line numbers
 */
export interface ProcessAiResponseResult {
  updatedPages: Page[];
  updatedLines: number[][];
}

export const processAiResponse = (
  chunk: string,
  pages: Page[]
): ProcessAiResponseResult => {
  const updatedLines: number[][] = [];
  const updatedPages = [...pages];

  // Process UPDATE_FILE blocks
  const updateFileRegex = new RegExp(
    `${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\s]+)\\s*${UPDATE_FILE_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([\\s\\S]*?)(?=${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|$)`,
    'g'
  );
  let updateFileMatch;

  while ((updateFileMatch = updateFileRegex.exec(chunk)) !== null) {
    const [, filePath, fileContent] = updateFileMatch;

    const pageIndex = updatedPages.findIndex(p => p.path === filePath);
    if (pageIndex !== -1) {
      let pageHtml = updatedPages[pageIndex].html;

      let processedContent = fileContent;
      const htmlMatch = fileContent.match(/```html\s*([\s\S]*?)\s*```/);
      if (htmlMatch) {
        processedContent = htmlMatch[1];
      }
      let position = 0;
      let moreBlocks = true;

      while (moreBlocks) {
        const searchStartIndex = processedContent.indexOf(SEARCH_START, position);
        if (searchStartIndex === -1) {
          moreBlocks = false;
          continue;
        }

        const dividerIndex = processedContent.indexOf(DIVIDER, searchStartIndex);
        if (dividerIndex === -1) {
          moreBlocks = false;
          continue;
        }

        const replaceEndIndex = processedContent.indexOf(REPLACE_END, dividerIndex);
        if (replaceEndIndex === -1) {
          moreBlocks = false;
          continue;
        }

        const searchBlock = processedContent.substring(
          searchStartIndex + SEARCH_START.length,
          dividerIndex
        );
        const replaceBlock = processedContent.substring(
          dividerIndex + DIVIDER.length,
          replaceEndIndex
        );

        if (searchBlock.trim() === "") {
          pageHtml = `${replaceBlock}\n${pageHtml}`;
          updatedLines.push([1, replaceBlock.split("\n").length]);
        } else {
          const regex = createFlexibleHtmlRegex(searchBlock);
          const match = regex.exec(pageHtml);

          if (match) {
            const matchedText = match[0];
            const beforeText = pageHtml.substring(0, match.index);
            const startLineNumber = beforeText.split("\n").length;
            const replaceLines = replaceBlock.split("\n").length;
            const endLineNumber = startLineNumber + replaceLines - 1;

            updatedLines.push([startLineNumber, endLineNumber]);
            pageHtml = pageHtml.replace(matchedText, replaceBlock);
          }
        }

        position = replaceEndIndex + REPLACE_END.length;
      }

      updatedPages[pageIndex].html = pageHtml;
    }
  }

  // Process NEW_FILE blocks
  const newFileRegex = new RegExp(
    `${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\s]+)\\s*${NEW_FILE_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([\\s\\S]*?)(?=${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|$)`,
    'g'
  );
  let newFileMatch;

  while ((newFileMatch = newFileRegex.exec(chunk)) !== null) {
    const [, filePath, fileContent] = newFileMatch;

    let fileData = fileContent;
    // Try to extract content from code blocks
    const htmlMatch = fileContent.match(/```html\s*([\s\S]*?)\s*```/);
    const cssMatch = fileContent.match(/```css\s*([\s\S]*?)\s*```/);
    const jsMatch = fileContent.match(/```javascript\s*([\s\S]*?)\s*```/);

    if (htmlMatch) {
      fileData = htmlMatch[1];
    } else if (cssMatch) {
      fileData = cssMatch[1];
    } else if (jsMatch) {
      fileData = jsMatch[1];
    }

    const existingFileIndex = updatedPages.findIndex(p => p.path === filePath);

    if (existingFileIndex !== -1) {
      updatedPages[existingFileIndex] = {
        path: filePath,
        html: fileData.trim()
      };
    } else {
      updatedPages.push({
        path: filePath,
        html: fileData.trim()
      });
    }
  }

  // Fallback: process SEARCH/REPLACE blocks without UPDATE_FILE wrapper (backward compatibility)
  if (updatedPages.length === pages.length && !chunk.includes(UPDATE_FILE_START)) {
    let position = 0;
    let moreBlocks = true;
    let newHtml = updatedPages[0]?.html || "";

    while (moreBlocks) {
      const searchStartIndex = chunk.indexOf(SEARCH_START, position);
      if (searchStartIndex === -1) {
        moreBlocks = false;
        continue;
      }

      const dividerIndex = chunk.indexOf(DIVIDER, searchStartIndex);
      if (dividerIndex === -1) {
        moreBlocks = false;
        continue;
      }

      const replaceEndIndex = chunk.indexOf(REPLACE_END, dividerIndex);
      if (replaceEndIndex === -1) {
        moreBlocks = false;
        continue;
      }

      const searchBlock = chunk.substring(
        searchStartIndex + SEARCH_START.length,
        dividerIndex
      );
      const replaceBlock = chunk.substring(
        dividerIndex + DIVIDER.length,
        replaceEndIndex
      );

      if (searchBlock.trim() === "") {
        newHtml = `${replaceBlock}\n${newHtml}`;
        updatedLines.push([1, replaceBlock.split("\n").length]);
      } else {
        const regex = createFlexibleHtmlRegex(searchBlock);
        const match = regex.exec(newHtml);

        if (match) {
          const matchedText = match[0];
          const beforeText = newHtml.substring(0, match.index);
          const startLineNumber = beforeText.split("\n").length;
          const replaceLines = replaceBlock.split("\n").length;
          const endLineNumber = startLineNumber + replaceLines - 1;

          updatedLines.push([startLineNumber, endLineNumber]);
          newHtml = newHtml.replace(matchedText, replaceBlock);
        }
      }

      position = replaceEndIndex + REPLACE_END.length;
    }

    const mainPageIndex = updatedPages.findIndex(p => p.path === '/' || p.path === '/index' || p.path === 'index');
    if (mainPageIndex !== -1) {
      updatedPages[mainPageIndex].html = newHtml;
    }
  }

  return { updatedPages, updatedLines };
};

/**
 * Convert pages to File objects for upload to HuggingFace
 */
export const pagesToFiles = (pages: Page[]): File[] => {
  const files: File[] = [];
  pages.forEach((page: Page) => {
    let mimeType = "text/html";
    if (page.path.endsWith(".css")) {
      mimeType = "text/css";
    } else if (page.path.endsWith(".js")) {
      mimeType = "text/javascript";
    } else if (page.path.endsWith(".json")) {
      mimeType = "application/json";
    }
    const file = new File([page.html], page.path, { type: mimeType });
    files.push(file);
  });
  return files;
};

/**
 * Extract project name from AI response
 */
export const extractProjectName = (chunk: string): string | null => {
  const projectName = chunk.match(/<<<<<<< PROJECT_NAME_START\s*([\s\S]*?)\s*>>>>>>> PROJECT_NAME_END/)?.[1]?.trim();
  return projectName || null;
};