liufumingren 81a5a8888d 打包:开发/生产环境配置 + 版本号 + 自动更新(version.json)+ 保留5个包
一、打包配置(desktop/installer/package.config.json)
- 两个环境各自的域名:Development = http://127.0.0.1:7300,Production = 占位正式域名(发布前替换)。
- keepVersions = 5。
- build.ps1 -Environment Production 自动用生产域名打 exe 与下载地址;-ServerBaseUrl 可临时覆盖。

二、build.ps1
- 新增 -Environment / -Version / -Keep / -ReleaseNotes;版本默认取 csproj,可覆盖,
  通过 -p:Version 注入程序集(AssemblyVersion/FileVersion 一起变)。
- 打完后:算 MD5、写 version.json(version/downloadUrl/md5/size/publishedAt/buildId/environment/releaseNotes),
  复制 MSI → backend/app/public/download/,version.json → backend/app/public/version/。
- 本地 out/ 与后端目录各只保留最近 5 个安装包(按版本号排序清理)。
- 补丁版保护:后端已有更高版本时,不覆盖 version.json(避免补打旧版把版本降回去)。

三、后端静态分发 + 缓存(关键)
- Egg 的 static 生产默认强缓存一年,version.json 若走静态会**永远检测不到更新**。
  且实测 koa-static 命中文件后**不再 next()**,后置中间件改不了它的响应头(先写了 middleware 验证不可行,已删)。
  → version.json 放到 app/public/version/(不在静态目录),由路由 GET /download/version.json 提供:
    Cache-Control: no-store, no-cache, must-revalidate, max-age=0 + Pragma/Expires,且不产生 ETag/Last-Modified。
- MSI 仍走 egg-static(prefix /download/,maxAge 31536000),文件名带版本号可长缓存。
- middleware/frontend.js 放行 /download/*,否则会被 SPA 入口接管。
- 实测响应头:version.json 无 ETag/Last-Modified、cache-control: no-store…;
  MSI cache-control: public, max-age=31536000。

四、桌面端自动更新(Services/UpdateChecker.cs + App)
- 启动登录后后台请求 {后端}/download/version.json?t=毫秒时间戳(带 no-cache 头),
  比较程序集版本;有新版则弹窗(版本/说明/大小),点是 → 浏览器打开 downloadUrl。
- 失败静默(网络问题不打扰);日志记录发现新版本/已打开下载。
- 实测:安装 1.0.1 → version.json 1.0.1 不提示;改成 1.0.2 后重启 →
  日志「发现新版本 1.0.2(当前 1.0.1.0)→ 已打开下载」。

五、.gitignore
- 忽略后端分发产物:backend/app/public/{download,version}/* 但保留 .gitkeep。

⚠️ backend/config/config.default.js 本次提交同时带入了该文件里已有的未提交改动
   (后端默认端口 7001 → 7300 及注释),因为 static 配置必须写在同一个文件里;
   其它 backend/extension/frontend 的未提交 WIP 未包含在本次提交中。
2026-10-17 12:07:13 +08:00

110 lines
4.6 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.

'use strict';
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const serve = require('koa-static');
/**
* 前端入口:**后端不再渲染任何页面**,`/` 这一侧要么反代给前端 dev server、要么托管前端构建产物
*
* - **开发(`env=local`)**:把非 `/api`、`/health` 的请求反向代理到前端 dev server
* (`config.frontend.devServer`,默认 `http://127.0.0.1:7301`,即 `frontend && npm run dev`)。
* 这样联调只开一个地址(后端 `:7300`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。
* - **生产**:托管 `config.frontend.distDir`(默认 `../frontend/dist`)里的静态资源,
* 找不到文件且浏览器要 HTML 时回退到 `index.html`(SPA 深链刷新不会 404)。
* - **单测(`env=unittest`)**:整体跳过(不连前端、也不要求 dist 存在),
* 于是未匹配的路径还是走框架/路由自己的 404。
*
* 只接管 GET/HEAD 的「非接口」请求:`/api/*`、`/health` 一律交给后面的路由。
*/
module.exports = (options, app) => {
const cfg = app.config.frontend || {};
const env = app.config.env;
const isDev = env === 'local';
const enabled = Boolean(cfg.enable) && env !== 'unittest';
const distDir = cfg.distDir;
const indexFile = path.join(distDir, 'index.html');
// 静态中间件(生产用):只管真实文件,交给 koa-static 处理缓存/条件请求
const staticMw = enabled && !isDev ? serve(distDir, { index: false, defer: false }) : null;
if (enabled && isDev) {
app.logger.info('[frontend] dev 反代已启用: %s(页面请求转发给前端 dev server)', cfg.devServer);
// 前端 dev server 的 HMR 走 WebSocket:HTTP server 的 upgrade 事件也得转过去,
// 否则页面能打开、但改代码不会热更新(升级请求没人管会直接断开)
app.once('server', server => {
server.on('upgrade', (req, socket, head) => {
const url = String(req.url || '');
if (url.startsWith('/api/') || url === '/health') return; // 接口侧不接管
getProxy(cfg.devServer).ws(req, socket, head, { target: cfg.devServer });
});
});
} else if (enabled && staticMw) {
app.logger.info('[frontend] 静态托管已启用: %s(存在 index.html = %s)', distDir, fs.existsSync(indexFile));
}
return async function frontend(ctx, next) {
if (!enabled || !isFrontendRequest(ctx)) return next();
if (isDev) return proxyToDevServer(ctx, cfg.devServer);
// 生产:先当静态资源找,找不到再回退 index.html(SPA 路由)
await staticMw(ctx, async () => {});
if (ctx.status !== 404) return;
if (!fs.existsSync(indexFile)) {
ctx.status = 503;
ctx.type = 'html';
ctx.body = '<h1>前端还没构建</h1><p>请在 frontend/ 执行 <code>npm run build</code>(或用 FRONTEND_DIST 指定目录)。</p>';
return;
}
ctx.type = 'html';
ctx.body = fs.createReadStream(indexFile);
};
};
/** 只接管「页面」请求:非接口 + GET/HEAD;`/download/*` 是安装包静态资源,不接管 */
function isFrontendRequest(ctx) {
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false;
if (ctx.path.startsWith('/download/')) return false;
return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health';
}
/** 开发:反代到前端 dev server(含 HMR 的 WebSocket 升级) */
function proxyToDevServer(ctx, target) {
// koa 不再自己写响应,完全交给反代
ctx.respond = false;
const proxy = getProxy(target);
proxy.web(ctx.req, ctx.res, { target }, (err) => {
if (ctx.res.headersSent) return;
ctx.status = 502;
ctx.type = 'html';
ctx.body = `<h1>前端 dev server 连不上</h1><p>${err.message}</p>`
+ `<p>请先启动前端:<code>cd frontend; npm run dev</code>(目标 ${target})</p>`;
});
}
/** 按 target 缓存代理实例(同一个 target 复用连接池) */
const proxies = new Map();
function getProxy(target) {
if (proxies.has(target)) return proxies.get(target);
// ws: true —— 允许 `proxy.ws()` 把 HMR 的升级请求转过去
const proxy = httpProxy.createProxyServer({ changeOrigin: true, xfwd: true, ws: true });
proxy.on('error', (err, req, res) => {
// HTTP 请求的错误在 proxyToDevServer 的回调里处理;这里只兑底(避免 unhandled error 抛到进程)
if (res && !res.headersSent && res.writeHead) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
}
void err;
});
proxies.set(target, proxy);
return proxy;
}