正文
增加 2902 行删除 772 行
17 行未改动1819202122232425265 行未改动3233343536373839404142434425 行未改动70717273747576777879808182838485868710 行未改动989910010110210310410510610710875 行未改动18418518618718818919019124 行未改动2162172182192202212222232246 行未改动23123223323423523623723823924024124224324488 行未改动3333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633642 行未改动36736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742814 行未改动4434444454464474484494504519 行未改动4614624634644654664674684694704714724739 行未改动4834844854864874884894904914924934944954964978 行未改动50650750850951051151251351451551651727 行未改动54554654754854955055155255374 行未改动62862963063163263363463563612 行未改动649650651652653654655656657101 行未改动全部展开7597607617627637647657667677687697707717727737747757767772 行未改动7807817827837847857867877887897907917924 行未改动79779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399411 行未改动100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110514 行未改动1120112111221123112411251126112711282 行未改动1131113211331134113511361137113811391140114111421143114417 行未改动116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712085 行未改动12141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812593 行未改动126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136840 行未改动14091410141114121413141414151416141718 行未改动14361437143814391440144114421443144415 行未改动1460146114621463146414651466146714681469147011 行未改动14821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215338 行未改动15421543154415451546154715481549155015511552155315541555155641 行未改动1598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616274 行未改动16321633163416351636163716381639164019 行未改动1660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173012 行未改动1743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617872 行未改动1790179117921793179417951796179731 行未改动1829183018311832183318341835183618371838183918401841184218431844184518461847184816 行未改动18651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719282 行未改动193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197916 行未改动19961997199819992000200120022003200420052006200720082009201020112012201324 行未改动203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210415 行未改动2120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521468 行未改动215521562157215821592160216121622163216421659 行未改动21752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221647 行未改动2264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222939 行未改动2303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245717 行未改动```javascript// ==UserScript==// @name LuoguSP// @namespace https://github.com/ShanireZ/LuoguSP// @version 2.11.5// @description LuoguSP:题目难度着色 / 私信 Ctrl+Click(用户名+头像) 跳转主页 / 显示隐藏的个人简介 / IDE 一键测试样例 / 受限文章与剪贴板直接显示// @author ShanireZ, realskc (Until 1.8.2)// @license GPL-3.0// @match https://www.luogu.com.cn/*5 行未改动// @require https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js// @require https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js// @require https://cdn.jsdelivr.net/npm/dompurify@3.0.9/dist/purify.min.js// @require https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js// @run-at document-end// ==/UserScript=="use strict";(function () {// ============================================================// 配置区(日常维护改这里)// ============================================================25 行未改动chatTrigger: '[slot="trigger"]', // 私信用户名触发点(旧 data-v 选择器已失效,用语义属性)userIntroColumn: ".sidebar-container .main", // 用户主页右侧内容列(补显简介的挂载点)nativeIntro: ".introduction", // 洛谷原生简介元素(存在=已显示,脚本不重复补)voidAnchor: "a[data-v-bade3303][data-v-4842157a]", // 题号着色里特殊的 javascript:void 0 链接// —— IDE 模式(2026-07 columba 前端;侦察实录 docs/superpowers/specs/2026-07-22-ide-mode-recon-notes.md)——ideToolbar: ".ide-toolbar", // IDE 三个分区(代码/输入/输出)各一条工具栏ideToolbarText: ".title .text", // 工具栏标题文字(代码/输入/输出)ideToolbarActions: ".actions", // 工具栏右侧按钮容器ideRunResult: ".run-result", // 输出工具栏里的 时间+内存 / RE 原因ideTextarea: "textarea.ide-textarea", // 输入/输出面板的文本域ideSampleBlock: ".io-sample-block", // 题面样例块(输入 #N / 输出 #N 各一块)cmContent: ".cm-content", // CodeMirror 6 内容层lentilleContext: "script#lentille-context", // 新版页面数据(JSON,含 problem.samples)// —— 安全访问中心拦截页(侦察实录 docs/superpowers/specs/2026-07-22-saver-api-recon-notes.md)——restrictedUrlPre: "pre#url", // 拦截页里的目标链接文本restrictedGoButton: "button#go", // 拦截页「继续访问」按钮};10 行未改动get: (k) => localStorage.getItem(k) === "true",set: (k, v) => localStorage.setItem(k, String(v)),has: (k) => localStorage.getItem(k) !== null,};// 首次运行:所有功能默认开启for (const k of FEATURE_LABELS.keys())if (!storage.has(k)) storage.set(k, true);// ============================================================// 设置面板(页内浮层,替代原来的 window.open + document.write)// ============================================================75 行未改动`;(document.head || document.documentElement).appendChild(style);}function openSettings() {if (document.getElementById("luogusp-settings")) return; // 避免重复打开const overlay = document.createElement("div");overlay.id = "luogusp-settings";24 行未改动</div>`;document.body.appendChild(overlay);const boxes = () => overlay.querySelectorAll('input[type="checkbox"]');const close = () => overlay.remove();overlay.addEventListener("click", (e) => {const t = e.target;if (t.classList.contains("luogusp-mask")) return close();6 行未改动close();if (confirm("设置已保存,是否立即刷新页面生效?")) location.reload();}});document.addEventListener("keydown", function esc(e) {if (e.key === "Escape") {close();document.removeEventListener("keydown", esc);}});}// 齿轮图标(24×24 Material settings,fill=currentColor 跟随导航文字色)const GEAR_PATH =88 行未改动// ★受限内容接管页 document.write 后旧 body 上的观察器全灭——接管流程会重新调用本函数。// 格式随导航自适应:旧版竖排栏(nav.lfe-body,首页/剪贴板同款)=「插件/设置」两行,// 新版侧栏(nav.sidebar,columba 文章页等)=「插件设置」单行。function watchSettingButton() {let scheduled = false;const tick = () => {scheduled = false;try {addSettingButton();} catch (e) {console.error("LuoguSP setting entry:", e);}};new MutationObserver(() => {if (!scheduled) {scheduled = true;requestAnimationFrame(tick);}}).observe(document.body, { childList: true, subtree: true });addSettingButton();}// ============================================================// 私信界面 Ctrl+Click 打开用户主页(用户名 + 头像)// ============================================================function addMessageLink() {const bound = new WeakSet(); // 去重,避免重复绑定const uidCache = new Map(); // username -> uid 缓存const openUser = (uid) => {if (uid) window.open(`/user/${uid}`, "_blank");};2 行未改动el.closest('a[href*="/user/"], a[href*="/space/"]');async function getUidByName(username) {if (uidCache.has(username)) return uidCache.get(username);try {const res = await fetch(`/api/user/search?keyword=${encodeURIComponent(username)}`,);const data = await res.json();const uid = data && data.users && data.users[0] && data.users[0].uid;uidCache.set(username, uid);return uid;} catch (e) {console.error("LuoguSP getUid:", e);}}// 用户名触发点:Ctrl+Click → 按用户名查 uidfunction bindName(trigger) {if (bound.has(trigger) || inUserLink(trigger)) return;bound.add(trigger);trigger.addEventListener("click", async (e) => {if (!e.ctrlKey) return;e.preventDefault();e.stopPropagation(); // Ctrl 时才拦,普通点击不影响洛谷原有行为const name = (trigger.textContent || "").trim();if (name) openUser(await getUidByName(name));});}// 头像:Ctrl+Click → 直接从 src(usericon/{uid})取 uid,无需查接口const AVATAR_RE = /\/usericon\/(\d+)/;function bindAvatar(img) {if (bound.has(img) || inUserLink(img) || !AVATAR_RE.test(img.src || ""))return;bound.add(img);img.style.cursor = "pointer";img.addEventListener("click", (e) => {if (!e.ctrlKey) return;e.preventDefault();e.stopPropagation();const m = (img.src || "").match(AVATAR_RE); // 点击时再读,兼容虚拟滚动换头像if (m) openUser(m[1]);});}const scan = (root) => {if (!root.querySelectorAll) return;root.querySelectorAll(SELECTORS.chatTrigger).forEach(bindName);root.querySelectorAll("img").forEach(bindAvatar);};scan(document);new MutationObserver((muts) => {for (const m of muts)for (const n of m.addedNodes)if (n.nodeType === Node.ELEMENT_NODE) {if (n.matches && n.matches(SELECTORS.chatTrigger)) bindName(n);if (n.matches && n.matches("img")) bindAvatar(n);scan(n);}}).observe(document, { childList: true, subtree: true });}// ============================================================// 显示隐藏的个人简介14 行未改动}})(obj, 0);return result;}async function getIntroduction(uid) {// 1) 整页加载:简介就在页面同源 SSR 脚本 JSON 里for (const s of document.querySelectorAll("script")) {const t = (s.textContent || "").trim();if (t[0] !== "{" || t.indexOf('"introduction"') === -1) continue;9 行未改动// 正确姿势是带 x-lentille-request 头。try {const r = await fetch(`/user/${uid}`, {headers: { "x-lentille-request": "content-only" },});const intro = digIntro(await r.json(), uid);if (intro != null) return intro;} catch (e) {console.error("LuoguSP intro fetch:", e);}return null;}// 主渲染:优先用 @require 的 marked(真 GFM 解析器:表格+对齐/任务列表/嵌套列表/删除线/自动链接/裸 HTML 全支持)9 行未改动null;const tt = (f, d) => {if (!kx) return null;try {return kx.renderToString(f, { throwOnError: false, displayMode: d });} catch (e) {return null;}};const math = [];const hold = (h) => `%%LGMATH${math.push(h) - 1}%%`; // 数学占位:纯文本,过 marked/DOMPurify 不变,最后回填const src = md.replace(/\$\$([\s\S]+?)\$\$/g, (m, f) => {const h = tt(f.trim(), true);return h ? hold(h) : m;8 行未改动} catch (e) {return renderMarkdownLite(md);}html = dp.sanitize(html, { ADD_ATTR: ["target"] }); // 消毒:剥离 script/on*/javascript: 等return html.replace(/<a /gi, '<a target="_blank" rel="noopener noreferrer" ') // 链接新标签打开.replace(/<img /gi, '<img style="max-width:100%" ') // 图片限宽防溢出.replace(/%%LGMATH(\d+)%%/g, (_, i) => math[i]); // 回填 KaTeX(可信,消毒后再插)}// 内置轻量 Markdown → HTML(marked 未加载时的回退;XSS 安全:转义 HTML 实体防注入;URL 仅允许 http(s)/相对,挡 javascript:;// 洛谷允许的少量裸 HTML 走白名单消毒:img/a 校验 URL、安全内联标签去所有属性防 on* 注入、其余标签转义成文本)。27 行未改动return null;}};const spans = []; // 抽出的「原样片段」(代码/公式/白名单裸 HTML),最后回填const stash = (html) => `@@LGB${spans.push(html) - 1}@@`; // 占位符:printable、不含 esc 目标字符、正常文本不会出现const ga = (t, re) => (t.match(re) || [])[1] || ""; // 取标签属性值const inline = (s) =>s.replace(/`([^`]+)`/g, (_, c) => `<code>${c}</code>`)74 行未改动const html = src.split(/\n{2,}/).map((block) => {const b = block.trim();if (/^@@LGB\d+@@$/.test(b)) return b; // 独占一段的占位(代码块 / 行间公式)const lines = block.split("\n");if (lines.length >= 2 &&/^\s*\|.*\|\s*$/.test(lines[0]) &&12 行未改动return `<blockquote>${inline(lines.map((l) => l.replace(/^>\s?/, "")).join("<br>"))}</blockquote>`; // > 已被 esc 转成 >return `<p>${inline(block).replace(/\n/g, "<br>")}</p>`;}).join("");return html.replace(/@@LGB(\d+)@@/g, (_, i) => spans[i]); // 回填占位(inline 公式也在此步)}function normalizeCodeLanguageClass(code) {const lang = [...code.classList].find((c) => c.startsWith("language-"));const pre = code.closest("pre");101 行未改动全部展开body.appendChild(content);card.append(header, body);col.appendChild(card);}async function showHiddenIntro() {const m = location.pathname.match(/^\/(?:user|space)\/(\d+)/);if (!m) return;const route = currentUserRoute();if (!route.isHome) return;const uid = m[1];document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove()); // 清换页残留if (document.querySelector(SELECTORS.nativeIntro)) return; // 原生已显示,不重复补const intro = await getIntroduction(uid);if (!intro || !intro.trim()) return;const place = () => {if (document.querySelector(".introduction:not(.luogusp-intro-card *)"))return true; // 原生简介已出现(管理员等)→ 别补if (document.querySelector(".luogusp-intro-card")) return true;const col = document.querySelector(SELECTORS.userIntroColumn); // 只挂内层内容列,绝不回退外层全宽(否则内容顶到最左被裁)2 行未改动return true;};if (place()) return;// 内容列尚未渲染(SPA 换页):等它出现再补,8s 后放弃const obs = new MutationObserver(() => {if (place()) obs.disconnect();});obs.observe(document.body, { childList: true, subtree: true });setTimeout(() => obs.disconnect(), 8000);}// SPA 换页时 URL 变但脚本不重跑:监听用户主页 uid 变化补显。function currentUserRoute() {const m = location.pathname.match(/^\/(?:user|space)\/(\d+)/);4 行未改动isHome:!!m && (!hash || hash === "#" || hash === "#home" || hash === "#main"),};}function watchUrlChange(onChange) {if (!history.pushState._luoguspWrapped) {for (const method of ["pushState", "replaceState"]) {const raw = history[method];const wrapped = function (...args) {const ret = raw.apply(this, args);window.dispatchEvent(new Event("luogusp:urlchange"));return ret;};wrapped._luoguspWrapped = true;history[method] = wrapped;}}window.addEventListener("popstate", onChange);window.addEventListener("hashchange", onChange);window.addEventListener("luogusp:urlchange", onChange);}function watchHiddenIntro() {let requestedRouteKey = "";const check = () => {const route = currentUserRoute();const uid = route.uid;// 原生简介出现(管理员等原生可见)→ 移除我的卡,避免重复渲染if (document.querySelector(".introduction:not(.luogusp-intro-card *)")) {document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove());requestedRouteKey = route.key;return;}if (!uid || !route.isHome) {document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove());requestedRouteKey = "";return;}if (document.querySelector(".luogusp-intro-card")) {requestedRouteKey = route.key;return;}if (route.key !== requestedRouteKey) {requestedRouteKey = route.key;showHiddenIntro();}};check();let scheduled = false;const queueCheck = () => {if (!scheduled) {scheduled = true;requestAnimationFrame(() => {scheduled = false;check();});}};new MutationObserver(queueCheck).observe(document.body, {childList: true,subtree: true,});watchUrlChange(queueCheck);}// ============================================================// 题目难度着色// ============================================================class FetchRateLimiter {// launchGap:相邻两次发起 fetch 的最小间隔(越小越快,但过快可能被洛谷限流)// concurrency:最大同时在飞请求数(并发上限,网络慢时防堆积)// 单队列 FIFO:按入队顺序处理 = 页面 DOM 顺序(主列表在前先染,讨论标签最后)。constructor(launchGap, concurrency) {this.launchGap = launchGap;this.concurrency = concurrency;this.queue = [];this.active = 0;this.nextAt = 0;this.cache = new Map();}_drain() {while (this.active < this.concurrency && this.queue.length) {const wait = this.nextAt - Date.now();if (wait > 0) {setTimeout(() => this._drain(), wait);return;} // 距上次发起未满 launchGapthis.nextAt = Date.now() + this.launchGap;const job = this.queue.shift();this.active++;fetch(job.url).then(job.resolve, job.reject).finally(() => {this.active--;this._drain();});}}fetchText(url) {if (this.cache.has(url)) return this.cache.get(url);const p = new Promise((resolve, reject) => {this.queue.push({ url, resolve, reject });this._drain();}).then((res) => res.text());this.cache.set(url, p);return p;}}const limiter = new FetchRateLimiter(200, 3); // 200ms 发起间隔、最多 3 并发(原为 300ms 串行)const colorCache = new Map(); // pid -> css 颜色const DIFF_RE = /"difficulty":\s*(\d+)/; // HTML 回退用let contentOnlyOk = null; // null 未知 / true 支持 / false 不支持// 优先走 _contentOnly JSON 接口(轻量、结构稳定),失败回退整页 HTML 正则。async function fetchDifficulty(pid) {if (contentOnlyOk !== false) {let text;try {text = await limiter.fetchText(`/problem/${pid}?_contentOnly=1`);} catch (e) {/* 网络错误,别据此判定接口不支持 */}if (text != null) {try {const d = JSON.parse(text)?.currentData?.problem?.difficulty;if (typeof d === "number") {contentOnlyOk = true;return d;}} catch (e) {if (contentOnlyOk === null) contentOnlyOk = false; // 拿到的是整页 HTML,判定不支持}}}try {const html = await limiter.fetchText(`/problem/${pid}`);const m = html.match(DIFF_RE);if (m) return Number(m[1]);} catch (e) {console.error("LuoguSP difficulty:", pid, e);}return null;}// 记录列表 / 练习页:洛谷已把整批题目难度注入 _feInstance,直接批量取,省去逐题抓取。function cacheDifficulty(pid, difficulty) {if (pid && typeof difficulty === "number")colorCache.set(pid, diffColor(difficulty));}function harvestFromFeInstance() {const cur = window._feInstance && window._feInstance.currentData;if (!cur) return;const url = location.href;if (url.startsWith("https://www.luogu.com.cn/record/list")) {const list = cur.records && cur.records.result;if (list && !list._luogusp) {for (const it of list)cacheDifficulty(it.problem && it.problem.pid,it.problem && it.problem.difficulty,);list._luogusp = true;}}if (/^https:\/\/www\.luogu\.com\.cn\/user\/\d+#practice$/.test(url)) {for (const key of ["submittedProblems", "passedProblems"]) {const list = cur[key];if (list && !list._luogusp) {for (const it of list) cacheDifficulty(it.pid, it.difficulty);list._luogusp = true;}}}}async function getProblemColor(pid) {harvestFromFeInstance();if (colorCache.has(pid)) return colorCache.get(pid);const d = await fetchDifficulty(pid);if (d == null) return null;const color = diffColor(d);colorCache.set(pid, color);return color;}function isProblemId(id) {if (id.startsWith("AT_")) return true;return /[a-zA-Z]/.test(id) && /[0-9]/.test(id);}// 把子树中第一处 pid 文本包成 <b>(纯 DOM,避免 innerHTML.replace 误伤属性内同名子串、// 重建整个锚点子树、抖掉已绑定的监听)。返回是否成功包裹。function wrapPidText(root, pid, color) {const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);11 行未改动}return false;}async function colorAnchor(a) {let pid = a.href.split("/").pop();let isForum = false;if (pid.includes("?forum=")) {pid = pid.split("=").pop();isForum = true;}pid = pid.split("?")[0].split("=").pop();let isVoid = false;if (a.matches(SELECTORS.voidAnchor) && pid === "javascript:void 0") {pid = a.innerText.split(" ")[0];isVoid = true;}if (!isProblemId(pid)) return;// 只处理确属题目的锚点——/problem/ 链接、讨论区 ?forum= 标签、void 特链。// 避免把 /paste/xxx、/user/xxx 等「字母+数字」尾段误判成题号而空跑请求。if (!isForum && !isVoid && !a.href.includes("/problem/")) return;if (!a.innerText.startsWith(pid)) return;if (a.dataset.luoguspPid === pid) return; // 已着色,跳过(防重复处理/嵌套 <b>)const span = a.children[0];if (span && span.matches("span.pid") && span.innerText === pid) {const color = await getProblemColor(pid);if (color) {span.style.color = color;span.style.fontWeight = "bold";a.dataset.luoguspPid = pid;}} else {const color = await getProblemColor(pid);if (color && wrapPidText(a, pid, color)) a.dataset.luoguspPid = pid;}}function addProblemsColor() {new MutationObserver(async (muts) => {for (const m of muts) {if (m.type === "childList") {for (const n of m.addedNodes) {if (n.nodeType !== Node.ELEMENT_NODE) continue;if (n.matches && n.matches("a[href]")) colorAnchor(n);if (n.querySelectorAll)n.querySelectorAll("a[href]").forEach(colorAnchor);}} else if (m.type === "characterData") {const span = m.target.parentElement;if (span && span.matches && span.matches("span.pid")) {const color = await getProblemColor(span.textContent);if (color) {span.style.color = color;span.style.fontWeight = "bold";}}}}}).observe(document, {childList: true,subtree: true,characterData: true,});document.querySelectorAll("a[href]").forEach(colorAnchor);}// ============================================================// IDE 一键测试样例// 洛谷新版题目页(columba)IDE 模式(#ide)下,逐组驱动题面样例的原生「运行」,// 结果从输出面板 DOM 捕获(结果经页面常驻 WS 推送,网络层拿不到——勿改走拦截)。// 锚点与配色的事实来源:docs/superpowers/specs/2026-07-22-ide-mode-recon-notes.md// ============================================================function ideToolbarByTitle(title) {for (const tb of document.querySelectorAll(SELECTORS.ideToolbar)) {const t = tb.querySelector(SELECTORS.ideToolbarText);if (t && t.textContent.trim() === title) return tb;}return null;}const IDE_BATCH = {running: false, // 批测进行中(防重入)stopReq: false, // 「停止」请求:当前组跑完即停driving: false, // 程序化点击原生按钮的瞬间为 true(区分用户手点)activeTab: "custom", // custom=原生输入输出 / samples=样例面板tabBar: null,panel: null,ioLayout: null, // 原生 输入|输出 水平分栏(tab 切换时显隐)rowsEl: null,summaryEl: null,stopBtn: null,results: null, // 本轮各组结果(过期标注用)stale: false,inputSnapshot: null, // 批测前用户自定义输入快照};function ideModeActive() {return (14 行未改动function currentPid() {const m = location.pathname.match(/^\/problem\/([A-Za-z0-9_]+)/);return m ? m[1] : "";}async function getIdeSamples() {const pid = currentPid();if (!pid) return null;const p = lentilleProblem();if (p && p.pid === pid && Array.isArray(p.samples)) return p.samples;2 行未改动// 正确姿势是带 x-lentille-request 头(真机实测 2026-07-22)。try {const res = await fetch(`/problem/${pid}`, {headers: { "x-lentille-request": "content-only" },});const json = await res.json();const prob = json && json.data && json.data.problem;if (prob && Array.isArray(prob.samples)) return prob.samples;} catch (e) {console.error("LuoguSP ide samples:", e);}return null;}function sampleRunButtons() {17 行未改动return content.textContent || "";}let ideSubmitWaiter = null;function installIdeSubmitObserver() {if (XMLHttpRequest.prototype.open.__luoguspIde) return;const rawOpen = XMLHttpRequest.prototype.open;const rawSend = XMLHttpRequest.prototype.send;const open = function (method, url) {this.__luoguspIdeSubmit =typeof url === "string" && url.indexOf("/api/ide_submit") !== -1;return rawOpen.apply(this, arguments);};const send = function () {if (this.__luoguspIdeSubmit)this.addEventListener("loadend", () => {if (ideSubmitWaiter) {const w = ideSubmitWaiter;ideSubmitWaiter = null;w(this.status);}});return rawSend.apply(this, arguments);};open.__luoguspIde = true;XMLHttpRequest.prototype.open = open;XMLHttpRequest.prototype.send = send;}function waitIdeSubmit(ms) {return new Promise((resolve) => {const timer = setTimeout(() => {if (ideSubmitWaiter === fn) ideSubmitWaiter = null;resolve(null);}, ms);const fn = (status) => {clearTimeout(timer);resolve(status);};ideSubmitWaiter = fn;});}const sleep = (ms) => new Promise((r) => setTimeout(r, ms));function outputParts() {const tb = ideToolbarByTitle("输出");if (!tb) return null;const actions = tb.querySelector(SELECTORS.ideToolbarActions);5 行未改动? tb.parentElement.querySelector(SELECTORS.ideTextarea): null,};}// 完成锚点:胶囊 存在→消失→重现(实测清空 300~560ms、结果 1~3.5s;详见侦察实录)// 注意:此处不看 stopReq——设计口径是「当前组跑完即停」,停止只在组间生效async function waitIdePill(present, timeoutMs) {const t0 = Date.now();while (Date.now() - t0 < timeoutMs) {const parts = outputParts();if (!parts) return null; // IDE 已卸载if (!!parts.pill === present) return parts.pill || true;await sleep(150);}return null;}async function runOneSample(runBtn) {const before = outputParts();if (!before) return { verdict: "UKE", note: "IDE 面板不存在" };const hadPill = !!before.pill;let submitP = waitIdeSubmit(10000);IDE_BATCH.driving = true;runBtn.click();IDE_BATCH.driving = false;let status = await submitP;if (status === 429) {await sleep(3000); // 限流:等 3s 原地重试一次submitP = waitIdeSubmit(10000);IDE_BATCH.driving = true;runBtn.click();IDE_BATCH.driving = false;status = await submitP;}if (status == null || status < 200 || status >= 300)return {verdict: "UKE",note: status == null ? "未观测到提交请求" : `提交失败 HTTP ${status}`,};if (hadPill && (await waitIdePill(false, 5000)) === null)return { verdict: "UKE", note: "旧结果未清空,疑似运行未开始" };const pill = await waitIdePill(true, 30000);if (!pill || pill === true)return { verdict: "UKE", note: "30s 未返回结果" };const parts = outputParts();return {3 行未改动output: parts.textarea ? parts.textarea.value : "",};}function ideBatchHint(msg) {const btn = document.querySelector(".luogusp-ide-batch-btn");if (!btn) return;const old = btn.textContent;btn.textContent = msg;btn.disabled = true;setTimeout(() => {btn.textContent = old;btn.disabled = IDE_BATCH.running;}, 1500);}async function startIdeBatch() {if (IDE_BATCH.running) return;mountIdeTabs();const samples = await getIdeSamples();if (!samples || !samples.length) return ideBatchHint("本题无样例");if (!readIdeCode().trim()) return ideBatchHint("代码为空");const runBtns = sampleRunButtons();if (!runBtns.length) return ideBatchHint("找不到样例运行按钮");const n = Math.min(samples.length, runBtns.length);if (runBtns.length !== samples.length)console.error("LuoguSP ide batch: 样例数与运行按钮数不一致",samples.length,runBtns.length,);IDE_BATCH.running = true;IDE_BATCH.stopReq = false;IDE_BATCH.stale = false;IDE_BATCH.results = new Array(n).fill(null);const inputTa = (() => {const tb = ideToolbarByTitle("输入");return tb && tb.parentElement? tb.parentElement.querySelector(SELECTORS.ideTextarea): null;})();IDE_BATCH.inputSnapshot = inputTa ? inputTa.value : null;const batchBtn = document.querySelector(".luogusp-ide-batch-btn");const selfTest = (() => {const tb = ideToolbarByTitle("代码");const actions = tb && tb.querySelector(SELECTORS.ideToolbarActions);return actions? [...actions.querySelectorAll("button")].find((b) => (b.textContent || "").trim() === "自测",): null;})();if (batchBtn) batchBtn.disabled = true;if (selfTest) selfTest.disabled = true; // 批测中禁原生自测防互相干扰if (IDE_BATCH.stopBtn) IDE_BATCH.stopBtn.style.display = "";switchIdeTab("samples");renderIdeRows(samples);if (IDE_BATCH.summaryEl) IDE_BATCH.summaryEl.textContent = "测试中…";let ceLog = null;for (let i = 0; i < n; i++) {if (IDE_BATCH.stopReq) break;const p = ideRowParts(i);if (p) {p.pill.setAttribute("style", IDE_PILL_RUN);p.pill.textContent = "运行中";}expandIdeRow(i);let r;try {r = await runOneSample(runBtns[i]);} catch (e) {console.error("LuoguSP ide batch:", e);r = { verdict: "UKE", note: String(e) };}IDE_BATCH.results[i] = r;applyIdeResult(i, r, samples[i]);if (r.verdict === "CE") {ceLog = r.output || "";for (let j = i + 1; j < n; j++) {IDE_BATCH.results[j] = {verdict: "CE",output: ceLog,note: "编译错误",};applyIdeResult(j, IDE_BATCH.results[j], samples[j]);}break;}if (i < n - 1 && !IDE_BATCH.stopReq) await sleep(500); // 组间限速}if (inputTa && IDE_BATCH.inputSnapshot != null) {inputTa.value = IDE_BATCH.inputSnapshot; // 还原用户自定义输入inputTa.dispatchEvent(new Event("input", { bubbles: true })); // 同步 Vue 绑定}IDE_BATCH.running = false;if (batchBtn) batchBtn.disabled = false;if (selfTest) selfTest.disabled = false;if (IDE_BATCH.stopBtn) IDE_BATCH.stopBtn.style.display = "none";finishIdeSummary();}// 判定口径同洛谷:CRLF 归一、去行尾空格、去末尾空行。仅用于 diff 渲染与交叉校验,// 最终判定以原生胶囊为准(AC/WA 由洛谷前端本地比较,侦察实录 §6)。function normalizeIdeOut(s) {return String(s == null ? "" : s).replace(/\r\n?/g, "\n").split("\n")40 行未改动);p.detail.innerHTML = "";p.detail.classList.remove("luogusp-ide-log");if (r.verdict === "CE") {// CE:不显示三栏,直接展示编译日志(输出框捕获;侦察实录 §5)p.meta.textContent = "";p.detail.classList.add("luogusp-ide-log");p.detail.appendChild(idePane(18 行未改动}if (r.verdict === "RE" && r.detail) {const note = document.createElement("p");note.className = "luogusp-ide-note";note.textContent = r.detail; // RE 原因在 run-result 位置(侦察实录 §5)p.detail.appendChild(note);p.meta.textContent = "";}const expLines = normalizeIdeOut(sample[1]).split("\n");15 行未改动),);}function finishIdeSummary() {if (!IDE_BATCH.summaryEl || !IDE_BATCH.results) return;const rs = IDE_BATCH.results;const counts = {};let ac = 0,tested = 0;rs.forEach((r) => {11 行未改动const p = ideRowParts(i);if (p) p.pill.textContent = "未测";});}IDE_BATCH.summaryEl.textContent = text;const firstBad = rs.findIndex((r) => r && r.verdict !== "AC");if (firstBad !== -1) expandIdeRow(firstBad);else if (IDE_BATCH.rowsEl)IDE_BATCH.rowsEl.querySelectorAll(".luogusp-ide-row.open").forEach((r) => r.classList.remove("open"));}function markIdeStale() {if (IDE_BATCH.stale || IDE_BATCH.running || !IDE_BATCH.results) return;IDE_BATCH.stale = true;if (IDE_BATCH.summaryEl && document.contains(IDE_BATCH.summaryEl))IDE_BATCH.summaryEl.textContent += " · 结果可能已过期,建议重新测试";}function hookIdeStaleAndGuard() {// 代码变更 → 过期标注(CM6 是 contenteditable,input/keydown 均会冒泡)const stale = (e) => {if (e.target && e.target.closest && e.target.closest(SELECTORS.cmContent))markIdeStale();};document.addEventListener("input", stale, true);document.addEventListener("keydown", stale, true);// 批测中拦掉用户手点原生 运行/自测(程序化点击带 driving 标记放行)document.addEventListener("click",(e) => {if (!IDE_BATCH.running || IDE_BATCH.driving) return;const t =e.target &&e.target.closest &&e.target.closest(`${SELECTORS.ideSampleBlock} a, ${SELECTORS.ideToolbar} a.run`,);if (t) {e.preventDefault();e.stopPropagation();}},true,);}function mountIdeButton() {const tb = ideToolbarByTitle("代码");if (!tb) return;const actions = tb.querySelector(SELECTORS.ideToolbarActions);if (!actions || actions.querySelector(".luogusp-ide-batch-btn")) return;8 行未改动btn.disabled = false;btn.addEventListener("click", (e) => {e.preventDefault();e.stopPropagation();startIdeBatch();});actions.insertBefore(btn, selfTest);}function mountIdeTabs() {if (IDE_BATCH.tabBar && document.contains(IDE_BATCH.tabBar)) return;const inputTb = ideToolbarByTitle("输入");if (!inputTb) return;const ioLayout = inputTb.closest(".panel-layout"); // 底部 输入|输出 水平分栏const host = ioLayout && ioLayout.parentElement;41 行未改动});headBtns.appendChild(b);return b;};IDE_BATCH.stopBtn = mkBtn("停止", "luogusp-ide-stop", () => {IDE_BATCH.stopReq = true;});IDE_BATCH.stopBtn.style.display = "none";mkBtn("重新测试", "luogusp-ide-rerun", () => startIdeBatch());host.insertBefore(tabBar, ioLayout);host.appendChild(panel);IDE_BATCH.tabBar = tabBar;IDE_BATCH.panel = panel;IDE_BATCH.ioLayout = ioLayout;IDE_BATCH.rowsEl = panel.querySelector(".luogusp-ide-rows");IDE_BATCH.summaryEl = panel.querySelector(".luogusp-ide-summary");syncIdeTabVisibility();}function switchIdeTab(tab) {IDE_BATCH.activeTab = tab;syncIdeTabVisibility();}function syncIdeTabVisibility() {const { tabBar, panel, ioLayout } = IDE_BATCH;if (!tabBar || !document.contains(tabBar) || !panel || !ioLayout) return;const samples = IDE_BATCH.activeTab === "samples";ioLayout.style.display = samples ? "none" : "";panel.style.display = samples ? "" : "none";tabBar.querySelectorAll(".luogusp-ide-tab").forEach((t) => {t.classList.toggle("on", (t.dataset.tab === "samples") === samples);4 行未改动"background-color:#bfbfbf;border-color:#b3b3b3;color:#fff;";const IDE_PILL_RUN ="background-color:#3498db;border-color:#2f89c5;color:#fff;";function renderIdeRows(samples) {const rowsEl = IDE_BATCH.rowsEl;if (!rowsEl) return;rowsEl.innerHTML = samples.map((s, i) => `19 行未改动});}function ideRowParts(i) {const row =IDE_BATCH.rowsEl &&IDE_BATCH.rowsEl.querySelector(`.luogusp-ide-row[data-idx="${i}"]`);if (!row) return null;return {row,pill: row.querySelector(".luogusp-ide-pill"),meta: row.querySelector(".luogusp-ide-meta"),detail: row.querySelector(".luogusp-ide-detail"),};}function expandIdeRow(i) {if (!IDE_BATCH.rowsEl) return;IDE_BATCH.rowsEl.querySelectorAll(".luogusp-ide-row.open").forEach((r) => r.classList.remove("open"));const p = ideRowParts(i);if (p) p.row.classList.add("open");}function ensureIdeBatchUI() {if (!ideModeActive()) {unmountIdeBatchUI();return;}mountIdeButton();mountIdeTabs();syncIdeTabVisibility();}function unmountIdeBatchUI() {if (IDE_BATCH.running) IDE_BATCH.stopReq = true; // 退出 IDE/换题:请求停止IDE_BATCH.activeTab = "custom"; // 复位,防再次进入时默认落在空面板IDE_BATCH.tabBar = IDE_BATCH.panel = IDE_BATCH.ioLayout = null;IDE_BATCH.rowsEl = IDE_BATCH.summaryEl = IDE_BATCH.stopBtn = null;}// SPA:进出 IDE 模式/换题时补挂与清理(rAF 节流,同既有 watchSettingButton 模式)function watchIdeBatch() {installIdeSubmitObserver();hookIdeStaleAndGuard();let scheduled = false;const tick = () => {scheduled = false;try {ensureIdeBatchUI();} catch (e) {console.error("LuoguSP ide batch:", e);}};const queue = () => {if (!scheduled) {scheduled = true;requestAnimationFrame(tick);}};new MutationObserver(queue).observe(document.body, {childList: true,subtree: true,});watchUrlChange(queue);ensureIdeBatchUI();}// ============================================================// 受限文章/剪贴板直接显示(原生壳注入)// 国内站访问非本人/未审核的 /article、/paste 会落在「安全访问中心」拦截页// (独立静态页、零全站样式、无 CSP)。本功能在拦截页上重建官方页面:12 行未改动// 作者数据走 .cn 同源 /api/user/search(owner 要求不吃保存站/国际站的用户数据)。// ★保存站硬边界:payload 的 createdAt 是入档时间,非原文发布时间(无接口可取原始时间)。// ============================================================const SAVER_API = "https://api.luogu.me";async function saverGet(path) {const res = await fetch(SAVER_API + path);return res.json(); // 统一壳 {code,message,data};业务码 404=未收录}async function saverPost(path, body) {const res = await fetch(SAVER_API + path, {method: "POST",headers: body ? { "content-type": "application/json" } : undefined,body: body ? JSON.stringify(body) : undefined,});return res.json();}// 拦截页判定:URL 形态 + 标题 + pre#url 内容三重锚点;不满足=正常页面,绝不接管function restrictedPageInfo() {const m = location.pathname.match(/^\/(article|paste)\/([A-Za-z0-9]+)\/?$/);if (!m) return null;if (document.title.indexOf("安全访问中心") === -1) return null;const pre = document.querySelector(SELECTORS.restrictedUrlPre);const target = pre ? (pre.textContent || "").trim() : "";if (target.indexOf(`/${m[1]}/${m[2]}`) === -1) return null;return {type: m[1],id: m[2],origUrl: target || `https://www.luogu.com/${m[1]}/${m[2]}`,};}// 最小自有样式:加载层/失败卡(注入拦截页文档),扩展按钮样式随壳 HTML 走(见 RST_EXTRA_CSS)function injectRstStyle() {if (document.getElementById("luogusp-rst-style")) return;const style = document.createElement("style");style.id = "luogusp-rst-style";style.textContent = `.luogusp-rst-loader{position:fixed;inset:0;z-index:2147483000;background:#f5f5f5;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;color:#595959;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Helvetica Neue","PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;}.luogusp-rst-spinner{width:36px;height:36px;border:3px solid rgba(52,152,219,.25);border-top-color:#3498db;border-radius:50%;animation:luogusp-rst-spin .8s linear infinite;}@keyframes luogusp-rst-spin{to{transform:rotate(360deg);}}.luogusp-rst-plain{margin:0;background:#f5f5f5;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Helvetica Neue","PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;color:#404040;}.luogusp-rst-plain a{color:#3498db;text-decoration:none;}.luogusp-rst-plaincard{max-width:640px;margin:15vh auto 0;background:#fff;border-radius:4px;box-shadow:0 1px 3px rgba(26,26,26,.1);padding:1.5em;}.luogusp-rst-note{color:#999;font-size:12px;text-align:center;margin:24px 0;}2 行未改动}// 扩展按钮样式(写进壳文档;蓝色=与原生灰色互动钮区分,owner 拍板)。// ★button-2line 的官方规则是 data-v 作用域的,注入节点吃不到 → 布局自带(镜像官方值)。const RST_EXTRA_CSS =".luogusp-rst-abtn{display:flex;flex-direction:column;align-items:center;margin:0 1em;cursor:pointer;}" +".luogusp-rst-abtn .icon{font-size:1.25em;margin-bottom:.3em;}" +".luogusp-rst-abtn .text{text-align:center;font-size:.75em;}" +".luogusp-rst-abtn>*{color:#3498db !important;}" +31 行未改动// 作者等用户数据一律走国内站同源接口(owner 要求:不吃保存站/国际站的用户数据;头像也全走 .cn CDN)。// 接口=/api/user/search?keyword={uid}(拦截页源实测可用;旧 /user/{uid}?_contentOnly=1 已死,返回 HTML),// 返回 userSummary:{uid,name,avatar,slogan,badge,color,ccfLevel,xcpcLevel,…}。失败回退存档快照。const rstUserCache = new Map();async function rstCnUser(uid) {if (!uid) return null;if (rstUserCache.has(uid)) return rstUserCache.get(uid);let user = null;try {const res = await fetch(`/api/user/search?keyword=${encodeURIComponent(uid)}`,);const json = await res.json();const list = (json && json.users) || [];user = list.find((u) => u && Number(u.uid) === Number(uid)) || null;} catch (e) {/* 回退存档快照 */}rstUserCache.set(uid, user);return user;16 行未改动background: "",};}// 加载动效覆盖层:检测命中后立即出现(盖住拦截页),document.write 重建文档时自然消失function rstShowLoader(text) {injectRstStyle();let el = document.getElementById("luogusp-rst-loader");if (!el) {el = document.createElement("div");el.id = "luogusp-rst-loader";el.className = "luogusp-rst-loader";el.innerHTML ='<div class="luogusp-rst-spinner"></div><div class="msg">加载中…</div>';(document.body || document.documentElement).appendChild(el);}el.querySelector(".msg").textContent = text || "加载中…";}function rstHideLoader() {const el = document.getElementById("luogusp-rst-loader");if (el) el.remove();}function rstBuildFailure(info, reason) {document.title =(info.type === "article" ? "文章" : "云剪贴板") + " - 洛谷";document.body.className = "luogusp-rst-plain";document.body.innerHTML = `<div class="luogusp-rst-plaincard"><h1 style="font-size:20px;margin:0 0 10px;">未能获取内容</h1><p></p><p>可能原因:内容未公开、未通过审核,或保存站暂时不可用。</p><p><a href="${info.origUrl}" rel="noopener noreferrer">前往国际站查看原文 →</a></p><p class="luogusp-rst-note">此页面由 LuoguSP 生成 · 数据来源:洛谷保存站</p></div>`;document.querySelector(".luogusp-rst-plaincard p").textContent =String(reason);}// 壳骨架收割:候选源逐个尝试(2026-07-22 实测:/ranking、/discuss 已迁 columba;// /image、/theme/list 仍为 lfe。任一命中即用;全挂=降级失败卡)async function rstHarvest(kind) {const sources =kind === "columba" ? ["/ranking", "/discuss"] : ["/image", "/theme/list"];const marker = kind === "columba" ? "lentille-context" : "_feInjection";for (const src of sources) {try {const res = await fetch(src);const html = await res.text();if (html.includes(marker)) return html;} catch (e) {/* 换下一个源 */}}return null;}// 嵌入 <script> 的 JSON 防拆壳(内容里出现 </script> 会截断壳文档)function rstJsonForScript(obj) {return JSON.stringify(obj).replace(/</g, "\\u003C");}// 评论接口桩:官方文章组件启动后会 GET /article/{lid}/replies(?sort=&after=)。// window.fetch 包装器不随 document.write 重建,天然对新文档生效;其余请求全部放行。function rstStubReplies(lid, comments) {const mapped = comments.map((c, i) => {const a = c.author || {};return {2 行未改动time: Number(c.time) || 0,content: String(c.content || ""),};});const re = new RegExp(`/article/${lid}/replies`);const realFetch = window.fetch.bind(window);window.fetch = function (input, init) {const url =typeof input === "string" ? input : (input && input.url) || "";if (re.test(url)) {let list = mapped;try {const q = new URL(url, location.origin).searchParams;if (q.get("sort") === "time-d")list = [...mapped].sort((x, y) => y.time - x.time);const after = Number(q.get("after"));let start = 0;if (after) {const idx = list.findIndex((r) => r.id === after);start = idx >= 0 ? idx + 1 : list.length;}list = list.slice(start, start + 20);} catch (e) {list = mapped.slice(0, 20);}return Promise.resolve(new Response(JSON.stringify({ replySlice: list }), {status: 200,headers: { "content-type": "application/json" },}),);}return realFetch(input, init);};}// 文章页:合成 lentille-context(template article.show)+ 官方 columba 前端async function rstBootArticle(info, data) {const [scaffold, cnUser, commentsQ] = await Promise.all([rstHarvest("columba"),rstCnUser(data.authorId),saverGet(`/article/comments/${info.id}`).catch(() => null),]);if (!scaffold)return rstBuildFailure(info, "无法获取洛谷页面骨架,暂不能就地渲染。");const pick = (re) => {const m = scaffold.match(re);return m ? m[1] : null;};16 行未改动...scaffold.matchAll(/<link rel="stylesheet" href="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+)"/g,),].map((m) => m[1]);if (!ctxRaw || !scripts.length)return rstBuildFailure(info, "洛谷页面骨架解析失败(结构可能已改版)。");let viewer = null;try {viewer = JSON.parse(ctxRaw).user || null;} catch (e) {/* 匿名兜底 */}const comments =(commentsQ && commentsQ.data && commentsQ.data.comments) || [];const ctx = {instance: "main",template: "article.show",status: 200,24 行未改动},user: viewer,time: Math.floor(Date.now() / 1000),};rstStubReplies(info.id, comments);const title = String(data.title || "文章").replace(/</g, "<");const html =`<!DOCTYPE html><html lang="zh-CN" class="no-js"><head><meta charset="utf-8">` +`<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">` +`<meta name="csrf-token" content="${csrf}">` +`<title>${title} - 洛谷专栏</title>` +`<link rel="icon" href="https://fecdn.luogu.com.cn/favicon.ico">` +`<script>${globalsRaw}<\/script>` +`<script id="lentille-context" type="application/json">${rstJsonForScript(ctx)}<\/script>` +scripts.map((s) => `<script src="${s}" charset="utf-8" defer><\/script>`).join("") +cssLinks.map((c) => `<link rel="stylesheet" href="${c}" />`).join("") +`<script id="luogu-theme" type="application/json">${themeRaw}<\/script>` +`<style>${RST_EXTRA_CSS}</style>` +`</head><body><div id="app"></div></body></html>`;document.open();document.write(html);document.close();rstOnNewDocReady(() => {rstMountArticleButtons(info, data);// document.write 把旧文档上的监听/观察器全部抹掉 → 全量功能重挂// (设置入口/难度着色/简介/IDE 批测等;受限接管自身重跑会因拦截页锚点不匹配安全空转)startFeatures();rstArmReturnReload();});}// 剪贴板页:合成 window._feInjection(currentTemplate PasteShow)+ 官方 lfe 前端async function rstBootPaste(info, data) {const [scaffold, cnUser] = await Promise.all([rstHarvest("lfe"),rstCnUser(data.authorId),]);if (!scaffold)return rstBuildFailure(info, "无法获取洛谷页面骨架,暂不能就地渲染。");const injRaw = (scaffold.match(/_feInjection = JSON\.parse\(decodeURIComponent\("([^"]+)"\)\)/,) || [])[1];const feCfg = (scaffold.match(/window\._feConfigVersion=(\d+)/) || [])[1];const tagVer = (scaffold.match(/window\._tagVersion=(\d+)/) || [])[1];const csrf =(scaffold.match(/<meta name="csrf-token" content="([^"]+)"/) || [])[1] ||"";const loaderCss = (scaffold.match(/<link rel="stylesheet" href="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+loader\.css[^"]*)"/,) || [])[1];const loaderJs = (scaffold.match(/<script src="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+loader\.js[^"]*)"/,) || [])[1];if (!injRaw || !loaderJs || !loaderCss)return rstBuildFailure(info, "洛谷页面骨架解析失败(结构可能已改版)。");let scafInj = {};try {scafInj = JSON.parse(decodeURIComponent(injRaw)) || {};} catch (e) {/* 匿名/默认主题兜底 */}const inj = {code: 200,currentTemplate: "PasteShow",currentData: {15 行未改动const html =`<!DOCTYPE html><html class="no-js" lang="zh"><head><meta charset="utf-8">` +`<meta http-equiv="X-UA-Compatible" content="IE=edge">` +`<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">` +`<meta name="csrf-token" content="${csrf}">` +`<meta name="renderer" content="webkit">` +`<title>云剪贴板 - 洛谷 | 计算机科学教育新生态</title>` +`<link rel="shortcut icon" type="image/x-icon" href="https://fecdn.luogu.com.cn/favicon.ico" media="screen"/>` +`<link rel="stylesheet" href="${loaderCss}">` +`<style>${RST_EXTRA_CSS}</style>` +`<script>window._feInjection = JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(inj))}"));window._feConfigVersion=${feCfg};window._tagVersion=${tagVer};<\/script>` +`<script src="${loaderJs}" charset="utf-8" defer><\/script>` +`</head><body><div id="app"><noscript><h3>请<b style="color:#f00;">不要禁用</b>脚本,否则网页无法正常加载</h3></noscript></div></body></html>`;document.open();document.write(html);document.close();rstOnNewDocReady(() => {rstMountPasteButtons(info, data);// document.write 把旧文档上的监听/观察器全部抹掉 → 全量功能重挂// (设置入口/难度着色/简介/IDE 批测等;受限接管自身重跑会因拦截页锚点不匹配安全空转)startFeatures();rstArmReturnReload();});}// 扩展按钮(文章页):等官方前端渲染出互动条再注入;Vue 重渲染会抹节点,观察器负责补种。// 同时在正文底部「创建时间:…」后方补「更新时间」=保存站存档最近更新时间(updatedAt),8 行未改动div.addEventListener("click", onClick);return div;};const inject = () => {document.querySelectorAll(".article-content .actions").forEach((bar) => {// owner 拍板:左浮条(left-mode)不放扩展按钮,只挂内联互动条if (bar.classList.contains("left-mode")) return;if (bar.querySelector(".luogusp-rst-abtn")) return;bar.appendChild(make(RST_BTN_ICONS.refresh,9 行未改动);});// owner 要求:指向创建/更新时间不出浏览器悬浮泡 → 整条时间栏剥 title// (removeAttribute 无属性时不产生变更记录,天然幂等)document.querySelectorAll(".article-content .update-info").forEach((bar) => {bar.removeAttribute("title");bar.querySelectorAll("[title]").forEach((n) => n.removeAttribute("title"));});if (updText)document.querySelectorAll(".article-content .update-info").forEach((bar) => {if (bar.querySelector(".luogusp-rst-updtime")) return;const ref = [...bar.querySelectorAll("span")].find((s) =>/创建时间/.test(s.textContent || ""),);const span = document.createElement("span");if (ref)for (const at of ref.attributes)if (at.name.startsWith("data-v-"))span.setAttribute(at.name, at.value); // 继承 data-v 作用域样式span.classList.add("luogusp-rst-updtime");span.textContent = `更新时间:${updText}`;const sep = document.createTextNode(" ");if (ref) ref.after(sep, span);else bar.append(sep, span);});rstApplyRefreshBtns(); // Vue 重种出的「申请更新」按钮要重新套用当前状态};inject();new MutationObserver(inject).observe(document.body || document.documentElement,{ childList: true, subtree: true },);}// 扩展按钮(剪贴板页):内容卡首行(content-card-top)最右侧两枚实心蓝钮// (首行是 flex space-between,作者信息在左,本容器落位最右)。// 同时在「发表时间: …」行下方补「更新时间」行=保存站存档最近更新时间(updatedAt)。47 行未改动row.appendChild(span);pubRow.after(row);}rstApplyRefreshBtns(); // Vue 重种出的「申请更新」按钮要重新套用当前状态};inject();new MutationObserver(inject).observe(document.body || document.documentElement,{ childList: true, subtree: true },);}function rstQuery(info) {return saverGet(`/${info.type}/query/${info.id}`);}function rstTriggerSave(info) {return saverPost(`/workflow/create/template/${info.type}-save-pipeline`, {targetId: info.id,});}// 申请更新(手动):状态机 idle=可点 / busy=更新中… / done=已申请。// owner 口径(2026-07-23):提交成功即锁定「已申请」且不可再点,不轮询不自动刷新,// 直至用户主动刷新页面(保存工作流异步完成,刷新后自然装配新档);仅提交失败允许重试。// Vue 重渲染会抹掉按钮由观察器重种,故状态存模块级、每次补种后重新套用(rstApplyRefreshBtns)。let rstRefreshState = "idle";let rstRefreshText = "申请更新";// ★本函数被 inject 观察器(body childList+subtree)的回调无条件调用,必须幂等:// textContent 同值重写也会删旧建新 Text 节点、产生 childList 变更记录,// 会把观察器自己再触发一遍 → 微任务死循环整页卡死(2.11.0 事故),故同值不写。function rstApplyRefreshBtns() {9 行未改动rstRefreshState = state;rstRefreshText = text;rstApplyRefreshBtns();}async function rstManualRefresh(info) {if (rstRefreshState !== "idle") return;rstSetRefresh("busy", "更新中…");try {const r = await rstTriggerSave(info);if (r && typeof r.code === "number" && r.code >= 500)throw new Error(`保存站返回 ${r.code}`);if (info.type === "article")saverPost(`/article/comments/${info.id}/refresh`).catch(() => {});rstSetRefresh("done", "已申请");} catch (e) {console.error("LuoguSP restricted refresh:", e);rstSetRefresh("idle", "更新失败");setTimeout(() => {if (rstRefreshState === "idle") rstSetRefresh("idle", "申请更新");}, 3000);}}// 接管文档是官方 SPA:站内路由(pushState/popstate,含浏览器前进后退)驶向任一// article/paste 路由时,官方前端会去真实接口取数——受限内容必失败,且没有页面加载、// 脚本不会重跑(本次接管文档的监听已随 document.write 重挂,history 包装器天然存活)。// 侦测到 pathname 切到 article/paste 即整页刷新:受限 → 服务器重出拦截页 → 脚本重新接管;// 公开 → 原生页面正常整页加载,无副作用。function rstArmReturnReload() {let lastPath = location.pathname;watchUrlChange(() => {const p = location.pathname;if (p === lastPath) return; // 同路径 hash/query 变化不刷lastPath = p;if (/^\/(article|paste)\/[A-Za-z0-9]+\/?$/.test(p)) location.reload();});}// ★document.write 的新文档解析是异步收尾的:close() 返回时 body 可能尚未建出,// 直接 observe(document.body) 会抛 TypeError(真机实测 2026-07-23)→ 等 body 就绪再挂。function rstOnNewDocReady(fn) {const run = () => {try {fn();} catch (e) {console.error("LuoguSP restricted post-boot:", e);}};if (document.body) return run();document.addEventListener("DOMContentLoaded", run, { once: true });}async function rstBootPage(info, data) {try {if (info.type === "article") await rstBootArticle(info, data);else await rstBootPaste(info, data);} catch (e) {console.error("LuoguSP restricted boot:", e);rstBuildFailure(info, `原生页面装配失败:${e}`);}}async function rstRun() {const info = restrictedPageInfo();if (!info) return;let q;try {q = await rstQuery(info);} catch (e) {// 保存站不可达:撤掉加载层还原拦截页,仅置顶提示,保留原生跳转能力console.error("LuoguSP restricted:", e);rstHideLoader();const tip = document.createElement("p");tip.style.cssText ="margin:12px auto;max-width:640px;color:#e74c3c;font-size:13px;text-align:center;";tip.textContent ="LuoguSP:保存站(api.luogu.me)不可达,无法直接显示该内容。";document.body.insertBefore(tip, document.body.firstChild);return;}injectRstStyle();if (q && q.code === 200 && q.data) {// 已收录:直接装配存档,不自动申请更新(owner 拍板:更新只走「申请更新」按钮)return rstBootPage(info, q.data);}// 未收录:发起保存并等待入库(加载层持续转圈,完成后装配)rstShowLoader("该内容尚未被保存站收录,已自动发起收录…");try {await rstTriggerSave(info);} catch (e) {console.error("LuoguSP restricted save:", e);return rstBuildFailure(info, "向保存站发起收录请求失败。");}for (let i = 0; i < 15; i++) {await sleep(3000);let poll;try {poll = await rstQuery(info);} catch (e) {continue;}if (poll && poll.code === 200 && poll.data) {return rstBootPage(info, poll.data);}}rstBuildFailure(info, "保存站在限定时间内未能完成收录。");}function watchRestrictedPage() {// 拦截页是独立静态页,无 SPA。命中即刻盖上加载动效层(不闪原生跳转确认页),// 随后异步取数装配;取数失败会撤层还原拦截页。try {if (restrictedPageInfo()) rstShowLoader();} catch (e) {console.error("LuoguSP restricted loader:", e);}rstRun().catch((e) => console.error("LuoguSP restricted:", e));}// ============================================================// 启动// ============================================================const isChatPage = location.href.startsWith("https://www.luogu.com.cn/chat");const FEATURES = [{ always: true, run: watchSettingButton },{key: `${STORAGE_PREFIX}addProblemsColor`,run: () => setTimeout(addProblemsColor, 500),},{key: `${STORAGE_PREFIX}addMessageLink`,run: () => {if (isChatPage) setTimeout(addMessageLink, 500);},},{ key: `${STORAGE_PREFIX}showIntro`, run: watchHiddenIntro },{ key: `${STORAGE_PREFIX}ideBatchSampleTest`, run: watchIdeBatch },{ key: `${STORAGE_PREFIX}showRestrictedContent`, run: watchRestrictedPage },];// 受限内容接管 document.write 重建文档后也会调用本函数,重挂全部功能function startFeatures() {injectStyle();for (const f of FEATURES) {if (!f.always && !storage.get(f.key)) continue;try {f.run();} catch (e) {console.error("LuoguSP feature failed:", e);}}}startFeatures();})();```17 行未改动1819202122232425265 行未改动323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177025 行未改动17961797179817991800180118021803180418051806180718081809181018111812181310 行未改动1824182518261827182818291830183118321833183418351836183775 行未改动19131914191519161917191819191920192124 行未改动194619471948194919501951195219531954195519561957195819591960196119621963196419656 行未改动19721973197419751976197719781979198088 行未改动206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092 行未改动21122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219514 行未改动2210221122122213221422152216221722189 行未改动2228222922302231223222332234223522362237223822392240224122429 行未改动22522253225422552256225722582259226022612262226322642265226622672268226922708 行未改动227922802281228222832284228522862287228822892290229127 行未改动2319232023212322232323242325232623272328232974 行未改动24042405240624072408240924102411241212 行未改动242524262427242824292430243124322433243424352436101 行未改动全部展开25382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652 行未改动256825692570257125722573257425752576257725782579258025812582258325842585258625874 行未改动2592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270111 行未改动27132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285314 行未改动2868286928702871287228732874287528762 行未改动287928802881288228832884288528862887288828892890289128922893289417 行未改动29122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029815 行未改动29872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383 行未改动304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306640 行未改动31073108310931103111311231133114311518 行未改动31343135313631373138313931403141314215 行未改动3158315931603161316231633164316531663167316811 行未改动31803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032318 行未改动32403241324232433244324532463247324832493250325132523253325441 行未改动32963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233234 行未改动33283329333033313332333333343335333619 行未改动33563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358012 行未改动35933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336442 行未改动36473648364936503651365236533654365531 行未改动368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373516 行未改动3752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238532 行未改动385638573858385938603861386238633864386538663867386838693870387138723873387438753876387716 行未改动38943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392924 行未改动3954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400315 行未改动4019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440758 行未改动40844085408640874088408940904091409240934094409540969 行未改动4106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414347 行未改动4191419241934194419541964197419841994200420142024203420442054206420742084209421042119 行未改动422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458717 行未改动```javascript// ==UserScript==// @name LuoguSP// @namespace https://github.com/ShanireZ/LuoguSP// @version 2.12.2// @description LuoguSP:题目难度着色 / 私信 Ctrl+Click(用户名+头像) 跳转主页 / 显示隐藏的个人简介 / IDE 一键测试样例 / 受限文章与剪贴板直接显示// @author ShanireZ, realskc (Until 1.8.2)// @license GPL-3.0// @match https://www.luogu.com.cn/*5 行未改动// @require https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js// @require https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js// @require https://cdn.jsdelivr.net/npm/dompurify@3.0.9/dist/purify.min.js// @require https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js// @run-at document-start// ==/UserScript==(function () {"use strict";function createGetRequestScheduler(config) {const {fetch: fetchImpl,clock,launchGap = 300,concurrency = 3,timeoutMs = 15000,maxRetries = 1,createAbortController = () => new AbortController(),} = config || {};if (typeof fetchImpl !== "function")throw new TypeError("GET scheduler requires a fetch adapter");if (!clock ||typeof clock.now !== "function" ||typeof clock.setTimeout !== "function" ||typeof clock.clearTimeout !== "function")throw new TypeError("GET scheduler requires a clock adapter");const queue = [];const inflight = new Map();const controllers = new Set();let active = 0;let nextAt = 0;let wakeTimer = null;let disposed = false;const abortError = () => {const error = new Error("GET scheduler disposed");error.name = "AbortError";return error;};const retryAfterMs = (raw) => {if (!raw) return 0;const seconds = Number(raw);if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);const at = Date.parse(raw);return Number.isFinite(at) ? Math.max(0, at - clock.now()) : 0;};const defer = (ms) => {if (disposed || !(ms > 0)) return;const until = clock.now() + ms;if (until <= nextAt) return;nextAt = until;if (wakeTimer !== null) {clock.clearTimeout(wakeTimer);wakeTimer = null;}drain();};const drain = () => {if (disposed) return;while (active < concurrency && queue.length) {const wait = nextAt - clock.now();if (wait > 0) {if (wakeTimer === null) {wakeTimer = clock.setTimeout(() => {wakeTimer = null;drain();}, wait);}return;}nextAt = clock.now() + launchGap;const job = queue.shift();const controller = createAbortController();const timeout = clock.setTimeout(() => controller.abort(), timeoutMs);controllers.add(controller);active++;(async () => {try {const response = await fetchImpl(job.url, {signal: controller.signal,});if (disposed) throw abortError();if (!response.ok) {const error = new Error(`HTTP ${response.status} ${job.url}`);error.status = response.status;if ((response.status === 429 || response.status === 503) &&job.retries < maxRetries) {job.retries++;const retryAfter =response.headers &&typeof response.headers.get === "function" &&response.headers.get("retry-after");defer(retryAfterMs(retryAfter) || launchGap);queue.unshift(job);return;}throw error;}const text = await response.text();if (disposed) throw abortError();job.resolve(text);} catch (error) {job.reject(error);} finally {clock.clearTimeout(timeout);controllers.delete(controller);active--;drain();}})();}};const attachSignal = (promise, signal) => {if (!signal) return promise;if (signal.aborted) return Promise.reject(abortError());return new Promise((resolve, reject) => {const onAbort = () => {cleanup();reject(abortError());};const cleanup = () => signal.removeEventListener("abort", onAbort);signal.addEventListener("abort", onAbort, { once: true });promise.then((value) => {cleanup();resolve(value);},(error) => {cleanup();reject(error);},);});};const text = (url, options) => {if (disposed) return Promise.reject(abortError());let promise = inflight.get(url);if (!promise) {promise = new Promise((resolve, reject) => {queue.push({ url, resolve, reject, retries: 0 });drain();}).finally(() => {if (inflight.get(url) === promise) inflight.delete(url);});inflight.set(url, promise);}return attachSignal(promise, options && options.signal);};const dispose = () => {if (disposed) return;disposed = true;if (wakeTimer !== null) clock.clearTimeout(wakeTimer);wakeTimer = null;const error = abortError();while (queue.length) queue.shift().reject(error);for (const controller of controllers) controller.abort();};return Object.freeze({ text, dispose });}function createProblemIdentityResolver(config) {const { getOrigin, voidAnchorSelector } = config || {};if (typeof getOrigin !== "function")throw new TypeError("Problem Identity requires an origin adapter");const isProblemId = (id) => {if (typeof id !== "string" || !id) return false;if (id.startsWith("AT_")) return true;return /[a-zA-Z]/.test(id) && /[0-9]/.test(id);};const anchorShowsPid = (anchor, pid) => {const first = anchor.firstElementChild;if (first &&first.matches("span.pid") &&(first.innerText || first.textContent || "").trim() === pid)return true;const text = (anchor.innerText ||anchor.textContent ||"").trimStart();if (!text.startsWith(pid)) return false;return !/[A-Za-z0-9_]/.test(text.charAt(pid.length));};const resolve = (anchor) => {if (!anchor || !anchor.matches) return null;if (voidAnchorSelector && anchor.matches(voidAnchorSelector)) {const pid = (anchor.innerText ||anchor.textContent ||"").trim().split(/\s+/)[0];return isProblemId(pid) && anchorShowsPid(anchor, pid)? { pid, kind: "void", key: `void:${pid}` }: null;}const origin = getOrigin();let url;try {url = new URL(anchor.href, origin);} catch (error) {return null;}if (url.origin !== origin) return null;const forumPid = url.searchParams.get("forum");if (forumPid)return isProblemId(forumPid) && anchorShowsPid(anchor, forumPid)? { pid: forumPid, kind: "forum", key: `forum:${url.href}` }: null;const path = url.pathname.match(/^\/problem\/([A-Za-z0-9_]+)\/?$/);const pid = path && path[1];return isProblemId(pid) && anchorShowsPid(anchor, pid)? { pid, kind: "problem", key: `problem:${url.href}` }: null;};return Object.freeze({ resolve });}function createProblemPipeline(config) {const {identity,documentAdapter,routeAdapter,difficultySource,colorForDifficulty,cacheLimit = 1000,createAbortController = () => new AbortController(),logError = () => {},} = config || {};if (!identity || typeof identity.resolve !== "function")throw new TypeError("Problem Pipeline requires a Problem Identity adapter");if (!documentAdapter ||typeof documentAdapter.anchors !== "function" ||typeof documentAdapter.observeAnchors !== "function" ||typeof documentAdapter.applyColor !== "function")throw new TypeError("Problem Pipeline requires a document adapter");if (!difficultySource || typeof difficultySource.text !== "function")throw new TypeError("Problem Pipeline requires a difficulty source");if (typeof colorForDifficulty !== "function")throw new TypeError("Problem Pipeline requires a color adapter");const DIFFICULTY_RE = /"difficulty":\s*(\d+)/;const colors = new Map();const harvestedLists = new WeakSet();let coloringAnchors = new WeakMap();let contentOnlySupport = null;let mounted = false;let generation = 0;let stopObserving = null;let activeController = null;const routeToken = () =>routeAdapter && typeof routeAdapter.token === "function"? routeAdapter.token(): "";const rememberColor = (pid, color) => {if (!pid || !color) return;if (colors.has(pid)) colors.delete(pid);colors.set(pid, color);if (colors.size > cacheLimit) colors.delete(colors.keys().next().value);};const rememberDifficulty = (pid, difficulty) => {if (pid && typeof difficulty === "number")rememberColor(pid, colorForDifficulty(difficulty));};const harvest = () => {if (typeof difficultySource.harvest !== "function") return;const batches = difficultySource.harvest() || [];for (const batch of batches) {if (!batch ||!batch.source ||(typeof batch.source !== "object" &&typeof batch.source !== "function") ||harvestedLists.has(batch.source))continue;const problems =typeof batch.problems === "function"? batch.problems(): batch.problems;for (const problem of problems || [])rememberDifficulty(problem && problem.pid, problem && problem.difficulty);harvestedLists.add(batch.source);}};const fetchDifficulty = async (pid, signal) => {if (contentOnlySupport !== false) {let text;try {text = await difficultySource.text(`/problem/${pid}?_contentOnly=1`,{ signal },);} catch (error) {if (signal.aborted) return null;/* 临时网络错误不能永久降级 _contentOnly。 */}if (text != null) {try {const difficulty =JSON.parse(text)?.currentData?.problem?.difficulty;if (typeof difficulty === "number") {contentOnlySupport = true;return difficulty;}} catch (error) {const htmlDifficulty = text.match(DIFFICULTY_RE);if (htmlDifficulty) {contentOnlySupport = false;return Number(htmlDifficulty[1]);}}}}if (signal.aborted) return null;try {const html = await difficultySource.text(`/problem/${pid}`, { signal });const match = html.match(DIFFICULTY_RE);return match ? Number(match[1]) : null;} catch (error) {if (!signal.aborted) logError(pid, error);return null;}};const getColor = async (pid, signal) => {harvest();if (colors.has(pid)) return colors.get(pid);const difficulty = await fetchDifficulty(pid, signal);if (signal.aborted || difficulty == null) return null;const color = colorForDifficulty(difficulty);rememberColor(pid, color);return color;};const colorAnchor = async (anchor) => {const controller = activeController;if (!controller) return;const taskGeneration = generation;const taskRoute = routeToken();const taskIdentity = identity.resolve(anchor);if (!taskIdentity) return;if (typeof documentAdapter.appliedPid === "function" &&documentAdapter.appliedPid(anchor) === taskIdentity.pid)return;if (coloringAnchors.get(anchor) === taskIdentity.key) return;coloringAnchors.set(anchor, taskIdentity.key);try {const color = await getColor(taskIdentity.pid, controller.signal);const currentIdentity = identity.resolve(anchor);if (!mounted ||generation !== taskGeneration ||routeToken() !== taskRoute ||!color ||(typeof documentAdapter.isConnected === "function" &&!documentAdapter.isConnected(anchor)) ||!currentIdentity ||currentIdentity.key !== taskIdentity.key)return;documentAdapter.applyColor(anchor, taskIdentity.pid, color);} finally {if (coloringAnchors.get(anchor) === taskIdentity.key)coloringAnchors.delete(anchor);}};const acceptAnchors = (anchors) => {for (const anchor of anchors || []) colorAnchor(anchor);};const scan = (root) => acceptAnchors(documentAdapter.anchors(root));const dispose = () => {if (!mounted) return;mounted = false;generation++;if (activeController) activeController.abort();activeController = null;if (stopObserving) stopObserving();stopObserving = null;coloringAnchors = new WeakMap();};const mount = () => {if (mounted) return dispose;mounted = true;generation++;activeController = createAbortController();stopObserving = documentAdapter.observeAnchors(acceptAnchors) || null;scan(documentAdapter.root);return dispose;};return Object.freeze({ mount, dispose });}function createIdeBatchRunner(config) {const {ideDriver,clock,createAbortController = () => new AbortController(),logError = () => {},} = config || {};if (!ideDriver ||typeof ideDriver.prepare !== "function" ||typeof ideDriver.runSample !== "function")throw new TypeError("IDE Batch Runner requires a browser driver");if (!clock ||typeof clock.setTimeout !== "function" ||typeof clock.clearTimeout !== "function")throw new TypeError("IDE Batch Runner requires a clock adapter");let state = "idle";let runId = 0;let mounted = false;let disposed = false;let driving = false;let stale = false;let results = null;let stopMount = null;let mountKey = null;let delay = null;let activeController = null;const cancelDelay = () => {if (!delay) return;clock.clearTimeout(delay.timer);const resolve = delay.resolve;delay = null;resolve(false);};const pause = (ms, taskRunId) =>new Promise((resolve) => {const timer = clock.setTimeout(() => {if (delay && delay.timer === timer) delay = null;resolve(taskRunId === runId && !disposed);}, ms);delay = { timer, resolve };});const isCurrent = (taskRunId, context, signal) =>taskRunId === runId &&!disposed &&!signal.aborted &&(!ideDriver.isCurrent || ideDriver.isCurrent(context));const drive = (taskRunId, action) => {if (taskRunId !== runId || disposed) return;driving = true;try {return action();} finally {driving = false;}};const invalidate = () => {if (state === "idle") return;if (activeController) activeController.abort();activeController = null;runId++;state = "idle";driving = false;cancelDelay();if (typeof ideDriver.cancel === "function") ideDriver.cancel();};const stop = () => {if (state === "preparing" || state === "running") state = "stopping";};const markStale = () => {if (stale || state !== "idle" || !results) return;stale = true;if (typeof ideDriver.markStale === "function") ideDriver.markStale();};const start = async () => {if (disposed || state !== "idle") return;const taskRunId = ++runId;const controller = createAbortController();activeController = controller;let context = null;state = "preparing";try {context = await ideDriver.prepare({runId: taskRunId,signal: controller.signal,});if (taskRunId !== runId || disposed) return;if (!context || context.kind !== "ready") {if (context && context.message && typeof ideDriver.hint === "function")ideDriver.hint(context.message);return;}if (state === "stopping") return;if (!isCurrent(taskRunId, context, controller.signal)) {if (typeof ideDriver.hint === "function")ideDriver.hint("页面已切换");return;}state = "running";stale = false;results = new Array(context.count).fill(null);if (typeof ideDriver.begin === "function")ideDriver.begin(context, results);for (let index = 0; index < context.count; index++) {if (state === "stopping" ||!isCurrent(taskRunId, context, controller.signal))break;if (typeof ideDriver.setRunning === "function")ideDriver.setRunning(context, index);let result;try {result = await ideDriver.runSample(context, index, {runId: taskRunId,signal: controller.signal,drive: (action) => drive(taskRunId, action),isCurrent: () =>isCurrent(taskRunId, context, controller.signal),wait: (ms) => pause(ms, taskRunId),});} catch (error) {if (controller.signal.aborted) break;logError(error);result = { verdict: "UKE", note: String(error) };}if (!isCurrent(taskRunId, context, controller.signal)) break;results[index] = result;if (typeof ideDriver.applyResult === "function")ideDriver.applyResult(context, index, result);if (result.verdict === "CE") {for (let rest = index + 1; rest < context.count; rest++) {results[rest] = {verdict: "CE",output: result.output || "",note: "编译错误",};if (typeof ideDriver.applyResult === "function")ideDriver.applyResult(context, rest, results[rest]);}break;}if (index < context.count - 1 && state !== "stopping") {const continued = await pause(500, taskRunId);if (!continued ||!isCurrent(taskRunId, context, controller.signal))break;}}} catch (error) {if (!controller.signal.aborted) logError(error);} finally {if (activeController === controller) activeController = null;const shouldRestore =context &&taskRunId === runId &&!disposed &&!controller.signal.aborted &&(!ideDriver.isCurrent || ideDriver.isCurrent(context));if (shouldRestore && typeof ideDriver.restore === "function") {try {ideDriver.restore(context);} catch (error) {logError(error);}}if (taskRunId === runId) {state = "idle";driving = false;cancelDelay();if (context && context.kind === "ready" && ideDriver.finish)ideDriver.finish(context, results);}}};const mount = () => {if (disposed) return dispose;const nextMountKey =typeof ideDriver.mountKey === "function"? ideDriver.mountKey(): ideDriver;if (mounted && mountKey === nextMountKey) return dispose;if (mounted) {invalidate();if (stopMount) stopMount();stopMount = null;mounted = false;}mounted = true;mountKey = nextMountKey;if (typeof ideDriver.mount === "function")stopMount =ideDriver.mount({start,stop,invalidate,markStale,isRunning: () => state === "running" || state === "stopping",isDriving: () => driving,}) || null;return dispose;};const unmount = () => {if (!mounted) return;invalidate();if (stopMount) stopMount();stopMount = null;mountKey = null;mounted = false;};const dispose = () => {if (disposed) return;if (mounted) unmount();else invalidate();disposed = true;};const getState = () =>Object.freeze({ state, runId, driving, stale, mounted, disposed });return Object.freeze({mount,unmount,start,stop,markStale,dispose,getState,});}function createSaverTransport(config) {const {baseUrl,fetch: fetchImpl,clock,timeoutMs = 15000,createAbortController = () => new AbortController(),} = config || {};if (typeof fetchImpl !== "function")throw new TypeError("Saver transport requires a fetch adapter");if (!clock ||typeof clock.setTimeout !== "function" ||typeof clock.clearTimeout !== "function")throw new TypeError("Saver transport requires a clock adapter");const fail = (kind, message, extra) =>Object.assign(new Error(message), { kind, ...(extra || {}) });const request = async (path, init, options) => {const controller = createAbortController();const externalSignal = options && options.signal;let timedOut = false;const abortFromCaller = () => controller.abort();if (externalSignal && externalSignal.aborted)throw fail("cancelled", "保存站请求已取消");if (externalSignal)externalSignal.addEventListener("abort", abortFromCaller, {once: true,});const timer = clock.setTimeout(() => {timedOut = true;controller.abort();}, timeoutMs);try {const response = await fetchImpl(baseUrl + path, {...(init || {}),signal: controller.signal,});if (!response.ok)throw fail("transport", `保存站 HTTP ${response.status}`, {status: response.status,});let payload;try {payload = await response.json();} catch (error) {throw fail("malformed-response", "保存站响应不是有效 JSON");}if (!payload || typeof payload.code !== "number")throw fail("malformed-response", "保存站响应格式无效");return payload;} catch (error) {if (error && error.name === "AbortError")throw timedOut? fail("timeout", `保存站请求超时(${timeoutMs / 1000}s)`): fail("cancelled", "保存站请求已取消");if (error && error.kind) throw error;throw fail("transport", String((error && error.message) || error));} finally {clock.clearTimeout(timer);if (externalSignal)externalSignal.removeEventListener("abort", abortFromCaller);}};return Object.freeze({get: (path, options) => request(path, null, options),post: (path, body, options) =>request(path,{method: "POST",headers: body ? { "content-type": "application/json" } : undefined,body: body ? JSON.stringify(body) : undefined,},options,),});}function createSaverProtocol() {const isSuccess = (payload) =>!!(payload &&typeof payload.code === "number" &&payload.code >= 200 &&payload.code < 300);const failureMessage = (payload, fallback) => {const code =payload && typeof payload.code === "number" ? ` ${payload.code}` : "";const message =payload && typeof payload.message === "string" && payload.message.trim()? `:${payload.message.trim()}`: "";return `${fallback}${code}${message}`;};const classifyLookup = (payload) => {if (payload && payload.code === 200 && payload.data)return { kind: "archived", data: payload.data };if (payload && payload.code === 404) return { kind: "missing" };return {kind: "unavailable",reason: failureMessage(payload, "保存站查询失败"),retryable: false,category: "business",};};const classifyAction = (payload, fallback = "保存站拒绝请求") =>isSuccess(payload)? { kind: "accepted" }: {kind: "unavailable",reason: failureMessage(payload, fallback),retryable: true,category: "business",};return Object.freeze({isSuccess,failureMessage,classifyLookup,classifyAction,});}function createSaverWorkflow(config, policy) {const {transport,protocol = createSaverProtocol(),clock,createAbortController = () => new AbortController(),} = config || {};const {pollAttempts = 15,pollIntervalMs = 3000,} = policy || {};if (!transport ||typeof transport.get !== "function" ||typeof transport.post !== "function")throw new TypeError("Saver Workflow requires a transport adapter");if (!clock ||typeof clock.setTimeout !== "function" ||typeof clock.clearTimeout !== "function")throw new TypeError("Saver Workflow requires a clock adapter");let disposed = false;const controllers = new Set();const timers = new Map();const unavailableFromError = (error) => ({kind: "unavailable",reason: String((error && error.message) || error || "保存站暂时不可用"),retryable: !!(error &&(error.kind === "transport" || error.kind === "timeout")),category: (error && error.kind) || "transport",});const unknownFromPost = (error) => ({kind: "unknown",reason: String((error && error.message) || error || "请求结果未知"),retryable: false,category: (error && error.kind) || "transport",});const validateTarget = (type, id) =>(type === "article" || type === "paste") &&typeof id === "string" &&/^[A-Za-z0-9]+$/.test(id);const invalidTarget = () => ({kind: "unavailable",reason: "保存站目标无效",retryable: false,category: "invariant",});const withTask = async (externalSignal, task) => {if (disposed)return {kind: "unavailable",reason: "保存工作流已取消",retryable: true,category: "cancelled",};const controller = createAbortController();const abort = () => controller.abort();if (externalSignal && externalSignal.aborted) abort();else if (externalSignal)externalSignal.addEventListener("abort", abort, { once: true });controllers.add(controller);try {return await task(controller.signal);} finally {controllers.delete(controller);if (externalSignal)externalSignal.removeEventListener("abort", abort);}};const pause = (ms, signal) =>new Promise((resolve) => {if (signal.aborted) return resolve(false);const finish = (value) => {if (!timers.has(timer)) return;clock.clearTimeout(timer);timers.delete(timer);signal.removeEventListener("abort", cancel);resolve(value);};const cancel = () => finish(false);const timer = clock.setTimeout(() => finish(true), ms);timers.set(timer, cancel);signal.addEventListener("abort", cancel, { once: true });});const lookupRaw = async (type, id, signal) => {try {const payload = await transport.get(`/${type}/query/${id}`, { signal });return protocol.classifyLookup(payload);} catch (error) {return unavailableFromError(error);}};const postRaw = async (path, body, signal, fallback) => {try {const payload = await transport.post(path, body, { signal });return protocol.classifyAction(payload, fallback);} catch (error) {if (error && error.kind === "cancelled")return unavailableFromError(error);return unknownFromPost(error);}};const lookup = (type, id, options) => {if (!validateTarget(type, id)) return Promise.resolve(invalidTarget());return withTask(options && options.signal, (signal) =>lookupRaw(type, id, signal),);};const ensureArchived = (type, id, options) => {if (!validateTarget(type, id)) return Promise.resolve(invalidTarget());return withTask(options && options.signal, async (signal) => {const initial = await lookupRaw(type, id, signal);if (initial.kind !== "missing")return initial.kind === "unavailable"? { ...initial, stage: "lookup" }: initial;const created = await postRaw(`/workflow/create/template/${type}-save-pipeline`,{ targetId: id },signal,"保存站拒绝收录请求",);if (created.kind !== "accepted") return { ...created, stage: "create" };if (options && typeof options.onAccepted === "function")options.onAccepted();for (let attempt = 0; attempt < pollAttempts; attempt++) {if (!(await pause(pollIntervalMs, signal)))return {...unavailableFromError({kind: "cancelled",message: "保存工作流已取消",}),stage: "poll",};const result = await lookupRaw(type, id, signal);if (result.kind === "archived") return result;if (result.kind === "missing") continue;if (result.kind === "unavailable" &&result.retryable &&(result.category === "transport" || result.category === "timeout"))continue;return { ...result, stage: "poll" };}return {kind: "unavailable",reason: "保存站在限定时间内未能完成收录。",retryable: true,category: "timeout",stage: "poll",};});};const requestRefresh = (type, id, options) => {if (!validateTarget(type, id)) return Promise.resolve(invalidTarget());return withTask(options && options.signal, (signal) =>postRaw(`/workflow/create/template/${type}-save-pipeline`,{ targetId: id },signal,"保存站拒绝更新请求",),);};const loadComments = (id, options) =>withTask(options && options.signal, async (signal) => {try {const payload = await transport.get(`/article/comments/${id}`, {signal,});if (protocol.isSuccess(payload))return { kind: "available", data: payload.data || {} };return {...protocol.classifyAction(payload, "评论存档读取失败"),kind: "unavailable",};} catch (error) {return unavailableFromError(error);}});const refreshComments = (id, options) =>withTask(options && options.signal, (signal) =>postRaw(`/article/comments/${id}/refresh`,null,signal,"评论刷新请求失败",),);const dispose = () => {if (disposed) return;disposed = true;for (const controller of controllers) controller.abort();controllers.clear();for (const [timer, cancel] of timers) {clock.clearTimeout(timer);cancel();}timers.clear();};return Object.freeze({lookup,ensureArchived,requestRefresh,loadComments,refreshComments,dispose,});}function createBrowserRouteAdapter(config) {const {history: historyAdapter,eventTarget,token: getToken = () => "",logError = () => {},} = config || {};if (!historyAdapter ||typeof historyAdapter.pushState !== "function" ||typeof historyAdapter.replaceState !== "function")throw new TypeError("Route Adapter requires a history adapter");if (!eventTarget ||typeof eventTarget.addEventListener !== "function" ||typeof eventTarget.removeEventListener !== "function")throw new TypeError("Route Adapter requires an event target");const listeners = new Set();const originals = {};const wrappers = {};const wrapperStates = {};let installed = false;const notify = () => {for (const listener of [...listeners]) {try {listener();} catch (error) {logError(error);}}};const install = () => {if (installed) return;installed = true;for (const method of ["pushState", "replaceState"]) {const raw = historyAdapter[method];const wrapperState = { active: true };originals[method] = raw;const wrapped = function (...args) {const result = raw.apply(this, args);if (wrapperState.active) notify();return result;};wrappers[method] = wrapped;wrapperStates[method] = wrapperState;historyAdapter[method] = wrapped;}eventTarget.addEventListener("popstate", notify);eventTarget.addEventListener("hashchange", notify);};const uninstall = () => {if (!installed || listeners.size) return;installed = false;for (const method of ["pushState", "replaceState"]) {if (wrapperStates[method]) wrapperStates[method].active = false;if (originals[method] && historyAdapter[method] === wrappers[method])historyAdapter[method] = originals[method];delete originals[method];delete wrappers[method];delete wrapperStates[method];}eventTarget.removeEventListener("popstate", notify);eventTarget.removeEventListener("hashchange", notify);};return Object.freeze({token: () => getToken(),subscribe: (listener) => {if (typeof listener !== "function")throw new TypeError("Route Adapter listener must be a function");listeners.add(listener);install();let active = true;return () => {if (!active) return;active = false;listeners.delete(listener);uninstall();};},});}function createPageLifecycle(config) {const {routeAdapter,documentAdapter,storage,logError = () => {},} = config || {};if (!routeAdapter || typeof routeAdapter.subscribe !== "function")throw new TypeError("Page Lifecycle requires a route adapter");if (!documentAdapter ||typeof documentAdapter.schedule !== "function" ||typeof documentAdapter.whenReady !== "function")throw new TypeError("Page Lifecycle requires a document adapter");const features = new Map();let disposers = [];let routeDispose = null;let scheduledDispose = null;let readyDispose = null;let generation = 0;let started = false;let disposed = false;let replacing = false;let lastRouteToken = "";const context = () => {const contextGeneration = generation;return Object.freeze({generation,routeToken:typeof routeAdapter.token === "function" ? routeAdapter.token() : "",isCurrent: () =>!disposed && !replacing && generation === contextGeneration,});};const disposeFeatures = () => {const current = disposers;disposers = [];for (let index = current.length - 1; index >= 0; index--) {try {current[index]();} catch (error) {logError("dispose", error);}}};const mountFeatures = () => {if (!started || disposed || replacing) return;const mountContext = context();for (const feature of features.values()) {let enabled = true;try {enabled =typeof feature.enabled === "function"? !!feature.enabled(storage): true;if (!enabled) continue;const dispose = feature.mount(mountContext);if (typeof dispose === "function") disposers.push(dispose);} catch (error) {logError(feature.id, error);}}};const cancelScheduled = () => {if (!scheduledDispose) return;scheduledDispose();scheduledDispose = null;};const releaseReady = (dispose = readyDispose) => {if (dispose === readyDispose) readyDispose = null;if (typeof dispose !== "function") return;try {dispose();} catch (error) {logError("documentReadyDispose", error);}};const remount = () => {if (!started || disposed || replacing) return;cancelScheduled();disposeFeatures();generation++;scheduledDispose =documentAdapter.schedule(() => {scheduledDispose = null;mountFeatures();}) || null;};const handleRoute = () => {if (!started || disposed || replacing) return;const nextRouteToken =typeof routeAdapter.token === "function" ? routeAdapter.token() : "";if (nextRouteToken === lastRouteToken) return;const routeContext = Object.freeze({generation,previousRouteToken: lastRouteToken,routeToken: nextRouteToken,});for (const feature of features.values()) {if (typeof feature.onRoute !== "function") continue;try {feature.onRoute(routeContext);} catch (error) {logError(`${feature.id}:route`, error);}}lastRouteToken = nextRouteToken;remount();};const register = (feature) => {if (!feature ||typeof feature.id !== "string" ||typeof feature.mount !== "function")throw new TypeError("Page Lifecycle feature is invalid");if (features.has(feature.id))throw new Error(`Page Lifecycle feature already registered: ${feature.id}`);features.set(feature.id, feature);if (started && !disposed) remount();return lifecycle;};const start = () => {if (disposed || started) return;started = true;generation++;lastRouteToken =typeof routeAdapter.token === "function" ? routeAdapter.token() : "";routeDispose = routeAdapter.subscribe(handleRoute) || null;mountFeatures();};const replaceDocument = (commit) => {if (disposed || replacing || typeof commit !== "function") return false;cancelScheduled();disposeFeatures();generation++;const replacementGeneration = generation;replacing = true;let afterReady;try {afterReady = commit(context());} catch (error) {replacing = false;logError("replaceDocument", error);return false;}let readyFired = false;let pendingReadyDispose = null;try {const disposeReady = documentAdapter.whenReady(() => {readyFired = true;releaseReady();if (disposed || generation !== replacementGeneration) return;replacing = false;mountFeatures();if (typeof afterReady === "function") {try {afterReady(context());} catch (error) {logError("afterDocumentReady", error);}}});if (typeof disposeReady === "function")pendingReadyDispose = disposeReady;} catch (error) {replacing = false;logError("documentReady", error);return false;}if (readyFired) {releaseReady(pendingReadyDispose);} else readyDispose = pendingReadyDispose;return true;};const dispose = () => {if (disposed) return;disposed = true;cancelScheduled();releaseReady();disposeFeatures();if (routeDispose) routeDispose();routeDispose = null;};const getState = () =>Object.freeze({generation,started,disposed,replacing,featureCount: features.size,mountedCount: disposers.length,});const lifecycle = Object.freeze({register,start,replaceDocument,dispose,getState,});return lifecycle;}function createRestrictedLoadingGate(config) {const { pageAdapter, overlayAdapter } = config || {};if (!pageAdapter ||typeof pageAdapter.currentPath !== "function" ||typeof pageAdapter.isEnabled !== "function" ||typeof pageAdapter.isCandidateRoute !== "function" ||!overlayAdapter ||typeof overlayAdapter.mount !== "function")throw new TypeError("Restricted Loading Gate configuration is invalid");let active = false;let releaseOverlay = null;const start = () => {if (active) return true;if (!pageAdapter.isEnabled() ||!pageAdapter.isCandidateRoute(pageAdapter.currentPath()))return false;const release = overlayAdapter.mount();releaseOverlay = typeof release === "function" ? release : null;active = true;return true;};const release = () => {if (!active) return;active = false;const dispose = releaseOverlay;releaseOverlay = null;if (dispose) dispose();};const getState = () => Object.freeze({ active });return Object.freeze({ start, release, getState });}function createRestrictedDocumentBoot(config) {const {pageAdapter,saverWorkflow,documentBuilder,documentCommitter,pageLifecycle,createAbortController = () => new AbortController(),logError = () => {},} = config || {};if (!pageAdapter || typeof pageAdapter.detect !== "function")throw new TypeError("Restricted Document Boot requires a page adapter");if (!saverWorkflow || typeof saverWorkflow.ensureArchived !== "function")throw new TypeError("Restricted Document Boot requires Saver Workflow");if (!documentBuilder || typeof documentBuilder.prepare !== "function")throw new TypeError("Restricted Document Boot requires a document builder");if (!documentCommitter || typeof documentCommitter.commit !== "function")throw new TypeError("Restricted Document Boot requires a document committer");if (!pageLifecycle || typeof pageLifecycle.replaceDocument !== "function")throw new TypeError("Restricted Document Boot requires Page Lifecycle");let taskId = 0;let activeController = null;let rebuiltPath = "";const isCancelled = (error) =>error &&(error.kind === "cancelled" ||error.name === "AbortError" ||error.category === "cancelled");const mount = (lifecycleContext) => {const currentTask = ++taskId;let info;try {info = pageAdapter.detect();} catch (error) {logError(error);if (typeof pageAdapter.hideLoader === "function")pageAdapter.hideLoader();return () => {};}if (!info) {if (typeof pageAdapter.hideLoader === "function")pageAdapter.hideLoader();return () => {if (typeof documentBuilder.dispose === "function")documentBuilder.dispose();};}const controller = createAbortController();activeController = controller;pageAdapter.showLoader();const current = () =>currentTask === taskId &&!controller.signal.aborted &&(!lifecycleContext || lifecycleContext.isCurrent());(async () => {try {const archive = await saverWorkflow.ensureArchived(info.type, info.id, {signal: controller.signal,onAccepted: () => {if (current())pageAdapter.showLoader("该内容尚未被保存站收录,已自动发起收录…",);},});if (!current()) return;if (archive.kind !== "archived") {if (archive.category === "cancelled") return;if (archive.stage === "lookup")return pageAdapter.showUnavailable(info,`LuoguSP:${archive.reason},未自动发起收录。`,);return pageAdapter.showFailure(info,archive.kind === "unknown"? "收录请求已发送,但保存站未在超时前确认结果,请稍后刷新页面查看。": archive.stage === "create"? "向保存站发起收录请求失败。": archive.reason || "保存站在限定时间内未能完成收录。",);}const prepared = await documentBuilder.prepare(info,archive.data,controller.signal,);if (!current()) return;const replaced = pageLifecycle.replaceDocument(() => {documentCommitter.commit(prepared);rebuiltPath = info.path || "";return () => {if (typeof prepared.afterReady === "function")prepared.afterReady();};});if (!replaced)pageAdapter.showFailure(info,"原生页面提交失败,请刷新页面后重试。",);} catch (error) {if (!current() || isCancelled(error)) return;logError(error);pageAdapter.showFailure(info,error && error.userMessage? error.userMessage: `原生页面装配失败:${error}`,);} finally {if (activeController === controller) activeController = null;}})();return () => {if (currentTask === taskId) {taskId++;controller.abort();if (activeController === controller) activeController = null;}if (typeof documentBuilder.dispose === "function")documentBuilder.dispose();if (typeof pageAdapter.hideLoader === "function")pageAdapter.hideLoader();};};const onRoute = () => {if (rebuiltPath &&pageAdapter.currentPath() !== rebuiltPath &&pageAdapter.isRestrictedRoute(pageAdapter.currentPath()))pageAdapter.reload();};const dispose = () => {taskId++;if (activeController) activeController.abort();activeController = null;rebuiltPath = "";if (typeof documentBuilder.dispose === "function")documentBuilder.dispose();if (typeof pageAdapter.hideLoader === "function")pageAdapter.hideLoader();};const getState = () =>Object.freeze({ taskId, rebuiltPath, running: !!activeController });return Object.freeze({ mount, onRoute, dispose, getState });}function serializeJsonForScript(value) {return JSON.stringify(value).replace(/</g, "\\u003C");}function createRestrictedDocumentCommitter(config) {const { documentAdapter, resourcePolicy } = config || {};if (!documentAdapter ||typeof documentAdapter.open !== "function" ||typeof documentAdapter.write !== "function" ||typeof documentAdapter.close !== "function")throw new TypeError("Document Committer requires a document adapter");if (!resourcePolicy || typeof resourcePolicy.isAllowed !== "function")throw new TypeError("Document Committer requires a resource policy");const committed = new WeakSet();const commit = (prepared) => {if (!prepared ||typeof prepared !== "object" ||typeof prepared.html !== "string" ||!prepared.html.startsWith("<!DOCTYPE html>") ||!prepared.html.includes('<div id="app"') ||committed.has(prepared))throw Object.assign(new Error("受限文档提交数据无效"), {kind: "invariant",});const resourceTags =prepared.html.match(/<(?:script|link)\b[^>]*(?:src|href)\s*=[^>]+>/gi,) || [];const resources = resourceTags.map((tag) => {const match = tag.match(/(?:src|href)\s*=\s*(["'])([^"']+)\1/i);if (!match)throw Object.assign(new Error("受限文档资源地址格式无效"), {kind: "invariant",});return match[2];});if (!resources.every(resourcePolicy.isAllowed))throw Object.assign(new Error("受限文档包含未授权资源"), {kind: "invariant",});committed.add(prepared);try {if (typeof prepared.install === "function") prepared.install();documentAdapter.open();documentAdapter.write(prepared.html);documentAdapter.close();} catch (error) {if (typeof prepared.rollback === "function") prepared.rollback();throw error;}};return Object.freeze({ commit });}function parseRestrictedPasteScaffold(scaffold) {if (typeof scaffold !== "string") return null;const match = (pattern) => {const result = scaffold.match(pattern);return result ? result[1] : null;};const encodedInjection = match(/_feInjection\s*=\s*JSON\.parse\(decodeURIComponent\("([^"]+)"\)\)/,);const configVersionLiteral = match(/window\._feConfigVersion\s*=\s*((?:["']\d+["'])|\d+)\s*;/,);const tagVersionLiteral = match(/window\._tagVersion\s*=\s*((?:["']\d+["'])|\d+)\s*;/,);const csrf = match(/<meta name="csrf-token" content="([^"]+)"/);const loaderCss = match(/<link rel="stylesheet" href="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+loader\.css[^"]*)"/,);const loaderJs = match(/<script src="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+loader\.js[^"]*)"/,);if (!encodedInjection ||!configVersionLiteral ||!tagVersionLiteral ||!loaderJs ||!loaderCss)return null;let injection;try {injection = JSON.parse(decodeURIComponent(encodedInjection)) || {};} catch (error) {return null;}return Object.freeze({injection,configVersionLiteral,tagVersionLiteral,csrf: csrf || "",loaderCss,loaderJs,});}function createRestrictedUrlPolicy() {const validate = (type, id) =>(type === "article" || type === "paste") &&typeof id === "string" &&/^[A-Za-z0-9]+$/.test(id);return Object.freeze({originalUrl: (type, id) => {if (!validate(type, id))throw new TypeError("Restricted original URL target is invalid");return `https://www.luogu.com/${type}/${id}`;},});}function createRestrictedPageDetector(config) {const { path, title, target, urlPolicy } = config || {};if (typeof path !== "function" ||typeof title !== "function" ||typeof target !== "function" ||!urlPolicy ||typeof urlPolicy.originalUrl !== "function")throw new TypeError("Restricted Page Detector configuration is invalid");const detect = () => {const pathname = path();const match = pathname.match(/^\/(article|paste)\/([A-Za-z0-9]+)\/?$/,);if (!match || !title().includes("安全访问中心")) return null;const originalAnchor = String(target() || "").trim();if (!new RegExp(`/${match[1]}/${match[2]}(?:[/?#]|$)`).test(originalAnchor,))return null;return Object.freeze({type: match[1],id: match[2],path: pathname,origUrl: urlPolicy.originalUrl(match[1], match[2]),});};return Object.freeze({ detect });}function createRestrictedReplyFetchAdapter(config) {const {fetch: realFetch,origin,Response: ResponseCtor,URL: URLCtor,lid,replies,} = config || {};if (typeof realFetch !== "function")throw new TypeError("Reply fetch adapter requires fetch");if (typeof ResponseCtor !== "function" ||typeof URLCtor !== "function" ||typeof origin !== "string" ||typeof lid !== "string" ||!/^[A-Za-z0-9]+$/.test(lid) ||!Array.isArray(replies))throw new TypeError("Reply fetch adapter configuration is invalid");const repliesPath = `/article/${lid}/replies`;const wrappedFetch = function (input, init) {const rawUrl =typeof input === "string" || input instanceof URLCtor? String(input): (input && input.url) || "";const method = String((init && init.method) || (input && input.method) || "GET",).toUpperCase();let requestUrl = null;try {requestUrl = new URLCtor(rawUrl, origin);} catch (error) {/* 无法解析的请求交给原 fetch */}if (method !== "GET" ||!requestUrl ||requestUrl.origin !== origin ||requestUrl.pathname !== repliesPath)return realFetch(input, init);let list = replies;const query = requestUrl.searchParams;if (query.get("sort") === "time-d")list = [...replies].sort((left, right) => right.time - left.time);const after = Number(query.get("after"));let start = 0;if (after) {const index = list.findIndex((reply) => reply.id === after);start = index >= 0 ? index + 1 : list.length;}list = list.slice(start, start + 20);return Promise.resolve(new ResponseCtor(JSON.stringify({ replySlice: list }), {status: 200,headers: { "content-type": "application/json" },}),);};return Object.freeze({ fetch: wrappedFetch });}function createRestrictedReplyFetchInstaller(config) {const {host,origin,Response: ResponseCtor,URL: URLCtor,brand = Symbol("LuoguSP restricted replies"),} = config || {};if (!host || typeof host.fetch !== "function")throw new TypeError("Reply fetch installer requires a host fetch");let currentDispose = null;const dispose = () => {if (currentDispose) currentDispose();currentDispose = null;};const install = (lid, replies) => {const installed = host.fetch && host.fetch[brand];if (installed && typeof installed.dispose === "function")installed.dispose();dispose();const realFetch = host.fetch;const adapter = createRestrictedReplyFetchAdapter({fetch: (input, init) => realFetch.call(host, input, init),origin,Response: ResponseCtor,URL: URLCtor,lid,replies,});const interceptingFetch = adapter.fetch;let active = true;const wrapped = function (input, init) {return active? interceptingFetch(input, init): realFetch.call(host, input, init);};const release = () => {active = false;if (host.fetch === wrapped) host.fetch = realFetch;if (currentDispose === release) currentDispose = null;};Object.defineProperty(wrapped, brand, {value: Object.freeze({ dispose: release }),});host.fetch = wrapped;currentDispose = release;return release;};return Object.freeze({ install, dispose });}function createLuoguSPApp(options = {}) {// ============================================================// 配置区(日常维护改这里)// ============================================================25 行未改动chatTrigger: '[slot="trigger"]', // 私信用户名触发点(旧 data-v 选择器已失效,用语义属性)userIntroColumn: ".sidebar-container .main", // 用户主页右侧内容列(补显简介的挂载点)nativeIntro: ".introduction", // 洛谷原生简介元素(存在=已显示,脚本不重复补)voidAnchor: "a[data-v-bade3303][data-v-4842157a]", // 题号着色里特殊的 javascript:void 0 链接// —— IDE 模式(2026-07 columba 前端;锚点与实测时序见下方 IDE 区段注释)——ideToolbar: ".ide-toolbar", // IDE 三个分区(代码/输入/输出)各一条工具栏ideToolbarText: ".title .text", // 工具栏标题文字(代码/输入/输出)ideToolbarActions: ".actions", // 工具栏右侧按钮容器ideRunResult: ".run-result", // 输出工具栏里的 时间+内存 / RE 原因ideTextarea: "textarea.ide-textarea", // 输入/输出面板的文本域ideSampleBlock: ".io-sample-block", // 题面样例块(输入 #N / 输出 #N 各一块)cmContent: ".cm-content", // CodeMirror 6 内容层lentilleContext: "script#lentille-context", // 新版页面数据(JSON,含 problem.samples)// —— 安全访问中心拦截页(接口与接管边界见下方受限内容区段注释)——restrictedUrlPre: "pre#url", // 拦截页里的目标链接文本restrictedGoButton: "button#go", // 拦截页「继续访问」按钮};10 行未改动get: (k) => localStorage.getItem(k) === "true",set: (k, v) => localStorage.setItem(k, String(v)),has: (k) => localStorage.getItem(k) !== null,};const restrictedLoadingGate = options.restrictedLoadingGate || null;function initializeFeatureDefaults() {// 首次运行:所有功能默认开启。只在浏览器显式启动时访问 localStorage。for (const k of FEATURE_LABELS.keys())if (!storage.has(k)) storage.set(k, true);}// ============================================================// 设置面板(页内浮层,替代原来的 window.open + document.write)// ============================================================75 行未改动`;(document.head || document.documentElement).appendChild(style);}let closeSettingsOverlay = null;function openSettings() {if (document.getElementById("luogusp-settings")) return; // 避免重复打开const overlay = document.createElement("div");overlay.id = "luogusp-settings";24 行未改动</div>`;document.body.appendChild(overlay);const boxes = () => overlay.querySelectorAll('input[type="checkbox"]');let closed = false;function esc(e) {if (e.key === "Escape") close();}const close = () => {if (closed) return;closed = true;overlay.remove();document.removeEventListener("keydown", esc);if (closeSettingsOverlay === close) closeSettingsOverlay = null;};closeSettingsOverlay = close;overlay.addEventListener("click", (e) => {const t = e.target;if (t.classList.contains("luogusp-mask")) return close();6 行未改动close();if (confirm("设置已保存,是否立即刷新页面生效?")) location.reload();}});document.addEventListener("keydown", esc);}// 齿轮图标(24×24 Material settings,fill=currentColor 跟随导航文字色)const GEAR_PATH =88 行未改动// ★受限内容接管页 document.write 后旧 body 上的观察器全灭——接管流程会重新调用本函数。// 格式随导航自适应:旧版竖排栏(nav.lfe-body,首页/剪贴板同款)=「插件/设置」两行,// 新版侧栏(nav.sidebar,columba 文章页等)=「插件设置」单行。function watchSettingButton() {let frame = null;const tick = () => {frame = null;try {addSettingButton();} catch (e) {console.error("LuoguSP setting entry:", e);}};const observer = new MutationObserver(() => {if (frame === null) frame = requestAnimationFrame(tick);});observer.observe(document.body, { childList: true, subtree: true });addSettingButton();return () => {observer.disconnect();if (frame !== null) cancelAnimationFrame(frame);document.querySelectorAll(".luogusp-setting-entry").forEach((entry) => (entry.closest("li") || entry).remove());if (closeSettingsOverlay) closeSettingsOverlay();};}// ============================================================// 私信界面 Ctrl+Click 打开用户主页(用户名 + 头像)// ============================================================function addMessageLink() {const bound = new WeakSet(); // 去重,避免重复绑定const uidCache = new Map(); // username -> uid 缓存const cleanups = [];const controllers = new Set();let active = true;const openUser = (uid) => {if (uid) window.open(`/user/${uid}`, "_blank");};2 行未改动el.closest('a[href*="/user/"], a[href*="/space/"]');async function getUidByName(username) {if (uidCache.has(username)) return uidCache.get(username);const controller = new AbortController();controllers.add(controller);try {const res = await fetch(`/api/user/search?keyword=${encodeURIComponent(username)}`,{ signal: controller.signal },);const data = await res.json();const uid = data && data.users && data.users[0] && data.users[0].uid;if (active && !controller.signal.aborted) uidCache.set(username, uid);return uid;} catch (e) {if (!controller.signal.aborted) console.error("LuoguSP getUid:", e);} finally {controllers.delete(controller);}}// 用户名触发点:Ctrl+Click → 按用户名查 uidfunction bindName(trigger) {if (bound.has(trigger) || inUserLink(trigger)) return;bound.add(trigger);const onClick = async (e) => {if (!e.ctrlKey) return;e.preventDefault();e.stopPropagation(); // Ctrl 时才拦,普通点击不影响洛谷原有行为const name = (trigger.textContent || "").trim();const uid = name && (await getUidByName(name));if (active && uid) openUser(uid);};trigger.addEventListener("click", onClick);cleanups.push(() => trigger.removeEventListener("click", onClick));}// 头像:Ctrl+Click → 直接从 src(usericon/{uid})取 uid,无需查接口const AVATAR_RE = /\/usericon\/(\d+)/;function bindAvatar(img) {if (bound.has(img) || inUserLink(img) || !AVATAR_RE.test(img.src || ""))return;bound.add(img);const oldCursor = img.style.cursor;img.style.cursor = "pointer";const onClick = (e) => {if (!e.ctrlKey) return;e.preventDefault();e.stopPropagation();const m = (img.src || "").match(AVATAR_RE); // 点击时再读,兼容虚拟滚动换头像if (m) openUser(m[1]);};img.addEventListener("click", onClick);cleanups.push(() => {img.removeEventListener("click", onClick);img.style.cursor = oldCursor;});}const scan = (root) => {if (!root.querySelectorAll) return;root.querySelectorAll(SELECTORS.chatTrigger).forEach(bindName);root.querySelectorAll("img").forEach(bindAvatar);};scan(document);const observer = new MutationObserver((muts) => {for (const m of muts)for (const n of m.addedNodes)if (n.nodeType === Node.ELEMENT_NODE) {if (n.matches && n.matches(SELECTORS.chatTrigger)) bindName(n);if (n.matches && n.matches("img")) bindAvatar(n);scan(n);}});observer.observe(document, { childList: true, subtree: true });return () => {active = false;for (const controller of controllers) controller.abort();controllers.clear();observer.disconnect();for (const cleanup of cleanups) cleanup();};}// ============================================================// 显示隐藏的个人简介14 行未改动}})(obj, 0);return result;}async function getIntroduction(uid, signal) {// 1) 整页加载:简介就在页面同源 SSR 脚本 JSON 里for (const s of document.querySelectorAll("script")) {const t = (s.textContent || "").trim();if (t[0] !== "{" || t.indexOf('"introduction"') === -1) continue;9 行未改动// 正确姿势是带 x-lentille-request 头。try {const r = await fetch(`/user/${uid}`, {headers: { "x-lentille-request": "content-only" },signal,});const intro = digIntro(await r.json(), uid);if (intro != null) return intro;} catch (e) {if (!signal || !signal.aborted)console.error("LuoguSP intro fetch:", e);}return null;}// 主渲染:优先用 @require 的 marked(真 GFM 解析器:表格+对齐/任务列表/嵌套列表/删除线/自动链接/裸 HTML 全支持)9 行未改动null;const tt = (f, d) => {if (!kx) return null;try {return dp.sanitize(kx.renderToString(f, { throwOnError: false, displayMode: d }),);} catch (e) {return null;}};const math = [];let mathPrefix = "%%LGMATH";while (md.includes(mathPrefix)) mathPrefix += "X";const hold = (h) => `${mathPrefix}${math.push(h) - 1}%%`; // 选择正文中不存在的前缀,避免用户文本伪造占位符const src = md.replace(/\$\$([\s\S]+?)\$\$/g, (m, f) => {const h = tt(f.trim(), true);return h ? hold(h) : m;8 行未改动} catch (e) {return renderMarkdownLite(md);}html = dp.sanitize(html, { ADD_ATTR: ["target"] }); // 消毒:剥离 script/on*/javascript: 等const mathPattern = new RegExp(`${mathPrefix}(\\d+)%%`, "g");return html.replace(/<a /gi, '<a target="_blank" rel="noopener noreferrer" ') // 链接新标签打开.replace(/<img /gi, '<img style="max-width:100%" ') // 图片限宽防溢出.replace(mathPattern, (_, i) => math[i]); // 回填已单独消毒的 KaTeX}// 内置轻量 Markdown → HTML(marked 未加载时的回退;XSS 安全:转义 HTML 实体防注入;URL 仅允许 http(s)/相对,挡 javascript:;// 洛谷允许的少量裸 HTML 走白名单消毒:img/a 校验 URL、安全内联标签去所有属性防 on* 注入、其余标签转义成文本)。27 行未改动return null;}};const spans = []; // 抽出的「原样片段」(代码/公式/白名单裸 HTML),最后回填let spanPrefix = "@@LGB";while (md.includes(spanPrefix)) spanPrefix += "X";const stash = (html) => `${spanPrefix}${spans.push(html) - 1}@@`;const ga = (t, re) => (t.match(re) || [])[1] || ""; // 取标签属性值const inline = (s) =>s.replace(/`([^`]+)`/g, (_, c) => `<code>${c}</code>`)74 行未改动const html = src.split(/\n{2,}/).map((block) => {const b = block.trim();if (new RegExp(`^${spanPrefix}\\d+@@$`).test(b)) return b; // 独占一段的占位(代码块 / 行间公式)const lines = block.split("\n");if (lines.length >= 2 &&/^\s*\|.*\|\s*$/.test(lines[0]) &&12 行未改动return `<blockquote>${inline(lines.map((l) => l.replace(/^>\s?/, "")).join("<br>"))}</blockquote>`; // > 已被 esc 转成 >return `<p>${inline(block).replace(/\n/g, "<br>")}</p>`;}).join("");return html.replace(new RegExp(`${spanPrefix}(\\d+)@@`, "g"),(_, i) => spans[i],); // 回填占位(inline 公式也在此步)}function normalizeCodeLanguageClass(code) {const lang = [...code.classList].find((c) => c.startsWith("language-"));const pre = code.closest("pre");101 行未改动全部展开body.appendChild(content);card.append(header, body);col.appendChild(card);}const introWaiters = new Set();async function showHiddenIntro(expectedRoute, lifecycleContext, signal) {const route = expectedRoute || currentUserRoute();if (!route.uid || !route.isHome) return;const uid = route.uid;const routeKey = route.key;const stillCurrent = () => {const current = currentUserRoute();return ((!signal || !signal.aborted) &&(!lifecycleContext || lifecycleContext.isCurrent()) &¤t.uid === uid && current.key === routeKey && current.isHome);};document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove()); // 清换页残留if (document.querySelector(SELECTORS.nativeIntro)) return; // 原生已显示,不重复补const intro = await getIntroduction(uid, signal);if (!stillCurrent() || !intro || !intro.trim()) return;const place = () => {if (!stillCurrent()) return true; // 请求期间已换页:停止等待,绝不把旧简介挂到新路由if (document.querySelector(".introduction:not(.luogusp-intro-card *)"))return true; // 原生简介已出现(管理员等)→ 别补if (document.querySelector(".luogusp-intro-card")) return true;const col = document.querySelector(SELECTORS.userIntroColumn); // 只挂内层内容列,绝不回退外层全宽(否则内容顶到最左被裁)2 行未改动return true;};if (place()) return;// 内容列尚未渲染(SPA 换页):等它出现再补,8s 后放弃let timer = null;const obs = new MutationObserver(() => {if (place()) cleanup();});const cleanup = () => {obs.disconnect();if (timer !== null) clearTimeout(timer);introWaiters.delete(cleanup);};introWaiters.add(cleanup);obs.observe(document.body, { childList: true, subtree: true });timer = setTimeout(cleanup, 8000);}// SPA 换页时 URL 变但脚本不重跑:监听用户主页 uid 变化补显。function currentUserRoute() {const m = location.pathname.match(/^\/(?:user|space)\/(\d+)/);4 行未改动isHome:!!m && (!hash || hash === "#" || hash === "#home" || hash === "#main"),};}const browserRouteAdapter =options.routeAdapter ||(typeof window === "undefined"? Object.freeze({token: () => "",subscribe: () => () => {},}): createBrowserRouteAdapter({history,eventTarget: window,token: () =>`${location.pathname}${location.search}${location.hash}`,logError: (error) => console.error("LuoguSP route:", error),}));function watchHiddenIntro(lifecycleContext) {const controller = new AbortController();let requestedRouteKey = "";const check = () => {const route = currentUserRoute();const uid = route.uid;if (!uid || !route.isHome) {document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove());requestedRouteKey = "";return;}// 原生简介出现(管理员等原生可见)→ 移除我的卡,避免重复渲染if (document.querySelector(".introduction:not(.luogusp-intro-card *)")) {document.querySelectorAll(".luogusp-intro-card").forEach((e) => e.remove());requestedRouteKey = route.key;return;}if (document.querySelector(".luogusp-intro-card")) {requestedRouteKey = route.key;return;}if (route.key !== requestedRouteKey) {requestedRouteKey = route.key;showHiddenIntro(route, lifecycleContext, controller.signal).catch((e) => {if (!controller.signal.aborted)console.error("LuoguSP intro render:", e);});}};check();let frame = null;const queueCheck = () => {if (frame === null) {frame = requestAnimationFrame(() => {frame = null;check();});}};const observer = new MutationObserver(() => {const route = currentUserRoute();if (route.uid && route.isHome) queueCheck();});observer.observe(document.body, { childList: true, subtree: true });return () => {controller.abort();observer.disconnect();if (frame !== null) cancelAnimationFrame(frame);for (const cleanup of [...introWaiters]) cleanup();document.querySelectorAll(".luogusp-intro-card").forEach((card) => card.remove());};}// ============================================================// 题目难度着色// ============================================================// 单队列 FIFO:300ms 发起间隔、最多 3 并发、15s 超时。const limiter = createGetRequestScheduler({fetch: (url, init) => fetch(url, init),clock: {now: () => Date.now(),setTimeout: (fn, ms) => setTimeout(fn, ms),clearTimeout: (id) => clearTimeout(id),},launchGap: 300,concurrency: 3,timeoutMs: 15000,maxRetries: 1,});const PROBLEM_ANCHOR_SELECTOR = ['a[href*="/problem/"]','a[href*="?forum="]',SELECTORS.voidAnchor,].join(",");const problemIdentity = createProblemIdentityResolver({getOrigin: () => location.origin,voidAnchorSelector: SELECTORS.voidAnchor,});const problemAnchorIdentity = (anchor) => problemIdentity.resolve(anchor);// 把子树中第一处 pid 文本包成 <b>(纯 DOM,避免 innerHTML.replace 误伤属性内同名子串、// 重建整个锚点子树、抖掉已绑定的监听)。返回是否成功包裹。function wrapPidText(root, pid, color) {const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);11 行未改动}return false;}const problemPipeline =typeof document === "undefined"? null: createProblemPipeline({identity: problemIdentity,routeAdapter: {token: () =>`${location.origin}${location.pathname}${location.search}`,},difficultySource: {text: (path, options) => limiter.text(path, options),// 记录列表 / 练习页已把整批难度注入 _feInstance;返回来源对象与纯题目数据,// 去重和 LRU 均由 Problem Pipeline Module 持有,不污染洛谷原始数组。harvest: () => {const cur = window._feInstance && window._feInstance.currentData;if (!cur) return [];const batches = [];const url = location.href;if (url.startsWith("https://www.luogu.com.cn/record/list")) {const list = cur.records && cur.records.result;if (list && typeof list === "object")batches.push({source: list,problems: () => [...list].map((item) => ({pid: item.problem && item.problem.pid,difficulty: item.problem && item.problem.difficulty,})),});}if (/^https:\/\/www\.luogu\.com\.cn\/user\/\d+#practice$/.test(url)) {for (const key of ["submittedProblems", "passedProblems"]) {const list = cur[key];if (list && typeof list === "object")batches.push({ source: list, problems: () => [...list] });}}return batches;},},colorForDifficulty: (difficulty) => diffColor(difficulty),logError: (pid, error) =>console.error("LuoguSP difficulty:", pid, error),documentAdapter: {root: document,anchors: (root) => {if (!root || !root.querySelectorAll) return [];const anchors = [];if (root.matches && root.matches(PROBLEM_ANCHOR_SELECTOR))anchors.push(root);root.querySelectorAll(PROBLEM_ANCHOR_SELECTOR).forEach((anchor) => anchors.push(anchor));return anchors;},observeAnchors: (accept) => {const observer = new MutationObserver((mutations) => {const anchors = new Set();for (const mutation of mutations) {if (mutation.type === "childList") {for (const node of mutation.addedNodes) {if (node.nodeType !== Node.ELEMENT_NODE) continue;if (node.matches && node.matches(PROBLEM_ANCHOR_SELECTOR))anchors.add(node);if (node.querySelectorAll)node.querySelectorAll(PROBLEM_ANCHOR_SELECTOR).forEach((anchor) => anchors.add(anchor));}} else if (mutation.type === "characterData") {const span = mutation.target.parentElement;const anchor =span &&span.matches &&span.matches("span.pid") &&span.closest("a[href]");if (anchor) anchors.add(anchor);} else if (mutation.type === "attributes") {anchors.add(mutation.target);}}accept(anchors);});observer.observe(document, {childList: true,subtree: true,characterData: true,attributes: true,attributeFilter: ["href"],});return () => observer.disconnect();},appliedPid: (anchor) => anchor.dataset.luoguspPid,isConnected: (anchor) => anchor.isConnected,applyColor: (a, pid, color) => {// 虚拟列表可能在请求期间复用锚点;Problem Pipeline 已复核身份后才会到这里。const span = a.children[0];if (span &&span.matches("span.pid") &&(span.innerText || span.textContent || "").trim() === pid) {span.style.color = color;span.style.fontWeight = "bold";a.dataset.luoguspPid = pid;} else if (wrapPidText(a, pid, color)) {a.dataset.luoguspPid = pid;}},},});// ============================================================// IDE 一键测试样例// 洛谷新版题目页(columba)IDE 模式(#ide)下,逐组驱动题面样例的原生「运行」,// 结果从输出面板 DOM 捕获(结果经页面常驻 WS 推送,网络层拿不到——勿改走拦截)。// 锚点与配色均来自 2026-07 洛谷 columba IDE 的真实页面观测。// ============================================================function ideToolbarByTitle(title) {for (const tb of document.querySelectorAll(SELECTORS.ideToolbar)) {const t = tb.querySelector(SELECTORS.ideToolbarText);if (t && t.textContent.trim() === title) return tb;}return null;}const IDE_VIEW = {activeTab: "custom", // custom=原生输入输出 / samples=样例面板tabBar: null,panel: null,ioLayout: null, // 原生 输入|输出 水平分栏(tab 切换时显隐)rowsEl: null,summaryEl: null,stopBtn: null,};function ideModeActive() {return (14 行未改动function currentPid() {const m = location.pathname.match(/^\/problem\/([A-Za-z0-9_]+)/);return m ? m[1] : "";}async function getIdeSamples(signal) {const pid = currentPid();if (!pid) return null;const p = lentilleProblem();if (p && p.pid === pid && Array.isArray(p.samples)) return p.samples;2 行未改动// 正确姿势是带 x-lentille-request 头(真机实测 2026-07-22)。try {const res = await fetch(`/problem/${pid}`, {headers: { "x-lentille-request": "content-only" },signal,});const json = await res.json();const prob = json && json.data && json.data.problem;if (prob && Array.isArray(prob.samples)) return prob.samples;} catch (e) {if (!signal || !signal.aborted)console.error("LuoguSP ide samples:", e);}return null;}function sampleRunButtons() {17 行未改动return content.textContent || "";}let ideSubmitWaiter = null;let ideSubmitPatchDispose = null;function cancelIdeSubmitWaiter(runId) {if (!ideSubmitWaiter) return;if (runId != null && ideSubmitWaiter.runId !== runId) return;const waiter = ideSubmitWaiter;ideSubmitWaiter = null;waiter.resolve(null);}function installIdeSubmitObserver() {if (ideSubmitPatchDispose) return ideSubmitPatchDispose;const rawOpen = XMLHttpRequest.prototype.open;const rawSend = XMLHttpRequest.prototype.send;const submitRequests = new WeakMap();let active = true;const open = function (method, url) {if (active)submitRequests.set(this,typeof url === "string" && url.indexOf("/api/ide_submit") !== -1,);return rawOpen.apply(this, arguments);};const send = function () {if (active && submitRequests.get(this))this.addEventListener("loadend", () => {if (ideSubmitWaiter) {const w = ideSubmitWaiter;ideSubmitWaiter = null;w.resolve(this.status);}});return rawSend.apply(this, arguments);};XMLHttpRequest.prototype.open = open;XMLHttpRequest.prototype.send = send;const dispose = () => {active = false;cancelIdeSubmitWaiter();if (XMLHttpRequest.prototype.open === open)XMLHttpRequest.prototype.open = rawOpen;if (XMLHttpRequest.prototype.send === send)XMLHttpRequest.prototype.send = rawSend;if (ideSubmitPatchDispose === dispose) ideSubmitPatchDispose = null;};ideSubmitPatchDispose = dispose;return dispose;}function waitIdeSubmit(ms, runId) {cancelIdeSubmitWaiter();return new Promise((resolve) => {const timer = setTimeout(() => {if (ideSubmitWaiter && ideSubmitWaiter.resolve === fn)ideSubmitWaiter = null;resolve(null);}, ms);const fn = (status) => {clearTimeout(timer);resolve(status);};ideSubmitWaiter = { runId, resolve: fn };});}function outputParts() {const tb = ideToolbarByTitle("输出");if (!tb) return null;const actions = tb.querySelector(SELECTORS.ideToolbarActions);5 行未改动? tb.parentElement.querySelector(SELECTORS.ideTextarea): null,};}// 完成锚点:胶囊 存在→消失→重现(实测清空 300~560ms、结果 1~3.5s)// 注意:此处不看 stopReq——设计口径是「当前组跑完即停」,停止只在组间生效async function waitIdePill(present,timeoutMs,isCurrent = () => true,wait,) {const t0 = Date.now();while (Date.now() - t0 < timeoutMs) {if (!isCurrent()) return null;const parts = outputParts();if (!parts) return null; // IDE 已卸载if (!!parts.pill === present) return parts.pill || true;if (!(await wait(150))) return null;}return null;}async function runOneSample(runBtn, runId, drive, isCurrent, wait) {const before = outputParts();if (!before) return { verdict: "UKE", note: "IDE 面板不存在" };const hadPill = !!before.pill;let submitP = waitIdeSubmit(10000, runId);drive(() => runBtn.click());let status = await submitP;if (status === 429) {if (!(await wait(3000))) return { verdict: "UKE", note: "页面已切换" };if (!isCurrent()) return { verdict: "UKE", note: "页面已切换" };submitP = waitIdeSubmit(10000, runId);drive(() => runBtn.click());status = await submitP;}if (status == null || status < 200 || status >= 300)return {verdict: "UKE",note: status == null ? "未观测到提交请求" : `提交失败 HTTP ${status}`,};if (hadPill &&(await waitIdePill(false, 5000, isCurrent, wait)) === null)return { verdict: "UKE", note: "旧结果未清空,疑似运行未开始" };const pill = await waitIdePill(true, 30000, isCurrent, wait);if (!pill || pill === true)return { verdict: "UKE", note: "30s 未返回结果" };const parts = outputParts();return {3 行未改动output: parts.textarea ? parts.textarea.value : "",};}let ideHintTimer = null;function ideBatchHint(msg, running = false) {const btn = document.querySelector(".luogusp-ide-batch-btn");if (!btn) return;const old = btn.textContent;btn.textContent = msg;btn.disabled = true;if (ideHintTimer !== null) clearTimeout(ideHintTimer);ideHintTimer = setTimeout(() => {ideHintTimer = null;btn.textContent = old;btn.disabled = running;}, 1500);}// 判定口径同洛谷:CRLF 归一、去行尾空格、去末尾空行。仅用于 diff 渲染与交叉校验,// 最终判定以原生胶囊为准(AC/WA 由洛谷前端本地比较)。function normalizeIdeOut(s) {return String(s == null ? "" : s).replace(/\r\n?/g, "\n").split("\n")40 行未改动);p.detail.innerHTML = "";p.detail.classList.remove("luogusp-ide-log");if (r.verdict === "CE") {// CE:不显示三栏,直接展示从输出框捕获的编译日志p.meta.textContent = "";p.detail.classList.add("luogusp-ide-log");p.detail.appendChild(idePane(18 行未改动}if (r.verdict === "RE" && r.detail) {const note = document.createElement("p");note.className = "luogusp-ide-note";note.textContent = r.detail; // RE 原因位于原生 run-resultp.detail.appendChild(note);p.meta.textContent = "";}const expLines = normalizeIdeOut(sample[1]).split("\n");15 行未改动),);}function finishIdeSummary(results) {if (!IDE_VIEW.summaryEl || !results) return;const rs = results;const counts = {};let ac = 0,tested = 0;rs.forEach((r) => {11 行未改动const p = ideRowParts(i);if (p) p.pill.textContent = "未测";});}IDE_VIEW.summaryEl.textContent = text;const firstBad = rs.findIndex((r) => r && r.verdict !== "AC");if (firstBad !== -1) expandIdeRow(firstBad);else if (IDE_VIEW.rowsEl)IDE_VIEW.rowsEl.querySelectorAll(".luogusp-ide-row.open").forEach((r) => r.classList.remove("open"));}function showIdeStale() {if (IDE_VIEW.summaryEl && document.contains(IDE_VIEW.summaryEl))IDE_VIEW.summaryEl.textContent += " · 结果可能已过期,建议重新测试";}function hookIdeStaleAndGuard(controls) {// 代码变更 → 过期标注(CM6 是 contenteditable,input/keydown 均会冒泡)const stale = (e) => {if (e.target && e.target.closest && e.target.closest(SELECTORS.cmContent))controls.markStale();};document.addEventListener("input", stale, true);document.addEventListener("keydown", stale, true);// 批测中拦掉用户手点原生 运行/自测(程序化点击带 driving 标记放行)const guard = (e) => {if (!controls.isRunning() || controls.isDriving()) return;const t =e.target &&e.target.closest &&e.target.closest(`${SELECTORS.ideSampleBlock} a, ${SELECTORS.ideToolbar} a.run`,);if (t) {e.preventDefault();e.stopPropagation();}};document.addEventListener("click", guard, true);return () => {document.removeEventListener("input", stale, true);document.removeEventListener("keydown", stale, true);document.removeEventListener("click", guard, true);};}function mountIdeButton(controls) {const tb = ideToolbarByTitle("代码");if (!tb) return;const actions = tb.querySelector(SELECTORS.ideToolbarActions);if (!actions || actions.querySelector(".luogusp-ide-batch-btn")) return;8 行未改动btn.disabled = false;btn.addEventListener("click", (e) => {e.preventDefault();e.stopPropagation();controls.start();});actions.insertBefore(btn, selfTest);}function mountIdeTabs(controls) {if (IDE_VIEW.tabBar && document.contains(IDE_VIEW.tabBar)) return;const inputTb = ideToolbarByTitle("输入");if (!inputTb) return;const ioLayout = inputTb.closest(".panel-layout"); // 底部 输入|输出 水平分栏const host = ioLayout && ioLayout.parentElement;41 行未改动});headBtns.appendChild(b);return b;};IDE_VIEW.stopBtn = mkBtn("停止", "luogusp-ide-stop", controls.stop);IDE_VIEW.stopBtn.style.display = "none";mkBtn("重新测试", "luogusp-ide-rerun", controls.start);host.insertBefore(tabBar, ioLayout);host.appendChild(panel);IDE_VIEW.tabBar = tabBar;IDE_VIEW.panel = panel;IDE_VIEW.ioLayout = ioLayout;IDE_VIEW.rowsEl = panel.querySelector(".luogusp-ide-rows");IDE_VIEW.summaryEl = panel.querySelector(".luogusp-ide-summary");syncIdeTabVisibility();}function switchIdeTab(tab) {IDE_VIEW.activeTab = tab;syncIdeTabVisibility();}function syncIdeTabVisibility() {const { tabBar, panel, ioLayout } = IDE_VIEW;if (!tabBar || !document.contains(tabBar) || !panel || !ioLayout) return;const samples = IDE_VIEW.activeTab === "samples";ioLayout.style.display = samples ? "none" : "";panel.style.display = samples ? "" : "none";tabBar.querySelectorAll(".luogusp-ide-tab").forEach((t) => {t.classList.toggle("on", (t.dataset.tab === "samples") === samples);4 行未改动"background-color:#bfbfbf;border-color:#b3b3b3;color:#fff;";const IDE_PILL_RUN ="background-color:#3498db;border-color:#2f89c5;color:#fff;";function renderIdeRows(samples) {const rowsEl = IDE_VIEW.rowsEl;if (!rowsEl) return;rowsEl.innerHTML = samples.map((s, i) => `19 行未改动});}function ideRowParts(i) {const row =IDE_VIEW.rowsEl &&IDE_VIEW.rowsEl.querySelector(`.luogusp-ide-row[data-idx="${i}"]`);if (!row) return null;return {row,pill: row.querySelector(".luogusp-ide-pill"),meta: row.querySelector(".luogusp-ide-meta"),detail: row.querySelector(".luogusp-ide-detail"),};}function expandIdeRow(i) {if (!IDE_VIEW.rowsEl) return;IDE_VIEW.rowsEl.querySelectorAll(".luogusp-ide-row.open").forEach((r) => r.classList.remove("open"));const p = ideRowParts(i);if (p) p.row.classList.add("open");}function ensureIdeBatchUI(controls) {if (!ideModeActive()) {unmountIdeBatchUI();controls.invalidate();return;}mountIdeButton(controls);mountIdeTabs(controls);syncIdeTabVisibility();}function unmountIdeBatchUI() {IDE_VIEW.activeTab = "custom"; // 复位,防再次进入时默认落在空面板IDE_VIEW.tabBar = IDE_VIEW.panel = IDE_VIEW.ioLayout = null;IDE_VIEW.rowsEl = IDE_VIEW.summaryEl = IDE_VIEW.stopBtn = null;}const ideBrowserDriver = {mountKey: () => document.body,prepare: async ({ runId, signal }) => {mountIdeTabs(ideBrowserDriver.controls);const pid = currentPid();const routeToken = `${location.pathname}${location.search}${location.hash}`;const samples = await getIdeSamples(signal);if (!pid ||currentPid() !== pid ||`${location.pathname}${location.search}${location.hash}` !==routeToken ||!ideModeActive())return { kind: "hint", message: "页面已切换" };if (!samples || !samples.length)return { kind: "hint", message: "本题无样例" };if (!readIdeCode().trim())return { kind: "hint", message: "代码为空" };const runButtons = sampleRunButtons();if (!runButtons.length)return { kind: "hint", message: "找不到样例运行按钮" };const count = Math.min(samples.length, runButtons.length);if (runButtons.length !== samples.length)console.error("LuoguSP ide batch: 样例数与运行按钮数不一致",samples.length,runButtons.length,);const inputToolbar = ideToolbarByTitle("输入");const input =inputToolbar && inputToolbar.parentElement? inputToolbar.parentElement.querySelector(SELECTORS.ideTextarea): null;const codeToolbar = ideToolbarByTitle("代码");const actions =codeToolbar && codeToolbar.querySelector(SELECTORS.ideToolbarActions);const selfTest = actions? [...actions.querySelectorAll("button")].find((button) => (button.textContent || "").trim() === "自测",): null;return {kind: "ready",runId,pid,routeToken,samples,runButtons,count,input,inputSnapshot: input ? input.value : null,batchButton: document.querySelector(".luogusp-ide-batch-btn"),selfTest,};},isCurrent: (context) =>ideModeActive() &¤tPid() === context.pid &&`${location.pathname}${location.search}${location.hash}` ===context.routeToken,hint: (message) => ideBatchHint(message),begin: (context) => {if (context.batchButton) context.batchButton.disabled = true;if (context.selfTest) context.selfTest.disabled = true;if (IDE_VIEW.stopBtn) IDE_VIEW.stopBtn.style.display = "";switchIdeTab("samples");renderIdeRows(context.samples);if (IDE_VIEW.summaryEl) IDE_VIEW.summaryEl.textContent = "测试中…";},setRunning: (_context, index) => {const parts = ideRowParts(index);if (parts) {parts.pill.setAttribute("style", IDE_PILL_RUN);parts.pill.textContent = "运行中";}expandIdeRow(index);},runSample: async (context, index, task) => {try {return await runOneSample(context.runButtons[index],task.runId,task.drive,task.isCurrent,task.wait,);} catch (error) {cancelIdeSubmitWaiter(task.runId);throw error;}},applyResult: (context, index, result) =>applyIdeResult(index, result, context.samples[index]),restore: (context) => {if (context.input && context.inputSnapshot != null) {context.input.value = context.inputSnapshot;context.input.dispatchEvent(new Event("input", { bubbles: true }));}},finish: (context, results) => {if (context.batchButton) context.batchButton.disabled = false;if (context.selfTest) context.selfTest.disabled = false;if (IDE_VIEW.stopBtn) IDE_VIEW.stopBtn.style.display = "none";finishIdeSummary(results);},cancel: () => cancelIdeSubmitWaiter(),markStale: showIdeStale,mount: (controls) => {ideBrowserDriver.controls = controls;const unpatchSubmit = installIdeSubmitObserver();const unhook = hookIdeStaleAndGuard(controls);let frame = null;const tick = () => {frame = null;try {ensureIdeBatchUI(controls);} catch (error) {console.error("LuoguSP ide batch:", error);}};const queue = () => {if (frame === null) frame = requestAnimationFrame(tick);};const observer = new MutationObserver(() => {if (location.hash === "#ide" ||IDE_VIEW.tabBar ||controls.isRunning())queue();});observer.observe(document.body, { childList: true, subtree: true });ensureIdeBatchUI(controls);return () => {observer.disconnect();unpatchSubmit();unhook();if (ideHintTimer !== null) {clearTimeout(ideHintTimer);ideHintTimer = null;}if (frame !== null) cancelAnimationFrame(frame);cancelIdeSubmitWaiter();unmountIdeBatchUI();};},};const idePreparation = options.idePreparationAdapter;const ideDriver = idePreparation? {prepare: async ({ signal }) => {idePreparation.mountTabs();const pid = idePreparation.currentPid();const samples = await idePreparation.loadSamples(signal);if (!pid ||idePreparation.currentPid() !== pid ||!idePreparation.isModeActive())return { kind: "hint", message: "页面已切换" };if (!samples || !samples.length)return { kind: "hint", message: "本题无样例" };return { kind: "ready", count: 0, pid, samples };},isCurrent: () => true,hint: (message) => idePreparation.hint(message),runSample: async () => ({ verdict: "UKE" }),}: ideBrowserDriver;const ideBatchRunner = createIdeBatchRunner({ideDriver,clock: {setTimeout: (fn, ms) => setTimeout(fn, ms),clearTimeout: (id) => clearTimeout(id),},logError: (error) => console.error("LuoguSP ide batch:", error),});const startIdeBatch = () => ideBatchRunner.start();// ============================================================// 受限文章/剪贴板直接显示(原生壳注入)// 国内站访问非本人/未审核的 /article、/paste 会落在「安全访问中心」拦截页// (独立静态页、零全站样式、无 CSP)。本功能在拦截页上重建官方页面:12 行未改动// 作者数据走 .cn 同源 /api/user/search(owner 要求不吃保存站/国际站的用户数据)。// ★保存站硬边界:payload 的 createdAt 是入档时间,非原文发布时间(无接口可取原始时间)。// ============================================================const SAVER_API = "https://api.luogu.me";const saverClock = {setTimeout: (fn, ms) => setTimeout(fn, ms),clearTimeout: (id) => clearTimeout(id),};const saverTransport = createSaverTransport({baseUrl: SAVER_API,fetch: (url, init) => fetch(url, init),clock: saverClock,timeoutMs: 15000,});const saverProtocol = createSaverProtocol();const saverWorkflow = createSaverWorkflow({transport: saverTransport,protocol: saverProtocol,clock: saverClock,});const restrictedUrlPolicy = createRestrictedUrlPolicy();// 拦截页判定:URL 形态 + 标题 + pre#url 内容三重锚点;不满足=正常页面,绝不接管const restrictedPageDetector = createRestrictedPageDetector({path: () => location.pathname,title: () => document.title,target: () => {const pre = document.querySelector(SELECTORS.restrictedUrlPre);return pre ? (pre.textContent || "").trim() : "";},urlPolicy: restrictedUrlPolicy,});const RST_LOADER_CSS =".luogusp-rst-loader{position:fixed;inset:0;z-index:2147483000;background:#f5f5f5;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;color:#595959;font:14px/1.5 -apple-system,BlinkMacSystemFont,\"Helvetica Neue\",\"PingFang SC\",\"Noto Sans SC\",\"Microsoft YaHei\",sans-serif;}" +".luogusp-rst-spinner{width:36px;height:36px;border:3px solid rgba(52,152,219,.25);border-top-color:#3498db;border-radius:50%;animation:luogusp-rst-spin .8s linear infinite;}" +"@keyframes luogusp-rst-spin{to{transform:rotate(360deg);}}" +"@media (prefers-reduced-motion:reduce){.luogusp-rst-spinner{animation-duration:1.8s;}}";const RST_LOADER_CONTENT_HTML ='<div class="luogusp-rst-spinner" aria-hidden="true"></div><div class="msg">加载中…</div>';const RST_LOADER_HTML =`<div id="luogusp-rst-loader" class="luogusp-rst-loader" role="status" aria-live="polite">${RST_LOADER_CONTENT_HTML}</div>`;// 最小自有样式:加载层/失败卡(注入拦截页文档),扩展按钮样式随壳 HTML 走(见 RST_EXTRA_CSS)function injectRstStyle() {if (document.getElementById("luogusp-rst-style")) return;const style = document.createElement("style");style.id = "luogusp-rst-style";style.textContent = `${RST_LOADER_CSS}.luogusp-rst-plain{margin:0;background:#f5f5f5;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Helvetica Neue","PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;color:#404040;}.luogusp-rst-plain a{color:#3498db;text-decoration:none;}.luogusp-rst-plaincard{max-width:640px;margin:15vh auto 0;background:#fff;border-radius:4px;box-shadow:0 1px 3px rgba(26,26,26,.1);padding:1.5em;}.luogusp-rst-note{color:#999;font-size:12px;text-align:center;margin:24px 0;}2 行未改动}// 扩展按钮样式(写进壳文档;蓝色=与原生灰色互动钮区分,owner 拍板)。// ★button-2line 的官方规则是 data-v 作用域的,注入节点吃不到 → 布局自带(镜像官方值)。const RST_EXTRA_CSS =RST_LOADER_CSS +".luogusp-rst-abtn{display:flex;flex-direction:column;align-items:center;margin:0 1em;cursor:pointer;}" +".luogusp-rst-abtn .icon{font-size:1.25em;margin-bottom:.3em;}" +".luogusp-rst-abtn .text{text-align:center;font-size:.75em;}" +".luogusp-rst-abtn>*{color:#3498db !important;}" +31 行未改动// 作者等用户数据一律走国内站同源接口(owner 要求:不吃保存站/国际站的用户数据;头像也全走 .cn CDN)。// 接口=/api/user/search?keyword={uid}(拦截页源实测可用;旧 /user/{uid}?_contentOnly=1 已死,返回 HTML),// 返回 userSummary:{uid,name,avatar,slogan,badge,color,ccfLevel,xcpcLevel,…}。失败回退存档快照。const rstUserCache = new Map();async function rstFetch(input, signal) {const controller = new AbortController();let timedOut = false;const cancel = () => controller.abort();if (signal && signal.aborted)throw Object.assign(new Error("受限文档准备已取消"), {kind: "cancelled",});if (signal) signal.addEventListener("abort", cancel, { once: true });const timer = setTimeout(() => {timedOut = true;controller.abort();}, 15000);try {return await fetch(input, { signal: controller.signal });} catch (error) {if (error && error.name === "AbortError")throw Object.assign(new Error(timedOut ? "洛谷页面数据请求超时" : "受限文档准备已取消"),{ kind: timedOut ? "timeout" : "cancelled" },);throw error;} finally {clearTimeout(timer);if (signal) signal.removeEventListener("abort", cancel);}}async function rstCnUser(uid, signal) {if (!uid) return null;if (rstUserCache.has(uid)) return rstUserCache.get(uid);let user = null;try {const res = await rstFetch(`/api/user/search?keyword=${encodeURIComponent(uid)}`,signal,);const json = await res.json();const list = (json && json.users) || [];user = list.find((u) => u && Number(u.uid) === Number(uid)) || null;} catch (e) {if (e && e.kind === "cancelled") throw e;/* 回退存档快照 */}rstUserCache.set(uid, user);return user;16 行未改动background: "",};}// 加载动效覆盖层:接管 document-start 早期遮罩,并跨 document.write 保持到原生内容锚点就绪function rstShowLoader(text) {injectRstStyle();let el = document.getElementById("luogusp-rst-loader");if (!el) {el = document.createElement("div");el.id = "luogusp-rst-loader";el.className = "luogusp-rst-loader";el.setAttribute("role", "status");el.setAttribute("aria-live", "polite");el.innerHTML = RST_LOADER_CONTENT_HTML;(document.body || document.documentElement).appendChild(el);}el.querySelector(".msg").textContent = text || "加载中…";if (restrictedLoadingGate) restrictedLoadingGate.release();}function rstHideLoader() {const el = document.getElementById("luogusp-rst-loader");if (el) el.remove();if (restrictedLoadingGate) restrictedLoadingGate.release();}function rstShowUnavailableTip(info, message) {rstBuildFailure(info, message);}function rstBuildFailure(info, reason) {rstHideLoader();document.title =(info.type === "article" ? "文章" : "云剪贴板") + " - 洛谷";document.body.className = "luogusp-rst-plain";document.body.innerHTML = `<div class="luogusp-rst-plaincard"><h1 style="font-size:20px;margin:0 0 10px;">未能获取内容</h1><p></p><p>可能原因:内容未公开、未通过审核,或保存站暂时不可用。</p><p><a class="luogusp-rst-original" rel="noopener noreferrer">前往国际站查看原文 →</a></p><p class="luogusp-rst-note">此页面由 LuoguSP 生成 · 数据来源:洛谷保存站</p></div>`;document.querySelector(".luogusp-rst-plaincard p").textContent =String(reason);document.querySelector(".luogusp-rst-original").href = info.origUrl;}// 壳骨架收割:候选源逐个尝试(2026-07-22 实测:/ranking、/discuss 已迁 columba;// /image、/theme/list 仍为 lfe。任一命中即用;全挂=降级失败卡)async function rstHarvest(kind, signal) {const sources =kind === "columba" ? ["/ranking", "/discuss"] : ["/image", "/theme/list"];const marker = kind === "columba" ? "lentille-context" : "_feInjection";for (const src of sources) {try {const res = await rstFetch(src, signal);const html = await res.text();if (html.includes(marker)) return html;} catch (e) {if (e && e.kind === "cancelled") throw e;/* 换下一个源 */}}return null;}// 嵌入 <script> 的 JSON 防拆壳(内容里出现 </script> 会截断壳文档)const rstPreparationError = (message) =>Object.assign(new Error(message), {kind: "dom-drift",userMessage: message,});function rstTrustedCdnUrl(value) {try {const url = new URL(value);return (url.protocol === "https:" &&url.origin === "https://fecdn.luogu.com.cn");} catch (error) {return false;}}const rstSafeCsrf = (value) =>typeof value === "string" && !/["'<>\s]/.test(value);const rstEscapeHtmlText = (value) =>String(value).replace(/&/g, "&").replace(/</g, "<");// 评论接口桩:官方文章组件启动后会 GET /article/{lid}/replies(?sort=&after=)。// window.fetch 包装器不随 document.write 重建,天然对新文档生效;其余请求全部放行。const rstReplyFetchInstaller =typeof window === "undefined"? null: createRestrictedReplyFetchInstaller({host: window,origin: location.origin,Response,URL,});const rstDisposeReplyStub = () => {if (rstReplyFetchInstaller) rstReplyFetchInstaller.dispose();};function rstStubReplies(lid, comments) {const mapped = comments.map((c, i) => {const a = c.author || {};return {2 行未改动time: Number(c.time) || 0,content: String(c.content || ""),};});return rstReplyFetchInstaller? rstReplyFetchInstaller.install(lid, mapped): () => {};}// 文章页:合成 lentille-context(template article.show)+ 官方 columba 前端async function rstBootArticle(info, data, signal) {const [scaffold, cnUser, commentsResult] = await Promise.all([rstHarvest("columba", signal),rstCnUser(data.authorId, signal),saverWorkflow.loadComments(info.id, { signal }),]);if (!scaffold)throw rstPreparationError("无法获取洛谷页面骨架,暂不能就地渲染。");const pick = (re) => {const m = scaffold.match(re);return m ? m[1] : null;};16 行未改动...scaffold.matchAll(/<link rel="stylesheet" href="(https:\/\/fecdn\.luogu\.com\.cn\/[^"]+)"/g,),].map((m) => m[1]);if (!ctxRaw ||!scripts.length ||!scripts.every(rstTrustedCdnUrl) ||!cssLinks.every(rstTrustedCdnUrl) ||!rstSafeCsrf(csrf) ||/<\/script/i.test(globalsRaw))throw rstPreparationError("洛谷页面骨架解析失败(结构可能已改版)。");let safeThemeRaw = "";if (themeRaw) {try {safeThemeRaw = serializeJsonForScript(JSON.parse(themeRaw));} catch (error) {throw rstPreparationError("洛谷主题数据解析失败(结构可能已改版)。");}}let viewer = null;try {viewer = JSON.parse(ctxRaw).user || null;} catch (e) {/* 匿名兜底 */}const comments =commentsResult.kind === "available" &&Array.isArray(commentsResult.data.comments)? commentsResult.data.comments: [];const ctx = {instance: "main",template: "article.show",status: 200,24 行未改动},user: viewer,time: Math.floor(Date.now() / 1000),};const title = rstEscapeHtmlText(data.title || "文章");const html =`<!DOCTYPE html><html lang="zh-CN" class="no-js"><head><meta charset="utf-8">` +`<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">` +`<meta name="csrf-token" content="${csrf}">` +`<title>${title} - 洛谷专栏</title>` +`<link rel="icon" href="https://fecdn.luogu.com.cn/favicon.ico">` +`<script>${globalsRaw}<\/script>` +`<script id="lentille-context" type="application/json">${serializeJsonForScript(ctx)}<\/script>` +scripts.map((s) => `<script src="${s}" charset="utf-8" defer><\/script>`).join("") +cssLinks.map((c) => `<link rel="stylesheet" href="${c}" />`).join("") +`<script id="luogu-theme" type="application/json">${safeThemeRaw}<\/script>` +`<style>${RST_EXTRA_CSS}</style>` +`</head><body><div id="app"></div>${RST_LOADER_HTML}</body></html>`;return {kind: "article",html,install: () => rstStubReplies(info.id, comments),rollback: rstDisposeReplyStub,afterReady: () => rstMountArticleButtons(info, data),};}// 剪贴板页:合成 window._feInjection(currentTemplate PasteShow)+ 官方 lfe 前端async function rstBootPaste(info, data, signal) {const [scaffold, cnUser] = await Promise.all([rstHarvest("lfe", signal),rstCnUser(data.authorId, signal),]);if (!scaffold)throw rstPreparationError("无法获取洛谷页面骨架,暂不能就地渲染。");const parsed = parseRestrictedPasteScaffold(scaffold);if (!parsed ||!rstTrustedCdnUrl(parsed.loaderJs) ||!rstTrustedCdnUrl(parsed.loaderCss) ||!rstSafeCsrf(parsed.csrf))throw rstPreparationError("洛谷页面骨架解析失败(结构可能已改版)。");const scafInj = parsed.injection;const inj = {code: 200,currentTemplate: "PasteShow",currentData: {15 行未改动const html =`<!DOCTYPE html><html class="no-js" lang="zh"><head><meta charset="utf-8">` +`<meta http-equiv="X-UA-Compatible" content="IE=edge">` +`<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">` +`<meta name="csrf-token" content="${parsed.csrf}">` +`<meta name="renderer" content="webkit">` +`<title>云剪贴板 - 洛谷 | 计算机科学教育新生态</title>` +`<link rel="shortcut icon" type="image/x-icon" href="https://fecdn.luogu.com.cn/favicon.ico" media="screen"/>` +`<link rel="stylesheet" href="${parsed.loaderCss}">` +`<style>${RST_EXTRA_CSS}</style>` +`<script>window._feInjection = JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(inj))}"));window._feConfigVersion=${parsed.configVersionLiteral};window._tagVersion=${parsed.tagVersionLiteral};<\/script>` +`<script src="${parsed.loaderJs}" charset="utf-8" defer><\/script>` +`</head><body><div id="app"><noscript><h3>请<b style="color:#f00;">不要禁用</b>脚本,否则网页无法正常加载</h3></noscript></div>${RST_LOADER_HTML}</body></html>`;return {kind: "paste",html,afterReady: () => rstMountPasteButtons(info, data),};}// 官方前端可能连续多次重绘;同一帧只补种一次,并在补种期间暂停观察,// 避免扩展节点自身触发下一轮全页扫描。const rstInjectionDisposers = new Set();function rstObserveInjection(inject) {const root = document.body || document.documentElement;const options = { childList: true, subtree: true };let frame = null;let observer = null;const run = () => {frame = null;if (observer) observer.disconnect();try {inject();} catch (e) {console.error("LuoguSP restricted inject:", e);} finally {if (observer) observer.observe(root, options);}};run(); // 首次同步补种,保持按钮出现时机不变observer = new MutationObserver(() => {if (frame === null) frame = requestAnimationFrame(run);});observer.observe(root, options);const dispose = () => {if (observer) observer.disconnect();if (frame !== null) cancelAnimationFrame(frame);observer = null;frame = null;rstInjectionDisposers.delete(dispose);};rstInjectionDisposers.add(dispose);return dispose;}// 扩展按钮(文章页):等官方前端渲染出互动条再注入;Vue 重渲染会抹节点,观察器负责补种。// 同时在正文底部「创建时间:…」后方补「更新时间」=保存站存档最近更新时间(updatedAt),8 行未改动div.addEventListener("click", onClick);return div;};const inject = () => {const actionBars = [...document.querySelectorAll(".article-content .actions"),].filter((bar) => !bar.classList.contains("left-mode"));actionBars.forEach((bar) => {// owner 拍板:左浮条(left-mode)不放扩展按钮,只挂内联互动条if (bar.querySelector(".luogusp-rst-abtn")) return;bar.appendChild(make(RST_BTN_ICONS.refresh,9 行未改动);});// owner 要求:指向创建/更新时间不出浏览器悬浮泡 → 整条时间栏剥 title// (removeAttribute 无属性时不产生变更记录,天然幂等)const updateBars = [...document.querySelectorAll(".article-content .update-info"),];updateBars.forEach((bar) => {bar.removeAttribute("title");bar.querySelectorAll("[title]").forEach((n) => n.removeAttribute("title"));});if (updText)updateBars.forEach((bar) => {if (bar.querySelector(".luogusp-rst-updtime")) return;const ref = [...bar.querySelectorAll("span")].find((s) =>/创建时间/.test(s.textContent || ""),);const span = document.createElement("span");if (ref)for (const at of ref.attributes)if (at.name.startsWith("data-v-"))span.setAttribute(at.name, at.value); // 继承 data-v 作用域样式span.classList.add("luogusp-rst-updtime");span.textContent = `更新时间:${updText}`;const sep = document.createTextNode(" ");if (ref) ref.after(sep, span);else bar.append(sep, span);});rstApplyRefreshBtns(); // Vue 重种出的「申请更新」按钮要重新套用当前状态if (actionBars.length && updateBars.length) rstHideLoader();};return rstObserveInjection(inject);}// 扩展按钮(剪贴板页):内容卡首行(content-card-top)最右侧两枚实心蓝钮// (首行是 flex space-between,作者信息在左,本容器落位最右)。// 同时在「发表时间: …」行下方补「更新时间」行=保存站存档最近更新时间(updatedAt)。47 行未改动row.appendChild(span);pubRow.after(row);}rstApplyRefreshBtns(); // Vue 重种出的「申请更新」按钮要重新套用当前状态if (author && pubRow) rstHideLoader();};return rstObserveInjection(inject);}// 申请更新(手动):状态机 idle=可点 / busy=更新中… / done=已申请。// owner 口径(2026-07-23):提交成功即锁定「已申请」且不可再点,不轮询不自动刷新,// 直至用户主动刷新页面(保存工作流异步完成,刷新后自然装配新档);仅提交失败允许重试。// Vue 重渲染会抹掉按钮由观察器重种,故状态存模块级、每次补种后重新套用(rstApplyRefreshBtns)。let rstRefreshState = "idle";let rstRefreshText = "申请更新";let rstRefreshResetTimer = null;let rstRefreshController = null;// ★本函数被 inject 观察器(body childList+subtree)的回调无条件调用,必须幂等:// textContent 同值重写也会删旧建新 Text 节点、产生 childList 变更记录,// 会把观察器自己再触发一遍 → 微任务死循环整页卡死(2.11.0 事故),故同值不写。function rstApplyRefreshBtns() {9 行未改动rstRefreshState = state;rstRefreshText = text;rstApplyRefreshBtns();}function rstScheduleRefreshReset() {if (rstRefreshResetTimer !== null)clearTimeout(rstRefreshResetTimer);rstRefreshResetTimer = setTimeout(() => {rstRefreshResetTimer = null;if (rstRefreshState === "idle") rstSetRefresh("idle", "申请更新");}, 3000);}async function rstManualRefresh(info) {if (rstRefreshState !== "idle") return;const controller = new AbortController();rstRefreshController = controller;const current = () =>rstRefreshController === controller && !controller.signal.aborted;let commentsPending = false;rstSetRefresh("busy", "更新中…");try {const result = await saverWorkflow.requestRefresh(info.type, info.id, {signal: controller.signal,});if (!current()) return;if (result.kind === "unknown") {rstSetRefresh("idle", "结果未知");rstScheduleRefreshReset();return;}if (result.kind !== "accepted")throw new Error(result.reason || "保存站拒绝更新请求");rstSetRefresh("done", "已申请");if (info.type === "article") {commentsPending = true;const finishComments = () => {if (rstRefreshController === controller)rstRefreshController = null;};void saverWorkflow.refreshComments(info.id, { signal: controller.signal }).then(finishComments, finishComments);}} catch (e) {if (!current()) return;console.error("LuoguSP restricted refresh:", e);rstSetRefresh("idle", "更新失败");rstScheduleRefreshReset();} finally {if (!commentsPending && rstRefreshController === controller)rstRefreshController = null;}}const restrictedDocumentBuilder = {prepare: async (info, data, signal) => {if (signal.aborted)throw Object.assign(new Error("受限文档准备已取消"), {kind: "cancelled",});const prepared =info.type === "article"? await rstBootArticle(info, data, signal): await rstBootPaste(info, data, signal);if (signal.aborted)throw Object.assign(new Error("受限文档准备已取消"), {kind: "cancelled",});return prepared;},dispose: () => {if (rstRefreshController) rstRefreshController.abort();rstRefreshController = null;rstDisposeReplyStub();for (const dispose of [...rstInjectionDisposers]) dispose();if (rstRefreshResetTimer !== null) {clearTimeout(rstRefreshResetTimer);rstRefreshResetTimer = null;}rstRefreshState = "idle";rstRefreshText = "申请更新";document.querySelectorAll(".luogusp-rst-abtn,.luogusp-rst-pactions,.luogusp-rst-updtime",).forEach((node) => node.remove());},};const restrictedDocumentCommitter = createRestrictedDocumentCommitter({documentAdapter: {open: () => document.open(),write: (html) => document.write(html),close: () => document.close(),},resourcePolicy: { isAllowed: rstTrustedCdnUrl },});let restrictedDocumentBoot = null;// ============================================================// 启动// ============================================================const FEATURES = [{id: "settings",mount: () => {injectStyle();return watchSettingButton();},},{id: "problem-pipeline",enabled: () => storage.get(`${STORAGE_PREFIX}addProblemsColor`),mount: (context) => {let disposePipeline = null;const timer = setTimeout(() => {if (!context.isCurrent()) return;try {disposePipeline = problemPipeline? problemPipeline.mount(): () => {};} catch (error) {console.error("LuoguSP lifecycle problem-pipeline:", error);}}, 500);return () => {clearTimeout(timer);if (disposePipeline) disposePipeline();};},},{id: "chat-shortcut",enabled: () => storage.get(`${STORAGE_PREFIX}addMessageLink`),mount: (context) => {if (!location.pathname.startsWith("/chat")) return;let disposeChat = null;const timer = setTimeout(() => {if (!context.isCurrent()) return;try {disposeChat = addMessageLink();} catch (error) {console.error("LuoguSP lifecycle chat-shortcut:", error);}}, 500);return () => {clearTimeout(timer);if (disposeChat) disposeChat();};},},{id: "hidden-intro",enabled: () => storage.get(`${STORAGE_PREFIX}showIntro`),mount: (context) => watchHiddenIntro(context),},{id: "ide-batch",enabled: () => storage.get(`${STORAGE_PREFIX}ideBatchSampleTest`),mount: () => {ideBatchRunner.mount();return () => ideBatchRunner.unmount();},},{id: "restricted-document",enabled: () => storage.get(`${STORAGE_PREFIX}showRestrictedContent`),mount: (context) =>restrictedDocumentBoot? restrictedDocumentBoot.mount(context): () => {},onRoute: () => {if (restrictedLoadingGate) restrictedLoadingGate.start();if (restrictedDocumentBoot) restrictedDocumentBoot.onRoute();},},];const pageLifecycle = createPageLifecycle({routeAdapter: browserRouteAdapter,documentAdapter: {schedule: (callback) => {const frame = requestAnimationFrame(callback);return () => cancelAnimationFrame(frame);},whenReady: (callback) => {if (document.body) return callback();let active = true;const ready = () => {if (active) callback();};document.addEventListener("DOMContentLoaded", ready, {once: true,});return () => {active = false;document.removeEventListener("DOMContentLoaded", ready);};},},storage,logError: (id, error) =>console.error(`LuoguSP lifecycle ${id}:`, error),});FEATURES.forEach((feature) => pageLifecycle.register(feature));restrictedDocumentBoot = createRestrictedDocumentBoot({pageAdapter: {detect: () => restrictedPageDetector.detect(),showLoader: rstShowLoader,hideLoader: rstHideLoader,showUnavailable: rstShowUnavailableTip,showFailure: rstBuildFailure,currentPath: () => location.pathname,isRestrictedRoute: (path) =>/^\/(article|paste)\/[A-Za-z0-9]+\/?$/.test(path),reload: () => location.reload(),},saverWorkflow,documentBuilder: restrictedDocumentBuilder,documentCommitter: restrictedDocumentCommitter,pageLifecycle,logError: (error) => console.error("LuoguSP restricted boot:", error),});let bootstrapped = false;const bootstrapAdapter =options.bootstrapAdapter ||Object.freeze({initialize: () => initializeFeatureDefaults(),start: () => pageLifecycle.start(),});function bootstrapBrowser() {if (bootstrapped) return;bootstrapped = true;bootstrapAdapter.initialize();bootstrapAdapter.start();}const app = { bootstrapBrowser };if (options.exposeTestInterface) {app.test = Object.freeze({startIdeBatch,ideState: () => ideBatchRunner.getState(),});}return Object.freeze(app);}const LUOGUSP_NODE_MODULE =typeof window === "undefined" &&typeof module === "object" &&module &&module.exports &&typeof process === "object" &&process &&process.versions &&process.versions.node;if (LUOGUSP_NODE_MODULE) {module.exports = Object.freeze({createGetRequestScheduler,createProblemIdentityResolver,createProblemPipeline,createIdeBatchRunner,createSaverTransport,createSaverProtocol,createSaverWorkflow,createBrowserRouteAdapter,createPageLifecycle,createRestrictedLoadingGate,createRestrictedDocumentBoot,serializeJsonForScript,createRestrictedDocumentCommitter,parseRestrictedPasteScaffold,createRestrictedUrlPolicy,createRestrictedPageDetector,createRestrictedReplyFetchAdapter,createRestrictedReplyFetchInstaller,createLuoguSPApp,});} else {const restrictedLoadingGate = createRestrictedLoadingGate({pageAdapter: {currentPath: () => location.pathname,isEnabled: () => {try {const value = localStorage.getItem("LuoguSP.showRestrictedContent",);return value === null || value === "true";} catch (error) {return false;}},isCandidateRoute: (path) =>/^\/(article|paste)\/[A-Za-z0-9]+\/?$/.test(path),},overlayAdapter: {mount: () => {const className = "luogusp-rst-preparing";const styleId = "luogusp-rst-early-style";let observer = null;let mountedRoot = null;let previousBusy = null;const attach = () => {const root = document.documentElement;if (!root) return false;mountedRoot = root;previousBusy = root.getAttribute("aria-busy");root.setAttribute("aria-busy", "true");root.classList.add(className);if (!document.getElementById(styleId)) {const style = document.createElement("style");style.id = styleId;style.textContent = `html.${className},html.${className} body{overflow:hidden!important;background:#f5f5f5!important;}html.${className} body>*{visibility:hidden!important;}html.${className}::before{content:"";position:fixed;left:50%;top:50%;z-index:2147483646;width:36px;height:36px;margin:-31px 0 0 -21px;border:3px solid rgba(52,152,219,.25);border-top-color:#3498db;border-radius:50%;animation:luogusp-rst-early-spin .8s linear infinite;}html.${className}::after{content:"加载中…";position:fixed;left:0;right:0;top:calc(50% + 17px);z-index:2147483646;color:#595959;text-align:center;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Helvetica Neue","PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;}@keyframes luogusp-rst-early-spin{to{transform:rotate(360deg);}}@media (prefers-reduced-motion:reduce){html.${className}::before{animation-duration:1.8s;}}`;(document.head || root).appendChild(style);}return true;};if (!attach()) {observer = new MutationObserver(() => {if (!attach()) return;observer.disconnect();observer = null;});observer.observe(document, { childList: true, subtree: true });}return () => {if (observer) observer.disconnect();observer = null;const root = mountedRoot || document.documentElement;if (root) {root.classList.remove(className);if (previousBusy === null) root.removeAttribute("aria-busy");else root.setAttribute("aria-busy", previousBusy);}const style = document.getElementById(styleId);if (style) style.remove();};},},});try {restrictedLoadingGate.start();} catch (error) {console.error("LuoguSP restricted early loader:", error);}const bootstrap = () => {try {createLuoguSPApp({ restrictedLoadingGate }).bootstrapBrowser();} catch (error) {restrictedLoadingGate.release();throw error;}};if (document.readyState === "loading")document.addEventListener("DOMContentLoaded", bootstrap, { once: true });else bootstrap();}})();```