Mahdi Naser Moghadasi
Add multi-language support (Python, JavaScript, Java, C++)
fe2a1b2
Raw History Blame Contribute Delete
3.66 kB
import { NextRequest, NextResponse } from 'next/server'
import { spawn } from 'child_process'
import { writeFile, unlink } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
export async function POST(request: NextRequest) {
let tempFile: string | null = null
try {
const body = await request.json()
const { code, testCase, functionName } = body
if (!code || !testCase) {
return NextResponse.json(
{ error: 'Code and test case are required' },
{ status: 400 }
)
}
// Create a temporary JavaScript file
const tempDir = tmpdir()
tempFile = join(tempDir, `js_exec_${Date.now()}_${Math.random().toString(36).substring(7)}.js`)
// Wrap user code and execute test case
const wrappedCode = `
${code}
// Test execution
const testInput = ${JSON.stringify(testCase.input)};
try {
let result;
if (Array.isArray(testInput) && testInput.length === 1) {
result = ${functionName}(testInput[0]);
} else if (Array.isArray(testInput) && testInput.length === 2) {
result = ${functionName}(testInput[0], testInput[1]);
} else {
result = ${functionName}(testInput);
}
console.log(JSON.stringify(result));
} catch (error) {
console.error('ERROR: ' + error.message);
console.error(error.stack);
process.exit(1);
}
`
await writeFile(tempFile, wrappedCode, 'utf-8')
// Execute JavaScript code with Node.js
const result = await new Promise<{ output: string; error: string; exitCode: number }>((resolve) => {
const node = spawn('node', [tempFile!])
let output = ''
let error = ''
node.stdout.on('data', (data) => {
output += data.toString()
})
node.stderr.on('data', (data) => {
error += data.toString()
})
node.on('close', (code) => {
resolve({ output: output.trim(), error: error.trim(), exitCode: code || 0 })
})
// Timeout after 5 seconds
setTimeout(() => {
node.kill()
resolve({ output: '', error: 'Execution timeout (5 seconds)', exitCode: -1 })
}, 5000)
})
// Clean up temp file
if (tempFile) {
try {
await unlink(tempFile)
} catch (e) {
// Ignore cleanup errors
}
}
if (result.exitCode !== 0 || result.error) {
if (result.output && result.output.trim()) {
try {
const actualOutput = JSON.parse(result.output)
return NextResponse.json({
success: true,
output: actualOutput,
})
} catch (e) {
// If parsing fails, return the error
}
}
return NextResponse.json({
success: false,
error: result.error || 'Execution failed',
output: result.output,
})
}
if (!result.output || !result.output.trim()) {
return NextResponse.json({
success: false,
error: 'No output from code execution',
rawOutput: result.output,
})
}
try {
const actualOutput = JSON.parse(result.output)
return NextResponse.json({
success: true,
output: actualOutput,
})
} catch (e) {
return NextResponse.json({
success: false,
error: `Failed to parse output as JSON: ${result.output}`,
rawOutput: result.output,
})
}
} catch (error: any) {
// Clean up temp file on error
if (tempFile) {
try {
await unlink(tempFile)
} catch (e) {
// Ignore cleanup errors
}
}
return NextResponse.json(
{ error: error.message || 'Internal server error' },
{ status: 500 }
)
}
}