File size: 7,175 Bytes
f91a684
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback, useState, useRef } from 'react';

export const LANGUAGE_OPTIONS = [
  { value: 'python',     label: 'Python',     monacoLanguage: 'python',     extension: 'py',   pistonLang: 'python',     pistonVersion: '3.10.0' },
  { value: 'python3',    label: 'Python 3',   monacoLanguage: 'python',     extension: 'py',   pistonLang: 'python3',    pistonVersion: '3.10.0' },
  { value: 'javascript', label: 'JavaScript', monacoLanguage: 'javascript', extension: 'js',   pistonLang: 'javascript', pistonVersion: '18.15.0' },
  { value: 'java',       label: 'Java',       monacoLanguage: 'java',       extension: 'java', pistonLang: 'java',       pistonVersion: '15.0.2' },
  { value: 'c',          label: 'C',          monacoLanguage: 'c',          extension: 'c',    pistonLang: 'c',          pistonVersion: '10.2.0' },
  { value: 'cpp',        label: 'C++',        monacoLanguage: 'cpp',        extension: 'cpp',  pistonLang: 'c++',        pistonVersion: '10.2.0' },
];

export const DEFAULT_CODE_BY_LANGUAGE = {
  python: `# Type your input in the terminal box below after clicking RUN
name = input("Enter your name: ")
print(f"Hello, {name}!")
`,
  python3: `# Type your input in the terminal box below after clicking RUN
name = input("Enter your name: ")
print(f"Hello, {name}!")
`,
  javascript: `const fs = require("fs");
const input = fs.readFileSync(0, "utf8").trim();

console.log(\`Hello, \${input}!\`);
`,
  java: `import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.next();
        System.out.println("Hello, " + name + "!");
    }
}
`,
  c: `#include <stdio.h>

int main() {
    char name[100];
    scanf("%99s", name);
    printf("Hello, %s!\\n", name);
    return 0;
}
`,
  cpp: `#include <iostream>
using namespace std;

int main() {
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;
    return 0;
}
`,
};

function compilerApiUrl() {
  const base = (import.meta.env.VITE_COMPILER_API_BASE ?? '').trim().replace(/\/$/, '');
  return `${base}/api/compile`;
}

async function parseResponse(response) {
  const text = await response.text();
  if (!text) return {};
  try {
    return JSON.parse(text);
  } catch {
    return { error: text };
  }
}

export default function useCompiler(initialLanguage = 'python') {
  const [language, setLanguage] = useState(initialLanguage);
  const [code, setCode] = useState(DEFAULT_CODE_BY_LANGUAGE[initialLanguage]);
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [executionTime, setExecutionTime] = useState(null);
  const [status, setStatus] = useState('idle'); // idle | running | success | error | compile_error
  const [compileOutput, setCompileOutput] = useState('');
  const [analysis, setAnalysis] = useState(null);

  const [executionId, setExecutionId] = useState(null);
  const eventSourceRef = useRef(null);

  const handleRunInteractive = useCallback(
    async (overrides = {}) => {
      const runCode = overrides.code ?? code;
      const runLanguage = overrides.language ?? language;
      const onStdout = overrides.onStdout ?? (() => {});
      const onStderr = overrides.onStderr ?? (() => {});
      const onDone   = overrides.onDone   ?? (() => {});

      if (!runCode.trim()) {
        onStderr('Code is required.');
        onDone('error', 0);
        return;
      }

      setLoading(true);
      setOutput('');
      setError('');
      setExecutionTime(null);
      setStatus('running');
      setCompileOutput('');
      setAnalysis(null);
      setExecutionId(null);

      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
      }

      try {
        const base = (import.meta.env.VITE_COMPILER_API_BASE ?? '').trim().replace(/\/$/, '');
        const startRes = await fetch(`${base}/api/compile/start`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ code: runCode, language: runLanguage }),
        });

        const startData = await parseResponse(startRes);
        if (!startRes.ok || !startData.executionId) {
          throw new Error(startData.error || 'Failed to start execution');
        }

        const id = startData.executionId;
        setExecutionId(id);

        const es = new EventSource(`${base}/api/compile/stream/${id}`);
        eventSourceRef.current = es;

        es.addEventListener('stdout', (e) => {
          try {
            const text = JSON.parse(e.data);
            setOutput(prev => prev + text);
            onStdout(text);
          } catch(err) {}
        });

        es.addEventListener('stderr', (e) => {
          try {
            const text = JSON.parse(e.data);
            setError(prev => prev + text);
            onStderr(text);
          } catch(err) {}
        });

        es.addEventListener('done', (e) => {
          try {
            const data = JSON.parse(e.data);
            setStatus(data.status);
            setExecutionTime(data.executionTime);
            onDone(data.status, data.executionTime);
          } catch(err) {}
          setLoading(false);
          es.close();
          eventSourceRef.current = null;
        });

        es.onerror = () => {
          if (es.readyState === EventSource.CLOSED) return;
          const msg = '\n[Connection lost — is the compiler server running?]';
          setError(prev => prev + msg);
          onStderr(msg);
          onDone('error', 0);
          setStatus('error');
          setLoading(false);
          es.close();
          eventSourceRef.current = null;
        };

      } catch (err) {
        const msg = err.message;
        setError(msg);
        onStderr(msg);
        onDone('error', 0);
        setStatus('error');
        setLoading(false);
      }
    },
    [code, language],
  );


  const sendInput = useCallback(async (text) => {
    if (!executionId || status !== 'running') return;
    try {
      const base = (import.meta.env.VITE_COMPILER_API_BASE ?? '').trim().replace(/\/$/, '');
      await fetch(`${base}/api/compile/input/${executionId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ input: text + '\n' }),
      });
    } catch (err) {
      console.error('Failed to send input', err);
    }
  }, [executionId, status]);

  const resetResult = useCallback(() => {
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
      eventSourceRef.current = null;
    }
    setOutput('');
    setError('');
    setExecutionTime(null);
    setStatus('idle');
    setCompileOutput('');
    setAnalysis(null);
    setExecutionId(null);
  }, []);

  return {
    code,
    setCode,
    language,
    setLanguage,
    input,
    setInput,
    output,
    setOutput,
    error,
    setError,
    loading,
    executionTime,
    status,
    compileOutput,
    analysis,
    handleRunInteractive,
    sendInput,
    resetResult,
  };
}