Files
yun-xue-tang-assistant/dev/serve.mjs
T
void ae117222df feat: v2.8.0 无头运行器、考试自动交卷、改为退避重试不跳课
新增无头运行能力,解决 Linux 无图形化服务器上无法常驻的问题;同时改掉
"遇到考试课/无进展课就跳过"的策略,改为在同门课上退避重试。

- runner/:自己起无头 Chromium,用 CDP 把构建产物注入页面主世界(等价
  @grant none),不装插件、不需要桌面环境或 Xvfb;含浏览器探测与启动参数、
  持久化 profile、陈旧 SingletonLock 清理、优雅退出、日志轮转、启动预检
- runner.config.mjs / start-headless.cmd:通用配置 + Windows 一键入口;
  凭据只走 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD 环境变量
- src/exam.js:含考试章节的课程自动进考试 → 开始/继续 → 空卷提交 → 确定,
  交卷后靠平台记账推进课程;maxExamTries 限制同门课交卷次数,防不记账时死循环
- 去掉跳过与黑名单:没学完就退避重试(30s 起翻倍,最长 5 分钟),
  同门课超过 maxCourseRetries 次才停整轮并提示,替代原 maxConsecutiveFailures
- 每完成一门都重新拉列表接口取平台实时状态再选下一门,避免用陈旧队列
- 学习进度改存 sessionStorage(yun-xue-tang-run-state-v3),整页跳转/刷新可续;
  运行开关不跨会话,浏览器重启后必须显式开跑
- dev/:新增 real-cdp / real-run / real-test / real-e2e 实跑脚本与 check.mjs
  统一静态检查(JS 22 + 批处理 2),替代逐文件 node --check
- docs/evidence/headless-linux-evidence.txt + 实跑截图,README 补无头部署章节
2026-10-25 23:04:40 +08:00

154 lines
5.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 云学堂助手 · 本地开发服务器
*
* 作用:把工作目录里的 yun-xue-tang-assistant.user.js 暴露给浏览器里的
* Tampermonkey 热加载器(dev/dev-loader.user.js)拉取。
*
* 端点:
* GET / 说明页
* GET /src 最新脚本源码(no-store)
* GET /version { hash, size, mtime },热加载器靠 hash 判断是否变更
* GET /loader.user.js 热加载器本体(用于安装)
*
* 用法:node dev/serve.mjs [端口] 默认端口 8899
*/
import http from 'node:http';
import path from 'node:path';
import crypto from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const HOST = '127.0.0.1';
const PORT = Number(process.env.YUN_XUE_TANG_DEV_PORT || process.argv[2] || 8899);
const FILES = {
'/src': path.join(ROOT, 'yun-xue-tang-assistant.user.js'),
'/loader.user.js': path.join(HERE, 'dev-loader.user.js'),
};
const BASE = `http://${HOST}:${PORT}`;
function hashOf(buf) {
return crypto.createHash('sha1').update(buf).digest('hex').slice(0, 12);
}
function send(res, status, body, type, origin) {
const headers = {
'Content-Type': type || 'text/plain; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
Pragma: 'no-cache',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS',
'X-Content-Type-Options': 'nosniff',
};
// 只放行云学堂页面(Tampermonkey 的 GM_xmlhttpRequest 本来也不受 CORS 限制,
// 这里拒绝其它站点读取是为了别让随便哪个网页都能拉到你的脚本)
if (origin && /^https?:\/\/([a-z0-9-]+\.)*yunxuetang\.cn(:\d+)?$/i.test(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers.Vary = 'Origin';
}
res.writeHead(status, headers);
res.end(body);
}
function indexHtml() {
return `<!doctype html><meta charset="utf-8"><title>YXT Assistant · 本地开发服务</title>
<style>body{font:14px/1.7 system-ui,"Microsoft YaHei";max-width:760px;margin:40px auto;padding:0 16px;color:#222}
code{background:#f2f2f4;padding:1px 5px;border-radius:4px}a{color:#2f7d5b}
.ok{color:#2f7d5b;font-weight:600}</style>
<h2>云学堂助手 · 本地开发服务 <span class="ok">运行中</span></h2>
<p>源码文件:<code>${path.join(ROOT, 'yun-xue-tang-assistant.user.js')}</code></p>
<ul>
<li><a href="/loader.user.js">安装 / 更新热加载器</a>(Tampermonkey 会弹出安装页)</li>
<li><a href="/src">查看当前源码</a></li>
<li><a href="/version">版本哈希</a></li>
</ul>
<p>改完源码保存后,浏览器页面约 1 秒内自动热替换,无需刷新、无需重装脚本。</p>`;
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, BASE);
const route = url.pathname.replace(/\/+$/, '') || '/';
const origin = req.headers.origin || '';
const reply = (status, body, type) => send(res, status, body, type, origin);
if (req.method === 'OPTIONS') return reply(204, '');
if (route === '/favicon.ico') return reply(204, '');
if (route === '/') {
return reply(200, indexHtml(), 'text/html; charset=utf-8');
}
if (route === '/version') {
try {
const file = FILES['/src'];
const [buf, st] = await Promise.all([readFile(file), stat(file)]);
const body = JSON.stringify({
hash: hashOf(buf),
size: buf.length,
mtime: st.mtimeMs,
at: Date.now(),
});
return reply(200, body, 'application/json; charset=utf-8');
} catch (e) {
return reply(500, JSON.stringify({ error: String(e.message || e) }), 'application/json; charset=utf-8');
}
}
const file = FILES[route];
if (file) {
try {
const buf = await readFile(file);
const type = route === '/src'
? 'application/javascript; charset=utf-8'
: 'text/plain; charset=utf-8';
if (route === '/src') {
console.log(`[${time()}] /src ${buf.length}B ${hashOf(buf)}`);
}
return reply(200, buf, type);
} catch (e) {
console.error(`[${time()}] ${route} 读取失败: ${e.message}`);
return reply(500, `读取失败: ${e.message}`);
}
}
return reply(404, 'not found: ' + route);
});
function time() {
return new Date().toLocaleTimeString('zh-CN', { hour12: false });
}
server.listen(PORT, HOST, () => {
console.log('');
console.log(' YXT Assistant · 本地开发服务已启动');
console.log(' ------------------------------------');
console.log(` 脚本源码 : ${FILES['/src']}`);
console.log(` 热加载器 : ${BASE}/loader.user.js`);
console.log(` 版本接口 : ${BASE}/version`);
console.log(` 首页 : ${BASE}/`);
console.log(' ------------------------------------');
console.log(' 保持本窗口开启;关闭窗口 = 停止服务。');
console.log('');
});
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.error(`端口 ${PORT} 已被占用。可能服务已在运行,或用 "node dev/serve.mjs 8900" 换端口。`);
} else {
console.error('服务启动失败:', e);
}
process.exit(1);
});
for (const sig of ['SIGINT', 'SIGTERM']) {
process.on(sig, () => {
console.log('\n服务已停止。');
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1500).unref();
});
}