import { NextRequest, NextResponse } from "next/server"; import { withApiError, ApiError } from "@/lib/api-error"; import { resolveProblem } from "@/lib/coding/store"; import { runJavaScriptTests } from "@/lib/coding/harness"; import { isExecutableProblem, isExecutableLanguage } from "@/lib/coding/types"; interface RunBody { instanceId?: string; code?: string; } /** * POST /api/coding/run * Body: { instanceId, code } * * Executes the user's code against the *public* example tests in the sandbox * and returns the results + captured stdout. No XP — this is the "Run" button * that lets a user iterate before submitting. Hidden tests are not run here. */ export const POST = withApiError(async (request: NextRequest) => { let body: RunBody; try { body = await request.json(); } catch { throw new ApiError(400, "Invalid JSON body"); } const { instanceId, code } = body; if (!instanceId || typeof code !== "string") { throw new ApiError(400, "instanceId and code are required"); } const problem = resolveProblem(instanceId); if (!problem) { throw new ApiError(404, "Problem not found (it may have expired — regenerate it)."); } if (!isExecutableProblem(problem)) { throw new ApiError(400, "This problem type is not executable. Submit a written answer instead."); } if (!isExecutableLanguage(problem.language)) { throw new ApiError( 400, `Live execution supports JavaScript/TypeScript. ${problem.language} answers are graded on submit.`, ); } const publicTests = problem.tests.filter((t) => !t.hidden); const run = runJavaScriptTests(code, problem.entryFunction, publicTests); return NextResponse.json({ ran: true, entryFunction: problem.entryFunction, passed: run.passed, total: run.total, allPassed: run.allPassed, results: run.results, stdout: run.stdout, compileError: run.compileError ?? null, note: publicTests.length === 0 ? "No example tests are shown for this problem — submit to run the full suite." : undefined, }); });