File size: 2,088 Bytes
9580dce | 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 | 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,
});
});
|