2
0

server.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import 'dotenv/config'
  2. import fs from 'node:fs/promises';
  3. import { URL } from 'node:url';
  4. import { Transform } from 'node:stream';
  5. import { Readable } from 'node:stream';
  6. import { pipeline } from 'node:stream/promises';
  7. import { Hono } from 'hono';
  8. import { cors } from 'hono/cors'
  9. import { logger } from 'hono/logger';
  10. import { createServer as createNodeServer } from 'node:http';
  11. import process from 'node:process';
  12. import { createAdaptorServer } from '@hono/node-server'
  13. // 新增:导入 Socket.IO
  14. import { Server } from 'socket.io';
  15. import { progressTrackingPlugin} from './vite-plugin-compile-progress.js';
  16. // 创建 Hono 应用
  17. const app = new Hono();// API路由
  18. // 全局使用 Hono 日志中间件(记录所有请求)
  19. // app.use('*', logger());
  20. app.use('*', cors(
  21. // {
  22. // origin: ['http://localhost:3000'],
  23. // allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  24. // credentials: true
  25. // }
  26. ))
  27. // 常量定义
  28. const isProduction = process.env.NODE_ENV === 'production';
  29. const port = process.env.PORT || 8080;
  30. const base = process.env.BASE || '/';
  31. const ABORT_DELAY = 10000;
  32. console.log('========================================');
  33. console.log('开始初始化服务器...');
  34. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  35. console.log(`端口: ${port}`);
  36. console.log(`基础路径: ${base}`);
  37. console.log('========================================');
  38. // 解析基础路径为 URL 对象,方便后续处理
  39. const baseUrl = new URL(base, `http://localhost:${port}`);
  40. console.log(`基础URL解析完成: ${baseUrl.href}`);
  41. // 先创建服务器实例
  42. console.log('正在创建服务器实例...');
  43. const parentServer = createAdaptorServer({
  44. fetch: app.fetch,
  45. createServer: createNodeServer,
  46. port: port,
  47. })
  48. console.log('服务器实例创建成功');
  49. // 新增:初始化 Socket.IO 服务器
  50. console.log('正在初始化 Socket.IO 服务器...');
  51. const io = new Server(parentServer, {
  52. // // 配置 CORS,根据实际需求调整
  53. // cors: {
  54. // origin: isProduction ? process.env.FRONTEND_URL || false : "http://localhost:8080",
  55. // methods: ["GET", "POST"],
  56. // credentials: true
  57. // },
  58. // // 路径配置,避免与其他路由冲突
  59. // path: `${base}socket.io`
  60. });
  61. console.log('Socket.IO 服务器初始化完成');
  62. // 生产环境中间件
  63. let compressionMiddleware;
  64. let sirvMiddleware;
  65. if (isProduction) {
  66. console.log('生产环境: 加载压缩和静态文件中间件...');
  67. compressionMiddleware = (await import('compression')).default();
  68. sirvMiddleware = (await import('sirv')).default('./dist/client', {
  69. extensions: [],
  70. baseUrl: base
  71. });
  72. console.log('生产环境中间件加载完成');
  73. }
  74. // Vite 开发服务器
  75. /** @type {import('vite').ViteDevServer | undefined} */
  76. let vite;
  77. if (!isProduction) {
  78. console.log('开发环境: 初始化 Vite 开发服务器...');
  79. const { createServer } = await import('vite');
  80. vite = await createServer({
  81. server: {
  82. middlewareMode: {
  83. server: parentServer
  84. },
  85. hmr: {
  86. port: 8081,
  87. clientPort: 443,
  88. path: 'vite-hmr'
  89. },
  90. proxy: {
  91. '/vite-hmr': {
  92. target: 'ws://localhost:8081',
  93. ws: true,
  94. },
  95. },
  96. },
  97. appType: 'custom',
  98. base,
  99. plugins: [
  100. progressTrackingPlugin(),
  101. ],
  102. });
  103. console.log('Vite 开发服务器初始化完成');
  104. }
  105. // 加载 API 路由
  106. if (!isProduction) {
  107. console.log('开发环境: 从 Vite 加载 API 路由...');
  108. const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
  109. app.route('/', apiModule.default);
  110. console.log('API 路由加载完成');
  111. }else{
  112. console.log('生产环境: 加载编译后的 API 路由...');
  113. const api = (await import('./dist/api/api.js')).default
  114. app.route('/', api);
  115. console.log('API 路由加载完成');
  116. }
  117. // 新增:加载 Socket.IO 中间件和路由
  118. if (!isProduction) {
  119. console.log('开发环境: 从 Vite 加载 Socket.IO 路由和中间件...');
  120. try {
  121. const socketModule = await vite.ssrLoadModule('./src/server/socket.ts');
  122. // 应用认证中间件
  123. if (socketModule.authMiddleware) {
  124. console.log('应用 Socket.IO 认证中间件');
  125. io.use(socketModule.authMiddleware);
  126. }
  127. // 应用路由
  128. if (socketModule.default) {
  129. console.log('注册 Socket.IO 路由处理');
  130. socketModule.default(io);
  131. }
  132. console.log('Socket.IO 路由和中间件加载完成');
  133. } catch (err) {
  134. console.error('开发环境加载 Socket.IO 模块失败:', err);
  135. }
  136. } else {
  137. console.log('生产环境: 加载编译后的 Socket.IO 路由和中间件...');
  138. try {
  139. const socket = (await import('./dist/socket/socket.js')).default;
  140. // 应用认证中间件
  141. if (socket.authMiddleware) {
  142. console.log('应用 Socket.IO 认证中间件');
  143. io.use(socket.authMiddleware);
  144. }
  145. // 应用路由
  146. if (socket.default) {
  147. console.log('注册 Socket.IO 路由处理');
  148. socket.default(io);
  149. }
  150. console.log('Socket.IO 路由和中间件加载完成');
  151. } catch (err) {
  152. console.error('加载 Socket.IO 模块失败:', err);
  153. }
  154. }
  155. // 请求处理中间件 - 通用逻辑
  156. app.use(async (c, next) => {
  157. try {
  158. // 使用 c.env 获取原生请求响应对象
  159. const req = c.env.incoming;
  160. const res = c.env.outgoing;
  161. const url = new URL(req.url, `http://${req.headers.host}`);
  162. const path = url.pathname;
  163. // 检查是否匹配基础路径
  164. if (!path.startsWith(baseUrl.pathname)) {
  165. return c.text('未找到', 404);
  166. }
  167. // 开发环境:使用 Vite 中间件
  168. if (!isProduction && vite) {
  169. // 使用 Vite 中间件处理请求
  170. const handled = await new Promise((resolve) => {
  171. vite.middlewares(req, res, () => resolve(false));
  172. });
  173. // 如果 Vite 中间件已经处理了请求,直接返回
  174. if (handled) {
  175. return c.body;
  176. }
  177. }
  178. // 生产环境:使用 compression 和 sirv 中间件
  179. else if (isProduction) {
  180. // 先尝试 compression 中间件
  181. const compressed = await new Promise((resolve) => {
  182. compressionMiddleware(req, res, () => resolve(false));
  183. });
  184. if (compressed) {
  185. return c.body;
  186. }
  187. // 再尝试 sirv 中间件处理静态文件
  188. const served = await new Promise((resolve) => {
  189. sirvMiddleware(req, res, () => resolve(false));
  190. });
  191. if (served) {
  192. return c.body;
  193. }
  194. }
  195. await next()
  196. } catch (e) {
  197. if (!isProduction && vite) {
  198. vite.ssrFixStacktrace(e);
  199. }
  200. console.error('请求处理中间件错误:', e.stack);
  201. return c.text('服务器内部错误', 500);
  202. }
  203. });
  204. // 请求处理中间件 - SSR 渲染逻辑
  205. app.use(async (c) => {
  206. try {
  207. // 使用 c.env 获取原生请求响应对象
  208. const req = c.env.incoming;
  209. const res = c.env.outgoing;
  210. const url = new URL(req.url, `http://${req.headers.host}`);
  211. const path = url.pathname;
  212. // 检查是否匹配基础路径
  213. if (!path.startsWith(baseUrl.pathname)) {
  214. return c.text('未找到', 404);
  215. }
  216. // 处理基础路径
  217. const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
  218. console.log(`处理请求: ${normalizedUrl}`);
  219. // 处理所有其他请求的 SSR 逻辑
  220. /** @type {string} */
  221. let template;
  222. /** @type {import('./src/server/index.tsx').render} */
  223. let render;
  224. if (!isProduction && vite) {
  225. console.log('开发环境: 加载模板和渲染函数...');
  226. // 开发环境:读取最新模板并转换
  227. const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
  228. template = module.template;
  229. template = await vite.transformIndexHtml(normalizedUrl, template);
  230. render = module.render;
  231. console.log('开发环境模板处理完成');
  232. } else {
  233. // 生产环境:使用缓存的模板
  234. console.log('生产环境: 加载编译后的模板和渲染函数...');
  235. const module = await import('./dist/server/index.js');
  236. // 读取 manifest.json 并处理模板
  237. try {
  238. // 读取 manifest
  239. const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
  240. const manifestContent = await fs.readFile(manifestPath, 'utf-8');
  241. const manifest = JSON.parse(manifestContent);
  242. console.log('生产环境: 成功读取 manifest.json');
  243. // 获取 index.html 对应的资源信息
  244. const indexManifest = manifest['index.html'];
  245. if (!indexManifest) {
  246. throw new Error('manifest 中未找到 index.html 入口配置');
  247. }
  248. template = module.template;
  249. // 替换 CSS 链接
  250. const cssLinks = indexManifest.css?.map(cssFile => {
  251. // 结合基础路径生成完整 URL(处理 base 前缀)
  252. const cssUrl = new URL(cssFile, baseUrl).pathname;
  253. return `<link href="${cssUrl}" rel="stylesheet" />`;
  254. }).join('\n') || ''; // 无 CSS 则清空
  255. // 替换入口脚本
  256. const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
  257. const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
  258. // 执行替换
  259. template = template
  260. .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
  261. .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
  262. console.log('生产环境模板处理完成');
  263. } catch (err) {
  264. console.error('生产环境模板处理失败:', err);
  265. throw err; // 终止启动,避免使用错误模板
  266. }
  267. render = module.render;
  268. }
  269. let didError = false;
  270. let abortController;
  271. // 创建一个可读流用于 SSR 渲染内容
  272. const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
  273. const ssrStream = new Readable({ read: () => {} });
  274. // 写入 HTML 头部
  275. ssrStream.push(htmlStart);
  276. // 设置响应头和状态码
  277. c.header('Content-Type', 'text/html');
  278. // 处理渲染
  279. const { pipe, abort } = render(normalizedUrl, {
  280. onShellError() {
  281. didError = true;
  282. c.status(500);
  283. ssrStream.push('<h1>服务器渲染出错</h1>');
  284. ssrStream.push(null); // 结束流
  285. },
  286. onShellReady() {
  287. console.log(`开始渲染页面: ${normalizedUrl}`);
  288. // 将渲染结果通过管道传入 ssrStream
  289. const transformStream = new Transform({
  290. transform(chunk, encoding, callback) {
  291. ssrStream.push(chunk, encoding);
  292. callback();
  293. }
  294. });
  295. pipe(transformStream);
  296. // 当 transformStream 完成时,添加 HTML 尾部
  297. transformStream.on('finish', () => {
  298. ssrStream.push(htmlEnd);
  299. ssrStream.push(null); // 结束流
  300. console.log(`页面渲染完成: ${normalizedUrl}`);
  301. });
  302. },
  303. onError(error) {
  304. didError = true;
  305. console.error('渲染过程出错:', error);
  306. },
  307. });
  308. // 设置超时中止
  309. abortController = new AbortController();
  310. const abortTimeout = setTimeout(() => {
  311. console.log(`渲染超时,终止请求: ${normalizedUrl}`);
  312. abort();
  313. abortController.abort();
  314. }, ABORT_DELAY);
  315. // 将流通过 Hono 响应返回
  316. return c.body(ssrStream, {
  317. onEnd: () => {
  318. clearTimeout(abortTimeout);
  319. }
  320. });
  321. } catch (e) {
  322. if (!isProduction && vite) {
  323. vite.ssrFixStacktrace(e);
  324. }
  325. console.error('SSR 处理错误:', e.stack);
  326. return c.text('服务器内部错误', 500);
  327. }
  328. });
  329. // 启动服务器
  330. console.log('准备启动服务器...');
  331. parentServer.listen(port, () => {
  332. console.log('========================================');
  333. console.log(`服务器已成功启动!`);
  334. console.log(`访问地址: http://localhost:${port}`);
  335. console.log(`Socket.IO 路径: ${base}socket.io`);
  336. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  337. console.log('========================================');
  338. })
  339. // 统一的服务器关闭处理函数
  340. const shutdownServer = async () => {
  341. console.log('正在关闭服务器...');
  342. // 关闭 Vite 开发服务器(包括 HMR 服务)
  343. if (!isProduction && vite) {
  344. console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
  345. try {
  346. await vite.close();
  347. console.log('Vite 开发服务器已关闭');
  348. } catch (err) {
  349. console.error('关闭 Vite 服务器时出错:', err);
  350. }
  351. }
  352. // 关闭主服务器
  353. parentServer.close((err) => {
  354. if (err) {
  355. console.error('关闭主服务器时出错:', err);
  356. process.exit(1);
  357. }
  358. console.log('主服务器已关闭');
  359. process.exit(0);
  360. });
  361. };
  362. // 处理进程终止信号(包括 Ctrl+C)
  363. process.on('SIGINT', shutdownServer); // 处理 Ctrl+C
  364. process.on('SIGTERM', shutdownServer); // 处理 kill 命令