|
| 1 | +const LANGUAGE_IDS = { // https://ce.judge0.com/languages |
| 2 | + "c": 50, |
| 3 | + "cpp": 54, |
| 4 | + "go": 95, |
| 5 | + "java": 91, |
| 6 | + "javascript": 93, |
| 7 | + "python": 92, |
| 8 | + "ruby": 72 |
| 9 | +}; |
| 10 | + |
| 11 | +const LANGUAGE_ALIASES = { |
| 12 | + "c++": "cpp", |
| 13 | + "golang": "go", |
| 14 | + "js": "javascript" |
| 15 | +} |
| 16 | + |
| 17 | +function getLanguageId(language) { |
| 18 | + let l = language.toLowerCase(); |
| 19 | + return LANGUAGE_IDS[LANGUAGE_ALIASES[l] || l] || 0; |
| 20 | +} |
| 21 | + |
| 22 | +function encode(str) { |
| 23 | + return btoa(unescape(encodeURIComponent(str || ""))); |
| 24 | +} |
| 25 | + |
| 26 | +function decode(bytes) { |
| 27 | + var escaped = escape(atob(bytes || "")); |
| 28 | + try { |
| 29 | + return decodeURIComponent(escaped); |
| 30 | + } catch { |
| 31 | + return unescape(escaped); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +async function code_execution(params, userSettings) { |
| 36 | + const { source_code, language } = params; |
| 37 | + const { rapidApiKey } = userSettings; |
| 38 | + |
| 39 | + const languageId = getLanguageId(language); |
| 40 | + if (languageId == 0) { |
| 41 | + return `Unsupported language ${language}`; |
| 42 | + } |
| 43 | + |
| 44 | + const requestHeaders = new Headers(); |
| 45 | + requestHeaders.append("x-rapidapi-key", rapidApiKey); |
| 46 | + requestHeaders.append("Content-Type", "application/json"); |
| 47 | + |
| 48 | + const requestData = { |
| 49 | + "language_id": languageId, |
| 50 | + "source_code": encode(source_code), |
| 51 | + "redirect_stderr_to_stdout": true |
| 52 | + }; |
| 53 | + |
| 54 | + let response = await fetch("https://judge0-ce.p.rapidapi.com/submissions?base64_encoded=true&wait=true", { |
| 55 | + method: "POST", |
| 56 | + headers: requestHeaders, |
| 57 | + body: JSON.stringify(requestData) |
| 58 | + }); |
| 59 | + |
| 60 | + if (!response.ok) { |
| 61 | + return "Network error"; |
| 62 | + } |
| 63 | + |
| 64 | + let responseData = await response.json(); |
| 65 | + return [decode(responseData["compile_output"]), decode(responseData["stdout"])].join("\n").trim(); |
| 66 | +} |
0 commit comments