UNPKG

un-oj

Version:

Unified Online Judge information collector.

73 lines (71 loc) 2.5 kB
import { NotFoundError, Platform, UnOJError, UnexpectedResponseError, getFirstKey } from "./platform-BncnsqE0.js"; import { FetchError } from "ofetch"; //#region src/platforms/hydro.ts const HydroProblemTypeMap = { interactive: "interactive", submit_answer: "submission", objective: "objective" }; /** * Parses the problem document from Hydro-like platforms. * @param pdoc The `pdoc` field from the API response. * @param lang The language code, defaults to the first appeared language in the content. * @returns The parsed problem object, @{link Problem.link} is empty string. */ function parseHydroProblem(pdoc, lang) { let content = JSON.parse(pdoc.content); content = lang == null ? content[getFirstKey(content)] : content[lang]; const samples = []; const r = (i, s) => new RegExp(`\`\`\`${s}${i}\\n([\\s\\S]+?)\`\`\``); for (let i = 1, match; match = r(i, "input").exec(content); i++) samples.push({ input: match[1].trim(), output: r(i, "output").exec(content)?.[1].trim() || "" }); return { id: pdoc.pid, type: HydroProblemTypeMap[pdoc.config.type] ?? "traditional", title: pdoc.title, link: "", description: content, samples, timeLimit: pdoc.config?.timeLimit ?? pdoc.config?.timeMax, memoryLimit: (pdoc.config?.memoryLimit ?? pdoc.config?.memoryMax) * 1024 * 1024, difficulty: pdoc.difficulty, tags: pdoc.tag }; } const DEFAULT_BASE_URL = "https://hydro.ac"; /** HydroOJ platform. */ var Hydro = class extends Platform { constructor(options) { super(options, DEFAULT_BASE_URL); } /** * Fetches a problem from HydroOJ using internal API. * @param domain The domain the problem belongs to, defaults to the system domain. */ async getProblem(id, domain) { const path = domain ? `/d/${domain}/p/${id}` : `/p/${id}`; let data; try { data = await this.ofetch(path, { query: { pjax: 1 }, headers: { accept: "application/json" }, responseType: "json" }); } catch (e) { if (e instanceof FetchError && e.statusCode === 404) throw new NotFoundError("problem"); throw new UnOJError(`Failed to fetch problem ${id}`, { cause: e }); } const pdoc = data?.raw?.pdoc; if (!pdoc) throw new UnexpectedResponseError(data); const link = new URL(domain ? `/d/${domain}/p/${id}` : `/p/${id}`, this.baseURL); if (this.locale) link.searchParams.append("lang", this.locale); return { ...parseHydroProblem(pdoc, this.locale), link: link.href }; } }; //#endregion export { DEFAULT_BASE_URL, Hydro, parseHydroProblem };