serve-dist.mjs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /**
  2. * 本地静态开发服务器(用于跑**生产构建**做真实环境回归)
  3. *
  4. * ## 与 `npm start` 的分工
  5. *
  6. * | 命令 | 用途 |
  7. * |---|---|
  8. * | `npm start` | `ng serve` + `proxy.conf.js`,日常开发,热更新 |
  9. * | `npm run serve:dist` | 托管 `dist/` 里的构建产物,**接近线上**的运行形态 |
  10. * | `npm run dev:logged-in` | 同上 + 自动注入登录态 → 打开即已登录,可自动化 |
  11. *
  12. * ## 为什么要单独一个服务器
  13. *
  14. * `scripts/smoke-imhub.mjs` 里内联的静态服务只够冒烟用(无 SPA 回退以外的细节)。
  15. * 手工回归时需要一个**能长期开着**的服务器,并且要能在不改源文件的前提下注入
  16. * 登录态 —— 这就是本脚本的第二个职责(见 `scripts/dev-login.mjs`)。
  17. *
  18. * ## 用法
  19. *
  20. * ```bash
  21. * npm run build # 先构建
  22. * npm run serve:dist # http://127.0.0.1:4300/?mode=desktop
  23. * npm run dev:logged-in # 同上,且自动登录
  24. * PORT=4400 npm run serve:dist # 换端口
  25. * ```
  26. */
  27. import { createServer } from 'node:http';
  28. import { readFile, stat } from 'node:fs/promises';
  29. import { existsSync } from 'node:fs';
  30. import { join, extname, resolve, dirname } from 'node:path';
  31. import { fileURLToPath } from 'node:url';
  32. import { loadDevLogin, injectIntoHtml } from './dev-login.mjs';
  33. const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  34. const distDir = resolve(root, 'dist/fmode-app-v2/browser');
  35. const port = Number(process.env.PORT ?? 4300);
  36. const wantLogin = process.argv.includes('--login') || process.env.DEV_LOGIN === '1';
  37. const MIME = {
  38. '.html': 'text/html; charset=utf-8',
  39. '.js': 'text/javascript; charset=utf-8',
  40. '.mjs': 'text/javascript; charset=utf-8',
  41. '.css': 'text/css; charset=utf-8',
  42. '.json': 'application/json; charset=utf-8',
  43. '.svg': 'image/svg+xml',
  44. '.woff2': 'font/woff2',
  45. '.woff': 'font/woff',
  46. '.ttf': 'font/ttf',
  47. '.ico': 'image/x-icon',
  48. '.png': 'image/png',
  49. '.jpg': 'image/jpeg',
  50. '.webp': 'image/webp',
  51. '.map': 'application/json; charset=utf-8',
  52. };
  53. if (!existsSync(distDir)) {
  54. console.error(`❌ 未找到构建产物:${distDir}\n 先执行 npm run build`);
  55. process.exit(2);
  56. }
  57. let login = { enabled: false, reason: '未启用(加 --login 或 DEV_LOGIN=1 才注入)' };
  58. if (wantLogin) login = loadDevLogin();
  59. if (wantLogin && !login.enabled) {
  60. console.error(`❌ 开发态登录未生效:${login.reason}`);
  61. console.error(` 按 docs/05-operations/开发态登录.md 填好 .claude/dev-login.json 后重试。`);
  62. process.exit(2);
  63. }
  64. /** 只在内存里改 HTML,不碰磁盘上的源文件 */
  65. async function readIndex() {
  66. const html = await readFile(join(distDir, 'index.html'), 'utf8');
  67. return login.enabled ? injectIntoHtml(html, login.payload) : html;
  68. }
  69. const server = createServer(async (req, res) => {
  70. try {
  71. const urlPath = decodeURIComponent((req.url ?? '/').split('?')[0]);
  72. const file = join(distDir, urlPath);
  73. // 目录穿越防护:解析后必须仍在 dist 内
  74. if (!resolve(file).startsWith(distDir)) {
  75. res.writeHead(403).end('forbidden');
  76. return;
  77. }
  78. let onDisk = false;
  79. try {
  80. onDisk = (await stat(file)).isFile();
  81. } catch {
  82. onDisk = false;
  83. }
  84. if (onDisk && extname(file) !== '.html') {
  85. const body = await readFile(file);
  86. res.writeHead(200, {
  87. 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream',
  88. // 本地调试时不缓存,避免改了构建产物还看到旧的
  89. 'Cache-Control': 'no-store',
  90. });
  91. res.end(body);
  92. return;
  93. }
  94. // SPA 回退:所有路由都返回 index.html
  95. res.writeHead(200, { 'Content-Type': MIME['.html'], 'Cache-Control': 'no-store' });
  96. res.end(await readIndex());
  97. } catch (e) {
  98. res.writeHead(500).end(`server error: ${e.message}`);
  99. }
  100. });
  101. server.listen(port, '127.0.0.1', () => {
  102. const base = `http://127.0.0.1:${port}`;
  103. console.log(`静态服务:${base}`);
  104. console.log(`产物目录:${distDir}`);
  105. console.log(
  106. login.enabled
  107. ? `🔓 开发态登录已启用(用户:${login.payload.me.name || login.payload.me.id})—— 打开即已登录`
  108. : `🔒 未注入登录态:${login.reason}`,
  109. );
  110. console.log(`\n 桌面端 ${base}/desktop/chat`);
  111. console.log(` 移动端 ${base}/mobile/messages\n`);
  112. });