@exercode/problem-utils 2.4.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/checkAllProblems.cjs +1 -1
- package/dist/cli/checkAllProblems.cjs.map +1 -1
- package/dist/cli/checkAllProblems.js +1 -1
- package/dist/cli/checkAllProblems.js.map +1 -1
- package/dist/helpers/checkProblemDirIsolation.cjs +1 -1
- package/dist/helpers/checkProblemDirIsolation.js +1 -1
- package/dist/helpers/cleanWorkingDirectory.cjs +1 -1
- package/dist/helpers/cleanWorkingDirectory.cjs.map +1 -1
- package/dist/helpers/cleanWorkingDirectory.d.ts +2 -6
- package/dist/helpers/cleanWorkingDirectory.js +1 -1
- package/dist/helpers/cleanWorkingDirectory.js.map +1 -1
- package/dist/helpers/compareExpectedOutputFiles.cjs +1 -1
- package/dist/helpers/compareExpectedOutputFiles.cjs.map +1 -1
- package/dist/helpers/compareExpectedOutputFiles.js +1 -1
- package/dist/helpers/compareExpectedOutputFiles.js.map +1 -1
- package/dist/helpers/copyTestCaseFileInput.cjs +1 -1
- package/dist/helpers/copyTestCaseFileInput.cjs.map +1 -1
- package/dist/helpers/copyTestCaseFileInput.js +1 -1
- package/dist/helpers/copyTestCaseFileInput.js.map +1 -1
- package/dist/helpers/readOutputFiles.cjs +1 -1
- package/dist/helpers/readOutputFiles.cjs.map +1 -1
- package/dist/helpers/readOutputFiles.d.ts +0 -9
- package/dist/helpers/readOutputFiles.js +1 -1
- package/dist/helpers/readOutputFiles.js.map +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs.map +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.d.ts +0 -3
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.js +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.js.map +1 -1
- package/dist/helpers/spawnSyncWithTimeout.cjs +1 -1
- package/dist/helpers/spawnSyncWithTimeout.cjs.map +1 -1
- package/dist/helpers/spawnSyncWithTimeout.d.ts +0 -7
- package/dist/helpers/spawnSyncWithTimeout.js +1 -1
- package/dist/helpers/spawnSyncWithTimeout.js.map +1 -1
- package/dist/helpers/startHttpServer.cjs +1 -1
- package/dist/helpers/startHttpServer.cjs.map +1 -1
- package/dist/helpers/startHttpServer.js +1 -1
- package/dist/helpers/startHttpServer.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js +1 -1
- package/dist/presets/command.cjs +1 -1
- package/dist/presets/command.cjs.map +1 -1
- package/dist/presets/command.d.ts +0 -16
- package/dist/presets/command.js +1 -1
- package/dist/presets/command.js.map +1 -1
- package/dist/presets/evaluation.cjs +4 -4
- package/dist/presets/evaluation.cjs.map +1 -1
- package/dist/presets/evaluation.js +4 -4
- package/dist/presets/evaluation.js.map +1 -1
- package/dist/presets/guiCommand.cjs +3 -3
- package/dist/presets/guiCommand.cjs.map +1 -1
- package/dist/presets/guiCommand.d.ts +0 -24
- package/dist/presets/guiCommand.js +3 -3
- package/dist/presets/guiCommand.js.map +1 -1
- package/dist/presets/stdio.cjs +1 -1
- package/dist/presets/stdio.cjs.map +1 -1
- package/dist/presets/stdio.js +1 -1
- package/dist/presets/stdio.js.map +1 -1
- package/dist/types/language.cjs +2 -2
- package/dist/types/language.cjs.map +1 -1
- package/dist/types/language.js +2 -2
- package/dist/types/language.js.map +1 -1
- package/package.json +4 -4
- package/dist/helpers/runCustomRunner.cjs +0 -2
- package/dist/helpers/runCustomRunner.cjs.map +0 -1
- package/dist/helpers/runCustomRunner.d.ts +0 -8
- package/dist/helpers/runCustomRunner.js +0 -2
- package/dist/helpers/runCustomRunner.js.map +0 -1
- package/dist/helpers/safeFs.cjs +0 -2
- package/dist/helpers/safeFs.cjs.map +0 -1
- package/dist/helpers/safeFs.d.ts +0 -29
- package/dist/helpers/safeFs.js +0 -2
- package/dist/helpers/safeFs.js.map +0 -1
- package/dist/helpers/sandboxUser.cjs +0 -3
- package/dist/helpers/sandboxUser.cjs.map +0 -1
- package/dist/helpers/sandboxUser.d.ts +0 -146
- package/dist/helpers/sandboxUser.js +0 -3
- package/dist/helpers/sandboxUser.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{
|
|
2
|
-
`);for(let e of n){if(e.includes(`Root window id:`)||e.includes(`Parent window id:`)||e.includes(`()`))continue;let n=/^\s{5}(0x[\da-f]+) /.exec(e);n?.[1]&&t.push(Number.parseInt(n[1],16).toString())}return t}function
|
|
3
|
-
`).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)&&e>0).reduce((e,t)=>e+t*1024,0)}function
|
|
1
|
+
import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{parseArgs as t}from"../helpers/parseArgs.js";import{readTestCases as n}from"../helpers/readTestCases.js";import{languageIdToDefinition as r}from"../types/language.js";import{DecisionCode as i}from"../types/decisionCode.js";import{cleanWorkingDirectory as a,snapshotWorkingDirectory as o}from"../helpers/cleanWorkingDirectory.js";import{copyTestCaseFileInput as s}from"../helpers/copyTestCaseFileInput.js";import{findEntryPointFile as c}from"../helpers/findEntryPointFile.js";import{findLanguageDefinitionByPath as l}from"../helpers/findLanguageDefinitionByPath.js";import{judgeByStaticAnalysis as u}from"../helpers/judgeByStaticAnalysis.js";import{readOutputFiles as d}from"../helpers/readOutputFiles.js";import{readProblemMarkdownFrontMatter as f}from"../helpers/readProblemMarkdownFrontMatter.js";import{spawnSyncWithTimeout as p}from"../helpers/spawnSyncWithTimeout.js";import m from"node:path";import{z as h}from"zod";import g from"node:fs/promises";import _ from"node:child_process";import v from"node:os";import{setTimeout as y}from"node:timers/promises";const b=.3,x=[v.platform()===`darwin`?`gtime`:`/usr/bin/time`,`--format`,`%e %M`],S=h.object({language:h.union([h.string(),h.array(h.string())]).optional()});async function C(n,r){let p=t(process.argv);if(!p.cwd)throw Error(`cwd argument required`);let m=S.parse(p.params),h=p.cwd,g=await f(n),_=await(r.readTestCases??O)(n),v=_.length>0?_:[{id:`default`}],y=v[0]?.id??`prebuild`,x=await u(p.cwd,g);if(x){e({testCaseId:y,...x});return}let C=r.mainFilePath??await c(p.cwd,m.language);if(!C){e({testCaseId:y,decisionCode:i.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:r.mainFilePath?`required main file not found: ${r.mainFilePath}`:`main file not found${m.language?`: language: ${m.language}`:``}`});return}let A=l(C);if(!A){e({testCaseId:y,decisionCode:i.WRONG_ANSWER,stderr:`unsupported language`});return}let j={...process.env,CI:``,FORCE_COLOR:`0`},M=await w({cwd:p.cwd,language:m.language,configuredMainFilePath:r.mainFilePath});if(A.prebuild)try{await A.prebuild(p.cwd);let e=await w({cwd:p.cwd,language:m.language??T(C),configuredMainFilePath:r.mainFilePath,allowConfiguredPathFallback:!0});e&&(M=e)}catch(t){e({testCaseId:y,decisionCode:i.BUILD_ERROR,stderr:R(t)});return}if(!M){e({testCaseId:y,decisionCode:i.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:r.mainFilePath?`required main file not found: ${r.mainFilePath}`:`main file not found${m.language?`: language: ${m.language}`:``}`});return}let P;if(r.prepare)try{P=await r.prepare({cwd:h,env:j,mainFilePath:M,problemMarkdownFrontMatter:g})}catch(t){e({testCaseId:y,decisionCode:i.BUILD_ERROR,stderr:R(t)});return}let F=P??E({cwd:p.cwd,env:j,mainFilePath:M,languageDefinition:A});if(F){e({testCaseId:y,decisionCode:F.decisionCode??i.BUILD_ERROR,feedbackMarkdown:F.feedbackMarkdown,stderr:F.stderr,stdout:F.stdout,outputFiles:F.outputFiles});return}let I=await o(p.cwd),L,z=y,B;try{L=r.runCommand?void 0:await N();let t=_.shared?.fileInputPath;for(let n of v){z=n.id,t&&await s(t,p.cwd),n.fileInputPath&&await s(n.fileInputPath,p.cwd);let o=typeof g.timeLimitMs==`number`?g.timeLimitMs/1e3:r.runTimeoutSeconds??5,c=L?{...j,DISPLAY:L.display}:j,l=await r.resolveInput?.({testCase:n,cwd:p.cwd,env:c})??n.input??``;B=l;let u=await r.command?.({testCase:n,cwd:p.cwd,env:c,mainFilePath:M})??A.command(M),f;try{f=r.runCommand?await r.runCommand({testCase:n,command:u,stdin:l,cwd:h,env:c,timeLimitSeconds:o,screenshotWaitSeconds:r.screenshotWaitSeconds??b,stopDetectionThreshold:r.stopDetectionThreshold??5}):await k({command:u,stdin:l,cwd:p.cwd,env:c,timeLimitSeconds:o,screenshotWaitSeconds:r.screenshotWaitSeconds??b,stopDetectionThreshold:r.stopDetectionThreshold??5})}catch(t){e({testCaseId:n.id,decisionCode:i.RUNTIME_ERROR,stdin:l,stderr:R(t)}),await a(p.cwd,I);return}let m=await d(p.cwd,g.requiredOutputFilePaths??[]),_={timeLimitSeconds:o,problemMarkdownFrontMatter:{memoryLimitByte:g.memoryLimitByte,requiredOutputFilePaths:g.requiredOutputFilePaths}},v=D({runResult:f,outputFiles:m,context:_}),y=v;if(v.decisionCode===i.ACCEPTED)try{let e=await r.test({testCase:n,runResult:f,outputFiles:m,cwd:p.cwd,context:_});y={decisionCode:e.decisionCode??v.decisionCode,feedbackMarkdown:e.feedbackMarkdown,stderr:e.stderr,stdout:e.stdout,outputFiles:e.outputFiles}}catch(e){y={decisionCode:i.RUNTIME_ERROR,stderr:R(e)}}let x=y.decisionCode??i.ACCEPTED,S=y.stdout??f.stdout,C=y.stderr??f.stderr;if(e({testCaseId:n.id,decisionCode:x,exitStatus:f.status,stdin:f.stdin||void 0,stdout:S||void 0,stderr:C||void 0,timeSeconds:f.timeSeconds,memoryBytes:f.memoryBytes,feedbackMarkdown:y.feedbackMarkdown,outputFiles:y.outputFiles??(m.length>0?m:void 0)}),await a(p.cwd,I),x!==i.ACCEPTED)break}}catch(t){e({testCaseId:z,decisionCode:i.RUNTIME_ERROR,stdin:B,stderr:R(t)}),await a(p.cwd,I)}finally{await L?.dispose()}}async function w(e){if(e.configuredMainFilePath){if(await L(m.join(e.cwd,e.configuredMainFilePath)))return e.configuredMainFilePath;if(!e.allowConfiguredPathFallback)return}return await c(e.cwd,e.language)}function T(e){let t=Object.entries(r).filter(([,t])=>t.fileExtensions.some(t=>e.endsWith(t))).map(([e])=>e);return t.length>0?t:void 0}function E(e){let t=e.languageDefinition.buildCommand?.(e.mainFilePath);if(!t)return;let n=p(t[0],t.slice(1),{cwd:e.cwd,encoding:`utf8`,env:e.env},10);if(n.timeSeconds>10)return{decisionCode:i.BUILD_TIME_LIMIT_EXCEEDED,stderr:n.stderr||void 0};if(n.status!==0)return{decisionCode:i.BUILD_ERROR,stderr:n.stderr||n.stdout||void 0}}function D(e){if(e.runResult.stopReason===`timeout`)return{decisionCode:i.TIME_LIMIT_EXCEEDED,stderr:e.runResult.stderr};if(e.runResult.status!==0)return{decisionCode:i.RUNTIME_ERROR,stderr:e.runResult.stderr};if(e.runResult.memoryBytes>(e.context.problemMarkdownFrontMatter.memoryLimitByte??1/0))return{decisionCode:i.MEMORY_LIMIT_EXCEEDED,stderr:e.runResult.stderr};let t=e.context.problemMarkdownFrontMatter.requiredOutputFilePaths?.length??0;return e.outputFiles.length<t?{decisionCode:i.MISSING_REQUIRED_OUTPUT_FILE_ERROR}:{decisionCode:i.ACCEPTED}}async function O(e){return await n(m.join(e,`test_cases`))}async function k(e){let t=_.spawn(`timeout`,[e.timeLimitSeconds.toFixed(3),...x,...e.command],{cwd:e.cwd,env:e.env,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`]});t.stdout.setEncoding(`utf8`),t.stderr.setEncoding(`utf8`);let n=``,r=``,i,a,o=`process_exit`,s=[],c=[],l=Date.now()/1e3,u=0;t.stdout.on(`data`,e=>{n+=e}),t.stderr.on(`data`,e=>{r+=e}),t.on(`error`,e=>{a=e,i=1}),t.stdin.on(`error`,()=>{}),t.on(`close`,(e,t)=>{if(e===124){o=`timeout`,i=0;return}if(t){i=1,r=r?`${r}\nprocess terminated by signal: ${t}`:`process terminated by signal: ${t}`;return}i=e??1});try{for(e.stdin&&t.stdin.write(e.stdin),t.stdin.end();i===void 0;){if(await y(e.screenshotWaitSeconds*1e3),u=Math.max(u,F(t.pid)),c=A(e.env.DISPLAY).toSorted((e,t)=>e.data.length-t.data.length),c.length>0){let t=c.map(e=>e.data).toSorted();if(s.unshift(t),s.length=Math.min(s.length,e.stopDetectionThreshold),s.length===e.stopDetectionThreshold&&s.every(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))){o=`stable_screenshot`,i=0;break}}if(Date.now()/1e3-l>e.timeLimitSeconds){o=`timeout`,i=0;break}}o!==`process_exit`&&t.exitCode===null&&(t.removeAllListeners(`close`),t.removeAllListeners(`error`))}finally{await P(t)}if(a)throw a;let{memoryBytes:d,stderr:f,timeSeconds:p}=M(r,l,u);return{stdin:e.stdin,stdout:n.trimEnd(),stderr:f,status:i,timeSeconds:p,memoryBytes:d,screenshots:c,stopReason:o}}function A(e){let t={...process.env,DISPLAY:e??process.env.DISPLAY},n=_.spawnSync(`xwininfo`,[`-root`,`-tree`],{encoding:`utf8`,env:t});if(n.error)throw n.error;if(n.status!==0||!n.stdout)return[];let r=[];for(let e of j(n.stdout)){let n=_.spawnSync(`maim`,[`-i`,e],{env:t});if(n.error)throw n.error;if(n.status!==0||n.stdout.length===0)continue;let i=_.spawnSync(`xdotool`,[`getwindowname`,e],{encoding:`utf8`,env:t});if(i.error)throw i.error;let a=i.stdout.trim().replaceAll(/[\s/]/g,`_`);r.push({path:`${a||`window`}_${e}.png`,data:n.stdout.toString(`base64`),encoding:`base64`})}return r}function j(e){let t=[],n=e.split(`
|
|
2
|
+
`);for(let e of n){if(e.includes(`Root window id:`)||e.includes(`Parent window id:`)||e.includes(`()`))continue;let n=/^\s{5}(0x[\da-f]+) /.exec(e);n?.[1]&&t.push(Number.parseInt(n[1],16).toString())}return t}function M(e,t,n){let r=/(?:^|\n)(\d+\.\d+) (\d+)\s*$/.exec(e),i=r?e.slice(0,r.index).trimEnd():e.trimEnd(),a=Number(r?.[2])*1024||0;return{stderr:i,timeSeconds:Number(r?.[1])||Date.now()/1e3-t,memoryBytes:Math.max(a,n)}}async function N(){if(process.platform!==`linux`)throw Error(`GUI screenshot capture is supported only on Linux.`);for(let e=90;e<100;e++){let t=`:${e}`,n,r=_.spawn(`Xvfb`,[t,`-screen`,`0`,`1280x1024x24`,`-ac`],{stdio:`ignore`});if(r.on(`error`,e=>{n=e}),await y(300),n)throw n;if(r.exitCode===null)return{display:t,dispose:async()=>{r.killed||(r.kill(`SIGTERM`),await y(100),r.exitCode===null&&r.kill(`SIGKILL`))}}}throw Error(`Xvfb could not be started.`)}async function P(e){e.pid&&(I(e.pid,`SIGTERM`),await y(200),e.exitCode===null&&I(e.pid,`SIGKILL`))}function F(e){if(!e||process.platform!==`linux`)return 0;let t=_.spawnSync(`ps`,[`-o`,`rss=`,`--no-headers`,`--pgroup`,String(e)],{encoding:`utf8`});return t.error||t.status!==0||!t.stdout?0:t.stdout.split(`
|
|
3
|
+
`).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)&&e>0).reduce((e,t)=>e+t*1024,0)}function I(e,t){try{if(process.platform!==`win32`){process.kill(-e,t);return}}catch{}try{process.kill(e,t)}catch{}}async function L(e){try{return await g.access(e),!0}catch{return!1}}function R(e){return e instanceof Error?e.message:String(e)}export{C as guiCommandJudgePreset};
|
|
4
4
|
//# sourceMappingURL=guiCommand.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guiCommand.js","names":["readFileTestCases","childProcess","wait"],"sources":["../../src/presets/guiCommand.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { setTimeout as wait } from 'node:timers/promises';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { readProblemMarkdownFrontMatter } from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases as readFileTestCases } from '../helpers/readTestCases.js';\nimport { runCustomRunner } from '../helpers/runCustomRunner.js';\nimport {\n getSandboxUserEnvOverrides,\n getTrustedHelperEnv,\n killSandboxUserProcesses,\n makeAccessibleToSandboxUser,\n sandboxUserName,\n startSandboxTimeoutWatchdog,\n TIMEOUT_COMMAND,\n wrapCommandWithSandboxUser,\n} from '../helpers/sandboxUser.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport { languageIdToDefinition } from '../types/language.js';\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 5;\nconst SCREENSHOT_WAIT_SECONDS = 0.3;\nconst XVFB_STARTUP_WAIT_SECONDS = 0.3;\nconst XVFB_SHUTDOWN_WAIT_SECONDS = 0.1;\nconst PROCESS_SHUTDOWN_WAIT_SECONDS = 0.2;\nconst STOP_DETECTION_THRESHOLD = 5;\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\n/** What every GUI test case needs; a custom `readTestCases` may add any fields of its own. */\ninterface BaseGuiTestCase {\n id: string;\n /** Standard input (`test_cases/<id>.in`). */\n input?: string;\n /** Directory copied into the working directory before the run (`test_cases/<id>.fin/`). */\n fileInputPath?: string;\n}\n\n/** A test case read from `test_cases/` by the default reader. */\nexport interface GuiTestCase extends BaseGuiTestCase {\n /** Expected standard output (`test_cases/<id>.out`), for the problem's `test` to compare. */\n output?: string;\n /** Directory of expected output files (`test_cases/<id>.fout/`), for the problem's `test` to compare. */\n fileOutputPath?: string;\n}\n\nexport interface GuiScreenshotFile {\n path: string;\n data: string;\n encoding: 'base64';\n}\n\nexport interface GuiCommandRunResult {\n stdin: string;\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n screenshots: GuiScreenshotFile[];\n stopReason: 'process_exit' | 'stable_screenshot' | 'timeout';\n}\n\ninterface GuiJudgeContext {\n timeLimitSeconds: number;\n problemMarkdownFrontMatter: Pick<ProblemMarkdownFrontMatter, 'memoryLimitByte' | 'requiredOutputFilePaths'>;\n}\n\ntype GuiJudgeCaseResult = Pick<\n TestCaseResult,\n 'decisionCode' | 'feedbackMarkdown' | 'stderr' | 'stdout' | 'outputFiles'\n>;\n\nexport interface GuiCommandJudgePresetOptions<TTestCase extends BaseGuiTestCase = GuiTestCase> {\n mainFilePath?: string;\n runTimeoutSeconds?: number;\n screenshotWaitSeconds?: number;\n stopDetectionThreshold?: number;\n readTestCases?: (problemDir: string) => Promise<readonly TTestCase[]>;\n prepare?: (context: {\n cwd: string;\n /**\n * Build the submission with it. Under `EXERCODE_SANDBOX_USER` delegation it already carries the\n * sandbox user's overrides, but the handler must still wrap whatever it spawns with\n * `wrapCommandWithSandboxUser` (both exported): a build runs the submission's own scripts\n * (`package.json` lifecycle scripts, `build.gradle`, `build.rs`), which as the trusted harness\n * user could read the problem's test cases and rewrite the harness. The preset terminates\n * leftover sandbox processes after the handler returns.\n */\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n problemMarkdownFrontMatter: ProblemMarkdownFrontMatter;\n }) => Promise<Partial<GuiJudgeCaseResult> | undefined> | Partial<GuiJudgeCaseResult> | undefined;\n /**\n * Runs as the trusted harness user with the submission's `cwd`. Fixture files it creates there\n * must be written with `createDirectoryWithoutFollowingSymlinks`/`writeFileWithoutFollowingSymlinks`\n * (both exported): a submission can plant a symlink at a fixture path, and a plain `fs.writeFile`\n * would follow it into a file only the harness can write.\n */\n resolveInput?: (context: { testCase: TTestCase; cwd: string; env: NodeJS.ProcessEnv }) => Promise<string> | string;\n command?: (context: {\n testCase: TTestCase;\n cwd: string;\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n }) => Promise<readonly [string, ...string[]]> | readonly [string, ...string[]];\n runCommand?: (context: {\n testCase: TTestCase;\n /**\n * The command to run. Under `EXERCODE_SANDBOX_USER` delegation it is already wrapped so it\n * executes as the sandbox user; spawn it as given (with the supplied `env`) instead of\n * reconstructing it, or the submission runs as the trusted harness user.\n *\n * Its direct child is then a root-owned `sudo` whose descendants belong to the sandbox user, so\n * the handler cannot signal them: enforce `timeLimitSeconds` with `startSandboxTimeoutWatchdog`\n * and `killSandboxUserProcesses` (both exported) rather than `child.kill()` or an outer\n * `timeout`. The preset terminates leftover sandbox processes after the handler returns.\n */\n command: readonly [string, ...string[]];\n stdin: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n screenshotWaitSeconds: number;\n stopDetectionThreshold: number;\n }) => Promise<GuiCommandRunResult> | GuiCommandRunResult;\n test: (context: {\n testCase: TTestCase;\n runResult: GuiCommandRunResult;\n outputFiles: NonNullable<TestCaseResult['outputFiles']>;\n /** The submission's working directory, e.g. for `compareExpectedOutputFiles(cwd, testCase.fileOutputPath)`. */\n cwd: string;\n context: GuiJudgeContext;\n }) => Promise<Partial<GuiJudgeCaseResult>> | Partial<GuiJudgeCaseResult>;\n}\n\n/**\n * A preset function for judging GUI programs by collecting screenshots while the program runs.\n *\n * Keep problem-specific logic in `prepare`, `command`, and `test`.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { DecisionCode } from '@exercode/problem-utils';\n * import { guiCommandJudgePreset } from '@exercode/problem-utils/presets/guiCommand';\n *\n * await guiCommandJudgePreset(import.meta.dirname, {\n * mainFilePath: 'Main.java',\n * readTestCases: async () => [{ id: 'default' }],\n * test: ({ runResult }) => {\n * return runResult.screenshots.length > 0\n * ? { decisionCode: DecisionCode.ACCEPTED }\n * : { decisionCode: DecisionCode.WRONG_ANSWER };\n * },\n * });\n * ```\n */\nexport async function guiCommandJudgePreset<TTestCase extends BaseGuiTestCase = GuiTestCase>(\n problemDir: string,\n options: GuiCommandJudgePresetOptions<TTestCase>\n): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n const submissionDir = args.cwd;\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(submissionDir);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const configuredTestCases = await (options.readTestCases ?? readGuiTestCases<TTestCase>)(problemDir);\n const testCases =\n configuredTestCases.length > 0 ? configuredTestCases : ([{ id: 'default' }] as unknown as readonly TTestCase[]);\n const prebuildTestCaseId = testCases[0]?.id ?? 'prebuild';\n\n const staticAnalysisResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisResult) {\n printTestCaseResult({ testCaseId: prebuildTestCaseId, ...staticAnalysisResult });\n return;\n }\n\n const initialMainFilePath = options.mainFilePath ?? (await findEntryPointFile(args.cwd, params.language));\n if (!initialMainFilePath) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: options.mainFilePath\n ? `required main file not found: ${options.mainFilePath}`\n : `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(initialMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let resolvedMainFilePath = await resolveMainFilePath({\n cwd: args.cwd,\n language: params.language,\n configuredMainFilePath: options.mainFilePath,\n });\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n const prebuiltMainFilePath = await resolveMainFilePath({\n cwd: args.cwd,\n language: params.language ?? inferLanguageIdsByPath(initialMainFilePath),\n configuredMainFilePath: options.mainFilePath,\n allowConfiguredPathFallback: true,\n });\n if (prebuiltMainFilePath) resolvedMainFilePath = prebuiltMainFilePath;\n } catch (error) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: errorToMessage(error),\n });\n return;\n }\n }\n if (!resolvedMainFilePath) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: options.mainFilePath\n ? `required main file not found: ${options.mainFilePath}`\n : `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n let customPrepareResult: Partial<GuiJudgeCaseResult> | undefined;\n if (options.prepare) {\n try {\n customPrepareResult = await runCustomRunner(() =>\n options.prepare?.({\n cwd: submissionDir,\n env: { ...env, ...getSandboxUserEnvOverrides(env) },\n mainFilePath: resolvedMainFilePath,\n problemMarkdownFrontMatter,\n })\n );\n } catch (error) {\n // Like the `prebuild` step above: report the failed build rather than letting the throw (from\n // the handler itself, or from the fail-closed sandbox sweep around it) end the run resultless.\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: errorToMessage(error),\n });\n return;\n }\n }\n const prepareResult =\n customPrepareResult ??\n runDefaultPrepare({\n cwd: args.cwd,\n env,\n mainFilePath: resolvedMainFilePath,\n languageDefinition,\n });\n if (prepareResult) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: prepareResult.decisionCode ?? DecisionCode.BUILD_ERROR,\n feedbackMarkdown: prepareResult.feedbackMarkdown,\n stderr: prepareResult.stderr,\n stdout: prepareResult.stdout,\n outputFiles: prepareResult.outputFiles,\n });\n return;\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n let displayServer: Awaited<ReturnType<typeof ensureDisplayServer>> | undefined;\n let currentTestCaseId = prebuildTestCaseId;\n let currentStdin: string | undefined;\n try {\n displayServer = options.runCommand ? undefined : await ensureDisplayServer();\n const sharedFileInputPath = (configuredTestCases as { shared?: { fileInputPath?: string } }).shared?.fileInputPath;\n for (const testCase of testCases) {\n currentTestCaseId = testCase.id;\n if (sharedFileInputPath) await copyTestCaseFileInput(sharedFileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n const timeLimitSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : (options.runTimeoutSeconds ?? JUDGE_DEFAULT_TIMEOUT_SECONDS);\n\n const runEnv = displayServer ? { ...env, DISPLAY: displayServer.display } : env;\n const stdin = (await options.resolveInput?.({ testCase, cwd: args.cwd, env: runEnv })) ?? testCase.input ?? '';\n currentStdin = stdin;\n const command =\n (await options.command?.({ testCase, cwd: args.cwd, env: runEnv, mainFilePath: resolvedMainFilePath })) ??\n languageDefinition.command(resolvedMainFilePath);\n\n let runResult: GuiCommandRunResult;\n try {\n runResult = options.runCommand\n ? await runCustomRunner(\n () =>\n // Hand custom runners a command that is already sandbox-wrapped, and the matching\n // environment: they spawn it themselves, so an unwrapped command would run the\n // submission as the trusted harness user and defeat the delegation boundary.\n options.runCommand?.({\n testCase,\n command: wrapCommandWithSandboxUser(command),\n stdin,\n cwd: submissionDir,\n env: { ...runEnv, ...getSandboxUserEnvOverrides(runEnv) },\n timeLimitSeconds,\n screenshotWaitSeconds: options.screenshotWaitSeconds ?? SCREENSHOT_WAIT_SECONDS,\n stopDetectionThreshold: options.stopDetectionThreshold ?? STOP_DETECTION_THRESHOLD,\n }) as Promise<GuiCommandRunResult>\n )\n : await spawnGuiProgram({\n command,\n stdin,\n cwd: args.cwd,\n env: runEnv,\n timeLimitSeconds,\n screenshotWaitSeconds: options.screenshotWaitSeconds ?? SCREENSHOT_WAIT_SECONDS,\n stopDetectionThreshold: options.stopDetectionThreshold ?? STOP_DETECTION_THRESHOLD,\n });\n } catch (error) {\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin,\n stderr: errorToMessage(error),\n });\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n return;\n }\n\n const outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n const judgeContext: GuiJudgeContext = {\n timeLimitSeconds,\n problemMarkdownFrontMatter: {\n memoryLimitByte: problemMarkdownFrontMatter.memoryLimitByte,\n requiredOutputFilePaths: problemMarkdownFrontMatter.requiredOutputFilePaths,\n },\n };\n const baseJudgeResult = evaluateGuiRunResult({ runResult, outputFiles, context: judgeContext });\n let judgeResult = baseJudgeResult;\n if (baseJudgeResult.decisionCode === DecisionCode.ACCEPTED) {\n try {\n const extendedJudgeResult = await options.test({\n testCase,\n runResult,\n outputFiles,\n cwd: args.cwd,\n context: judgeContext,\n });\n judgeResult = {\n decisionCode: extendedJudgeResult.decisionCode ?? baseJudgeResult.decisionCode,\n feedbackMarkdown: extendedJudgeResult.feedbackMarkdown,\n stderr: extendedJudgeResult.stderr,\n stdout: extendedJudgeResult.stdout,\n outputFiles: extendedJudgeResult.outputFiles,\n };\n } catch (error) {\n judgeResult = {\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stderr: errorToMessage(error),\n };\n }\n }\n\n const decisionCode = judgeResult.decisionCode ?? DecisionCode.ACCEPTED;\n const stdout = judgeResult.stdout ?? runResult.stdout;\n const stderr = judgeResult.stderr ?? runResult.stderr;\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: runResult.status,\n stdin: runResult.stdin || undefined,\n stdout: stdout || undefined,\n stderr: stderr || undefined,\n timeSeconds: runResult.timeSeconds,\n memoryBytes: runResult.memoryBytes,\n feedbackMarkdown: judgeResult.feedbackMarkdown,\n outputFiles: judgeResult.outputFiles ?? (outputFiles.length > 0 ? outputFiles : undefined),\n });\n\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n } catch (error) {\n printTestCaseResult({\n testCaseId: currentTestCaseId,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: currentStdin,\n stderr: errorToMessage(error),\n });\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n } finally {\n try {\n // Sweep any sandbox processes the run left behind (e.g. a SIGTERM-ignoring forked child) so\n // they cannot race the harness's output reads or survive into the next test case/request.\n if (sandboxUserName) killSandboxUserProcesses();\n } finally {\n // Must run even when the sweep fails closed, or Xvfb keeps holding its display number and\n // later GUI requests exhaust the `:90`–`:99` range.\n await displayServer?.dispose();\n }\n }\n}\n\nasync function resolveMainFilePath(context: {\n cwd: string;\n language?: string | string[];\n configuredMainFilePath?: string;\n allowConfiguredPathFallback?: boolean;\n}): Promise<string | undefined> {\n if (context.configuredMainFilePath) {\n const resolvedPath = path.join(context.cwd, context.configuredMainFilePath);\n if (await pathExists(resolvedPath)) return context.configuredMainFilePath;\n if (!context.allowConfiguredPathFallback) return undefined;\n }\n\n return await findEntryPointFile(context.cwd, context.language);\n}\n\nfunction inferLanguageIdsByPath(filePath: string): string[] | undefined {\n const languageIds = Object.entries(languageIdToDefinition)\n .filter(([, definition]) => definition.fileExtensions.some((ext) => filePath.endsWith(ext)))\n .map(([languageId]) => languageId);\n return languageIds.length > 0 ? languageIds : undefined;\n}\n\nfunction runDefaultPrepare(context: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n languageDefinition: NonNullable<ReturnType<typeof findLanguageDefinitionByPath>>;\n}): Partial<GuiJudgeCaseResult> | undefined {\n const buildCommand = context.languageDefinition.buildCommand?.(context.mainFilePath);\n if (!buildCommand) return undefined;\n\n const buildResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: context.cwd, encoding: 'utf8', env: context.env },\n BUILD_TIMEOUT_SECONDS\n );\n\n if (buildResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n return {\n decisionCode: DecisionCode.BUILD_TIME_LIMIT_EXCEEDED,\n stderr: buildResult.stderr || undefined,\n };\n }\n\n if (buildResult.status !== 0) {\n return {\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: buildResult.stderr || buildResult.stdout || undefined,\n };\n }\n\n return undefined;\n}\n\nfunction evaluateGuiRunResult(context: {\n runResult: GuiCommandRunResult;\n outputFiles: NonNullable<TestCaseResult['outputFiles']>;\n context: GuiJudgeContext;\n}): Partial<GuiJudgeCaseResult> {\n if (context.runResult.stopReason === 'timeout') {\n return {\n decisionCode: DecisionCode.TIME_LIMIT_EXCEEDED,\n stderr: context.runResult.stderr,\n };\n }\n\n if (context.runResult.status !== 0) {\n return {\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stderr: context.runResult.stderr,\n };\n }\n\n if (\n context.runResult.memoryBytes >\n (context.context.problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)\n ) {\n return {\n decisionCode: DecisionCode.MEMORY_LIMIT_EXCEEDED,\n stderr: context.runResult.stderr,\n };\n }\n\n const requiredOutputFilesCount = context.context.problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0;\n if (context.outputFiles.length < requiredOutputFilesCount) {\n return {\n decisionCode: DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR,\n };\n }\n\n return { decisionCode: DecisionCode.ACCEPTED };\n}\n\nasync function readGuiTestCases<TTestCase extends BaseGuiTestCase>(problemDir: string): Promise<readonly TTestCase[]> {\n // The default reader yields the base shape; a narrower TTestCase must come from `options.readTestCases`.\n return (await readFileTestCases(path.join(problemDir, 'test_cases'))) as unknown as readonly TTestCase[];\n}\n\nasync function spawnGuiProgram(context: {\n command: readonly [string, ...string[]];\n stdin: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n screenshotWaitSeconds: number;\n stopDetectionThreshold: number;\n}): Promise<GuiCommandRunResult> {\n const wrappedCommand = wrapCommandWithSandboxUser([\n TIMEOUT_COMMAND,\n context.timeLimitSeconds.toFixed(3),\n ...TIME_COMMAND,\n ...context.command,\n ]);\n // A submission can signal its own sandboxed `timeout` and then wedge the event loop (e.g.\n // XGrabServer makes the synchronous `xwininfo`/`maim` block), so a harness-owned watchdog\n // force-kills the sandbox user at the deadline; killing the client also releases its X grab.\n // Armed before the submission starts: a submission that exhausts the PID cgroup would otherwise\n // prevent the watchdog from spawning at all.\n const watchdog = startSandboxTimeoutWatchdog(context.timeLimitSeconds);\n let child: childProcess.ChildProcessWithoutNullStreams;\n try {\n child = childProcess.spawn(wrappedCommand[0], wrappedCommand.slice(1), {\n cwd: context.cwd,\n env: { ...context.env, ...getSandboxUserEnvOverrides(context.env) },\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n } catch (error) {\n watchdog.cancel();\n throw error;\n }\n\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n\n let stdout = '';\n let stderr = '';\n let exitCode: number | undefined;\n let spawnError: Error | undefined;\n let stopReason: GuiCommandRunResult['stopReason'] = 'process_exit';\n let submissionStopped = false;\n const screenshotSignaturesHistory: string[][] = [];\n let screenshots: GuiScreenshotFile[] = [];\n const startTimeSeconds = Date.now() / 1000;\n let sampledMemoryBytes = 0;\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk;\n });\n child.on('error', (error) => {\n spawnError = error;\n exitCode = 1;\n });\n // A child that exits before the input is fully written makes the write fail; without a listener\n // that EPIPE would be an unhandled stream error terminating the harness mid-run.\n child.stdin.on('error', () => {\n // The submission simply stopped reading its input; the exit handling below reports the result.\n });\n child.on('close', (code, signal) => {\n if (code === 124) {\n stopReason = 'timeout';\n exitCode = 0;\n return;\n }\n if (signal) {\n exitCode = 1;\n stderr = stderr\n ? `${stderr}\\nprocess terminated by signal: ${signal}`\n : `process terminated by signal: ${signal}`;\n return;\n }\n exitCode = code ?? 1;\n });\n\n // Everything below must run under the `finally` that decides the watchdog's fate: it is cancelled\n // only once the submission is demonstrably stopped. When a helper throws first — `takeScreenshots`\n // rethrows spawn failures, which a submission can provoke by exhausting PIDs — the watchdog stays\n // armed on purpose, since nothing else would end the submission. The cost is that a detached\n // watchdog can outlive this harness and SIGKILL sandbox processes of a request that starts within\n // its remaining deadline, which is the same trade-off the package-manager runner accepts.\n try {\n if (context.stdin) child.stdin.write(context.stdin);\n child.stdin.end();\n\n while (exitCode === undefined) {\n await wait(context.screenshotWaitSeconds * 1000);\n sampledMemoryBytes = Math.max(sampledMemoryBytes, readProcessGroupMemoryBytes(child.pid));\n const currentScreenshots = takeScreenshots(context.env.DISPLAY);\n screenshots = currentScreenshots.toSorted((a, b) => a.data.length - b.data.length);\n\n if (screenshots.length > 0) {\n const screenshotSignatures = screenshots.map((file) => file.data).toSorted();\n screenshotSignaturesHistory.unshift(screenshotSignatures);\n screenshotSignaturesHistory.length = Math.min(\n screenshotSignaturesHistory.length,\n context.stopDetectionThreshold\n );\n if (\n screenshotSignaturesHistory.length === context.stopDetectionThreshold &&\n screenshotSignaturesHistory.every(\n (files) =>\n files.length === screenshotSignatures.length &&\n files.every((file, index) => file === screenshotSignatures[index])\n )\n ) {\n stopReason = 'stable_screenshot';\n exitCode = 0;\n break;\n }\n }\n\n if (Date.now() / 1000 - startTimeSeconds > context.timeLimitSeconds) {\n stopReason = 'timeout';\n exitCode = 0;\n break;\n }\n }\n\n if (stopReason !== 'process_exit' && child.exitCode === null) {\n child.removeAllListeners('close');\n child.removeAllListeners('error');\n }\n // A submission can kill its own same-UID `timeout` and be stopped by the watchdog instead,\n // which surfaces as a SIGKILL rather than a deadline. Report that as the timeout it is, not as\n // the runtime error the signal would otherwise imply — but only when the child's fate is what\n // decided the verdict. A `stable_screenshot` (or the loop's own `timeout`) was already decided\n // from the screenshots, so the watchdog must not overwrite it.\n const watchdogFired = stopReason === 'process_exit' && watchdog.fired();\n await stopProcess(child);\n submissionStopped = true;\n if (spawnError) throw spawnError;\n const {\n memoryBytes,\n stderr: normalizedStderr,\n timeSeconds,\n } = parseTimedStderr(stderr, startTimeSeconds, sampledMemoryBytes);\n\n return {\n stdin: context.stdin,\n stdout: stdout.trimEnd(),\n stderr: normalizedStderr,\n status: watchdogFired ? 0 : exitCode,\n timeSeconds,\n memoryBytes,\n screenshots,\n stopReason: watchdogFired ? 'timeout' : stopReason,\n };\n } finally {\n // Only once the submission is demonstrably stopped: if termination itself failed (or never ran\n // because a helper threw), the watchdog is the only thing left able to end it, and cancelling\n // would leave it running unchecked.\n if (submissionStopped) watchdog.cancel();\n }\n}\n\nfunction takeScreenshots(display: string | undefined): GuiScreenshotFile[] {\n // These helpers run as the trusted harness user, so they must not be resolved through a\n // submission-influenced `PATH` (see `getTrustedHelperEnv`).\n const env = getTrustedHelperEnv(display ? { DISPLAY: display } : { DISPLAY: process.env.DISPLAY });\n const xwininfo = childProcess.spawnSync('xwininfo', ['-root', '-tree'], { encoding: 'utf8', env });\n if (xwininfo.error) throw xwininfo.error;\n if (xwininfo.status !== 0 || !xwininfo.stdout) return [];\n\n const screenshots: GuiScreenshotFile[] = [];\n for (const windowId of extractTopLevelWindowIds(xwininfo.stdout)) {\n const screenshot = childProcess.spawnSync('maim', ['-i', windowId], { env });\n if (screenshot.error) throw screenshot.error;\n if (screenshot.status !== 0 || screenshot.stdout.length === 0) continue;\n\n const windowNameResult = childProcess.spawnSync('xdotool', ['getwindowname', windowId], { encoding: 'utf8', env });\n if (windowNameResult.error) throw windowNameResult.error;\n const windowName = windowNameResult.stdout.trim().replaceAll(/[\\s/]/g, '_');\n\n screenshots.push({\n path: `${windowName || 'window'}_${windowId}.png`,\n data: screenshot.stdout.toString('base64'),\n encoding: 'base64',\n });\n }\n\n return screenshots;\n}\n\nfunction extractTopLevelWindowIds(stdout: string): string[] {\n const windowIds: string[] = [];\n const lines = stdout.split('\\n');\n for (const line of lines) {\n if (line.includes('Root window id:') || line.includes('Parent window id:') || line.includes('()')) continue;\n\n const match = /^\\s{5}(0x[\\da-f]+) /.exec(line);\n if (!match?.[1]) continue;\n windowIds.push(Number.parseInt(match[1], 16).toString());\n }\n return windowIds;\n}\n\nfunction parseTimedStderr(\n stderr: string,\n startTimeSeconds: number,\n sampledMemoryBytes: number\n): Pick<GuiCommandRunResult, 'stderr' | 'timeSeconds' | 'memoryBytes'> {\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(stderr);\n const normalizedStderr = match ? stderr.slice(0, match.index).trimEnd() : stderr.trimEnd();\n const parsedMemoryBytes = Number(match?.[2]) * 1024 || 0;\n return {\n stderr: normalizedStderr,\n timeSeconds: Number(match?.[1]) || Date.now() / 1000 - startTimeSeconds,\n memoryBytes: Math.max(parsedMemoryBytes, sampledMemoryBytes),\n };\n}\n\nasync function ensureDisplayServer(): Promise<{ display: string; dispose: () => Promise<void> }> {\n if (process.platform !== 'linux') {\n throw new Error('GUI screenshot capture is supported only on Linux.');\n }\n\n for (let displayNumber = 90; displayNumber < 100; displayNumber++) {\n const display = `:${displayNumber}`;\n let spawnError: Error | undefined;\n const xvfb = childProcess.spawn('Xvfb', [display, '-screen', '0', '1280x1024x24', '-ac'], {\n stdio: 'ignore',\n // Runs as the trusted harness user, so pin the lookup to system paths.\n env: getTrustedHelperEnv(),\n });\n xvfb.on('error', (error) => {\n spawnError = error;\n });\n\n await wait(XVFB_STARTUP_WAIT_SECONDS * 1000);\n if (spawnError) throw spawnError;\n if (xvfb.exitCode !== null) continue;\n\n return {\n display,\n dispose: async () => {\n if (!xvfb.killed) {\n xvfb.kill('SIGTERM');\n await wait(XVFB_SHUTDOWN_WAIT_SECONDS * 1000);\n if (xvfb.exitCode === null) xvfb.kill('SIGKILL');\n }\n },\n };\n }\n\n throw new Error('Xvfb could not be started.');\n}\n\nasync function stopProcess(child: childProcess.ChildProcess): Promise<void> {\n if (!child.pid) return;\n // The current user cannot signal the root-owned sudo wrapper nor the sandbox user's processes, so\n // go through sudo. SIGKILL is unconditional after the grace period: `child.exitCode` reflects only\n // the sudo wrapper, so a daemonized child that ignored SIGTERM would survive if we gated on it.\n if (sandboxUserName) {\n killSandboxUserProcesses(['TERM']);\n await wait(PROCESS_SHUTDOWN_WAIT_SECONDS * 1000);\n killSandboxUserProcesses(['KILL']);\n return;\n }\n killProcessGroup(child.pid, 'SIGTERM');\n await wait(PROCESS_SHUTDOWN_WAIT_SECONDS * 1000);\n if (child.exitCode === null) killProcessGroup(child.pid, 'SIGKILL');\n}\n\nfunction readProcessGroupMemoryBytes(processGroupId: number | undefined): number {\n if (!processGroupId || process.platform !== 'linux') return 0;\n\n // The delegation contract requires sudoers `!use_pty`, so sudo execs the command in place and it\n // stays in the detached child's process group; `--pgroup` therefore still captures it there.\n const result = childProcess.spawnSync('ps', ['-o', 'rss=', '--no-headers', '--pgroup', String(processGroupId)], {\n encoding: 'utf8',\n // Runs as the trusted harness user, so pin the lookup to system paths.\n env: getTrustedHelperEnv(),\n });\n if (result.error || result.status !== 0 || !result.stdout) return 0;\n\n return result.stdout\n .split('\\n')\n .map((line) => Number(line.trim()))\n .filter((value) => Number.isFinite(value) && value > 0)\n .reduce((sum, value) => sum + value * 1024, 0);\n}\n\nfunction killProcessGroup(processGroupId: number, signal: NodeJS.Signals): void {\n try {\n if (process.platform !== 'win32') {\n process.kill(-processGroupId, signal);\n return;\n }\n } catch {\n // The process group may already be gone. Fall back to the direct PID below.\n }\n\n try {\n process.kill(processGroupId, signal);\n } catch {\n // The direct child may also already be gone.\n }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction errorToMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"87CAmCA,MAEM,EAA0B,GAG1B,EAAgC,GAEhC,EAAe,CAAC,EAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EAE3F,EAAoB,EAAE,OAAO,CACjC,SAAU,EAAE,MAAM,CAAC,EAAE,OAAO,EAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAmID,eAAsB,EACpB,EACA,EACe,CACf,IAAM,EAAO,EAAU,QAAQ,IAAI,EACnC,GAAI,CAAC,EAAK,IAAK,MAAU,MAAM,uBAAuB,EACtD,IAAM,EAAS,EAAkB,MAAM,EAAK,MAAM,EAC5C,EAAgB,EAAK,IAG3B,EAA4B,CAAa,EAEzC,IAAM,EAA6B,MAAM,EAA+B,CAAU,EAC5E,EAAsB,MAAO,EAAQ,eAAiB,EAAA,CAA6B,CAAU,EAC7F,EACJ,EAAoB,OAAS,EAAI,EAAuB,CAAC,CAAE,GAAI,SAAU,CAAC,EACtE,EAAqB,EAAU,EAAE,EAAE,IAAM,WAEzC,EAAuB,MAAM,EAAsB,EAAK,IAAK,CAA0B,EAC7F,GAAI,EAAsB,CACxB,EAAoB,CAAE,WAAY,EAAoB,GAAG,CAAqB,CAAC,EAC/E,MACF,CAEA,IAAM,EAAsB,EAAQ,cAAiB,MAAM,EAAmB,EAAK,IAAK,EAAO,QAAQ,EACvG,GAAI,CAAC,EAAqB,CACxB,EAAoB,CAClB,WAAY,EACZ,aAAc,EAAa,uCAC3B,OAAQ,EAAQ,aACZ,iCAAiC,EAAQ,eACzC,sBAAsB,EAAO,SAAW,eAAe,EAAO,WAAa,IACjF,CAAC,EACD,MACF,CAEA,IAAM,EAAqB,EAA6B,CAAmB,EAC3E,GAAI,CAAC,EAAoB,CACvB,EAAoB,CA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"sources":["../../src/presets/guiCommand.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { setTimeout as wait } from 'node:timers/promises';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { readProblemMarkdownFrontMatter } from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases as readFileTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport { languageIdToDefinition } from '../types/language.js';\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 5;\nconst SCREENSHOT_WAIT_SECONDS = 0.3;\nconst XVFB_STARTUP_WAIT_SECONDS = 0.3;\nconst XVFB_SHUTDOWN_WAIT_SECONDS = 0.1;\nconst PROCESS_SHUTDOWN_WAIT_SECONDS = 0.2;\nconst STOP_DETECTION_THRESHOLD = 5;\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\n/** What every GUI test case needs; a custom `readTestCases` may add any fields of its own. */\ninterface BaseGuiTestCase {\n id: string;\n /** Standard input (`test_cases/<id>.in`). */\n input?: string;\n /** Directory copied into the working directory before the run (`test_cases/<id>.fin/`). */\n fileInputPath?: string;\n}\n\n/** A test case read from `test_cases/` by the default reader. */\nexport interface GuiTestCase extends BaseGuiTestCase {\n /** Expected standard output (`test_cases/<id>.out`), for the problem's `test` to compare. */\n output?: string;\n /** Directory of expected output files (`test_cases/<id>.fout/`), for the problem's `test` to compare. */\n fileOutputPath?: string;\n}\n\nexport interface GuiScreenshotFile {\n path: string;\n data: string;\n encoding: 'base64';\n}\n\nexport interface GuiCommandRunResult {\n stdin: string;\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n screenshots: GuiScreenshotFile[];\n stopReason: 'process_exit' | 'stable_screenshot' | 'timeout';\n}\n\ninterface GuiJudgeContext {\n timeLimitSeconds: number;\n problemMarkdownFrontMatter: Pick<ProblemMarkdownFrontMatter, 'memoryLimitByte' | 'requiredOutputFilePaths'>;\n}\n\ntype GuiJudgeCaseResult = Pick<\n TestCaseResult,\n 'decisionCode' | 'feedbackMarkdown' | 'stderr' | 'stdout' | 'outputFiles'\n>;\n\nexport interface GuiCommandJudgePresetOptions<TTestCase extends BaseGuiTestCase = GuiTestCase> {\n mainFilePath?: string;\n runTimeoutSeconds?: number;\n screenshotWaitSeconds?: number;\n stopDetectionThreshold?: number;\n readTestCases?: (problemDir: string) => Promise<readonly TTestCase[]>;\n prepare?: (context: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n problemMarkdownFrontMatter: ProblemMarkdownFrontMatter;\n }) => Promise<Partial<GuiJudgeCaseResult> | undefined> | Partial<GuiJudgeCaseResult> | undefined;\n resolveInput?: (context: { testCase: TTestCase; cwd: string; env: NodeJS.ProcessEnv }) => Promise<string> | string;\n command?: (context: {\n testCase: TTestCase;\n cwd: string;\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n }) => Promise<readonly [string, ...string[]]> | readonly [string, ...string[]];\n runCommand?: (context: {\n testCase: TTestCase;\n command: readonly [string, ...string[]];\n stdin: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n screenshotWaitSeconds: number;\n stopDetectionThreshold: number;\n }) => Promise<GuiCommandRunResult> | GuiCommandRunResult;\n test: (context: {\n testCase: TTestCase;\n runResult: GuiCommandRunResult;\n outputFiles: NonNullable<TestCaseResult['outputFiles']>;\n /** The submission's working directory, e.g. for `compareExpectedOutputFiles(cwd, testCase.fileOutputPath)`. */\n cwd: string;\n context: GuiJudgeContext;\n }) => Promise<Partial<GuiJudgeCaseResult>> | Partial<GuiJudgeCaseResult>;\n}\n\n/**\n * A preset function for judging GUI programs by collecting screenshots while the program runs.\n *\n * Keep problem-specific logic in `prepare`, `command`, and `test`.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { DecisionCode } from '@exercode/problem-utils';\n * import { guiCommandJudgePreset } from '@exercode/problem-utils/presets/guiCommand';\n *\n * await guiCommandJudgePreset(import.meta.dirname, {\n * mainFilePath: 'Main.java',\n * readTestCases: async () => [{ id: 'default' }],\n * test: ({ runResult }) => {\n * return runResult.screenshots.length > 0\n * ? { decisionCode: DecisionCode.ACCEPTED }\n * : { decisionCode: DecisionCode.WRONG_ANSWER };\n * },\n * });\n * ```\n */\nexport async function guiCommandJudgePreset<TTestCase extends BaseGuiTestCase = GuiTestCase>(\n problemDir: string,\n options: GuiCommandJudgePresetOptions<TTestCase>\n): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n const submissionDir = args.cwd;\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const configuredTestCases = await (options.readTestCases ?? readGuiTestCases<TTestCase>)(problemDir);\n const testCases =\n configuredTestCases.length > 0 ? configuredTestCases : ([{ id: 'default' }] as unknown as readonly TTestCase[]);\n const prebuildTestCaseId = testCases[0]?.id ?? 'prebuild';\n\n const staticAnalysisResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisResult) {\n printTestCaseResult({ testCaseId: prebuildTestCaseId, ...staticAnalysisResult });\n return;\n }\n\n const initialMainFilePath = options.mainFilePath ?? (await findEntryPointFile(args.cwd, params.language));\n if (!initialMainFilePath) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: options.mainFilePath\n ? `required main file not found: ${options.mainFilePath}`\n : `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(initialMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let resolvedMainFilePath = await resolveMainFilePath({\n cwd: args.cwd,\n language: params.language,\n configuredMainFilePath: options.mainFilePath,\n });\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n const prebuiltMainFilePath = await resolveMainFilePath({\n cwd: args.cwd,\n language: params.language ?? inferLanguageIdsByPath(initialMainFilePath),\n configuredMainFilePath: options.mainFilePath,\n allowConfiguredPathFallback: true,\n });\n if (prebuiltMainFilePath) resolvedMainFilePath = prebuiltMainFilePath;\n } catch (error) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: errorToMessage(error),\n });\n return;\n }\n }\n if (!resolvedMainFilePath) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: options.mainFilePath\n ? `required main file not found: ${options.mainFilePath}`\n : `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n let customPrepareResult: Partial<GuiJudgeCaseResult> | undefined;\n if (options.prepare) {\n try {\n customPrepareResult = await options.prepare({\n cwd: submissionDir,\n env,\n mainFilePath: resolvedMainFilePath,\n problemMarkdownFrontMatter,\n });\n } catch (error) {\n // Like the `prebuild` step above: report the failed build rather than letting the throw end the\n // run resultless.\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: errorToMessage(error),\n });\n return;\n }\n }\n const prepareResult =\n customPrepareResult ??\n runDefaultPrepare({\n cwd: args.cwd,\n env,\n mainFilePath: resolvedMainFilePath,\n languageDefinition,\n });\n if (prepareResult) {\n printTestCaseResult({\n testCaseId: prebuildTestCaseId,\n decisionCode: prepareResult.decisionCode ?? DecisionCode.BUILD_ERROR,\n feedbackMarkdown: prepareResult.feedbackMarkdown,\n stderr: prepareResult.stderr,\n stdout: prepareResult.stdout,\n outputFiles: prepareResult.outputFiles,\n });\n return;\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n let displayServer: Awaited<ReturnType<typeof ensureDisplayServer>> | undefined;\n let currentTestCaseId = prebuildTestCaseId;\n let currentStdin: string | undefined;\n try {\n displayServer = options.runCommand ? undefined : await ensureDisplayServer();\n const sharedFileInputPath = (configuredTestCases as { shared?: { fileInputPath?: string } }).shared?.fileInputPath;\n for (const testCase of testCases) {\n currentTestCaseId = testCase.id;\n if (sharedFileInputPath) await copyTestCaseFileInput(sharedFileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n const timeLimitSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : (options.runTimeoutSeconds ?? JUDGE_DEFAULT_TIMEOUT_SECONDS);\n\n const runEnv = displayServer ? { ...env, DISPLAY: displayServer.display } : env;\n const stdin = (await options.resolveInput?.({ testCase, cwd: args.cwd, env: runEnv })) ?? testCase.input ?? '';\n currentStdin = stdin;\n const command =\n (await options.command?.({ testCase, cwd: args.cwd, env: runEnv, mainFilePath: resolvedMainFilePath })) ??\n languageDefinition.command(resolvedMainFilePath);\n\n let runResult: GuiCommandRunResult;\n try {\n runResult = options.runCommand\n ? await options.runCommand({\n testCase,\n command,\n stdin,\n cwd: submissionDir,\n env: runEnv,\n timeLimitSeconds,\n screenshotWaitSeconds: options.screenshotWaitSeconds ?? SCREENSHOT_WAIT_SECONDS,\n stopDetectionThreshold: options.stopDetectionThreshold ?? STOP_DETECTION_THRESHOLD,\n })\n : await spawnGuiProgram({\n command,\n stdin,\n cwd: args.cwd,\n env: runEnv,\n timeLimitSeconds,\n screenshotWaitSeconds: options.screenshotWaitSeconds ?? SCREENSHOT_WAIT_SECONDS,\n stopDetectionThreshold: options.stopDetectionThreshold ?? STOP_DETECTION_THRESHOLD,\n });\n } catch (error) {\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin,\n stderr: errorToMessage(error),\n });\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n return;\n }\n\n const outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n const judgeContext: GuiJudgeContext = {\n timeLimitSeconds,\n problemMarkdownFrontMatter: {\n memoryLimitByte: problemMarkdownFrontMatter.memoryLimitByte,\n requiredOutputFilePaths: problemMarkdownFrontMatter.requiredOutputFilePaths,\n },\n };\n const baseJudgeResult = evaluateGuiRunResult({ runResult, outputFiles, context: judgeContext });\n let judgeResult = baseJudgeResult;\n if (baseJudgeResult.decisionCode === DecisionCode.ACCEPTED) {\n try {\n const extendedJudgeResult = await options.test({\n testCase,\n runResult,\n outputFiles,\n cwd: args.cwd,\n context: judgeContext,\n });\n judgeResult = {\n decisionCode: extendedJudgeResult.decisionCode ?? baseJudgeResult.decisionCode,\n feedbackMarkdown: extendedJudgeResult.feedbackMarkdown,\n stderr: extendedJudgeResult.stderr,\n stdout: extendedJudgeResult.stdout,\n outputFiles: extendedJudgeResult.outputFiles,\n };\n } catch (error) {\n judgeResult = {\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stderr: errorToMessage(error),\n };\n }\n }\n\n const decisionCode = judgeResult.decisionCode ?? DecisionCode.ACCEPTED;\n const stdout = judgeResult.stdout ?? runResult.stdout;\n const stderr = judgeResult.stderr ?? runResult.stderr;\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: runResult.status,\n stdin: runResult.stdin || undefined,\n stdout: stdout || undefined,\n stderr: stderr || undefined,\n timeSeconds: runResult.timeSeconds,\n memoryBytes: runResult.memoryBytes,\n feedbackMarkdown: judgeResult.feedbackMarkdown,\n outputFiles: judgeResult.outputFiles ?? (outputFiles.length > 0 ? outputFiles : undefined),\n });\n\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n } catch (error) {\n printTestCaseResult({\n testCaseId: currentTestCaseId,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: currentStdin,\n stderr: errorToMessage(error),\n });\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n } finally {\n await displayServer?.dispose();\n }\n}\n\nasync function resolveMainFilePath(context: {\n cwd: string;\n language?: string | string[];\n configuredMainFilePath?: string;\n allowConfiguredPathFallback?: boolean;\n}): Promise<string | undefined> {\n if (context.configuredMainFilePath) {\n const resolvedPath = path.join(context.cwd, context.configuredMainFilePath);\n if (await pathExists(resolvedPath)) return context.configuredMainFilePath;\n if (!context.allowConfiguredPathFallback) return undefined;\n }\n\n return await findEntryPointFile(context.cwd, context.language);\n}\n\nfunction inferLanguageIdsByPath(filePath: string): string[] | undefined {\n const languageIds = Object.entries(languageIdToDefinition)\n .filter(([, definition]) => definition.fileExtensions.some((ext) => filePath.endsWith(ext)))\n .map(([languageId]) => languageId);\n return languageIds.length > 0 ? languageIds : undefined;\n}\n\nfunction runDefaultPrepare(context: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n mainFilePath: string;\n languageDefinition: NonNullable<ReturnType<typeof findLanguageDefinitionByPath>>;\n}): Partial<GuiJudgeCaseResult> | undefined {\n const buildCommand = context.languageDefinition.buildCommand?.(context.mainFilePath);\n if (!buildCommand) return undefined;\n\n const buildResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: context.cwd, encoding: 'utf8', env: context.env },\n BUILD_TIMEOUT_SECONDS\n );\n\n if (buildResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n return {\n decisionCode: DecisionCode.BUILD_TIME_LIMIT_EXCEEDED,\n stderr: buildResult.stderr || undefined,\n };\n }\n\n if (buildResult.status !== 0) {\n return {\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: buildResult.stderr || buildResult.stdout || undefined,\n };\n }\n\n return undefined;\n}\n\nfunction evaluateGuiRunResult(context: {\n runResult: GuiCommandRunResult;\n outputFiles: NonNullable<TestCaseResult['outputFiles']>;\n context: GuiJudgeContext;\n}): Partial<GuiJudgeCaseResult> {\n if (context.runResult.stopReason === 'timeout') {\n return {\n decisionCode: DecisionCode.TIME_LIMIT_EXCEEDED,\n stderr: context.runResult.stderr,\n };\n }\n\n if (context.runResult.status !== 0) {\n return {\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stderr: context.runResult.stderr,\n };\n }\n\n if (\n context.runResult.memoryBytes >\n (context.context.problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)\n ) {\n return {\n decisionCode: DecisionCode.MEMORY_LIMIT_EXCEEDED,\n stderr: context.runResult.stderr,\n };\n }\n\n const requiredOutputFilesCount = context.context.problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0;\n if (context.outputFiles.length < requiredOutputFilesCount) {\n return {\n decisionCode: DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR,\n };\n }\n\n return { decisionCode: DecisionCode.ACCEPTED };\n}\n\nasync function readGuiTestCases<TTestCase extends BaseGuiTestCase>(problemDir: string): Promise<readonly TTestCase[]> {\n // The default reader yields the base shape; a narrower TTestCase must come from `options.readTestCases`.\n return (await readFileTestCases(path.join(problemDir, 'test_cases'))) as unknown as readonly TTestCase[];\n}\n\nasync function spawnGuiProgram(context: {\n command: readonly [string, ...string[]];\n stdin: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n screenshotWaitSeconds: number;\n stopDetectionThreshold: number;\n}): Promise<GuiCommandRunResult> {\n const child = childProcess.spawn(\n 'timeout',\n [context.timeLimitSeconds.toFixed(3), ...TIME_COMMAND, ...context.command],\n {\n cwd: context.cwd,\n env: context.env,\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\n }\n );\n\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n\n let stdout = '';\n let stderr = '';\n let exitCode: number | undefined;\n let spawnError: Error | undefined;\n let stopReason: GuiCommandRunResult['stopReason'] = 'process_exit';\n const screenshotSignaturesHistory: string[][] = [];\n let screenshots: GuiScreenshotFile[] = [];\n const startTimeSeconds = Date.now() / 1000;\n let sampledMemoryBytes = 0;\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk;\n });\n child.on('error', (error) => {\n spawnError = error;\n exitCode = 1;\n });\n // A child that exits before the input is fully written makes the write fail; without a listener\n // that EPIPE would be an unhandled stream error terminating the harness mid-run.\n child.stdin.on('error', () => {\n // The submission simply stopped reading its input; the exit handling below reports the result.\n });\n child.on('close', (code, signal) => {\n if (code === 124) {\n stopReason = 'timeout';\n exitCode = 0;\n return;\n }\n if (signal) {\n exitCode = 1;\n stderr = stderr\n ? `${stderr}\\nprocess terminated by signal: ${signal}`\n : `process terminated by signal: ${signal}`;\n return;\n }\n exitCode = code ?? 1;\n });\n\n // Stop the program even when a helper throws (e.g. `xwininfo` missing); the spawned process\n // would otherwise outlive this run.\n try {\n if (context.stdin) child.stdin.write(context.stdin);\n child.stdin.end();\n\n while (exitCode === undefined) {\n await wait(context.screenshotWaitSeconds * 1000);\n sampledMemoryBytes = Math.max(sampledMemoryBytes, readProcessGroupMemoryBytes(child.pid));\n const currentScreenshots = takeScreenshots(context.env.DISPLAY);\n screenshots = currentScreenshots.toSorted((a, b) => a.data.length - b.data.length);\n\n if (screenshots.length > 0) {\n const screenshotSignatures = screenshots.map((file) => file.data).toSorted();\n screenshotSignaturesHistory.unshift(screenshotSignatures);\n screenshotSignaturesHistory.length = Math.min(\n screenshotSignaturesHistory.length,\n context.stopDetectionThreshold\n );\n if (\n screenshotSignaturesHistory.length === context.stopDetectionThreshold &&\n screenshotSignaturesHistory.every(\n (files) =>\n files.length === screenshotSignatures.length &&\n files.every((file, index) => file === screenshotSignatures[index])\n )\n ) {\n stopReason = 'stable_screenshot';\n exitCode = 0;\n break;\n }\n }\n\n if (Date.now() / 1000 - startTimeSeconds > context.timeLimitSeconds) {\n stopReason = 'timeout';\n exitCode = 0;\n break;\n }\n }\n\n if (stopReason !== 'process_exit' && child.exitCode === null) {\n child.removeAllListeners('close');\n child.removeAllListeners('error');\n }\n } finally {\n await stopProcess(child);\n }\n if (spawnError) throw spawnError;\n const {\n memoryBytes,\n stderr: normalizedStderr,\n timeSeconds,\n } = parseTimedStderr(stderr, startTimeSeconds, sampledMemoryBytes);\n\n return {\n stdin: context.stdin,\n stdout: stdout.trimEnd(),\n stderr: normalizedStderr,\n status: exitCode,\n timeSeconds,\n memoryBytes,\n screenshots,\n stopReason,\n };\n}\n\nfunction takeScreenshots(display: string | undefined): GuiScreenshotFile[] {\n // Node omits environment entries whose value is undefined, so a missing display is simply not set.\n const env = { ...process.env, DISPLAY: display ?? process.env.DISPLAY };\n const xwininfo = childProcess.spawnSync('xwininfo', ['-root', '-tree'], { encoding: 'utf8', env });\n if (xwininfo.error) throw xwininfo.error;\n if (xwininfo.status !== 0 || !xwininfo.stdout) return [];\n\n const screenshots: GuiScreenshotFile[] = [];\n for (const windowId of extractTopLevelWindowIds(xwininfo.stdout)) {\n const screenshot = childProcess.spawnSync('maim', ['-i', windowId], { env });\n if (screenshot.error) throw screenshot.error;\n if (screenshot.status !== 0 || screenshot.stdout.length === 0) continue;\n\n const windowNameResult = childProcess.spawnSync('xdotool', ['getwindowname', windowId], { encoding: 'utf8', env });\n if (windowNameResult.error) throw windowNameResult.error;\n const windowName = windowNameResult.stdout.trim().replaceAll(/[\\s/]/g, '_');\n\n screenshots.push({\n path: `${windowName || 'window'}_${windowId}.png`,\n data: screenshot.stdout.toString('base64'),\n encoding: 'base64',\n });\n }\n\n return screenshots;\n}\n\nfunction extractTopLevelWindowIds(stdout: string): string[] {\n const windowIds: string[] = [];\n const lines = stdout.split('\\n');\n for (const line of lines) {\n if (line.includes('Root window id:') || line.includes('Parent window id:') || line.includes('()')) continue;\n\n const match = /^\\s{5}(0x[\\da-f]+) /.exec(line);\n if (!match?.[1]) continue;\n windowIds.push(Number.parseInt(match[1], 16).toString());\n }\n return windowIds;\n}\n\nfunction parseTimedStderr(\n stderr: string,\n startTimeSeconds: number,\n sampledMemoryBytes: number\n): Pick<GuiCommandRunResult, 'stderr' | 'timeSeconds' | 'memoryBytes'> {\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(stderr);\n const normalizedStderr = match ? stderr.slice(0, match.index).trimEnd() : stderr.trimEnd();\n const parsedMemoryBytes = Number(match?.[2]) * 1024 || 0;\n return {\n stderr: normalizedStderr,\n timeSeconds: Number(match?.[1]) || Date.now() / 1000 - startTimeSeconds,\n memoryBytes: Math.max(parsedMemoryBytes, sampledMemoryBytes),\n };\n}\n\nasync function ensureDisplayServer(): Promise<{ display: string; dispose: () => Promise<void> }> {\n if (process.platform !== 'linux') {\n throw new Error('GUI screenshot capture is supported only on Linux.');\n }\n\n for (let displayNumber = 90; displayNumber < 100; displayNumber++) {\n const display = `:${displayNumber}`;\n let spawnError: Error | undefined;\n const xvfb = childProcess.spawn('Xvfb', [display, '-screen', '0', '1280x1024x24', '-ac'], { stdio: 'ignore' });\n xvfb.on('error', (error) => {\n spawnError = error;\n });\n\n await wait(XVFB_STARTUP_WAIT_SECONDS * 1000);\n if (spawnError) throw spawnError;\n if (xvfb.exitCode !== null) continue;\n\n return {\n display,\n dispose: async () => {\n if (!xvfb.killed) {\n xvfb.kill('SIGTERM');\n await wait(XVFB_SHUTDOWN_WAIT_SECONDS * 1000);\n if (xvfb.exitCode === null) xvfb.kill('SIGKILL');\n }\n },\n };\n }\n\n throw new Error('Xvfb could not be started.');\n}\n\nasync function stopProcess(child: childProcess.ChildProcess): Promise<void> {\n if (!child.pid) return;\n killProcessGroup(child.pid, 'SIGTERM');\n await wait(PROCESS_SHUTDOWN_WAIT_SECONDS * 1000);\n if (child.exitCode === null) killProcessGroup(child.pid, 'SIGKILL');\n}\n\nfunction readProcessGroupMemoryBytes(processGroupId: number | undefined): number {\n if (!processGroupId || process.platform !== 'linux') return 0;\n\n const result = childProcess.spawnSync('ps', ['-o', 'rss=', '--no-headers', '--pgroup', String(processGroupId)], {\n encoding: 'utf8',\n });\n if (result.error || result.status !== 0 || !result.stdout) return 0;\n\n return result.stdout\n .split('\\n')\n .map((line) => Number(line.trim()))\n .filter((value) => Number.isFinite(value) && value > 0)\n .reduce((sum, value) => sum + value * 1024, 0);\n}\n\nfunction killProcessGroup(processGroupId: number, signal: NodeJS.Signals): void {\n try {\n if (process.platform !== 'win32') {\n process.kill(-processGroupId, signal);\n return;\n }\n } catch {\n // The process group may already be gone. Fall back to the direct PID below.\n }\n\n try {\n process.kill(processGroupId, signal);\n } catch {\n // The direct child may also already be gone.\n }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction errorToMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"onCAwBA,MAEM,EAA0B,GAK1B,EAAe,CAAC,EAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EAE3F,EAAoB,E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5D,GAAI,CAEF,OADA,MAAM,EAAG,OAAO,CAAQ,EACjB,EACT,MAAQ,CACN,MAAO,EACT,CACF,CAEA,SAAS,EAAe,EAAwB,CAC9C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
|
package/dist/presets/stdio.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../helpers/printTestCaseResult.cjs"),n=require("../helpers/
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../helpers/printTestCaseResult.cjs"),n=require("../helpers/compareExpectedOutputFiles.cjs"),r=require("../helpers/parseArgs.cjs"),i=require("../helpers/readTestCases.cjs"),a=require("../helpers/temporaryProblemDirCopy.cjs"),o=require("../types/decisionCode.cjs"),s=require("../helpers/cleanWorkingDirectory.cjs"),c=require("../helpers/copyTestCaseFileInput.cjs"),l=require("../helpers/findEntryPointFile.cjs"),u=require("../helpers/findLanguageDefinitionByPath.cjs"),d=require("../helpers/judgeByStaticAnalysis.cjs"),f=require("../helpers/readOutputFiles.cjs"),p=require("../helpers/readProblemMarkdownFrontMatter.cjs"),m=require("../helpers/spawnSyncWithTimeout.cjs");let h=require("node:fs");h=e.__toESM(h,1);let g=require("node:path");g=e.__toESM(g,1);let _=require("zod");const v=5e4,y=/example/,b=_.z.object({language:_.z.union([_.z.string(),_.z.array(_.z.string())]).optional()}),x=b.extend({stdin:_.z.string().optional()});async function S(e){let a=r.parseArgs(process.argv);if(!a.cwd)throw Error(`cwd argument required`);let h=b.parse(a.params),_=await p.readProblemMarkdownFrontMatter(e),y=await i.readTestCases(g.default.join(e,`test_cases`));if(!p.judgesTestCasesWithoutExpectations(_)){for(let e of y)if(e.output===void 0&&!await C(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let x=await d.judgeByStaticAnalysis(a.cwd,_);if(x){t.printTestCaseResult({testCaseId:y[0]?.id??`prebuild`,...x});return}let S=await l.findEntryPointFile(a.cwd,h.language);if(!S){t.printTestCaseResult({testCaseId:y[0]?.id??`prebuild`,decisionCode:o.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${h.language?`: language: ${h.language}`:``}`});return}let w=u.findLanguageDefinitionByPath(S);if(!w){t.printTestCaseResult({testCaseId:y[0]?.id??`prebuild`,decisionCode:o.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let T={...process.env,CI:``,FORCE_COLOR:`0`},E;if(w.prebuild)try{await w.prebuild(a.cwd),E=await l.findEntryPointFile(a.cwd,h.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:y[0]?.id??`prebuild`,decisionCode:o.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let D=E??S;if(w.buildCommand)try{let e=w.buildCommand(D),n=m.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:a.cwd,encoding:`utf8`,env:T},10),r=o.DecisionCode.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=o.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>v||n.stderr.length>v)&&(r=o.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=o.DecisionCode.BUILD_ERROR,r!==o.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:y[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,v)||void 0,stderr:n.stderr.slice(0,v)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:y[0]?.id??`build`,decisionCode:o.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let O=await s.snapshotWorkingDirectory(a.cwd);y.length===0&&t.printTestCaseResult({testCaseId:`default`,decisionCode:o.DecisionCode.ACCEPTED});for(let e of y){y.shared?.fileInputPath&&await c.copyTestCaseFileInput(y.shared.fileInputPath,a.cwd),e.fileInputPath&&await c.copyTestCaseFileInput(e.fileInputPath,a.cwd);let r=typeof _.timeLimitMs==`number`?_.timeLimitMs/1e3:2,i=w.command(D),l=m.spawnSyncWithTimeout(i[0],i.slice(1),{cwd:a.cwd,encoding:`utf8`,input:e.input,env:T},r),u=await f.readOutputFiles(a.cwd,_.requiredOutputFilePaths??[]),d=o.DecisionCode.ACCEPTED,p;if(l.status!==0)d=o.DecisionCode.RUNTIME_ERROR;else if(l.timeSeconds>r)d=o.DecisionCode.TIME_LIMIT_EXCEEDED;else if(l.memoryBytes>(_.memoryLimitByte??1/0))d=o.DecisionCode.MEMORY_LIMIT_EXCEEDED;else if(l.stdout.length>v||l.stderr.length>v)d=o.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(u.length<(_.requiredOutputFilePaths?.length??0))d=o.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let t=await n.judgeAgainstExpectations({stdout:l.stdout,expectedStdout:e.output,fileOutputPath:e.fileOutputPath,cwd:a.cwd,outputFiles:u});t.matches||(d=o.DecisionCode.WRONG_ANSWER),u=t.outputFiles}catch(e){d=o.DecisionCode.RUNTIME_ERROR,p=e instanceof Error?e.message:String(e)}if(t.printTestCaseResult({testCaseId:e.id,decisionCode:d,exitStatus:l.status??void 0,stdin:e.input,stdout:l.stdout.slice(0,v)||void 0,stderr:(p??l.stderr).slice(0,v)||void 0,timeSeconds:l.timeSeconds,memoryBytes:l.memoryBytes,outputFiles:u.length>0?u:void 0}),await s.cleanWorkingDirectory(a.cwd,O),d!==o.DecisionCode.ACCEPTED)break}}async function C(e){return e!==void 0&&(await h.default.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function w(e){let t=r.parseArgs(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let n=x.parse(t.params),i,o=()=>{i!==void 0&&a.forciblyRemoveDirectorySync(i),process.exit(1)};process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{await T(e,(await a.copyProblemDirToTemporaryRoot(t.cwd,{onTempRootCreated:e=>i=e})).copiedProblemDir,n)}finally{i!==void 0&&await a.forciblyRemoveDirectory(i),process.off(`SIGINT`,o),process.off(`SIGTERM`,o)}}async function T(e,n,r){let a=await p.readProblemMarkdownFrontMatter(e),s=await l.findEntryPointFile(n,r.language);if(!s){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:o.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${r.language?`: language: ${r.language}`:``}`});return}let d=u.findLanguageDefinitionByPath(s);if(!d){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:o.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let h={...process.env,CI:``,FORCE_COLOR:`0`},_;if(d.prebuild)try{await d.prebuild(n),_=await l.findEntryPointFile(n,r.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:o.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let b=_??s;if(d.buildCommand)try{let e=d.buildCommand(b),r=m.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:n,encoding:`utf8`,env:h},10),i=o.DecisionCode.ACCEPTED;if(r.status===0?r.timeSeconds>10?i=o.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(r.stdout.length>v||r.stderr.length>v)&&(i=o.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):i=o.DecisionCode.BUILD_ERROR,i!==o.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:`build`,decisionCode:i,exitStatus:r.status??void 0,stdout:r.stdout.slice(0,v)||void 0,stderr:r.stderr.slice(0,v)||void 0,timeSeconds:r.timeSeconds,memoryBytes:r.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:`build`,decisionCode:o.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let x=await i.readTestCases(g.default.join(e,`test_cases`));x.shared?.fileInputPath&&await c.copyTestCaseFileInput(x.shared.fileInputPath,n);let S=x.find(e=>y.test(e.id)&&e.fileInputPath)?.fileInputPath;S?await c.copyTestCaseFileInput(S,n):x.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let C=Math.max(10,(a.timeLimitMs??0)/1e3),w=d.command(b),T=m.spawnSyncWithTimeout(w[0],w.slice(1),{cwd:n,encoding:`utf8`,input:r.stdin,env:h},C),E=await f.readOutputFiles(n,a.requiredOutputFilePaths??[]),D=o.DecisionCode.ACCEPTED;T.status===0?T.timeSeconds>C?D=o.DecisionCode.TIME_LIMIT_EXCEEDED:T.memoryBytes>(a.memoryLimitByte??1/0)?D=o.DecisionCode.MEMORY_LIMIT_EXCEEDED:T.stdout.length>v||T.stderr.length>v?D=o.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED:E.length<(a.requiredOutputFilePaths?.length??0)&&(D=o.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR):D=o.DecisionCode.RUNTIME_ERROR,t.printTestCaseResult({testCaseId:`debug`,decisionCode:D,exitStatus:T.status??void 0,stdin:r.stdin,stdout:T.stdout.slice(0,v)||void 0,stderr:T.stderr.slice(0,v)||void 0,timeSeconds:T.timeSeconds,memoryBytes:T.memoryBytes,outputFiles:E.length>0?E:void 0})}exports.stdioDebugPreset=w,exports.stdioJudgePreset=S;
|
|
2
2
|
//# sourceMappingURL=stdio.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stdio.cjs","names":["z","parseArgs","readProblemMarkdownFrontMatter","readTestCases","path","judgesTestCasesWithoutExpectations","judgeByStaticAnalysis","findEntryPointFile","DecisionCode","findLanguageDefinitionByPath","spawnSyncWithTimeout","snapshotWorkingDirectory","copyTestCaseFileInput","readOutputFiles","judgeAgainstExpectations","cleanWorkingDirectory","fs","copyProblemDirToTemporaryRoot","forciblyRemoveDirectory"],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { makeAccessibleToSandboxUser, makeTraversableBySandboxUser } from '../helpers/sandboxUser.js';\nimport {\n judgesTestCasesWithoutExpectations,\n readProblemMarkdownFrontMatter,\n} from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(args.cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by manual scoring or the presence of required output files has an\n // expectation of its own. Checked before the static analysis so that an authoring error surfaces\n // regardless of the submission.\n if (!judgesTestCasesWithoutExpectations(problemMarkdownFrontMatter)) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n // `mkdtemp` creates a 0700 root: the sandbox user only traverses the root and the synthesized\n // ancestors, and gets full access to the copied answer directory alone.\n makeTraversableBySandboxUser(copy.tempRoot, path.dirname(copy.copiedProblemDir));\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mappings":"g8BA4BA,MAIM,EAAoB,IAEpB,EAA+B,UAE/B,EAAoBA,EAAAA,EAAE,OAAO,CACjC,SAAUA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,OAAO,EAAGA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAEK,EAAoB,EAAkB,OAAO,CACjD,MAAOA,EAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,CAC7B,CAAC,EAsBD,eAAsB,EAAiB,EAAmC,CACxE,IAAM,EAAOC,EAAAA,UAAU,QAAQ,IAAI,EACnC,GAAI,CAAC,EAAK,IAAK,MAAU,MAAM,uBAAuB,EACtD,IAAM,EAAS,EAAkB,MAAM,EAAK,MAAM,EAGlD,EAAA,4BAA4B,EAAK,GAAG,EAEpC,IAAM,EAA6B,MAAMC,EAAAA,+BAA+B,CAAU,EAC5E,EAAY,MAAMC,EAAAA,cAAcC,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AAO,OAAS,GAAqB,EAAY,OAAO,OAAS,EACtF,EAAeA,EAAAA,aAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAeA,EAAAA,aAAa,oCAR5B,EAAeA,EAAAA,aAAa,cAW9B,EAAA,oBAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"stdio.cjs","names":["z","parseArgs","readProblemMarkdownFrontMatter","readTestCases","path","judgesTestCasesWithoutExpectations","judgeByStaticAnalysis","findEntryPointFile","DecisionCode","findLanguageDefinitionByPath","spawnSyncWithTimeout","snapshotWorkingDirectory","copyTestCaseFileInput","readOutputFiles","judgeAgainstExpectations","cleanWorkingDirectory","fs","copyProblemDirToTemporaryRoot","forciblyRemoveDirectory"],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport {\n judgesTestCasesWithoutExpectations,\n readProblemMarkdownFrontMatter,\n} from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by manual scoring or the presence of required output files has an\n // expectation of its own. Checked before the static analysis so that an authoring error surfaces\n // regardless of the submission.\n if (!judgesTestCasesWithoutExpectations(problemMarkdownFrontMatter)) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mappings":"w5BA2BA,MAIM,EAAoB,IAEpB,EAA+B,UAE/B,EAAoBA,EAAAA,EAAE,OAAO,CACjC,SAAUA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,OAAO,EAAGA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAEK,EAAoB,EAAkB,OAAO,CACjD,MAAOA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CAAC,CAAC,EAEnG,EAA6BL,EAAAA,aAAa,SAE1C,EAAY,SAAW,EAEhB,EAAY,YAAc,EACnC,EAAeA,EAAAA,aAAa,oBACnB,EAAY,aAAe,EAA2B,iBAAmB,KAClF,EAAeA,EAAAA,aAAa,sBACnB,EAAY,OAAO,OAAS,GAAqB,EAAY,OAAO,OAAS,EACtF,EAAeA,EAAAA,aAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAeA,EAAAA,aAAa,oCAR5B,EAAeA,EAAAA,aAAa,cAW9B,EAAA,oBAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
|
package/dist/presets/stdio.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{
|
|
1
|
+
import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{judgeAgainstExpectations as t}from"../helpers/compareExpectedOutputFiles.js";import{parseArgs as n}from"../helpers/parseArgs.js";import{readTestCases as r}from"../helpers/readTestCases.js";import{copyProblemDirToTemporaryRoot as i,forciblyRemoveDirectory as a,forciblyRemoveDirectorySync as o}from"../helpers/temporaryProblemDirCopy.js";import{DecisionCode as s}from"../types/decisionCode.js";import{cleanWorkingDirectory as c,snapshotWorkingDirectory as l}from"../helpers/cleanWorkingDirectory.js";import{copyTestCaseFileInput as u}from"../helpers/copyTestCaseFileInput.js";import{findEntryPointFile as d}from"../helpers/findEntryPointFile.js";import{findLanguageDefinitionByPath as f}from"../helpers/findLanguageDefinitionByPath.js";import{judgeByStaticAnalysis as p}from"../helpers/judgeByStaticAnalysis.js";import{readOutputFiles as m}from"../helpers/readOutputFiles.js";import{judgesTestCasesWithoutExpectations as h,readProblemMarkdownFrontMatter as g}from"../helpers/readProblemMarkdownFrontMatter.js";import{spawnSyncWithTimeout as _}from"../helpers/spawnSyncWithTimeout.js";import v from"node:fs";import y from"node:path";import{z as b}from"zod";const x=5e4,S=/example/,C=b.object({language:b.union([b.string(),b.array(b.string())]).optional()}),w=C.extend({stdin:b.string().optional()});async function T(i){let a=n(process.argv);if(!a.cwd)throw Error(`cwd argument required`);let o=C.parse(a.params),v=await g(i),b=await r(y.join(i,`test_cases`));if(!h(v)){for(let e of b)if(e.output===void 0&&!await E(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let S=await p(a.cwd,v);if(S){e({testCaseId:b[0]?.id??`prebuild`,...S});return}let w=await d(a.cwd,o.language);if(!w){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${o.language?`: language: ${o.language}`:``}`});return}let T=f(w);if(!T){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let D={...process.env,CI:``,FORCE_COLOR:`0`},O;if(T.prebuild)try{await T.prebuild(a.cwd),O=await d(a.cwd,o.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let k=O??w;if(T.buildCommand)try{let t=T.buildCommand(k),n=_(t[0],t.slice(1),{cwd:a.cwd,encoding:`utf8`,env:D},10),r=s.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>x||n.stderr.length>x)&&(r=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.BUILD_ERROR,r!==s.ACCEPTED){e({testCaseId:b[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,x)||void 0,stderr:n.stderr.slice(0,x)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:b[0]?.id??`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let A=await l(a.cwd);b.length===0&&e({testCaseId:`default`,decisionCode:s.ACCEPTED});for(let n of b){b.shared?.fileInputPath&&await u(b.shared.fileInputPath,a.cwd),n.fileInputPath&&await u(n.fileInputPath,a.cwd);let r=typeof v.timeLimitMs==`number`?v.timeLimitMs/1e3:2,i=T.command(k),o=_(i[0],i.slice(1),{cwd:a.cwd,encoding:`utf8`,input:n.input,env:D},r),l=await m(a.cwd,v.requiredOutputFilePaths??[]),d=s.ACCEPTED,f;if(o.status!==0)d=s.RUNTIME_ERROR;else if(o.timeSeconds>r)d=s.TIME_LIMIT_EXCEEDED;else if(o.memoryBytes>(v.memoryLimitByte??1/0))d=s.MEMORY_LIMIT_EXCEEDED;else if(o.stdout.length>x||o.stderr.length>x)d=s.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(l.length<(v.requiredOutputFilePaths?.length??0))d=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let e=await t({stdout:o.stdout,expectedStdout:n.output,fileOutputPath:n.fileOutputPath,cwd:a.cwd,outputFiles:l});e.matches||(d=s.WRONG_ANSWER),l=e.outputFiles}catch(e){d=s.RUNTIME_ERROR,f=e instanceof Error?e.message:String(e)}if(e({testCaseId:n.id,decisionCode:d,exitStatus:o.status??void 0,stdin:n.input,stdout:o.stdout.slice(0,x)||void 0,stderr:(f??o.stderr).slice(0,x)||void 0,timeSeconds:o.timeSeconds,memoryBytes:o.memoryBytes,outputFiles:l.length>0?l:void 0}),await c(a.cwd,A),d!==s.ACCEPTED)break}}async function E(e){return e!==void 0&&(await v.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function D(e){let t=n(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let r=w.parse(t.params),s,c=()=>{s!==void 0&&o(s),process.exit(1)};process.once(`SIGINT`,c),process.once(`SIGTERM`,c);try{await O(e,(await i(t.cwd,{onTempRootCreated:e=>s=e})).copiedProblemDir,r)}finally{s!==void 0&&await a(s),process.off(`SIGINT`,c),process.off(`SIGTERM`,c)}}async function O(t,n,i){let a=await g(t),o=await d(n,i.language);if(!o){e({testCaseId:`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${i.language?`: language: ${i.language}`:``}`});return}let c=f(o);if(!c){e({testCaseId:`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let l={...process.env,CI:``,FORCE_COLOR:`0`},p;if(c.prebuild)try{await c.prebuild(n),p=await d(n,i.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let h=p??o;if(c.buildCommand)try{let t=c.buildCommand(h),r=_(t[0],t.slice(1),{cwd:n,encoding:`utf8`,env:l},10),i=s.ACCEPTED;if(r.status===0?r.timeSeconds>10?i=s.BUILD_TIME_LIMIT_EXCEEDED:(r.stdout.length>x||r.stderr.length>x)&&(i=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):i=s.BUILD_ERROR,i!==s.ACCEPTED){e({testCaseId:`build`,decisionCode:i,exitStatus:r.status??void 0,stdout:r.stdout.slice(0,x)||void 0,stderr:r.stderr.slice(0,x)||void 0,timeSeconds:r.timeSeconds,memoryBytes:r.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let v=await r(y.join(t,`test_cases`));v.shared?.fileInputPath&&await u(v.shared.fileInputPath,n);let b=v.find(e=>S.test(e.id)&&e.fileInputPath)?.fileInputPath;b?await u(b,n):v.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let C=Math.max(10,(a.timeLimitMs??0)/1e3),w=c.command(h),T=_(w[0],w.slice(1),{cwd:n,encoding:`utf8`,input:i.stdin,env:l},C),E=await m(n,a.requiredOutputFilePaths??[]),D=s.ACCEPTED;T.status===0?T.timeSeconds>C?D=s.TIME_LIMIT_EXCEEDED:T.memoryBytes>(a.memoryLimitByte??1/0)?D=s.MEMORY_LIMIT_EXCEEDED:T.stdout.length>x||T.stderr.length>x?D=s.OUTPUT_SIZE_LIMIT_EXCEEDED:E.length<(a.requiredOutputFilePaths?.length??0)&&(D=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR):D=s.RUNTIME_ERROR,e({testCaseId:`debug`,decisionCode:D,exitStatus:T.status??void 0,stdin:i.stdin,stdout:T.stdout.slice(0,x)||void 0,stderr:T.stderr.slice(0,x)||void 0,timeSeconds:T.timeSeconds,memoryBytes:T.memoryBytes,outputFiles:E.length>0?E:void 0})}export{D as stdioDebugPreset,T as stdioJudgePreset};
|
|
2
2
|
//# sourceMappingURL=stdio.js.map
|