2
0

server.js 13 KB

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