server.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 { serve } from '@hono/node-server';
  7. import { Hono } from 'hono';
  8. import { createServer as createNodeServer } from 'node:http';
  9. import process from 'node:process';
  10. // 创建 Hono 应用
  11. const app = new Hono();// API路由
  12. import api from './src/server/api.ts';
  13. app.route('/', api);
  14. // Constants
  15. const isProduction = process.env.NODE_ENV === 'production';
  16. const port = process.env.PORT || 8080;
  17. const base = process.env.BASE || '/';
  18. const ABORT_DELAY = 10000;
  19. // 解析基础路径为 URL 对象,方便后续处理
  20. const baseUrl = new URL(base, `http://localhost:${port}`);
  21. // 使用 Hono 的 serve 启动服务器
  22. const parentServer = serve({
  23. fetch: app.fetch,
  24. createServer: createNodeServer,
  25. port: port,
  26. }, () => {
  27. console.log(`Server started at http://localhost:${port}`);
  28. });
  29. // Cached production assets
  30. let templateHtml = '';
  31. if (isProduction) {
  32. templateHtml = await fs.readFile('./dist/client/index.html', 'utf-8');
  33. }
  34. // 生产环境中间件
  35. let compressionMiddleware;
  36. let sirvMiddleware;
  37. if (isProduction) {
  38. compressionMiddleware = (await import('compression')).default();
  39. sirvMiddleware = (await import('sirv')).default('./dist/client', {
  40. extensions: [],
  41. baseUrl: base
  42. });
  43. }
  44. // Vite 开发服务器
  45. /** @type {import('vite').ViteDevServer | undefined} */
  46. let vite;
  47. if (!isProduction) {
  48. const { createServer } = await import('vite');
  49. vite = await createServer({
  50. server: { middlewareMode: {
  51. server: parentServer
  52. },
  53. hmr: {
  54. port: 8081,
  55. clientPort: 443, // 或其他可用端口
  56. path: 'vite-hmr'
  57. },
  58. proxy: {
  59. '/vite-hmr': {
  60. target: 'ws://localhost:8081',
  61. // Proxying WebSocket
  62. ws: true,
  63. },
  64. },
  65. },
  66. appType: 'custom',
  67. base,
  68. });
  69. }
  70. // 将请求处理逻辑适配为 Hono 中间件
  71. app.use(async (c) => {
  72. try {
  73. // 使用 c.env 获取原生请求响应对象(关键修复)
  74. const req = c.env.incoming;
  75. const res = c.env.outgoing;
  76. const url = new URL(req.url, `http://${req.headers.host}`);
  77. const path = url.pathname;
  78. // 检查是否匹配基础路径
  79. if (!path.startsWith(baseUrl.pathname)) {
  80. return c.text('Not found', 404);
  81. }
  82. // 处理基础路径
  83. const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
  84. // 开发环境:使用 Vite 中间件
  85. if (!isProduction && vite) {
  86. // 使用 Vite 中间件处理请求
  87. const handled = await new Promise((resolve) => {
  88. vite.middlewares(req, res, () => resolve(false));
  89. });
  90. // 如果 Vite 中间件已经处理了请求,直接返回
  91. if (handled) {
  92. return c.body;
  93. }
  94. }
  95. // 生产环境:使用 compression 和 sirv 中间件
  96. else if (isProduction) {
  97. // 先尝试 compression 中间件
  98. const compressed = await new Promise((resolve) => {
  99. compressionMiddleware(req, res, () => resolve(false));
  100. });
  101. if (compressed) {
  102. return c.body;
  103. }
  104. // 再尝试 sirv 中间件处理静态文件
  105. const served = await new Promise((resolve) => {
  106. sirvMiddleware(req, res, () => resolve(false));
  107. });
  108. if (served) {
  109. return c.body;
  110. }
  111. }
  112. // 处理所有其他请求的 SSR 逻辑
  113. /** @type {string} */
  114. let template;
  115. /** @type {import('./src/server/index.tsx').render} */
  116. let render;
  117. if (!isProduction && vite) {
  118. // 开发环境:读取最新模板并转换
  119. template = await fs.readFile('./index.html', 'utf-8');
  120. template = await vite.transformIndexHtml(normalizedUrl, template);
  121. render = (await vite.ssrLoadModule('/src/server/index.tsx')).render;
  122. } else {
  123. // 生产环境:使用缓存的模板
  124. template = templateHtml;
  125. render = (await import('./dist/server/index.js')).render;
  126. }
  127. let didError = false;
  128. let abortController;
  129. // 创建一个可读流用于 SSR 渲染内容
  130. const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
  131. const ssrStream = new Readable({ read: () => {} });
  132. // 写入 HTML 头部
  133. ssrStream.push(htmlStart);
  134. // 设置响应头和状态码
  135. c.header('Content-Type', 'text/html');
  136. // 处理渲染
  137. const { pipe, abort } = render(normalizedUrl, {
  138. onShellError() {
  139. didError = true;
  140. c.status(500);
  141. ssrStream.push('<h1>Something went wrong</h1>');
  142. ssrStream.push(null); // 结束流
  143. },
  144. onShellReady() {
  145. // 将渲染结果通过管道传入 ssrStream
  146. const transformStream = new Transform({
  147. transform(chunk, encoding, callback) {
  148. ssrStream.push(chunk, encoding);
  149. callback();
  150. }
  151. });
  152. pipe(transformStream);
  153. // 当 transformStream 完成时,添加 HTML 尾部
  154. transformStream.on('finish', () => {
  155. ssrStream.push(htmlEnd);
  156. ssrStream.push(null); // 结束流
  157. });
  158. },
  159. onError(error) {
  160. didError = true;
  161. console.error(error);
  162. },
  163. });
  164. // 设置超时中止
  165. abortController = new AbortController();
  166. const abortTimeout = setTimeout(() => {
  167. abort();
  168. abortController.abort();
  169. }, ABORT_DELAY);
  170. // 将流通过 Hono 响应返回
  171. return c.body(ssrStream, {
  172. onEnd: () => {
  173. clearTimeout(abortTimeout);
  174. }
  175. });
  176. } catch (e) {
  177. if (!isProduction && vite) {
  178. vite.ssrFixStacktrace(e);
  179. }
  180. console.error(e.stack);
  181. return c.text(e.stack, 500);
  182. }
  183. });