2
0

server.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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, next) => {
  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. await next()
  177. } catch (e) {
  178. if (!isProduction && vite) {
  179. vite.ssrFixStacktrace(e);
  180. }
  181. console.error(e.stack);
  182. return c.text(e.stack, 500);
  183. }
  184. });
  185. // 将请求处理逻辑适配为 Hono 中间件
  186. app.use(async (c) => {
  187. try {
  188. // 使用 c.env 获取原生请求响应对象(关键修复)
  189. const req = c.env.incoming;
  190. const res = c.env.outgoing;
  191. const url = new URL(req.url, `http://${req.headers.host}`);
  192. const path = url.pathname;
  193. // 检查是否匹配基础路径
  194. if (!path.startsWith(baseUrl.pathname)) {
  195. return c.text('Not found', 404);
  196. }
  197. // 处理基础路径
  198. const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
  199. // 处理所有其他请求的 SSR 逻辑
  200. /** @type {string} */
  201. let template;
  202. /** @type {import('./src/server/index.tsx').render} */
  203. let render;
  204. if (!isProduction && vite) {
  205. // 开发环境:读取最新模板并转换
  206. // template = await fs.readFile('./index.html', 'utf-8');
  207. const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
  208. template = module.template;
  209. template = await vite.transformIndexHtml(normalizedUrl, template);
  210. render = module.render;
  211. } else {
  212. // 生产环境:使用缓存的模板
  213. const module = (await import('./dist/server/index.js'))
  214. template = module.template;
  215. render = module.render;
  216. }
  217. let didError = false;
  218. let abortController;
  219. // 创建一个可读流用于 SSR 渲染内容
  220. const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
  221. const ssrStream = new Readable({ read: () => {} });
  222. // 写入 HTML 头部
  223. ssrStream.push(htmlStart);
  224. // 设置响应头和状态码
  225. c.header('Content-Type', 'text/html');
  226. // 处理渲染
  227. const { pipe, abort } = render(normalizedUrl, {
  228. onShellError() {
  229. didError = true;
  230. c.status(500);
  231. ssrStream.push('<h1>Something went wrong</h1>');
  232. ssrStream.push(null); // 结束流
  233. },
  234. onShellReady() {
  235. // 将渲染结果通过管道传入 ssrStream
  236. const transformStream = new Transform({
  237. transform(chunk, encoding, callback) {
  238. ssrStream.push(chunk, encoding);
  239. callback();
  240. }
  241. });
  242. pipe(transformStream);
  243. // 当 transformStream 完成时,添加 HTML 尾部
  244. transformStream.on('finish', () => {
  245. ssrStream.push(htmlEnd);
  246. ssrStream.push(null); // 结束流
  247. });
  248. },
  249. onError(error) {
  250. didError = true;
  251. console.error(error);
  252. },
  253. });
  254. // 设置超时中止
  255. abortController = new AbortController();
  256. const abortTimeout = setTimeout(() => {
  257. abort();
  258. abortController.abort();
  259. }, ABORT_DELAY);
  260. // 将流通过 Hono 响应返回
  261. return c.body(ssrStream, {
  262. onEnd: () => {
  263. clearTimeout(abortTimeout);
  264. }
  265. });
  266. } catch (e) {
  267. if (!isProduction && vite) {
  268. vite.ssrFixStacktrace(e);
  269. }
  270. console.error(e.stack);
  271. return c.text(e.stack, 500);
  272. }
  273. });