@exercode/problem-utils 1.9.7 → 1.10.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.
Files changed (38) hide show
  1. package/dist/helpers/findModelAnswerDirs.cjs +2 -0
  2. package/dist/helpers/findModelAnswerDirs.cjs.map +1 -0
  3. package/dist/helpers/findModelAnswerDirs.d.ts +5 -0
  4. package/dist/helpers/findModelAnswerDirs.js +2 -0
  5. package/dist/helpers/findModelAnswerDirs.js.map +1 -0
  6. package/dist/helpers/parseArgs.cjs +1 -1
  7. package/dist/helpers/parseArgs.cjs.map +1 -1
  8. package/dist/helpers/parseArgs.d.ts +4 -1
  9. package/dist/helpers/parseArgs.js +1 -1
  10. package/dist/helpers/parseArgs.js.map +1 -1
  11. package/dist/helpers/printDebugBanner.cjs +2 -0
  12. package/dist/helpers/printDebugBanner.cjs.map +1 -0
  13. package/dist/helpers/printDebugBanner.d.ts +7 -0
  14. package/dist/helpers/printDebugBanner.js +2 -0
  15. package/dist/helpers/printDebugBanner.js.map +1 -0
  16. package/dist/helpers/resolveCwds.cjs +2 -0
  17. package/dist/helpers/resolveCwds.cjs.map +1 -0
  18. package/dist/helpers/resolveCwds.d.ts +19 -0
  19. package/dist/helpers/resolveCwds.js +2 -0
  20. package/dist/helpers/resolveCwds.js.map +1 -0
  21. package/dist/presets/command.cjs +1 -1
  22. package/dist/presets/command.cjs.map +1 -1
  23. package/dist/presets/command.d.ts +6 -0
  24. package/dist/presets/command.js +1 -1
  25. package/dist/presets/command.js.map +1 -1
  26. package/dist/presets/guiCommand.cjs +1 -1
  27. package/dist/presets/guiCommand.cjs.map +1 -1
  28. package/dist/presets/guiCommand.js +1 -1
  29. package/dist/presets/guiCommand.js.map +1 -1
  30. package/dist/presets/llm.cjs +1 -1
  31. package/dist/presets/llm.cjs.map +1 -1
  32. package/dist/presets/llm.js +1 -1
  33. package/dist/presets/llm.js.map +1 -1
  34. package/dist/presets/stdio.cjs +1 -1
  35. package/dist/presets/stdio.cjs.map +1 -1
  36. package/dist/presets/stdio.js +1 -1
  37. package/dist/presets/stdio.js.map +1 -1
  38. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"guiCommand.js","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\ninterface BaseGuiTestCase {\n id: string;\n input?: string;\n fileInputPath?: 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 = BaseGuiTestCase> {\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 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 = BaseGuiTestCase>(\n problemDir: string,\n options: GuiCommandJudgePresetOptions<TTestCase>\n): Promise<void> {\n const args = parseArgs(process.argv);\n const params = judgeParamsSchema.parse(args.params);\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 const prepareResult =\n (await options.prepare?.({\n cwd: args.cwd,\n env,\n mainFilePath: resolvedMainFilePath,\n problemMarkdownFrontMatter,\n })) ??\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: args.cwd,\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 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 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 = ['timeout', context.timeLimitSeconds.toFixed(3), ...TIME_COMMAND, ...context.command] as const;\n const child = childProcess.spawn(wrappedCommand[0], wrappedCommand.slice(1), {\n cwd: context.cwd,\n env: context.env,\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\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\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 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 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(screenshotSignaturesHistory.length, context.stopDetectionThreshold);\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 await stopProcess(child);\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 const env = display ? { ...process.env, DISPLAY: display } : process.env;\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 });\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"],"names":["TIME_COMMAND","os","platform","judgeParamsSchema","z","object","language","union","string","array","optional","guiCommandJudgePreset","_x","_x2","_guiCommandJudgePreset","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","_options$readTestCase","_testCases$0$id","_testCases$","_options$mainFilePath","_yield$options$prepar","_options$prepare","args","params","problemMarkdownFrontMatter","configuredTestCases","testCases","prebuildTestCaseId","staticAnalysisResult","initialMainFilePath","languageDefinition","env","resolvedMainFilePath","_params$language","prebuiltMainFilePath","prepareResult","_prepareResult$decisi","cwdSnapshot","displayServer","currentTestCaseId","currentStdin","_shared","sharedFileInputPath","_iterator2","_step2","_options$runTimeoutSe","_ref5","_yield$options$resolv","_options$resolveInput","_yield$options$comman","_options$command","_problemMarkdownFront","_judgeResult$decision","_judgeResult$stdout","_judgeResult$stderr","_judgeResult$outputFi","testCase","timeLimitSeconds","runEnv","stdin","command","runResult","_options$screenshotWa","_options$stopDetectio","_options$screenshotWa2","_options$stopDetectio2","outputFiles","judgeContext","baseJudgeResult","judgeResult","_extendedJudgeResult$","extendedJudgeResult","decisionCode","stdout","stderr","_displayServer","_t","_t2","_t4","_t5","_t7","_t9","_t1","_t10","_t11","_t12","_t13","_t14","w","_context","p","n","parseArgs","process","argv","parse","readProblemMarkdownFrontMatter","v","readTestCases","readGuiTestCases","length","id","judgeByStaticAnalysis","cwd","printTestCaseResult","_objectSpread","testCaseId","a","mainFilePath","findEntryPointFile","DecisionCode","MISSING_REQUIRED_SUBMISSION_FILE_ERROR","concat","findLanguageDefinitionByPath","WRONG_ANSWER","CI","FORCE_COLOR","resolveMainFilePath","configuredMainFilePath","prebuild","inferLanguageIdsByPath","allowConfiguredPathFallback","BUILD_ERROR","errorToMessage","prepare","call","runDefaultPrepare","feedbackMarkdown","snapshotWorkingDirectory","runCommand","undefined","ensureDisplayServer","shared","fileInputPath","_createForOfIteratorHelper","s","done","value","copyTestCaseFileInput","timeLimitMs","runTimeoutSeconds","DISPLAY","display","resolveInput","input","screenshotWaitSeconds","stopDetectionThreshold","spawnGuiProgram","RUNTIME_ERROR","cleanWorkingDirectory","readOutputFiles","requiredOutputFilePaths","memoryLimitByte","evaluateGuiRunResult","context","ACCEPTED","test","exitStatus","status","timeSeconds","memoryBytes","e","f","dispose","_x3","_resolveMainFilePath","_callee2","resolvedPath","_context2","path","join","pathExists","filePath","languageIds","Object","entries","languageIdToDefinition","filter","_ref","_slicedToArray","fileExtensions","some","ext","endsWith","map","_ref3","_context$languageDefi","_context$languageDefi2","buildCommand","buildResult","spawnSyncWithTimeout","slice","encoding","BUILD_TIME_LIMIT_EXCEEDED","_context$context$prob","_context$context$prob2","_context$context$prob3","stopReason","TIME_LIMIT_EXCEEDED","Number","POSITIVE_INFINITY","MEMORY_LIMIT_EXCEEDED","requiredOutputFilesCount","MISSING_REQUIRED_OUTPUT_FILE_ERROR","_x4","_readGuiTestCases","_callee3","_context3","readFileTestCases","_x5","_spawnGuiProgram","_callee4","wrappedCommand","child","exitCode","spawnError","screenshotSignaturesHistory","screenshots","startTimeSeconds","sampledMemoryBytes","_loop","_parseTimedStderr","normalizedStderr","_context5","toFixed","_toConsumableArray","childProcess","spawn","detached","stdio","setEncoding","Date","now","on","chunk","error","code","signal","write","end","currentScreenshots","screenshotSignatures","_context4","wait","Math","max","readProcessGroupMemoryBytes","pid","takeScreenshots","toSorted","b","data","file","unshift","min","every","files","index","d","_regeneratorValues","removeAllListeners","stopProcess","parseTimedStderr","trimEnd","xwininfo","spawnSync","_i","_extractTopLevelWindo","_step","windowIds","lines","split","_iterator","line","includes","match","exec","push","parseInt","toString","err","extractTopLevelWindowIds","windowId","screenshot","windowNameResult","windowName","trim","replaceAll","parsedMemoryBytes","_ensureDisplayServer","_callee6","_loop2","_ret2","displayNumber","_context8","Error","xvfb","_context7","XVFB_STARTUP_WAIT_SECONDS","_dispose","_callee5","_context6","killed","kill","XVFB_SHUTDOWN_WAIT_SECONDS","_x6","_stopProcess","_callee7","_context9","killProcessGroup","PROCESS_SHUTDOWN_WAIT_SECONDS","processGroupId","result","String","isFinite","reduce","sum","_unused","_unused2","_x7","_pathExists","_callee8","_context0","fs","access","message"],"mappings":"o0CAwBA,IAOMA,EAAe,CAAmB,WAAlBC,EAAGC,WAA0B,QAAU,gBAAiB,WAAY,SAEpFC,EAAoBC,EAAEC,OAAO,CACjCC,SAAUF,EAAEG,MAAM,CAACH,EAAEI,SAAUJ,EAAEK,MAAML,EAAEI,YAAYE,aA+FvD,SAAsBC,EAAqBC,EAAAC,GAAA,OAAAC,EAAAC,MAAAC,KAAAC,UAAA,CA+N1C,SAAAH,IAAA,OAAAA,EAAAI,EAAAC,IAAAC,EA/NM,SAAAC,EACLC,EACAC,GAAgD,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC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AO/O,OAAe,EAE3D+O,EAAO/O,OACXsM,MAAM,MACNvF,IAAI,SAACyF,GAAI,OAAK1E,OAAO0E,EAAKa,OAAO,GACjC7G,OAAO,SAACxC,GAAK,OAAK8D,OAAOmH,SAASjL,IAAUA,EAAQ,CAAC,GACrDkL,OAAO,SAACC,EAAKnL,GAAK,OAAKmL,EAAc,KAARnL,CAAY,EAAE,EAChD,CAEA,SAAS4K,EAAiBE,EAAwB1E,GAChD,IACE,GAAyB,UAArBhJ,QAAQnG,SAEV,YADAmG,QAAQkN,MAAMQ,EAAgB1E,EAGlC,CAAE,MAAAgF,GACA,CAGF,IACEhO,QAAQkN,KAAKQ,EAAgB1E,EAC/B,CAAE,MAAAiF,GACA,CAEJ,CAAC,SAEcnJ,EAAUoJ,GAAA,OAAAC,EAAAzT,MAAAC,KAAAC,UAAA,CAAA,SAAAuT,IAOxB,OAPwBA,EAAAtT,EAAAC,IAAAC,EAAzB,SAAAqT,EAA0BrJ,GAAgB,OAAAjK,IAAA6E,EAAA,SAAA0O,GAAA,cAAAA,EAAAxO,EAAAwO,EAAAvO,GAAA,KAAA,EAAA,OAAAuO,EAAAxO,EAAA,EAAAwO,EAAAvO,EAAA,EAEhCwO,EAAGC,OAAOxJ,GAAS,KAAA,EAAA,OAAAsJ,EAAAvN,EAAA,GAClB,GAAI,KAAA,EAAA,OAAAuN,EAAAxO,EAAA,EAAAwO,EAAAjO,EAAAiO,EAAAvN,EAAA,GAEJ,GAAK,EAAAsN,EAAA,KAAA,CAAA,CAAA,EAAA,IAAA,KAEf1T,MAAAC,KAAAC,UAAA,CAED,SAASkH,EAAegH,GACtB,OAAOA,aAAiB4D,MAAQ5D,EAAM0F,QAAUZ,OAAO9E,EACzD"}
1
+ {"version":3,"file":"guiCommand.js","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\ninterface BaseGuiTestCase {\n id: string;\n input?: string;\n fileInputPath?: 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 = BaseGuiTestCase> {\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 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 = BaseGuiTestCase>(\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\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 const prepareResult =\n (await options.prepare?.({\n cwd: args.cwd,\n env,\n mainFilePath: resolvedMainFilePath,\n problemMarkdownFrontMatter,\n })) ??\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: args.cwd,\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 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 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 = ['timeout', context.timeLimitSeconds.toFixed(3), ...TIME_COMMAND, ...context.command] as const;\n const child = childProcess.spawn(wrappedCommand[0], wrappedCommand.slice(1), {\n cwd: context.cwd,\n env: context.env,\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\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\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 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 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(screenshotSignaturesHistory.length, context.stopDetectionThreshold);\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 await stopProcess(child);\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 const env = display ? { ...process.env, DISPLAY: display } : process.env;\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 });\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"],"names":["TIME_COMMAND","os","platform","judgeParamsSchema","z","object","language","union","string","array","optional","guiCommandJudgePreset","_x","_x2","_guiCommandJudgePreset","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","_options$readTestCase","_testCases$0$id","_testCases$","_options$mainFilePath","_yield$options$prepar","_options$prepare","args","params","problemMarkdownFrontMatter","configuredTestCases","testCases","prebuildTestCaseId","staticAnalysisResult","initialMainFilePath","languageDefinition","env","resolvedMainFilePath","_params$language","prebuiltMainFilePath","prepareResult","_prepareResult$decisi","cwdSnapshot","displayServer","currentTestCaseId","currentStdin","_shared","sharedFileInputPath","_iterator2","_step2","_options$runTimeoutSe","_ref5","_yield$options$resolv","_options$resolveInput","_yield$options$comman","_options$command","_problemMarkdownFront","_judgeResult$decision","_judgeResult$stdout","_judgeResult$stderr","_judgeResult$outputFi","testCase","timeLimitSeconds","runEnv","stdin","command","runResult","_options$screenshotWa","_options$stopDetectio","_options$screenshotWa2","_options$stopDetectio2","outputFiles","judgeContext","baseJudgeResult","judgeResult","_extendedJudgeResult$","extendedJudgeResult","decisionCode","stdout","stderr","_displayServer","_t","_t2","_t4","_t5","_t7","_t9","_t1","_t10","_t11","_t12","_t13","_t14","w","_context","p","n","parseArgs","process","argv","cwd","Error","parse","readProblemMarkdownFrontMatter","v","readTestCases","readGuiTestCases","length","id","judgeByStaticAnalysis","printTestCaseResult","_objectSpread","testCaseId","a","mainFilePath","findEntryPointFile","DecisionCode","MISSING_REQUIRED_SUBMISSION_FILE_ERROR","concat","findLanguageDefinitionByPath","WRONG_ANSWER","CI","FORCE_COLOR","resolveMainFilePath","configuredMainFilePath","prebuild","inferLanguageIdsByPath","allowConfiguredPathFallback","BUILD_ERROR","errorToMessage","prepare","call","runDefaultPrepare","feedbackMarkdown","snapshotWorkingDirectory","runCommand","undefined","ensureDisplayServer","shared","fileInputPath","_createForOfIteratorHelper","s","done","value","copyTestCaseFileInput","timeLimitMs","runTimeoutSeconds","DISPLAY","display","resolveInput","input","screenshotWaitSeconds","stopDetectionThreshold","spawnGuiProgram","RUNTIME_ERROR","cleanWorkingDirectory","readOutputFiles","requiredOutputFilePaths","memoryLimitByte","evaluateGuiRunResult","context","ACCEPTED","test","exitStatus","status","timeSeconds","memoryBytes","e","f","dispose","_x3","_resolveMainFilePath","_callee2","resolvedPath","_context2","path","join","pathExists","filePath","languageIds","Object","entries","languageIdToDefinition","filter","_ref","_slicedToArray","fileExtensions","some","ext","endsWith","map","_ref3","_context$languageDefi","_context$languageDefi2","buildCommand","buildResult","spawnSyncWithTimeout","slice","encoding","BUILD_TIME_LIMIT_EXCEEDED","_context$context$prob","_context$context$prob2","_context$context$prob3","stopReason","TIME_LIMIT_EXCEEDED","Number","POSITIVE_INFINITY","MEMORY_LIMIT_EXCEEDED","requiredOutputFilesCount","MISSING_REQUIRED_OUTPUT_FILE_ERROR","_x4","_readGuiTestCases","_callee3","_context3","readFileTestCases","_x5","_spawnGuiProgram","_callee4","wrappedCommand","child","exitCode","spawnError","screenshotSignaturesHistory","screenshots","startTimeSeconds","sampledMemoryBytes","_loop","_parseTimedStderr","normalizedStderr","_context5","toFixed","_toConsumableArray","childProcess","spawn","detached","stdio","setEncoding","Date","now","on","chunk","error","code","signal","write","end","currentScreenshots","screenshotSignatures","_context4","wait","Math","max","readProcessGroupMemoryBytes","pid","takeScreenshots","toSorted","b","data","file","unshift","min","every","files","index","d","_regeneratorValues","removeAllListeners","stopProcess","parseTimedStderr","trimEnd","xwininfo","spawnSync","_i","_extractTopLevelWindo","_step","windowIds","lines","split","_iterator","line","includes","match","exec","push","parseInt","toString","err","extractTopLevelWindowIds","windowId","screenshot","windowNameResult","windowName","trim","replaceAll","parsedMemoryBytes","_ensureDisplayServer","_callee6","_loop2","_ret2","displayNumber","_context8","xvfb","_context7","XVFB_STARTUP_WAIT_SECONDS","_dispose","_callee5","_context6","killed","kill","XVFB_SHUTDOWN_WAIT_SECONDS","_x6","_stopProcess","_callee7","_context9","killProcessGroup","PROCESS_SHUTDOWN_WAIT_SECONDS","processGroupId","result","String","isFinite","reduce","sum","_unused","_unused2","_x7","_pathExists","_callee8","_context0","fs","access","message"],"mappings":"o0CAwBA,IAOMA,EAAe,CAAmB,WAAlBC,EAAGC,WAA0B,QAAU,gBAAiB,WAAY,SAEpFC,EAAoBC,EAAEC,OAAO,CACjCC,SAAUF,EAAEG,MAAM,CAACH,EAAEI,SAAUJ,EAAEK,MAAML,EAAEI,YAAYE,aA+FvD,SAAsBC,EAAqBC,EAAAC,GAAA,OAAAC,EAAAC,MAAAC,KAAAC,UAAA,CAgO1C,SAAAH,IAAA,OAAAA,EAAAI,EAAAC,IAAAC,EAhOM,SAAAC,EACLC,EACAC,GAAgD,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAAC,GAAA,OAAA5E,IAAA6E,EAAA,SAAAC,GAAA,cAAAA,EAAAC,EAAAD,EAAAE,GAAA,KAAA,EAEZ,IAA9BrE,EAAOsE,EAAUC,QAAQC,OACrBC,IAAG,CAAAN,EAAAE,EAAA,EAAA,KA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iL,OAAO,SAACC,EAAKlL,GAAK,OAAKkL,EAAc,KAARlL,CAAY,EAAE,EAChD,CAEA,SAAS2K,EAAiBE,EAAwBzE,GAChD,IACE,GAAyB,UAArBjJ,QAAQnG,SAEV,YADAmG,QAAQkN,MAAMQ,EAAgBzE,EAGlC,CAAE,MAAA+E,GACA,CAGF,IACEhO,QAAQkN,KAAKQ,EAAgBzE,EAC/B,CAAE,MAAAgF,GACA,CAEJ,CAAC,SAEclJ,EAAUmJ,GAAA,OAAAC,EAAAzT,MAAAC,KAAAC,UAAA,CAAA,SAAAuT,IAOxB,OAPwBA,EAAAtT,EAAAC,IAAAC,EAAzB,SAAAqT,EAA0BpJ,GAAgB,OAAAlK,IAAA6E,EAAA,SAAA0O,GAAA,cAAAA,EAAAxO,EAAAwO,EAAAvO,GAAA,KAAA,EAAA,OAAAuO,EAAAxO,EAAA,EAAAwO,EAAAvO,EAAA,EAEhCwO,EAAGC,OAAOvJ,GAAS,KAAA,EAAA,OAAAqJ,EAAAtN,EAAA,GAClB,GAAI,KAAA,EAAA,OAAAsN,EAAAxO,EAAA,EAAAwO,EAAA/N,EAAA+N,EAAAtN,EAAA,GAEJ,GAAK,EAAAqN,EAAA,KAAA,CAAA,CAAA,EAAA,IAAA,KAEf1T,MAAAC,KAAAC,UAAA,CAED,SAASmH,EAAegH,GACtB,OAAOA,aAAiB5I,MAAQ4I,EAAMyF,QAAUZ,OAAO7E,EACzD"}
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("../_virtual/_rollupPluginBabelHelpers.cjs"),r=require("node:fs"),t=require("node:path"),s=require("@ai-sdk/amazon-bedrock"),n=require("@ai-sdk/google"),a=require("@ai-sdk/openai"),o=require("@ai-sdk/xai"),i=require("ai"),u=require("zod"),c=require("../helpers/parseArgs.cjs"),d=require("../helpers/printTestCaseResult.cjs"),l=require("../helpers/readTestCases.cjs"),p=require("../types/decisionCode.cjs"),C={bedrock:s.bedrock,google:n.google,openai:a.openai,xai:o.xai},m=u.z.object({model:u.z.string().min(1)});function f(){return(f=e.asyncToGenerator(e.regenerator().m(function s(n,a){var o,u,C,f,v,b,q,k,T,w,h,j,E,D,x,R,A,y,P,z;return e.regenerator().w(function(s){for(;;)switch(s.p=s.n){case 0:return o=c.parseArgs(process.argv),u=m.parse(o.params),s.n=1,l.readTestCases(t.join(n,"test_cases"));case 1:return C=s.v,s.n=2,r.promises.readFile(t.join(o.cwd,"prompt.txt"),"utf8");case 2:f=s.v,v=e.createForOfIteratorHelper(C),s.p=3,v.s();case 4:if((b=v.n()).done){s.n=11;break}return q=b.value,k=Date.now(),s.p=5,s.n=6,i.generateText({model:g(u.model),prompt:null!=(T=null==(w=a.buildPrompt)?void 0:w.call(a,{prompt:f,testCase:q}))?T:f.replaceAll("{input}",null!=(h=q.input)?h:"")});case 6:return j=s.v,E=j.text,D=Date.now(),A=e.objectSpread2,y={testCaseId:q.id,decisionCode:p.DecisionCode.ACCEPTED,stdin:q.input,stdout:E,timeSeconds:(D-k)/1e3},s.n=7,a.test({testCase:q,result:{output:E}});case 7:if(x=A(y,s.v),d.printTestCaseResult(x),x.decisionCode===p.DecisionCode.ACCEPTED){s.n=8;break}return s.a(3,11);case 8:s.n=10;break;case 9:return s.p=9,P=s.v,R=Date.now(),d.printTestCaseResult({testCaseId:q.id,decisionCode:p.DecisionCode.RUNTIME_ERROR,stdin:q.input,stderr:P instanceof Error?P.message:String(P),timeSeconds:(R-k)/1e3}),s.a(3,11);case 10:s.n=4;break;case 11:s.n=13;break;case 12:s.p=12,z=s.v,v.e(z);case 13:return s.p=13,v.f(),s.f(13);case 14:return s.a(2)}},s,null,[[5,9],[3,12,13,14]])}))).apply(this,arguments)}function g(r){var t,s=r.split("/"),n=e.slicedToArray(s,2),a=n[0],o=n[1];if(!a||!o)throw new Error("bad model: ".concat(r));var i=null==(t=C[a])?void 0:t.call(C,o);if(!i)throw new Error("model not found: ".concat(r));return i}exports.llmJudgePreset=function(e,r){return f.apply(this,arguments)};
1
+ "use strict";var e=require("../_virtual/_rollupPluginBabelHelpers.cjs"),r=require("node:fs"),t=require("node:path"),s=require("@ai-sdk/amazon-bedrock"),n=require("@ai-sdk/google"),a=require("@ai-sdk/openai"),o=require("@ai-sdk/xai"),i=require("ai"),u=require("zod"),c=require("../helpers/parseArgs.cjs"),d=require("../helpers/printTestCaseResult.cjs"),l=require("../helpers/readTestCases.cjs"),p=require("../types/decisionCode.cjs"),C={bedrock:s.bedrock,google:n.google,openai:a.openai,xai:o.xai},m=u.z.object({model:u.z.string().min(1)});function f(){return(f=e.asyncToGenerator(e.regenerator().m(function s(n,a){var o,u,C,f,v,b,q,w,k,T,h,E,j,D,x,R,A,y,P,z;return e.regenerator().w(function(s){for(;;)switch(s.p=s.n){case 0:if((o=c.parseArgs(process.argv)).cwd){s.n=1;break}throw new Error("cwd argument required");case 1:return u=m.parse(o.params),s.n=2,l.readTestCases(t.join(n,"test_cases"));case 2:return C=s.v,s.n=3,r.promises.readFile(t.join(o.cwd,"prompt.txt"),"utf8");case 3:f=s.v,v=e.createForOfIteratorHelper(C),s.p=4,v.s();case 5:if((b=v.n()).done){s.n=12;break}return q=b.value,w=Date.now(),s.p=6,s.n=7,i.generateText({model:g(u.model),prompt:null!=(k=null==(T=a.buildPrompt)?void 0:T.call(a,{prompt:f,testCase:q}))?k:f.replaceAll("{input}",null!=(h=q.input)?h:"")});case 7:return E=s.v,j=E.text,D=Date.now(),A=e.objectSpread2,y={testCaseId:q.id,decisionCode:p.DecisionCode.ACCEPTED,stdin:q.input,stdout:j,timeSeconds:(D-w)/1e3},s.n=8,a.test({testCase:q,result:{output:j}});case 8:if(x=A(y,s.v),d.printTestCaseResult(x),x.decisionCode===p.DecisionCode.ACCEPTED){s.n=9;break}return s.a(3,12);case 9:s.n=11;break;case 10:return s.p=10,P=s.v,R=Date.now(),d.printTestCaseResult({testCaseId:q.id,decisionCode:p.DecisionCode.RUNTIME_ERROR,stdin:q.input,stderr:P instanceof Error?P.message:String(P),timeSeconds:(R-w)/1e3}),s.a(3,12);case 11:s.n=5;break;case 12:s.n=14;break;case 13:s.p=13,z=s.v,v.e(z);case 14:return s.p=14,v.f(),s.f(14);case 15:return s.a(2)}},s,null,[[6,10],[4,13,14,15]])}))).apply(this,arguments)}function g(r){var t,s=r.split("/"),n=e.slicedToArray(s,2),a=n[0],o=n[1];if(!a||!o)throw new Error("bad model: ".concat(r));var i=null==(t=C[a])?void 0:t.call(C,o);if(!i)throw new Error("model not found: ".concat(r));return i}exports.llmJudgePreset=function(e,r){return f.apply(this,arguments)};
2
2
  //# sourceMappingURL=llm.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"llm.cjs","sources":["../../src/presets/llm.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { bedrock } from '@ai-sdk/amazon-bedrock';\nimport { google } from '@ai-sdk/google';\nimport { openai } from '@ai-sdk/openai';\nimport { xai } from '@ai-sdk/xai';\nimport type { LanguageModel, ModelMessage } from 'ai';\nimport { generateText } from 'ai';\nimport { z } from 'zod';\n\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst PROMPT_FILENAME = 'prompt.txt';\n\nconst providerByName: Record<string, typeof bedrock | typeof google | typeof openai | typeof xai> = {\n // requires `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`\n bedrock,\n // requires `GOOGLE_GENERATIVE_AI_API_KEY`\n google,\n // requires `OPENAI_API_KEY`\n openai,\n // requires `XAI_API_KEY`\n xai,\n} as const;\n\nconst judgeParamsSchema = z.object({\n model: z.string().min(1),\n});\n\ninterface LlmJudgePresetOptions {\n buildPrompt?: (context: {\n prompt: string;\n testCase: { id: string; input?: string; output?: string };\n }) => string | ModelMessage[];\n test: (context: {\n testCase: { id: string; input?: string; output?: string };\n result: { output: string };\n }) => Partial<TestCaseResult> | Promise<Partial<TestCaseResult>>;\n}\n\n/**\n * A preset judge function for running and testing a user prompt in LLM.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { llmJudgePreset } from '@exercode/problem-utils/presets/llm';\n * import { DecisionCode } from '@exercode/problem-utils';\n *\n * await llmJudgePreset(import.meta.dirname, {\n * test: (context) {\n * return { decisionCode: context.result.output ? DecisionCode.ACCEPTED : DecisionCode.WRONG_ANSWER };\n * }\n * });\n * ```\n *\n * Run with the required parameters:\n * ```bash\n * bun judge.ts model_answers/java '{ \"model\": \"gemini-2.5-flash-lite\" }'\n * ```\n */\nexport async function llmJudgePreset(problemDir: string, options: LlmJudgePresetOptions): Promise<void> {\n const args = parseArgs(process.argv);\n const params = judgeParamsSchema.parse(args.params);\n\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n const prompt = await fs.promises.readFile(path.join(args.cwd, PROMPT_FILENAME), 'utf8');\n\n for (const testCase of testCases) {\n const startTimeMilliseconds = Date.now();\n try {\n const { text } = await generateText({\n model: toLanguageModel(params.model),\n prompt: options.buildPrompt?.({ prompt, testCase }) ?? prompt.replaceAll('{input}', testCase.input ?? ''),\n });\n\n const stopTimeMilliseconds = Date.now();\n\n const testCaseResult = {\n testCaseId: testCase.id,\n decisionCode: DecisionCode.ACCEPTED,\n stdin: testCase.input,\n stdout: text,\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n ...(await options.test({ testCase, result: { output: text } })),\n };\n\n printTestCaseResult(testCaseResult);\n\n if (testCaseResult.decisionCode !== DecisionCode.ACCEPTED) break;\n } catch (error) {\n const stopTimeMilliseconds = Date.now();\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: testCase.input,\n stderr: error instanceof Error ? error.message : String(error),\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n });\n\n break;\n }\n }\n}\n\nfunction toLanguageModel(model: string): LanguageModel {\n const [providerId, modelId] = model.split('/');\n if (!providerId || !modelId) throw new Error(`bad model: ${model}`);\n const languageModel = providerByName[providerId]?.(modelId);\n if (!languageModel) throw new Error(`model not found: ${model}`);\n return languageModel;\n}\n"],"names":["providerByName","bedrock","google","openai","xai","judgeParamsSchema","z","object","model","string","min","_llmJudgePreset","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","args","params","testCases","prompt","_iterator","_step","testCase","startTimeMilliseconds","_options$buildPrompt","_options$buildPrompt2","_testCase$input","_yield$generateText","text","stopTimeMilliseconds","testCaseResult","_stopTimeMilliseconds","_t","_t2","_t3","_t4","w","_context","p","n","parseArgs","process","argv","parse","readTestCases","path","join","v","fs","promises","readFile","cwd","_createForOfIteratorHelper","s","done","value","Date","now","generateText","toLanguageModel","buildPrompt","call","replaceAll","input","_objectSpread","testCaseId","id","decisionCode","DecisionCode","ACCEPTED","stdin","stdout","timeSeconds","test","result","output","printTestCaseResult","a","RUNTIME_ERROR","stderr","Error","message","String","e","f","apply","this","arguments","_providerByName$provi","_model$split","split","_model$split2","_slicedToArray","providerId","modelId","concat","languageModel","_x","_x2"],"mappings":"ibAmBMA,EAA8F,CAElGC,QAAAA,EAAAA,QAEAC,OAAAA,EAAAA,OAEAC,OAAAA,EAAAA,OAEAC,IAAAA,EAAAA,KAGIC,EAAoBC,EAAAA,EAAEC,OAAO,CACjCC,MAAOF,EAAAA,EAAEG,SAASC,IAAI,KA+EvB,SAAAC,IAAA,OAAAA,EAAAC,EAAAA,iBAAAC,gBAAAC,EA5CM,SAAAC,EAA8BC,EAAoBC,GAA8B,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAA,OAAAxB,gBAAAyB,EAAA,SAAAC,GAAA,cAAAA,EAAAC,EAAAD,EAAAE,GAAA,KAAA,EAElC,O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,wBApDA,SAAoCC,EAAAC,GAAA,OAAAzF,EAAA4E,MAAAC,KAAAC,UAAA"}
1
+ {"version":3,"file":"llm.cjs","sources":["../../src/presets/llm.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { bedrock } from '@ai-sdk/amazon-bedrock';\nimport { google } from '@ai-sdk/google';\nimport { openai } from '@ai-sdk/openai';\nimport { xai } from '@ai-sdk/xai';\nimport type { LanguageModel, ModelMessage } from 'ai';\nimport { generateText } from 'ai';\nimport { z } from 'zod';\n\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst PROMPT_FILENAME = 'prompt.txt';\n\nconst providerByName: Record<string, typeof bedrock | typeof google | typeof openai | typeof xai> = {\n // requires `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`\n bedrock,\n // requires `GOOGLE_GENERATIVE_AI_API_KEY`\n google,\n // requires `OPENAI_API_KEY`\n openai,\n // requires `XAI_API_KEY`\n xai,\n} as const;\n\nconst judgeParamsSchema = z.object({\n model: z.string().min(1),\n});\n\ninterface LlmJudgePresetOptions {\n buildPrompt?: (context: {\n prompt: string;\n testCase: { id: string; input?: string; output?: string };\n }) => string | ModelMessage[];\n test: (context: {\n testCase: { id: string; input?: string; output?: string };\n result: { output: string };\n }) => Partial<TestCaseResult> | Promise<Partial<TestCaseResult>>;\n}\n\n/**\n * A preset judge function for running and testing a user prompt in LLM.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { llmJudgePreset } from '@exercode/problem-utils/presets/llm';\n * import { DecisionCode } from '@exercode/problem-utils';\n *\n * await llmJudgePreset(import.meta.dirname, {\n * test: (context) {\n * return { decisionCode: context.result.output ? DecisionCode.ACCEPTED : DecisionCode.WRONG_ANSWER };\n * }\n * });\n * ```\n *\n * Run with the required parameters:\n * ```bash\n * bun judge.ts model_answers/java '{ \"model\": \"gemini-2.5-flash-lite\" }'\n * ```\n */\nexport async function llmJudgePreset(problemDir: string, options: LlmJudgePresetOptions): 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 testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n const prompt = await fs.promises.readFile(path.join(args.cwd, PROMPT_FILENAME), 'utf8');\n\n for (const testCase of testCases) {\n const startTimeMilliseconds = Date.now();\n try {\n const { text } = await generateText({\n model: toLanguageModel(params.model),\n prompt: options.buildPrompt?.({ prompt, testCase }) ?? prompt.replaceAll('{input}', testCase.input ?? ''),\n });\n\n const stopTimeMilliseconds = Date.now();\n\n const testCaseResult = {\n testCaseId: testCase.id,\n decisionCode: DecisionCode.ACCEPTED,\n stdin: testCase.input,\n stdout: text,\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n ...(await options.test({ testCase, result: { output: text } })),\n };\n\n printTestCaseResult(testCaseResult);\n\n if (testCaseResult.decisionCode !== DecisionCode.ACCEPTED) break;\n } catch (error) {\n const stopTimeMilliseconds = Date.now();\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: testCase.input,\n stderr: error instanceof Error ? error.message : String(error),\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n });\n\n break;\n }\n }\n}\n\nfunction toLanguageModel(model: string): LanguageModel {\n const [providerId, modelId] = model.split('/');\n if (!providerId || !modelId) throw new Error(`bad model: ${model}`);\n const languageModel = providerByName[providerId]?.(modelId);\n if (!languageModel) throw new Error(`model not found: ${model}`);\n return languageModel;\n}\n"],"names":["providerByName","bedrock","google","openai","xai","judgeParamsSchema","z","object","model","string","min","_llmJudgePreset","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","args","params","testCases","prompt","_iterator","_step","testCase","startTimeMilliseconds","_options$buildPrompt","_options$buildPrompt2","_testCase$input","_yield$generateText","text","stopTimeMilliseconds","testCaseResult","_stopTimeMilliseconds","_t","_t2","_t3","_t4","w","_context","p","n","parseArgs","process","argv","cwd","Error","parse","readTestCases","path","join","v","fs","promises","readFile","_createForOfIteratorHelper","s","done","value","Date","now","generateText","toLanguageModel","buildPrompt","call","replaceAll","input","_objectSpread","testCaseId","id","decisionCode","DecisionCode","ACCEPTED","stdin","stdout","timeSeconds","test","result","output","printTestCaseResult","a","RUNTIME_ERROR","stderr","message","String","e","f","apply","this","arguments","_providerByName$provi","_model$split","split","_model$split2","_slicedToArray","providerId","modelId","concat","languageModel","_x","_x2"],"mappings":"ibAmBMA,EAA8F,CAElGC,QAAAA,EAAAA,QAEAC,OAAAA,EAAAA,OAEAC,OAAAA,EAAAA,OAEAC,IAAAA,EAAAA,KAGIC,EAAoBC,EAAAA,EAAEC,OAAO,CACjCC,MAAOF,EAAAA,EAAEG,SAASC,IAAI,KAgFvB,SAAAC,IAAA,OAAAA,EAAAC,EAAAA,iBAAAC,gBAAAC,EA7CM,SAAAC,EAA8BC,EAAoBC,GAA8B,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAA,OAAAxB,gBAAAyB,EAAA,SAAAC,GAAA,cAAAA,EAAAC,EAAAD,EAAAE,GAAA,KAAA,EACjD,IAA9BvB,EAAOwB,EAAAA,UAAUC,QAAQC,OACrBC,IAAG,CAAAN,EAAAE,EAAA,EAAA,KAAA,CAAA,MAAQ,IAAIK,MAAM,yBAAwB,KAAA,EACJ,OAA7C3B,EAASd,EAAkB0C,MAAM7B,EAAKC,QAAOoB,EAAAE,EAAA,EAE3BO,EAAAA,cAAcC,EAAKC,KAAKlC,EAAY,eAAc,KAAA,EAA3D,OAATI,EAASmB,EAA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abelHelpers.js";import a from"node:fs";import n from"node:path";import{bedrock as i}from"@ai-sdk/amazon-bedrock";import{google as p}from"@ai-sdk/google";import{openai as c}from"@ai-sdk/openai";import{xai as d}from"@ai-sdk/xai";import{generateText as l}from"ai";import{z as m}from"zod";import{parseArgs as u}from"../helpers/parseArgs.js";import{printTestCaseResult as f}from"../helpers/printTestCaseResult.js";import{readTestCases as v}from"../helpers/readTestCases.js";import{DecisionCode as C}from"../types/decisionCode.js";var b={bedrock:i,google:p,openai:c,xai:d},g=m.object({model:m.string().min(1)});function k(e,r){return w.apply(this,arguments)}function w(){return(w=e(r().m(function e(s,i){var p,c,d,m,b,k,w,j,E,T,x,y,A,D,R,I,P,S,_,z;return r().w(function(e){for(;;)switch(e.p=e.n){case 0:return p=u(process.argv),c=g.parse(p.params),e.n=1,v(n.join(s,"test_cases"));case 1:return d=e.v,e.n=2,a.promises.readFile(n.join(p.cwd,"prompt.txt"),"utf8");case 2:m=e.v,b=t(d),e.p=3,b.s();case 4:if((k=b.n()).done){e.n=11;break}return w=k.value,j=Date.now(),e.p=5,e.n=6,l({model:h(c.model),prompt:null!=(E=null==(T=i.buildPrompt)?void 0:T.call(i,{prompt:m,testCase:w}))?E:m.replaceAll("{input}",null!=(x=w.input)?x:"")});case 6:return y=e.v,A=y.text,D=Date.now(),P=o,S={testCaseId:w.id,decisionCode:C.ACCEPTED,stdin:w.input,stdout:A,timeSeconds:(D-j)/1e3},e.n=7,i.test({testCase:w,result:{output:A}});case 7:if(R=P(S,e.v),f(R),R.decisionCode===C.ACCEPTED){e.n=8;break}return e.a(3,11);case 8:e.n=10;break;case 9:return e.p=9,_=e.v,I=Date.now(),f({testCaseId:w.id,decisionCode:C.RUNTIME_ERROR,stdin:w.input,stderr:_ instanceof Error?_.message:String(_),timeSeconds:(I-j)/1e3}),e.a(3,11);case 10:e.n=4;break;case 11:e.n=13;break;case 12:e.p=12,z=e.v,b.e(z);case 13:return e.p=13,b.f(),e.f(13);case 14:return e.a(2)}},e,null,[[5,9],[3,12,13,14]])}))).apply(this,arguments)}function h(e){var r,o=e.split("/"),t=s(o,2),a=t[0],n=t[1];if(!a||!n)throw new Error("bad model: ".concat(e));var i=null==(r=b[a])?void 0:r.call(b,n);if(!i)throw new Error("model not found: ".concat(e));return i}export{k as llmJudgePreset};
1
+ import{asyncToGenerator as e,regenerator as r,objectSpread2 as o,createForOfIteratorHelper as t,slicedToArray as a}from"../_virtual/_rollupPluginBabelHelpers.js";import s from"node:fs";import n from"node:path";import{bedrock as i}from"@ai-sdk/amazon-bedrock";import{google as p}from"@ai-sdk/google";import{openai as c}from"@ai-sdk/openai";import{xai as d}from"@ai-sdk/xai";import{generateText as m}from"ai";import{z as l}from"zod";import{parseArgs as u}from"../helpers/parseArgs.js";import{printTestCaseResult as f}from"../helpers/printTestCaseResult.js";import{readTestCases as v}from"../helpers/readTestCases.js";import{DecisionCode as w}from"../types/decisionCode.js";var C={bedrock:i,google:p,openai:c,xai:d},b=l.object({model:l.string().min(1)});function g(e,r){return k.apply(this,arguments)}function k(){return(k=e(r().m(function e(a,i){var p,c,d,l,C,g,k,E,j,T,x,y,A,D,R,I,P,S,_,z;return r().w(function(e){for(;;)switch(e.p=e.n){case 0:if((p=u(process.argv)).cwd){e.n=1;break}throw new Error("cwd argument required");case 1:return c=b.parse(p.params),e.n=2,v(n.join(a,"test_cases"));case 2:return d=e.v,e.n=3,s.promises.readFile(n.join(p.cwd,"prompt.txt"),"utf8");case 3:l=e.v,C=t(d),e.p=4,C.s();case 5:if((g=C.n()).done){e.n=12;break}return k=g.value,E=Date.now(),e.p=6,e.n=7,m({model:h(c.model),prompt:null!=(j=null==(T=i.buildPrompt)?void 0:T.call(i,{prompt:l,testCase:k}))?j:l.replaceAll("{input}",null!=(x=k.input)?x:"")});case 7:return y=e.v,A=y.text,D=Date.now(),P=o,S={testCaseId:k.id,decisionCode:w.ACCEPTED,stdin:k.input,stdout:A,timeSeconds:(D-E)/1e3},e.n=8,i.test({testCase:k,result:{output:A}});case 8:if(R=P(S,e.v),f(R),R.decisionCode===w.ACCEPTED){e.n=9;break}return e.a(3,12);case 9:e.n=11;break;case 10:return e.p=10,_=e.v,I=Date.now(),f({testCaseId:k.id,decisionCode:w.RUNTIME_ERROR,stdin:k.input,stderr:_ instanceof Error?_.message:String(_),timeSeconds:(I-E)/1e3}),e.a(3,12);case 11:e.n=5;break;case 12:e.n=14;break;case 13:e.p=13,z=e.v,C.e(z);case 14:return e.p=14,C.f(),e.f(14);case 15:return e.a(2)}},e,null,[[6,10],[4,13,14,15]])}))).apply(this,arguments)}function h(e){var r,o=e.split("/"),t=a(o,2),s=t[0],n=t[1];if(!s||!n)throw new Error("bad model: ".concat(e));var i=null==(r=C[s])?void 0:r.call(C,n);if(!i)throw new Error("model not found: ".concat(e));return i}export{g as llmJudgePreset};
2
2
  //# sourceMappingURL=llm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"llm.js","sources":["../../src/presets/llm.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { bedrock } from '@ai-sdk/amazon-bedrock';\nimport { google } from '@ai-sdk/google';\nimport { openai } from '@ai-sdk/openai';\nimport { xai } from '@ai-sdk/xai';\nimport type { LanguageModel, ModelMessage } from 'ai';\nimport { generateText } from 'ai';\nimport { z } from 'zod';\n\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst PROMPT_FILENAME = 'prompt.txt';\n\nconst providerByName: Record<string, typeof bedrock | typeof google | typeof openai | typeof xai> = {\n // requires `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`\n bedrock,\n // requires `GOOGLE_GENERATIVE_AI_API_KEY`\n google,\n // requires `OPENAI_API_KEY`\n openai,\n // requires `XAI_API_KEY`\n xai,\n} as const;\n\nconst judgeParamsSchema = z.object({\n model: z.string().min(1),\n});\n\ninterface LlmJudgePresetOptions {\n buildPrompt?: (context: {\n prompt: string;\n testCase: { id: string; input?: string; output?: string };\n }) => string | ModelMessage[];\n test: (context: {\n testCase: { id: string; input?: string; output?: string };\n result: { output: string };\n }) => Partial<TestCaseResult> | Promise<Partial<TestCaseResult>>;\n}\n\n/**\n * A preset judge function for running and testing a user prompt in LLM.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { llmJudgePreset } from '@exercode/problem-utils/presets/llm';\n * import { DecisionCode } from '@exercode/problem-utils';\n *\n * await llmJudgePreset(import.meta.dirname, {\n * test: (context) {\n * return { decisionCode: context.result.output ? DecisionCode.ACCEPTED : DecisionCode.WRONG_ANSWER };\n * }\n * });\n * ```\n *\n * Run with the required parameters:\n * ```bash\n * bun judge.ts model_answers/java '{ \"model\": \"gemini-2.5-flash-lite\" }'\n * ```\n */\nexport async function llmJudgePreset(problemDir: string, options: LlmJudgePresetOptions): Promise<void> {\n const args = parseArgs(process.argv);\n const params = judgeParamsSchema.parse(args.params);\n\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n const prompt = await fs.promises.readFile(path.join(args.cwd, PROMPT_FILENAME), 'utf8');\n\n for (const testCase of testCases) {\n const startTimeMilliseconds = Date.now();\n try {\n const { text } = await generateText({\n model: toLanguageModel(params.model),\n prompt: options.buildPrompt?.({ prompt, testCase }) ?? prompt.replaceAll('{input}', testCase.input ?? ''),\n });\n\n const stopTimeMilliseconds = Date.now();\n\n const testCaseResult = {\n testCaseId: testCase.id,\n decisionCode: DecisionCode.ACCEPTED,\n stdin: testCase.input,\n stdout: text,\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n ...(await options.test({ testCase, result: { output: text } })),\n };\n\n printTestCaseResult(testCaseResult);\n\n if (testCaseResult.decisionCode !== DecisionCode.ACCEPTED) break;\n } catch (error) {\n const stopTimeMilliseconds = Date.now();\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: testCase.input,\n stderr: error instanceof Error ? error.message : String(error),\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n });\n\n break;\n }\n }\n}\n\nfunction toLanguageModel(model: string): LanguageModel {\n const [providerId, modelId] = model.split('/');\n if (!providerId || !modelId) throw new Error(`bad model: ${model}`);\n const languageModel = providerByName[providerId]?.(modelId);\n if (!languageModel) throw new Error(`model not found: ${model}`);\n return languageModel;\n}\n"],"names":["providerByName","bedrock","google","openai","xai","judgeParamsSchema","z","object","model","string","min","llmJudgePreset","_x","_x2","_llmJudgePreset","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","args","params","testCases","prompt","_iterator","_step","testCase","startTimeMilliseconds","_options$buildPrompt","_options$buildPrompt2","_testCase$input","_yield$generateText","text","stopTimeMilliseconds","testCaseResult","_stopTimeMilliseconds","_t","_t2","_t3","_t4","w","_context","p","n","parseArgs","process","argv","parse","readTestCases","path","join","v","fs","promises","readFile","cwd","_createForOfIteratorHelper","s","done","value","Date","now","generateText","toLanguageModel","buildPrompt","call","replaceAll","input","_objectSpread","testCaseId","id","decisionCode","DecisionCode","ACCEPTED","stdin","stdout","timeSeconds","test","result","output","printTestCaseResult","a","RUNTIME_ERROR","stderr","Error","message","String","e","f","_providerByName$provi","_model$split","split","_model$split2","_slicedToArray","providerId","modelId","concat","languageModel"],"mappings":"+pBAiBA,IAEMA,EAA8F,CAElGC,QAAAA,EAEAC,OAAAA,EAEAC,OAAAA,EAEAC,IAAAA,GAGIC,EAAoBC,EAAEC,OAAO,CACjCC,MAAOF,EAAEG,SAASC,IAAI,KAmCxB,SAAsBC,EAAcC,EAAAC,GAAA,OAAAC,EAAAC,MAAAC,KAAAC,UAAA,CA4CnC,SAAAH,IAAA,OAAAA,EAAAI,EAAAC,IAAAC,EA5CM,SAAAC,EAA8BC,EAAoBC,GAA8B,IAAAC,EAAAC,EAAAC,EAAA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OAA7BR,EAAG7F,EAAekG,SAAW,EAA1BL,EAAAxB,KAAArE,EAA6BmG,GACnD,IAAKE,EAAe,MAAM,IAAIb,MAAK,oBAAAY,OAAqB5F,IACxD,OAAO6F,CACT"}
1
+ {"version":3,"file":"llm.js","sources":["../../src/presets/llm.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { bedrock } from '@ai-sdk/amazon-bedrock';\nimport { google } from '@ai-sdk/google';\nimport { openai } from '@ai-sdk/openai';\nimport { xai } from '@ai-sdk/xai';\nimport type { LanguageModel, ModelMessage } from 'ai';\nimport { generateText } from 'ai';\nimport { z } from 'zod';\n\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { DecisionCode } from '../types/decisionCode.js';\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nconst PROMPT_FILENAME = 'prompt.txt';\n\nconst providerByName: Record<string, typeof bedrock | typeof google | typeof openai | typeof xai> = {\n // requires `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`\n bedrock,\n // requires `GOOGLE_GENERATIVE_AI_API_KEY`\n google,\n // requires `OPENAI_API_KEY`\n openai,\n // requires `XAI_API_KEY`\n xai,\n} as const;\n\nconst judgeParamsSchema = z.object({\n model: z.string().min(1),\n});\n\ninterface LlmJudgePresetOptions {\n buildPrompt?: (context: {\n prompt: string;\n testCase: { id: string; input?: string; output?: string };\n }) => string | ModelMessage[];\n test: (context: {\n testCase: { id: string; input?: string; output?: string };\n result: { output: string };\n }) => Partial<TestCaseResult> | Promise<Partial<TestCaseResult>>;\n}\n\n/**\n * A preset judge function for running and testing a user prompt in LLM.\n *\n * @example\n * Create `judge.ts`:\n * ```ts\n * import { llmJudgePreset } from '@exercode/problem-utils/presets/llm';\n * import { DecisionCode } from '@exercode/problem-utils';\n *\n * await llmJudgePreset(import.meta.dirname, {\n * test: (context) {\n * return { decisionCode: context.result.output ? DecisionCode.ACCEPTED : DecisionCode.WRONG_ANSWER };\n * }\n * });\n * ```\n *\n * Run with the required parameters:\n * ```bash\n * bun judge.ts model_answers/java '{ \"model\": \"gemini-2.5-flash-lite\" }'\n * ```\n */\nexport async function llmJudgePreset(problemDir: string, options: LlmJudgePresetOptions): 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 testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n const prompt = await fs.promises.readFile(path.join(args.cwd, PROMPT_FILENAME), 'utf8');\n\n for (const testCase of testCases) {\n const startTimeMilliseconds = Date.now();\n try {\n const { text } = await generateText({\n model: toLanguageModel(params.model),\n prompt: options.buildPrompt?.({ prompt, testCase }) ?? prompt.replaceAll('{input}', testCase.input ?? ''),\n });\n\n const stopTimeMilliseconds = Date.now();\n\n const testCaseResult = {\n testCaseId: testCase.id,\n decisionCode: DecisionCode.ACCEPTED,\n stdin: testCase.input,\n stdout: text,\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n ...(await options.test({ testCase, result: { output: text } })),\n };\n\n printTestCaseResult(testCaseResult);\n\n if (testCaseResult.decisionCode !== DecisionCode.ACCEPTED) break;\n } catch (error) {\n const stopTimeMilliseconds = Date.now();\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode: DecisionCode.RUNTIME_ERROR,\n stdin: testCase.input,\n stderr: error instanceof Error ? error.message : String(error),\n timeSeconds: (stopTimeMilliseconds - startTimeMilliseconds) / 1000,\n });\n\n break;\n }\n }\n}\n\nfunction toLanguageModel(model: string): LanguageModel {\n const [providerId, modelId] = model.split('/');\n if (!providerId || !modelId) throw new Error(`bad model: ${model}`);\n const languageModel = providerByName[providerId]?.(modelId);\n if (!languageModel) throw new Error(`model not found: ${model}`);\n return languageModel;\n}\n"],"names":["providerByName","bedrock","google","openai","xai","judgeParamsSchema","z","object","model","string","min","llmJudgePreset","_x","_x2","_llmJudgePreset","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee","problemDir","options","args","params","testCases","prompt","_iterator","_step","testCase","startTimeMilliseconds","_options$buildPrompt","_options$buildPrompt2","_testCase$input","_yield$generateText","text","stopTimeMilliseconds","testCaseResult","_stopTimeMilliseconds","_t","_t2","_t3","_t4","w","_context","p","n","parseArgs","process","argv","cwd","Error","parse","readTestCases","path","join","v","fs","promises","readFile","_createForOfIteratorHelper","s","done","value","Date","now","generateText","toLanguageModel","buildPrompt","call","replaceAll","input","_objectSpread","testCaseId","id","decisionCode","DecisionCode","ACCEPTED","stdin","stdout","timeSeconds","test","result","output","printTestCaseResult","a","RUNTIME_ERROR","stderr","message","String","e","f","_providerByName$provi","_model$split","split","_model$split2","_slicedToArray","providerId","modelId","concat","languageModel"],"mappings":"+pBAiBA,IAEMA,EAA8F,CAElGC,QAAAA,EAEAC,OAAAA,EAEAC,OAAAA,EAEAC,IAAAA,GAGIC,EAAoBC,EAAEC,OAAO,CACjCC,MAAOF,EAAEG,SAASC,IAAI,KAmCxB,SAAsBC,EAAcC,EAAAC,GAAA,OAAAC,EAAAC,MAAAC,KAAAC,UAAA,CA6CnC,SAAAH,IAAA,OAAAA,EAAAI,EAAAC,IAAAC,EA7CM,SAAAC,EAA8BC,EAAoBC,GAA8B,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAA,OAAAxB,IAAAyB,EAAA,SAAAC,GAAA,cAAAA,EAAAC,EAAAD,EAAAE,GAAA,KAAA,EACjD,IAA9BvB,EAAOwB,EAAUC,QAAQC,OACrBC,IAAG,CAAAN,EAAAE,EAAA,EAAA,KAAA,CAAA,MAAQ,IAAIK,MAAM,yBAAwB,KAAA,EACJ,OAA7C3B,EAASpB,EAAkBgD,MAAM7B,EAAKC,QA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AA,IAAA,KAAA,EAAAzC,EAAAE,EAAA,GAAA,MAAA,KAAA,GAUtD,OAVsDF,EAAAC,EAAA,GAAAJ,EAAAG,EAAAY,EAEnDpB,EAAuB4B,KAAKC,MAElCmB,EAAoB,CAClBX,WAAY5C,EAAS6C,GACrBC,aAAcC,EAAaU,cAC3BR,MAAOjD,EAAS0C,MAChBgB,OAAQ9C,aAAiBU,MAAQV,EAAM+C,QAAUC,OAAMhD,GACvDuC,aAAc5C,EAAuBN,GAAyB,MAC7Dc,EAAAyC,EAAA,EAAA,IAAA,KAAA,GAAAzC,EAAAE,EAAA,EAAA,MAAA,KAAA,GAAAF,EAAAE,EAAA,GAAA,MAAA,KAAA,GAAAF,EAAAC,EAAA,GAAAH,EAAAE,EAAAY,EAAA7B,EAAA+D,EAAAhD,GAAA,KAAA,GAAA,OAAAE,EAAAC,EAAA,GAAAlB,EAAAgE,IAAA/C,EAAA+C,EAAA,IAAA,KAAA,GAAA,OAAA/C,EAAAyC,EAAA,GAAA,EAAAjE,EAAA,KAAA,CAAA,CAAA,EAAA,IAAA,CAAA,EAAA,GAAA,GAAA,KAAA,KAKRN,MAAAC,KAAAC,UAAA,CAED,SAASmD,EAAgB5D,GAA8B,IAAAqF,EACrDC,EAA8BtF,EAAMuF,MAAM,KAAIC,EAAAC,EAAAH,EAAA,GAAvCI,EAAUF,EAAA,GAAEG,EAAOH,EAAA,GAC1B,IAAKE,IAAeC,EAAS,MAAM,IAAI/C,MAAK,cAAAgD,OAAe5F,IAC3D,IAAM6F,EAA0C,OAA7BR,EAAG7F,EAAekG,SAAW,EAA1BL,EAAAvB,KAAAtE,EAA6BmG,GACnD,IAAKE,EAAe,MAAM,IAAIjD,MAAK,oBAAAgD,OAAqB5F,IACxD,OAAO6F,CACT"}
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("../_virtual/_rollupPluginBabelHelpers.cjs"),r=require("node:fs"),t=require("node:path"),s=require("zod"),n=require("../helpers/cleanWorkingDirectory.cjs"),i=require("../helpers/compareStdoutAsSpaceSeparatedTokens.cjs"),a=require("../helpers/copyTestCaseFileInput.cjs"),o=require("../helpers/findEntryPointFile.cjs"),d=require("../helpers/findLanguageDefinitionByPath.cjs"),u=require("../helpers/judgeByStaticAnalysis.cjs"),c=require("../helpers/parseArgs.cjs"),l=require("../helpers/printTestCaseResult.cjs"),p=require("../helpers/readOutputFiles.cjs"),C=require("../helpers/readProblemMarkdownFrontMatter.cjs"),E=require("../helpers/readTestCases.cjs"),I=require("../helpers/spawnSyncWithTimeout.cjs"),m=require("../types/decisionCode.cjs"),D=5e4,g=s.z.object({language:s.z.union([s.z.string(),s.z.array(s.z.string())]).optional()}),b=g.extend({stdin:s.z.string().optional()});function R(){return(R=e.asyncToGenerator(e.regenerator().m(function s(b){var R,f,T,_,S,h,v,y,k,O,P,M,w,F,L,B,U,j,N,q,A,W,G,X,x,z,Q,Y,Z,H,V,J,K,$,ee,re,te,se,ne,ie,ae,oe,de,ue,ce,le,pe,Ce,Ee,Ie,me,De,ge;return e.regenerator().w(function(s){for(;;)switch(s.p=s.n){case 0:return R=c.parseArgs(process.argv),f=g.parse(R.params),s.n=1,C.readProblemMarkdownFrontMatter(b);case 1:return T=s.v,s.n=2,E.readTestCases(t.join(b,"test_cases"));case 2:return _=s.v,s.n=3,u.judgeByStaticAnalysis(R.cwd,T);case 3:if(!(S=s.v)){s.n=4;break}return l.printTestCaseResult(e.objectSpread2({testCaseId:null!=(h=null==(v=_[0])?void 0:v.id)?h:"prebuild"},S)),s.a(2);case 4:return s.n=5,o.findEntryPointFile(R.cwd,f.language);case 5:if(y=s.v){s.n=6;break}return l.printTestCaseResult({testCaseId:null!=(k=null==(O=_[0])?void 0:O.id)?k:"prebuild",decisionCode:m.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:"main file not found".concat(f.language?": language: ".concat(f.language):"")}),s.a(2);case 6:if(P=d.findLanguageDefinitionByPath(y)){s.n=7;break}return l.printTestCaseResult({testCaseId:null!=(M=null==(w=_[0])?void 0:w.id)?M:"prebuild",decisionCode:m.DecisionCode.WRONG_ANSWER,stderr:"unsupported language"}),s.a(2);case 7:if(F=e.objectSpread2(e.objectSpread2({},process.env),{},{CI:"",FORCE_COLOR:"0"}),!P.prebuild){s.n=12;break}return s.p=8,s.n=9,P.prebuild(R.cwd);case 9:return s.n=10,o.findEntryPointFile(R.cwd,f.language);case 10:L=s.v,s.n=12;break;case 11:return s.p=11,Ee=s.v,console.error("prebuild error",Ee),l.printTestCaseResult({testCaseId:null!=(B=null==(U=_[0])?void 0:U.id)?B:"prebuild",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:Ee instanceof Error?Ee.message:String(Ee)}),s.a(2);case 12:if(j=null!=L?L:y,!P.buildCommand){s.n=16;break}if(s.p=13,N=P.buildCommand(j),q=I.spawnSyncWithTimeout(N[0],N.slice(1),{cwd:R.cwd,encoding:"utf8",env:F},10),A=m.DecisionCode.ACCEPTED,0!==q.status?A=m.DecisionCode.BUILD_ERROR:q.timeSeconds>10?A=m.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(q.stdout.length>D||q.stderr.length>D)&&(A=m.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED),A===m.DecisionCode.ACCEPTED){s.n=14;break}return l.printTestCaseResult({testCaseId:null!=(W=null==(G=_[0])?void 0:G.id)?W:"build",decisionCode:A,exitStatus:null!=(X=q.status)?X:void 0,stdout:q.stdout.slice(0,D)||void 0,stderr:q.stderr.slice(0,D)||void 0,timeSeconds:q.timeSeconds,memoryBytes:q.memoryBytes}),s.a(2);case 14:s.n=16;break;case 15:return s.p=15,Ie=s.v,console.error("build error",Ie),l.printTestCaseResult({testCaseId:null!=(x=null==(z=_[0])?void 0:z.id)?x:"build",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:Ie instanceof Error?Ie.message:String(Ie)}),s.a(2);case 16:return s.n=17,n.snapshotWorkingDirectory(R.cwd);case 17:Q=s.v,0===_.length&&l.printTestCaseResult({testCaseId:"default",decisionCode:m.DecisionCode.ACCEPTED}),Y=e.createForOfIteratorHelper(_),s.p=18,Y.s();case 19:if((Z=Y.n()).done){s.n=44;break}if(te=Z.value,null==(H=_.shared)||!H.fileInputPath){s.n=20;break}return s.n=20,a.copyTestCaseFileInput(_.shared.fileInputPath,R.cwd);case 20:if(!te.fileInputPath){s.n=21;break}return s.n=21,a.copyTestCaseFileInput(te.fileInputPath,R.cwd);case 21:return se="number"==typeof T.timeLimitMs?T.timeLimitMs/1e3:2,ne=P.command(j),ie=I.spawnSyncWithTimeout(ne[0],ne.slice(1),{cwd:R.cwd,encoding:"utf8",input:te.input,env:F},se),s.n=22,p.readOutputFiles(R.cwd,null!=(V=T.requiredOutputFilePaths)?V:[]);case 22:if(ae=s.v,oe=m.DecisionCode.ACCEPTED,0===ie.status){s.n=23;break}oe=m.DecisionCode.RUNTIME_ERROR,s.n=41;break;case 23:if(!(ie.timeSeconds>se)){s.n=24;break}oe=m.DecisionCode.TIME_LIMIT_EXCEEDED,s.n=41;break;case 24:if(!(ie.memoryBytes>(null!=(J=T.memoryLimitByte)?J:Number.POSITIVE_INFINITY))){s.n=25;break}oe=m.DecisionCode.MEMORY_LIMIT_EXCEEDED,s.n=41;break;case 25:if(!(ie.stdout.length>D||ie.stderr.length>D)){s.n=26;break}oe=m.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED,s.n=41;break;case 26:if(!(ae.length<(null!=(K=null==($=T.requiredOutputFilePaths)?void 0:$.length)?K:0))){s.n=27;break}oe=m.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR,s.n=41;break;case 27:if(i.compareStdoutAsSpaceSeparatedTokens(ie.stdout,null!=(ee=te.output)?ee:"")){s.n=28;break}oe=m.DecisionCode.WRONG_ANSWER,s.n=41;break;case 28:if(!te.fileOutputPath){s.n=41;break}return s.n=29,r.promises.readdir(te.fileOutputPath,{withFileTypes:!0,recursive:!0});case 29:de=s.v,ue=e.createForOfIteratorHelper(de),s.p=30,ue.s();case 31:if((ce=ue.n()).done){s.n=38;break}if((le=ce.value).isFile()){s.n=32;break}return s.a(3,37);case 32:return pe=t.relative(te.fileOutputPath,le.parentPath),s.n=33,r.promises.readFile(t.join(le.parentPath,le.name));case 33:return Ce=s.v,s.p=34,s.n=35,r.promises.readFile(t.join(R.cwd,pe,le.name));case 35:0!==s.v.compare(Ce)&&(oe=m.DecisionCode.WRONG_ANSWER),s.n=37;break;case 36:s.p=36,me=s.v,console.error(me),oe=m.DecisionCode.WRONG_ANSWER;case 37:s.n=31;break;case 38:s.n=40;break;case 39:s.p=39,De=s.v,ue.e(De);case 40:return s.p=40,ue.f(),s.f(40);case 41:return l.printTestCaseResult({testCaseId:te.id,decisionCode:oe,exitStatus:null!=(re=ie.status)?re:void 0,stdin:te.input,stdout:ie.stdout.slice(0,D)||void 0,stderr:ie.stderr.slice(0,D)||void 0,timeSeconds:ie.timeSeconds,memoryBytes:ie.memoryBytes,outputFiles:ae.length>0?ae:void 0}),s.n=42,n.cleanWorkingDirectory(R.cwd,Q);case 42:if(oe===m.DecisionCode.ACCEPTED){s.n=43;break}return s.a(3,44);case 43:s.n=19;break;case 44:s.n=46;break;case 45:s.p=45,ge=s.v,Y.e(ge);case 46:return s.p=46,Y.f(),s.f(46);case 47:return s.a(2)}},s,null,[[34,36],[30,39,40,41],[18,45,46,47],[13,15],[8,11]])}))).apply(this,arguments)}function f(){return(f=e.asyncToGenerator(e.regenerator().m(function r(t){var s,n,i,a,u,E,g,R,f,T,_,S,h,v,y,k,O,P,M,w,F,L,B,U,j;return e.regenerator().w(function(r){for(;;)switch(r.p=r.n){case 0:return s=c.parseArgs(process.argv),n=b.parse(s.params),r.n=1,C.readProblemMarkdownFrontMatter(t);case 1:return i=r.v,r.n=2,o.findEntryPointFile(s.cwd,n.language);case 2:if(a=r.v){r.n=3;break}return l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:"main file not found".concat(n.language?": language: ".concat(n.language):"")}),r.a(2);case 3:if(u=d.findLanguageDefinitionByPath(a)){r.n=4;break}return l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.WRONG_ANSWER,stderr:"unsupported language"}),r.a(2);case 4:if(E=e.objectSpread2(e.objectSpread2({},process.env),{},{CI:"",FORCE_COLOR:"0"}),!u.prebuild){r.n=9;break}return r.p=5,r.n=6,u.prebuild(s.cwd);case 6:return r.n=7,o.findEntryPointFile(s.cwd,n.language);case 7:g=r.v,r.n=9;break;case 8:return r.p=8,U=r.v,console.error("prebuild error",U),l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:U instanceof Error?U.message:String(U)}),r.a(2);case 9:if(R=null!=g?g:a,!u.buildCommand){r.n=13;break}if(r.p=10,f=u.buildCommand(R),T=I.spawnSyncWithTimeout(f[0],f.slice(1),{cwd:s.cwd,encoding:"utf8",env:E},10),_=m.DecisionCode.ACCEPTED,0!==T.status?_=m.DecisionCode.BUILD_ERROR:T.timeSeconds>10?_=m.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(T.stdout.length>D||T.stderr.length>D)&&(_=m.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED),_===m.DecisionCode.ACCEPTED){r.n=11;break}return l.printTestCaseResult({testCaseId:"build",decisionCode:_,exitStatus:null!=(S=T.status)?S:void 0,stdout:T.stdout.slice(0,D)||void 0,stderr:T.stderr.slice(0,D)||void 0,timeSeconds:T.timeSeconds,memoryBytes:T.memoryBytes}),r.a(2);case 11:r.n=13;break;case 12:return r.p=12,j=r.v,console.error("build error",j),l.printTestCaseResult({testCaseId:"build",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:j instanceof Error?j.message:String(j)}),r.a(2);case 13:return M=Math.max(10,(null!=(h=i.timeLimitMs)?h:0)/1e3),w=u.command(R),F=I.spawnSyncWithTimeout(w[0],w.slice(1),{cwd:s.cwd,encoding:"utf8",input:n.stdin,env:E},M),r.n=14,p.readOutputFiles(s.cwd,null!=(v=i.requiredOutputFilePaths)?v:[]);case 14:L=r.v,B=m.DecisionCode.ACCEPTED,0!==F.status?B=m.DecisionCode.RUNTIME_ERROR:F.timeSeconds>M?B=m.DecisionCode.TIME_LIMIT_EXCEEDED:F.memoryBytes>(null!=(y=i.memoryLimitByte)?y:Number.POSITIVE_INFINITY)?B=m.DecisionCode.MEMORY_LIMIT_EXCEEDED:F.stdout.length>D||F.stderr.length>D?B=m.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED:L.length<(null!=(k=null==(O=i.requiredOutputFilePaths)?void 0:O.length)?k:0)&&(B=m.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR),l.printTestCaseResult({testCaseId:"debug",decisionCode:B,exitStatus:null!=(P=F.status)?P:void 0,stdin:n.stdin,stdout:F.stdout.slice(0,D)||void 0,stderr:F.stderr.slice(0,D)||void 0,timeSeconds:F.timeSeconds,memoryBytes:F.memoryBytes,outputFiles:L.length>0?L:void 0});case 15:return r.a(2)}},r,null,[[10,12],[5,8]])}))).apply(this,arguments)}exports.stdioDebugPreset=function(e){return f.apply(this,arguments)},exports.stdioJudgePreset=function(e){return R.apply(this,arguments)};
1
+ "use strict";var e=require("../_virtual/_rollupPluginBabelHelpers.cjs"),r=require("node:fs"),t=require("node:path"),s=require("zod"),n=require("../helpers/cleanWorkingDirectory.cjs"),i=require("../helpers/compareStdoutAsSpaceSeparatedTokens.cjs"),a=require("../helpers/copyTestCaseFileInput.cjs"),o=require("../helpers/findEntryPointFile.cjs"),d=require("../helpers/findLanguageDefinitionByPath.cjs"),u=require("../helpers/judgeByStaticAnalysis.cjs"),c=require("../helpers/parseArgs.cjs"),l=require("../helpers/printTestCaseResult.cjs"),p=require("../helpers/readOutputFiles.cjs"),C=require("../helpers/readProblemMarkdownFrontMatter.cjs"),E=require("../helpers/readTestCases.cjs"),I=require("../helpers/spawnSyncWithTimeout.cjs"),m=require("../types/decisionCode.cjs"),D=5e4,g=s.z.object({language:s.z.union([s.z.string(),s.z.array(s.z.string())]).optional()}),b=g.extend({stdin:s.z.string().optional()});function R(){return(R=e.asyncToGenerator(e.regenerator().m(function s(b){var R,f,T,_,S,h,v,y,k,O,w,P,M,F,L,B,U,j,N,q,A,W,G,X,x,z,Q,Y,Z,H,V,J,K,$,ee,re,te,se,ne,ie,ae,oe,de,ue,ce,le,pe,Ce,Ee,Ie,me,De,ge;return e.regenerator().w(function(s){for(;;)switch(s.p=s.n){case 0:if((R=c.parseArgs(process.argv)).cwd){s.n=1;break}throw new Error("cwd argument required");case 1:return f=g.parse(R.params),s.n=2,C.readProblemMarkdownFrontMatter(b);case 2:return T=s.v,s.n=3,E.readTestCases(t.join(b,"test_cases"));case 3:return _=s.v,s.n=4,u.judgeByStaticAnalysis(R.cwd,T);case 4:if(!(S=s.v)){s.n=5;break}return l.printTestCaseResult(e.objectSpread2({testCaseId:null!=(h=null==(v=_[0])?void 0:v.id)?h:"prebuild"},S)),s.a(2);case 5:return s.n=6,o.findEntryPointFile(R.cwd,f.language);case 6:if(y=s.v){s.n=7;break}return l.printTestCaseResult({testCaseId:null!=(k=null==(O=_[0])?void 0:O.id)?k:"prebuild",decisionCode:m.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:"main file not found".concat(f.language?": language: ".concat(f.language):"")}),s.a(2);case 7:if(w=d.findLanguageDefinitionByPath(y)){s.n=8;break}return l.printTestCaseResult({testCaseId:null!=(P=null==(M=_[0])?void 0:M.id)?P:"prebuild",decisionCode:m.DecisionCode.WRONG_ANSWER,stderr:"unsupported language"}),s.a(2);case 8:if(F=e.objectSpread2(e.objectSpread2({},process.env),{},{CI:"",FORCE_COLOR:"0"}),!w.prebuild){s.n=13;break}return s.p=9,s.n=10,w.prebuild(R.cwd);case 10:return s.n=11,o.findEntryPointFile(R.cwd,f.language);case 11:L=s.v,s.n=13;break;case 12:return s.p=12,Ee=s.v,console.error("prebuild error",Ee),l.printTestCaseResult({testCaseId:null!=(B=null==(U=_[0])?void 0:U.id)?B:"prebuild",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:Ee instanceof Error?Ee.message:String(Ee)}),s.a(2);case 13:if(j=null!=L?L:y,!w.buildCommand){s.n=17;break}if(s.p=14,N=w.buildCommand(j),q=I.spawnSyncWithTimeout(N[0],N.slice(1),{cwd:R.cwd,encoding:"utf8",env:F},10),A=m.DecisionCode.ACCEPTED,0!==q.status?A=m.DecisionCode.BUILD_ERROR:q.timeSeconds>10?A=m.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(q.stdout.length>D||q.stderr.length>D)&&(A=m.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED),A===m.DecisionCode.ACCEPTED){s.n=15;break}return l.printTestCaseResult({testCaseId:null!=(W=null==(G=_[0])?void 0:G.id)?W:"build",decisionCode:A,exitStatus:null!=(X=q.status)?X:void 0,stdout:q.stdout.slice(0,D)||void 0,stderr:q.stderr.slice(0,D)||void 0,timeSeconds:q.timeSeconds,memoryBytes:q.memoryBytes}),s.a(2);case 15:s.n=17;break;case 16:return s.p=16,Ie=s.v,console.error("build error",Ie),l.printTestCaseResult({testCaseId:null!=(x=null==(z=_[0])?void 0:z.id)?x:"build",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:Ie instanceof Error?Ie.message:String(Ie)}),s.a(2);case 17:return s.n=18,n.snapshotWorkingDirectory(R.cwd);case 18:Q=s.v,0===_.length&&l.printTestCaseResult({testCaseId:"default",decisionCode:m.DecisionCode.ACCEPTED}),Y=e.createForOfIteratorHelper(_),s.p=19,Y.s();case 20:if((Z=Y.n()).done){s.n=45;break}if(te=Z.value,null==(H=_.shared)||!H.fileInputPath){s.n=21;break}return s.n=21,a.copyTestCaseFileInput(_.shared.fileInputPath,R.cwd);case 21:if(!te.fileInputPath){s.n=22;break}return s.n=22,a.copyTestCaseFileInput(te.fileInputPath,R.cwd);case 22:return se="number"==typeof T.timeLimitMs?T.timeLimitMs/1e3:2,ne=w.command(j),ie=I.spawnSyncWithTimeout(ne[0],ne.slice(1),{cwd:R.cwd,encoding:"utf8",input:te.input,env:F},se),s.n=23,p.readOutputFiles(R.cwd,null!=(V=T.requiredOutputFilePaths)?V:[]);case 23:if(ae=s.v,oe=m.DecisionCode.ACCEPTED,0===ie.status){s.n=24;break}oe=m.DecisionCode.RUNTIME_ERROR,s.n=42;break;case 24:if(!(ie.timeSeconds>se)){s.n=25;break}oe=m.DecisionCode.TIME_LIMIT_EXCEEDED,s.n=42;break;case 25:if(!(ie.memoryBytes>(null!=(J=T.memoryLimitByte)?J:Number.POSITIVE_INFINITY))){s.n=26;break}oe=m.DecisionCode.MEMORY_LIMIT_EXCEEDED,s.n=42;break;case 26:if(!(ie.stdout.length>D||ie.stderr.length>D)){s.n=27;break}oe=m.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED,s.n=42;break;case 27:if(!(ae.length<(null!=(K=null==($=T.requiredOutputFilePaths)?void 0:$.length)?K:0))){s.n=28;break}oe=m.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR,s.n=42;break;case 28:if(i.compareStdoutAsSpaceSeparatedTokens(ie.stdout,null!=(ee=te.output)?ee:"")){s.n=29;break}oe=m.DecisionCode.WRONG_ANSWER,s.n=42;break;case 29:if(!te.fileOutputPath){s.n=42;break}return s.n=30,r.promises.readdir(te.fileOutputPath,{withFileTypes:!0,recursive:!0});case 30:de=s.v,ue=e.createForOfIteratorHelper(de),s.p=31,ue.s();case 32:if((ce=ue.n()).done){s.n=39;break}if((le=ce.value).isFile()){s.n=33;break}return s.a(3,38);case 33:return pe=t.relative(te.fileOutputPath,le.parentPath),s.n=34,r.promises.readFile(t.join(le.parentPath,le.name));case 34:return Ce=s.v,s.p=35,s.n=36,r.promises.readFile(t.join(R.cwd,pe,le.name));case 36:0!==s.v.compare(Ce)&&(oe=m.DecisionCode.WRONG_ANSWER),s.n=38;break;case 37:s.p=37,me=s.v,console.error(me),oe=m.DecisionCode.WRONG_ANSWER;case 38:s.n=32;break;case 39:s.n=41;break;case 40:s.p=40,De=s.v,ue.e(De);case 41:return s.p=41,ue.f(),s.f(41);case 42:return l.printTestCaseResult({testCaseId:te.id,decisionCode:oe,exitStatus:null!=(re=ie.status)?re:void 0,stdin:te.input,stdout:ie.stdout.slice(0,D)||void 0,stderr:ie.stderr.slice(0,D)||void 0,timeSeconds:ie.timeSeconds,memoryBytes:ie.memoryBytes,outputFiles:ae.length>0?ae:void 0}),s.n=43,n.cleanWorkingDirectory(R.cwd,Q);case 43:if(oe===m.DecisionCode.ACCEPTED){s.n=44;break}return s.a(3,45);case 44:s.n=20;break;case 45:s.n=47;break;case 46:s.p=46,ge=s.v,Y.e(ge);case 47:return s.p=47,Y.f(),s.f(47);case 48:return s.a(2)}},s,null,[[35,37],[31,40,41,42],[19,46,47,48],[14,16],[9,12]])}))).apply(this,arguments)}function f(){return(f=e.asyncToGenerator(e.regenerator().m(function r(t){var s,n,i,a,u,E,g,R,f,T,_,S,h,v,y,k,O,w,P,M,F,L,B,U,j;return e.regenerator().w(function(r){for(;;)switch(r.p=r.n){case 0:if((s=c.parseArgs(process.argv)).cwd){r.n=1;break}throw new Error("cwd argument required");case 1:return n=b.parse(s.params),r.n=2,C.readProblemMarkdownFrontMatter(t);case 2:return i=r.v,r.n=3,o.findEntryPointFile(s.cwd,n.language);case 3:if(a=r.v){r.n=4;break}return l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:"main file not found".concat(n.language?": language: ".concat(n.language):"")}),r.a(2);case 4:if(u=d.findLanguageDefinitionByPath(a)){r.n=5;break}return l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.WRONG_ANSWER,stderr:"unsupported language"}),r.a(2);case 5:if(E=e.objectSpread2(e.objectSpread2({},process.env),{},{CI:"",FORCE_COLOR:"0"}),!u.prebuild){r.n=10;break}return r.p=6,r.n=7,u.prebuild(s.cwd);case 7:return r.n=8,o.findEntryPointFile(s.cwd,n.language);case 8:g=r.v,r.n=10;break;case 9:return r.p=9,U=r.v,console.error("prebuild error",U),l.printTestCaseResult({testCaseId:"prebuild",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:U instanceof Error?U.message:String(U)}),r.a(2);case 10:if(R=null!=g?g:a,!u.buildCommand){r.n=14;break}if(r.p=11,f=u.buildCommand(R),T=I.spawnSyncWithTimeout(f[0],f.slice(1),{cwd:s.cwd,encoding:"utf8",env:E},10),_=m.DecisionCode.ACCEPTED,0!==T.status?_=m.DecisionCode.BUILD_ERROR:T.timeSeconds>10?_=m.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(T.stdout.length>D||T.stderr.length>D)&&(_=m.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED),_===m.DecisionCode.ACCEPTED){r.n=12;break}return l.printTestCaseResult({testCaseId:"build",decisionCode:_,exitStatus:null!=(S=T.status)?S:void 0,stdout:T.stdout.slice(0,D)||void 0,stderr:T.stderr.slice(0,D)||void 0,timeSeconds:T.timeSeconds,memoryBytes:T.memoryBytes}),r.a(2);case 12:r.n=14;break;case 13:return r.p=13,j=r.v,console.error("build error",j),l.printTestCaseResult({testCaseId:"build",decisionCode:m.DecisionCode.BUILD_ERROR,stderr:j instanceof Error?j.message:String(j)}),r.a(2);case 14:return P=Math.max(10,(null!=(h=i.timeLimitMs)?h:0)/1e3),M=u.command(R),F=I.spawnSyncWithTimeout(M[0],M.slice(1),{cwd:s.cwd,encoding:"utf8",input:n.stdin,env:E},P),r.n=15,p.readOutputFiles(s.cwd,null!=(v=i.requiredOutputFilePaths)?v:[]);case 15:L=r.v,B=m.DecisionCode.ACCEPTED,0!==F.status?B=m.DecisionCode.RUNTIME_ERROR:F.timeSeconds>P?B=m.DecisionCode.TIME_LIMIT_EXCEEDED:F.memoryBytes>(null!=(y=i.memoryLimitByte)?y:Number.POSITIVE_INFINITY)?B=m.DecisionCode.MEMORY_LIMIT_EXCEEDED:F.stdout.length>D||F.stderr.length>D?B=m.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED:L.length<(null!=(k=null==(O=i.requiredOutputFilePaths)?void 0:O.length)?k:0)&&(B=m.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR),l.printTestCaseResult({testCaseId:"debug",decisionCode:B,exitStatus:null!=(w=F.status)?w:void 0,stdin:n.stdin,stdout:F.stdout.slice(0,D)||void 0,stderr:F.stderr.slice(0,D)||void 0,timeSeconds:F.timeSeconds,memoryBytes:F.memoryBytes,outputFiles:L.length>0?L:void 0});case 16:return r.a(2)}},r,null,[[11,13],[6,9]])}))).apply(this,arguments)}exports.stdioDebugPreset=function(e){return f.apply(this,arguments)},exports.stdioJudgePreset=function(e){return R.apply(this,arguments)};
2
2
  //# sourceMappingURL=stdio.cjs.map