File size: 7,351 Bytes
ffe328b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { ProjectFile } from '../types';

export interface ParsedFile {
  name: string;
  language: ProjectFile['language'];
  content: string;
}

/**
 * Infer file language from extension or block language tag
 */
export function inferLanguage(nameOrLang: string): ProjectFile['language'] {
  const lower = nameOrLang.toLowerCase();
  if (lower.endsWith('.html') || lower === 'html') return 'html';
  if (lower.endsWith('.css') || lower === 'css') return 'css';
  if (lower.endsWith('.js') || lower.endsWith('.jsx') || lower === 'javascript' || lower === 'js') return 'javascript';
  if (lower.endsWith('.ts') || lower.endsWith('.tsx') || lower === 'typescript' || lower === 'ts') return 'typescript';
  if (lower.endsWith('.json') || lower === 'json') return 'json';
  return 'markdown';
}

/**
 * Robust line-by-line markdown code block extractor
 */
export function parseMarkdownCodeFiles(markdown: string): ParsedFile[] {
  const files: ParsedFile[] = [];
  const lines = markdown.split('\n');

  let insideBlock = false;
  let currentLang = '';
  let currentFilename = '';
  let currentContent: string[] = [];
  let lastHeading = '';

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();

    // Check for headings like "# index.html" or "### style.css"
    const headingMatch = trimmed.match(/^#{1,6}\s+([a-zA-Z0-9_\-\.\/]+\.[a-zA-Z0-9]+)\s*$/i);
    if (headingMatch && !insideBlock) {
      lastHeading = headingMatch[1].trim();
      continue;
    }

    if (trimmed.startsWith('```')) {
      if (!insideBlock) {
        // Opening fence
        insideBlock = true;
        currentContent = [];
        const headerInfo = trimmed.replace(/^```/, '').trim();
        
        // Extract language and potential filename from headerInfo
        // Examples:
        // "html <!-- file: index.html -->"
        // "css /* file: style.css */"
        // "javascript // file: app.js"
        // "html index.html"
        // "html"
        let lang = '';
        let detectedFilename = '';

        // Clean out comment delimiters
        const cleaned = headerInfo
          .replace(/<!--|-->|\/\*|\*\/|\/\/|#/g, '')
          .replace(/file\s*:\s*/i, '')
          .trim();

        const parts = cleaned.split(/\s+/).filter(Boolean);
        if (parts.length >= 2) {
          lang = parts[0];
          detectedFilename = parts[1];
        } else if (parts.length === 1) {
          if (parts[0].includes('.')) {
            detectedFilename = parts[0];
            lang = inferLanguage(parts[0]);
          } else {
            lang = parts[0];
          }
        }

        if (!detectedFilename && lastHeading) {
          detectedFilename = lastHeading;
        }

        currentLang = lang || 'html';
        currentFilename = detectedFilename;
        lastHeading = ''; // Consume heading
      } else {
        // Closing fence
        insideBlock = false;
        const rawBody = currentContent.join('\n').trim();

        if (rawBody) {
          let finalName = currentFilename;
          if (!finalName) {
            if (currentLang === 'html' || rawBody.includes('<!DOCTYPE') || rawBody.includes('<html')) {
              finalName = 'index.html';
            } else if (currentLang === 'css') {
              finalName = 'style.css';
            } else if (currentLang === 'javascript' || currentLang === 'js') {
              finalName = 'app.js';
            } else {
              finalName = `file_${files.length + 1}.${currentLang || 'txt'}`;
            }
          }

          files.push({
            name: finalName,
            language: inferLanguage(finalName || currentLang),
            content: rawBody,
          });
        }
        currentLang = '';
        currentFilename = '';
        currentContent = [];
      }
    } else if (insideBlock) {
      currentContent.push(line);
    }
  }

  // Deduplicate by filename (latest occurrence wins)
  const fileMap = new Map<string, ParsedFile>();
  for (const f of files) {
    fileMap.set(f.name, f);
  }

  return Array.from(fileMap.values());
}

/**
 * Combines project files into a runnable standalone HTML string with console bridge
 */
export function assemblePreviewHtml(files: ProjectFile[]): string {
  const htmlFile = files.find(f => f.name.endsWith('.html')) || {
    content: '<!DOCTYPE html><html><head><title>Preview</title></head><body><div id="root"></div></body></html>'
  };
  const cssFiles = files.filter(f => f.name.endsWith('.css'));
  const jsFiles = files.filter(f => f.name.endsWith('.js') || f.name.endsWith('.jsx'));

  let htmlContent = htmlFile.content;

  // Strip relative local script tags (e.g. <script src="app.js"></script>) and local css links
  htmlContent = htmlContent.replace(/<script\s+src=["'](?:\.\/|\/)?(?!https?:\/\/)(?:[a-zA-Z0-9_\-\.\/]+\.js)["']\s*><\/script>/gi, '');
  htmlContent = htmlContent.replace(/<link\s+[^>]*href=["'](?:\.\/|\/)?(?!https?:\/\/)(?:[a-zA-Z0-9_\-\.\/]+\.css)["'][^>]*>/gi, '');

  // Virtual Console interceptor script
  const consoleBridgeScript = `
<script>
(function() {
  const emitLog = (type, args) => {
    try {
      const serialized = Array.from(args).map(arg => {
        if (typeof arg === 'object' && arg !== null) {
          try { return JSON.stringify(arg); } catch (e) { return String(arg); }
        }
        return String(arg);
      }).join(' ');
      window.parent.postMessage({
        type: 'RISHRE_CONSOLE_EVENT',
        payload: {
          type,
          message: serialized,
          timestamp: Date.now()
        }
      }, '*');
    } catch (e) {}
  };

  const _log = console.log;
  const _warn = console.warn;
  const _error = console.error;
  const _info = console.info;

  console.log = function(...args) { _log.apply(console, args); emitLog('log', args); };
  console.info = function(...args) { _info.apply(console, args); emitLog('info', args); };
  console.warn = function(...args) { _warn.apply(console, args); emitLog('warn', args); };
  console.error = function(...args) { _error.apply(console, args); emitLog('error', args); };

  window.addEventListener('error', function(e) {
    emitLog('error', [e.message + ' at ' + (e.filename || 'script') + ':' + e.lineno]);
  });

  window.addEventListener('unhandledrejection', function(e) {
    emitLog('error', ['Unhandled Promise Rejection: ' + (e.reason ? (e.reason.message || e.reason) : 'Unknown')]);
  });
})();
</script>
`;

  // Concatenate all CSS
  const combinedCss = cssFiles.map(f => `\n/* ${f.name} */\n${f.content}`).join('\n');
  const styleBlock = combinedCss ? `<style id="rishre-styles">${combinedCss}</style>` : '';

  // Concatenate all JS
  const combinedJs = jsFiles.map(f => `\n// ${f.name}\ntry {\n${f.content}\n} catch(err) { console.error(err); }`).join('\n');
  const scriptBlock = combinedJs ? `<script id="rishre-scripts">${combinedJs}</script>` : '';

  // Inject into HTML
  if (htmlContent.includes('</head>')) {
    htmlContent = htmlContent.replace('</head>', `${consoleBridgeScript}\n${styleBlock}\n</head>`);
  } else {
    htmlContent = `${consoleBridgeScript}\n${styleBlock}\n${htmlContent}`;
  }

  if (htmlContent.includes('</body>')) {
    htmlContent = htmlContent.replace('</body>', `${scriptBlock}\n</body>`);
  } else {
    htmlContent = `${htmlContent}\n${scriptBlock}`;
  }

  return htmlContent;
}