server.js 11 KB

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