Pārlūkot izejas kodu

✨ feat(deps): 添加dotenv和iframe通信插件依赖
- 添加dotenv@17.2.1用于环境变量管理
- 添加vite-plugin-iframe-communicator@0.0.10实现iframe通信

♻️ refactor(server): 重构服务器请求处理逻辑
- 引入dotenv配置加载
- 优化服务器初始化流程和代码结构
- 统一请求处理中间件,合并API和SSR渲染逻辑
- 提取模板处理函数,分离开发/生产环境逻辑

✨ feat(vite): 增强vite配置支持iframe通信
- 配置iframeCommunicationPlugin实现跨域通信
- 优化构建配置,指定客户端入口文件
- 调整开发服务器设置,优化HMR体验

♻️ refactor(api): 重构API路由加载方式
- 开发环境动态加载最新API模块
- 生产环境使用缓存的API路由
- 通过临时子应用处理API请求,提高隔离性

🔧 chore(process): 优化进程信号处理
- 简化SIGINT和SIGTERM信号处理代码
- 改进服务器关闭流程日志输出

yourname 4 mēneši atpakaļ
vecāks
revīzija
ab12401870
5 mainītis faili ar 205 papildinājumiem un 160 dzēšanām
  1. 3 1
      package.json
  2. 27 0
      pnpm-lock.yaml
  3. 157 159
      server.js
  4. 2 0
      src/server/index.tsx
  5. 16 0
      vite.config.ts

+ 3 - 1
package.json

@@ -25,6 +25,7 @@
     "compression": "^1.8.0",
     "dayjs": "^1.11.13",
     "debug": "^4.4.1",
+    "dotenv": "^17.2.1",
     "hono": "^4.8.5",
     "jsonwebtoken": "^9.0.2",
     "mysql2": "^3.14.2",
@@ -38,8 +39,8 @@
     "typeorm": "^0.3.25"
   },
   "devDependencies": {
-    "@types/debug": "^4.1.12",
     "@tailwindcss/vite": "^4.1.11",
+    "@types/debug": "^4.1.12",
     "@types/express": "^5.0.3",
     "@types/node": "^24.0.10",
     "@types/react": "^19.1.8",
@@ -50,6 +51,7 @@
     "tsx": "^4.20.3",
     "typescript": "~5.8.3",
     "vite": "^7.0.0",
+    "vite-plugin-iframe-communicator": "^0.0.10",
     "vite-progress-tracking-plugin": "^0.0.2"
   }
 }

+ 27 - 0
pnpm-lock.yaml

@@ -47,6 +47,9 @@ importers:
       debug:
         specifier: ^4.4.1
         version: 4.4.1
+      dotenv:
+        specifier: ^17.2.1
+        version: 17.2.1
       hono:
         specifier: ^4.8.5
         version: 4.8.9
@@ -117,6 +120,9 @@ importers:
       vite:
         specifier: ^7.0.0
         version: 7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0)
+      vite-plugin-iframe-communicator:
+        specifier: ^0.0.10
+        version: 0.0.10(vite@7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0))
       vite-progress-tracking-plugin:
         specifier: ^0.0.2
         version: 0.0.2(vite@7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0))
@@ -956,6 +962,9 @@ packages:
   csstype@3.1.3:
     resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
 
+  d8d-iframe-communicator@0.0.10:
+    resolution: {integrity: sha512-VuBVcXE2ZdW6eSvJ13TBM1nkau6I8RzIcPpHF9XopLiLvx6AylIujVHEFQ4Fl6kGuABnh6VdulMCkC4zr7R0zA==}
+
   dayjs@1.11.13:
     resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==}
 
@@ -1004,6 +1013,10 @@ packages:
     resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}
     engines: {node: '>=12'}
 
+  dotenv@17.2.1:
+    resolution: {integrity: sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==}
+    engines: {node: '>=12'}
+
   dunder-proto@1.0.1:
     resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
     engines: {node: '>= 0.4'}
@@ -1878,6 +1891,11 @@ packages:
     resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
     engines: {node: '>= 0.8'}
 
+  vite-plugin-iframe-communicator@0.0.10:
+    resolution: {integrity: sha512-gvgqH+GueeKAxRuW/oQR7bXjTf0W5svSz2P/6UgeknWrAHczexTZOuAEwhisPVqeOlwomwLwkof0dddQPKHF2A==}
+    peerDependencies:
+      vite: ^7.0.0
+
   vite-progress-tracking-plugin@0.0.2:
     resolution: {integrity: sha512-tm5KIwicitTSw+7EVZT3rJ7gLkv7LNloFAxUhJRYCvZ3jQh85l3/GYHHMwl2HbuAaPDYEQOUB2w5IM3fC/a12w==}
     peerDependencies:
@@ -2709,6 +2727,8 @@ snapshots:
 
   csstype@3.1.3: {}
 
+  d8d-iframe-communicator@0.0.10: {}
+
   dayjs@1.11.13: {}
 
   debug@2.6.9:
@@ -2735,6 +2755,8 @@ snapshots:
 
   dotenv@16.6.1: {}
 
+  dotenv@17.2.1: {}
+
   dunder-proto@1.0.1:
     dependencies:
       call-bind-apply-helpers: 1.0.2
@@ -3632,6 +3654,11 @@ snapshots:
 
   vary@1.1.2: {}
 
+  vite-plugin-iframe-communicator@0.0.10(vite@7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0)):
+    dependencies:
+      d8d-iframe-communicator: 0.0.10
+      vite: 7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0)
+
   vite-progress-tracking-plugin@0.0.2(vite@7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0)):
     dependencies:
       vite: 7.0.6(@types/node@24.1.0)(jiti@2.5.1)(lightningcss@1.30.1)(tsx@4.20.3)(yaml@2.8.0)

+ 157 - 159
server.js

@@ -1,20 +1,19 @@
+import 'dotenv/config'
 import fs from 'node:fs/promises';
 import { URL } from 'node:url';
 import { Transform } from 'node:stream';
 import { Readable } from 'node:stream';
-import { pipeline } from 'node:stream/promises';
 import { Hono } from 'hono';
-import { logger } from 'hono/logger'; // 引入 Hono 日志中间件
+import { logger } from 'hono/logger';
 import { createServer as createNodeServer } from 'node:http';
 import process from 'node:process';
 import { createAdaptorServer } from '@hono/node-server'  
 
-
 // 创建 Hono 应用
-const app = new Hono();// API路由
+const app = new Hono();
 
-// 全局使用 Hono 日志中间件(记录所有请求)
-app.use('*', logger()); // 新增:添加请求日志中间件
+// 全局使用 Hono 日志中间件
+app.use('*', logger());
 
 // 常量定义
 const isProduction = process.env.NODE_ENV === 'production';
@@ -29,17 +28,17 @@ console.log(`端口: ${port}`);
 console.log(`基础路径: ${base}`);
 console.log('========================================');
 
-// 解析基础路径为 URL 对象,方便后续处理
+// 解析基础路径为 URL 对象
 const baseUrl = new URL(base, `http://localhost:${port}`);
 console.log(`基础URL解析完成: ${baseUrl.href}`);
 
-// 创建服务器实例  
+// 创建服务器实例
 console.log('正在创建服务器实例...');
 const parentServer = createAdaptorServer({  
   fetch: app.fetch,  
   createServer: createNodeServer,  
   port: port,  
-})  
+})
 console.log('服务器实例创建成功');
 
 // 生产环境中间件
@@ -62,18 +61,18 @@ if (!isProduction) {
   console.log('开发环境: 初始化 Vite 开发服务器...');
   const { createServer } = await import('vite');
   vite = await createServer({
-    server: { middlewareMode: {
+    server: { 
+      middlewareMode: {
         server: parentServer
       },
       hmr: {  
         port: 8081,
-        clientPort: 443, // 或其他可用端口  
+        clientPort: 443,
         path: 'vite-hmr'
       },
       proxy: {
         '/vite-hmr': {
           target: 'ws://localhost:8081',
-          // 代理 WebSocket
           ws: true,
         },
       },
@@ -84,169 +83,77 @@ if (!isProduction) {
   console.log('Vite 开发服务器初始化完成');
 }
 
-// 加载 API 路由
-if (!isProduction) {
-  console.log('开发环境: 从 Vite 加载 API 路由...');
-  const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
-  app.route('/', apiModule.default);
-  console.log('API 路由加载完成');
-}else{
-  console.log('生产环境: 加载编译后的 API 路由...');
-  const api = (await import('./dist/api/api.js')).default
-  app.route('/', api);
-  console.log('API 路由加载完成');
-}
-
-// 请求处理中间件 - 通用逻辑
-app.use(async (c, next) => {
-  try {
-    // 使用 c.env 获取原生请求响应对象
-    const req = c.env.incoming;
-    const res = c.env.outgoing;
-    const url = new URL(req.url, `http://${req.headers.host}`);
-    const path = url.pathname;
 
-    // 检查是否匹配基础路径
-    if (!path.startsWith(baseUrl.pathname)) {
-      return c.text('未找到', 404);
-    }
+// 开发环境模板处理函数 - 仅处理模板转换
+const processDevTemplate = async (template) => {
+  if (!isProduction && vite) {
+    console.log('开发环境: 处理模板...');
+    const processedTemplate = await vite.transformIndexHtml('/', template);
+    console.log('开发环境模板处理完成');
+    return processedTemplate;
+  }
+  return template;
+};
 
-    // 开发环境:使用 Vite 中间件
-    if (!isProduction && vite) {
-      // 使用 Vite 中间件处理请求
-      const handled = await new Promise((resolve) => {
-        vite.middlewares(req, res, () => resolve(false));
-      });
-      
-      // 如果 Vite 中间件已经处理了请求,直接返回
-      if (handled) {
-        return c.body;
-      }
-    } 
-    // 生产环境:使用 compression 和 sirv 中间件
-    else if (isProduction) {
-      // 先尝试 compression 中间件
-      const compressed = await new Promise((resolve) => {
-        compressionMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (compressed) {
-        return c.body;
-      }
-      
-      // 再尝试 sirv 中间件处理静态文件
-      const served = await new Promise((resolve) => {
-        sirvMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (served) {
-        return c.body;
-      }
+// 生产环境模板处理函数 - 仅处理资源路径替换
+const processProdTemplate = async (template) => {
+  console.log('生产环境: 处理模板资源路径...');
+  try {
+    // 读取 manifest
+    const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
+    const manifestContent = await fs.readFile(manifestPath, 'utf-8');
+    const manifest = JSON.parse(manifestContent);
+    console.log('生产环境: 成功读取 manifest.json');
+
+    // 获取 src/client/index.tsx 对应的资源信息
+    const indexManifest = manifest['src/client/index.tsx'];
+    if (!indexManifest) {
+      throw new Error('manifest 中未找到 src/client/index.tsx 入口配置');
     }
 
-    await next()
-  } catch (e) {
-    if (!isProduction && vite) {
-      vite.ssrFixStacktrace(e);
+    // 获取 src/style.css 对应的资源信息
+    const styleManifest = manifest['src/style.css'];
+    if (!styleManifest) {
+      throw new Error('manifest 中未找到 src/style.css 入口配置');
     }
-    console.error('请求处理中间件错误:', e.stack);
-    return c.text('服务器内部错误', 500);
-  }
-});
 
-// 请求处理中间件 - SSR 渲染逻辑
-app.use(async (c) => {
-  
-  try {
-    // 使用 c.env 获取原生请求响应对象
-    const req = c.env.incoming;
-    const res = c.env.outgoing;
-    const url = new URL(req.url, `http://${req.headers.host}`);
-    const path = url.pathname;
+    const cssPath = new URL(styleManifest.file, baseUrl).pathname;
+    const cssLinks = `<link href="${cssPath}" rel="stylesheet" />`;
 
-    // 检查是否匹配基础路径
-    if (!path.startsWith(baseUrl.pathname)) {
-      return c.text('未找到', 404);
-    }
+    // 替换入口脚本
+    const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
+    const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
 
-    // 处理基础路径
-    const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
-    console.log(`处理请求: ${normalizedUrl}`);
+    // 执行替换
+    const processedTemplate = template
+      .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
+      .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
 
-    // 处理所有其他请求的 SSR 逻辑
-    /** @type {string} */
-    let template;
-    /** @type {import('./src/server/index.tsx').render} */
-    let render;
-    
-    if (!isProduction && vite) {
-      console.log('开发环境: 加载模板和渲染函数...');
-      // 开发环境:读取最新模板并转换
-      const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
-      template = module.template;
-      template = await vite.transformIndexHtml(normalizedUrl, template);
-      render = module.render;
-      console.log('开发环境模板处理完成');
-    } else {
-      // 生产环境:使用缓存的模板
-      console.log('生产环境: 加载编译后的模板和渲染函数...');
-      const module = await import('./dist/server/index.js');
-      
-      // 读取 manifest.json 并处理模板
-      try {
-        // 读取 manifest
-        const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
-        const manifestContent = await fs.readFile(manifestPath, 'utf-8');
-        const manifest = JSON.parse(manifestContent);
-        console.log('生产环境: 成功读取 manifest.json');
-
-        // 获取 index.html 对应的资源信息
-        const indexManifest = manifest['index.html'];
-        if (!indexManifest) {
-          throw new Error('manifest 中未找到 index.html 入口配置');
-        }
-
-        template = module.template;
-
-        // 替换 CSS 链接
-        const cssLinks = indexManifest.css?.map(cssFile => {
-          // 结合基础路径生成完整 URL(处理 base 前缀)
-          const cssUrl = new URL(cssFile, baseUrl).pathname;
-          return `<link href="${cssUrl}" rel="stylesheet" />`;
-        }).join('\n') || ''; // 无 CSS 则清空
-
-        // 替换入口脚本
-        const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
-        const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
-
-        // 执行替换
-        template = template
-          .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
-          .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
-
-        console.log('生产环境模板处理完成');
-
-      } catch (err) {
-        console.error('生产环境模板处理失败:', err);
-        throw err; // 终止启动,避免使用错误模板
-      }
+    console.log('生产环境模板处理完成');
+    return processedTemplate;
 
-      render = module.render;
-    }
+  } catch (err) {
+    console.error('生产环境模板处理失败:', err);
+    throw err;
+  }
+};
 
+// SSR 渲染中间件函数
+const createSsrHandler = (template, render, normalizedUrl) => {
+  return async (c) => {
     let didError = false;
     let abortController;
 
     // 创建一个可读流用于 SSR 渲染内容
     const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
     const ssrStream = new Readable({ read: () => {} });
-    
+
     // 写入 HTML 头部
     ssrStream.push(htmlStart);
 
     // 设置响应头和状态码
     c.header('Content-Type', 'text/html');
-    
+
     // 处理渲染
     const { pipe, abort } = render(normalizedUrl, {
       onShellError() {
@@ -266,7 +173,7 @@ app.use(async (c) => {
         });
 
         pipe(transformStream);
-        
+
         // 当 transformStream 完成时,添加 HTML 尾部
         transformStream.on('finish', () => {
           ssrStream.push(htmlEnd);
@@ -294,15 +201,106 @@ app.use(async (c) => {
         clearTimeout(abortTimeout);
       }
     });
+  };
+};
+
+// 统一的请求处理中间件 - 合并 API 和 SSR 渲染逻辑
+app.use(async (c) => {
+  try {
+    // 使用 c.env 获取原生请求响应对象
+    const req = c.env.incoming;
+    const res = c.env.outgoing;
+    const url = new URL(req.url, `http://${req.headers.host}`);
+    const path = url.pathname;
+
+    // 检查是否匹配基础路径
+    if (!path.startsWith(baseUrl.pathname)) {
+      return c.text('未找到', 404);
+    }
+
+    // 处理基础路径
+    const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
+    console.log(`处理请求: ${normalizedUrl}`);
+
+    // 开发环境:使用 Vite 中间件
+    if (!isProduction && vite) {
+      // 使用 Vite 中间件处理请求
+      const handled = await new Promise((resolve) => {
+        vite.middlewares(req, res, () => resolve(false));
+      });
+      
+      // 如果 Vite 中间件已经处理了请求,直接返回
+      if (handled) {
+        return c.body;
+      }
+
+
+      // 动态加载最新 API 模块
+      const apiModule = await vite.ssrLoadModule('./src/server/index.tsx');
+      
+      // 创建临时子应用并挂载路由
+      const apiApp = new Hono();
+      apiApp.route('/', apiModule.api);
+      
+      // 处理开发环境模板
+      const template = await processDevTemplate(apiModule.template);
+      apiApp.get('*', createSsrHandler(template, apiModule.render, normalizedUrl));
+
+      // 直接由子应用处理 API 请求
+      return apiApp.fetch(c.req.raw, {
+        ...c.env,
+        // 传递原始请求对象
+        incoming: c.env.incoming,
+        outgoing: c.env.outgoing
+      });
+    }
+    // 生产环境:使用 compression 和 sirv 中间件
+    else if (isProduction) {
+      // 先尝试 compression 中间件
+      const compressed = await new Promise((resolve) => {
+        compressionMiddleware(req, res, () => resolve(false));
+      });
+      
+      if (compressed) {
+        return c.body;
+      }
+      
+      // 再尝试 sirv 中间件处理静态文件
+      const served = await new Promise((resolve) => {
+        sirvMiddleware(req, res, () => resolve(false));
+      });
+      
+      if (served) {
+        return c.body;
+      }
+
+      // 生产环境:使用缓存的 API 路由
+      const { api, template: rawTemplate, render } = (await import('./dist/server/index.js'));
+      const apiApp = new Hono();
+      apiApp.route('/', api);
+
+      // 处理生产环境模板
+      const template = await processProdTemplate(rawTemplate);
+      apiApp.get('*', createSsrHandler(template, render, normalizedUrl));
+
+      return apiApp.fetch(c.req.raw, {
+        ...c.env,
+        incoming: c.env.incoming,
+        outgoing: c.env.outgoing
+      });
+    }
+
   } catch (e) {
     if (!isProduction && vite) {
       vite.ssrFixStacktrace(e);
     }
-    console.error('SSR 处理错误:', e.stack);
+    console.error('请求处理错误:', e.stack);
     return c.text('服务器内部错误', 500);
   }
 });
 
+// 移除生产环境的 API 路由预加载(已在统一中间件中处理)
+// 移除动态 API 路由中间件(已合并到统一中间件中)
 
 // 启动服务器
 console.log('准备启动服务器...');
@@ -322,7 +320,7 @@ const shutdownServer = async () => {
   if (!isProduction && vite) {
     console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
     try {
-      await vite.close(); // 关闭 Vite 实例,会自动终止 HMR 服务(8081 端口)
+      await vite.close();
       console.log('Vite 开发服务器已关闭');
     } catch (err) {
       console.error('关闭 Vite 服务器时出错:', err);
@@ -340,6 +338,6 @@ const shutdownServer = async () => {
   });
 };
 
-// 处理进程终止信号(包括 Ctrl+C)
-process.on('SIGINT', shutdownServer);  // 处理 Ctrl+C
-process.on('SIGTERM', shutdownServer); // 处理 kill 命令
+// 处理进程终止信号
+process.on('SIGINT', shutdownServer);
+process.on('SIGTERM', shutdownServer);

+ 2 - 0
src/server/index.tsx

@@ -23,3 +23,5 @@ export const template = renderToStaticMarkup(
   <Rooter />
 );
 
+// 导出 API 路由
+export { default as api } from './api';

+ 16 - 0
vite.config.ts

@@ -2,6 +2,7 @@ import { defineConfig } from 'vite'
 import react from '@vitejs/plugin-react-swc'
 import tailwindcss from '@tailwindcss/vite'
 import { progressTrackingPlugin } from 'vite-progress-tracking-plugin';
+import iframeCommunicationPlugin from 'vite-plugin-iframe-communicator';
 
 // https://vite.dev/config/
 export default defineConfig({
@@ -11,6 +12,9 @@ export default defineConfig({
     }),
     tailwindcss(),
     progressTrackingPlugin(),
+    iframeCommunicationPlugin({
+      hostOrigin: '*', // 可信的主页面源
+    })
   ],
   server: {
     allowedHosts:true
@@ -21,4 +25,16 @@ export default defineConfig({
       '@': '/src',
     },
   },
+  // 构建配置
+  build: {
+    // 对于SSR,我们不需要默认的index.html入口
+    // 为客户端构建指定JS入口文件
+    rollupOptions: {
+      input: {
+        // 这里指定你的客户端入口JS文件
+        main: 'src/client/index.tsx',
+        styles: 'src/style.css',
+      },
+    },
+  },
 })