vafast 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/auth/token.d.ts +40 -0
  2. package/dist/auth/token.js +124 -0
  3. package/dist/defineRoute.d.ts +2 -0
  4. package/dist/defineRoute.js +3 -0
  5. package/dist/index.d.ts +14 -459
  6. package/dist/index.js +14 -1400
  7. package/dist/index.js.map +1 -0
  8. package/dist/middleware/auth.d.ts +14 -0
  9. package/dist/middleware/auth.js +106 -0
  10. package/dist/middleware/authMiddleware.d.ts +2 -0
  11. package/dist/middleware/authMiddleware.js +13 -0
  12. package/dist/middleware/component-renderer.d.ts +6 -0
  13. package/dist/middleware/component-renderer.js +136 -0
  14. package/dist/middleware/component-router.d.ts +10 -0
  15. package/dist/middleware/component-router.js +39 -0
  16. package/dist/middleware/cors.d.ts +9 -0
  17. package/dist/middleware/cors.js +30 -0
  18. package/dist/middleware/rateLimit.d.ts +8 -0
  19. package/dist/middleware/rateLimit.js +33 -0
  20. package/dist/middleware.d.ts +18 -0
  21. package/dist/middleware.js +51 -0
  22. package/dist/monitoring/index.d.ts +29 -0
  23. package/dist/monitoring/index.js +24 -0
  24. package/dist/monitoring/native-monitor.d.ts +38 -0
  25. package/dist/monitoring/native-monitor.js +176 -0
  26. package/dist/monitoring/types.d.ts +146 -0
  27. package/dist/monitoring/types.js +8 -0
  28. package/dist/router.d.ts +17 -0
  29. package/dist/router.js +74 -0
  30. package/dist/server/base-server.d.ts +38 -0
  31. package/dist/server/base-server.js +167 -0
  32. package/dist/server/component-server.d.ts +32 -0
  33. package/dist/server/component-server.js +146 -0
  34. package/dist/server/index.d.ts +7 -0
  35. package/dist/server/index.js +9 -0
  36. package/dist/server/server-factory.d.ts +42 -0
  37. package/dist/server/server-factory.js +70 -0
  38. package/dist/server/server.d.ts +7 -0
  39. package/dist/server/server.js +73 -0
  40. package/dist/types/component-route.d.ts +25 -0
  41. package/dist/types/component-route.js +1 -0
  42. package/dist/types/route.d.ts +37 -0
  43. package/dist/types/route.js +1 -0
  44. package/dist/types.d.ts +18 -0
  45. package/dist/types.js +1 -0
  46. package/dist/utils/base64url.d.ts +2 -0
  47. package/dist/utils/base64url.js +11 -0
  48. package/dist/utils/dependency-manager.d.ts +23 -0
  49. package/dist/utils/dependency-manager.js +67 -0
  50. package/dist/utils/go-await.d.ts +26 -0
  51. package/dist/utils/go-await.js +33 -0
  52. package/dist/utils/handle.d.ts +10 -0
  53. package/dist/utils/handle.js +24 -0
  54. package/dist/utils/html-renderer.d.ts +18 -0
  55. package/dist/utils/html-renderer.js +64 -0
  56. package/dist/utils/parsers.d.ts +36 -0
  57. package/dist/utils/parsers.js +126 -0
  58. package/dist/utils/path-matcher.d.ts +23 -0
  59. package/dist/utils/path-matcher.js +82 -0
  60. package/dist/utils/request-validator.d.ts +63 -0
  61. package/dist/utils/request-validator.js +94 -0
  62. package/dist/utils/response.d.ts +12 -0
  63. package/dist/utils/response.js +69 -0
  64. package/dist/utils/route-handler-factory.d.ts +50 -0
  65. package/dist/utils/route-handler-factory.js +181 -0
  66. package/dist/utils/validators/schema-validator.d.ts +66 -0
  67. package/dist/utils/validators/schema-validator.js +222 -0
  68. package/dist/utils/validators/schema-validators-ultra.d.ts +51 -0
  69. package/dist/utils/validators/schema-validators-ultra.js +289 -0
  70. package/dist/utils/validators/validators.d.ts +30 -0
  71. package/dist/utils/validators/validators.js +54 -0
  72. package/package.json +3 -4
@@ -0,0 +1,167 @@
1
+ /**
2
+ * 服务器基类
3
+ * 包含所有服务器类型的公共逻辑
4
+ */
5
+ export class BaseServer {
6
+ globalMiddleware = [];
7
+ use(mw) {
8
+ this.globalMiddleware.push(mw);
9
+ }
10
+ /**
11
+ * 打印扁平化后的路由信息,用于调试
12
+ */
13
+ logFlattenedRoutes(routes, type = "路由") {
14
+ console.log(`🚀 扁平化后的${type}:`);
15
+ for (const route of routes) {
16
+ const method = route.method || "GET";
17
+ const path = route.fullPath || route.path;
18
+ console.log(` ${method} ${path}`);
19
+ if (route.middlewareChain && route.middlewareChain.length > 0) {
20
+ console.log(` 中间件链: ${route.middlewareChain.length} 个`);
21
+ }
22
+ }
23
+ console.log("");
24
+ }
25
+ /**
26
+ * 检测路由冲突
27
+ * 检查是否有路径相同但方法不同的路由,以及潜在的路径冲突
28
+ */
29
+ detectRouteConflicts(routes) {
30
+ const pathGroups = new Map();
31
+ // 按路径分组
32
+ for (const route of routes) {
33
+ const path = route.fullPath || route.path;
34
+ const method = route.method || "GET";
35
+ if (!pathGroups.has(path)) {
36
+ pathGroups.set(path, []);
37
+ }
38
+ pathGroups.get(path).push({ ...route, method });
39
+ }
40
+ // 检查冲突
41
+ for (const [path, routeList] of pathGroups) {
42
+ if (routeList.length > 1) {
43
+ const methods = routeList.map((r) => r.method);
44
+ const uniqueMethods = [...new Set(methods)];
45
+ if (uniqueMethods.length === 1) {
46
+ // 相同路径、相同方法 - 这是冲突!
47
+ console.warn(`⚠️ 路由冲突: ${uniqueMethods[0]} ${path} 定义了 ${routeList.length} 次`);
48
+ routeList.forEach((route, index) => {
49
+ console.warn(` ${index + 1}. ${route.method} ${path}`);
50
+ });
51
+ }
52
+ else {
53
+ // 相同路径、不同方法 - 这是正常的
54
+ console.log(`ℹ️ 路径 ${path} 支持方法: ${uniqueMethods.join(", ")}`);
55
+ }
56
+ }
57
+ }
58
+ // 检查潜在的路径冲突(动态路由可能冲突)
59
+ this.detectDynamicRouteConflicts(routes);
60
+ }
61
+ /**
62
+ * 检测动态路由的潜在冲突
63
+ */
64
+ detectDynamicRouteConflicts(routes) {
65
+ const dynamicRoutes = routes.filter((r) => {
66
+ const path = r.fullPath || r.path;
67
+ return path.includes(":") || path.includes("*");
68
+ });
69
+ for (let i = 0; i < dynamicRoutes.length; i++) {
70
+ for (let j = i + 1; j < dynamicRoutes.length; j++) {
71
+ const route1 = dynamicRoutes[i];
72
+ const route2 = dynamicRoutes[j];
73
+ const method1 = route1.method || "GET";
74
+ const method2 = route2.method || "GET";
75
+ if (method1 === method2) {
76
+ const path1 = route1.fullPath || route1.path;
77
+ const path2 = route2.fullPath || route2.path;
78
+ // 检查路径是否可能冲突
79
+ if (this.pathsMayConflict(path1, path2)) {
80
+ console.warn(`⚠️ 潜在路由冲突: ${method1} ${path1} 可能与 ${path2} 冲突`);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+ /**
87
+ * 判断两个路径是否可能冲突
88
+ */
89
+ pathsMayConflict(path1, path2) {
90
+ const parts1 = path1.split("/").filter(Boolean);
91
+ const parts2 = path2.split("/").filter(Boolean);
92
+ if (parts1.length !== parts2.length)
93
+ return false;
94
+ for (let i = 0; i < parts1.length; i++) {
95
+ const p1 = parts1[i];
96
+ const p2 = parts2[i];
97
+ // 如果两个部分都是静态的且不同,则不会冲突
98
+ if (!p1.startsWith(":") &&
99
+ !p1.startsWith("*") &&
100
+ !p2.startsWith(":") &&
101
+ !p2.startsWith("*") &&
102
+ p1 !== p2) {
103
+ return false;
104
+ }
105
+ // 如果一个是通配符,另一个是动态参数,可能冲突
106
+ if ((p1 === "*" && p2.startsWith(":")) ||
107
+ (p2 === "*" && p1.startsWith(":"))) {
108
+ return true;
109
+ }
110
+ }
111
+ return false;
112
+ }
113
+ /**
114
+ * 路径匹配
115
+ */
116
+ matchPath(pattern, path) {
117
+ const patternParts = pattern.split("/").filter(Boolean);
118
+ const pathParts = path.split("/").filter(Boolean);
119
+ if (patternParts.length !== pathParts.length) {
120
+ return false;
121
+ }
122
+ for (let i = 0; i < patternParts.length; i++) {
123
+ if (patternParts[i] !== pathParts[i] && !patternParts[i].startsWith(":")) {
124
+ return false;
125
+ }
126
+ }
127
+ return true;
128
+ }
129
+ /**
130
+ * 提取路径参数
131
+ */
132
+ extractParams(pattern, path) {
133
+ const params = {};
134
+ const patternParts = pattern.split("/").filter(Boolean);
135
+ const pathParts = path.split("/").filter(Boolean);
136
+ for (let i = 0; i < patternParts.length; i++) {
137
+ if (patternParts[i].startsWith(":")) {
138
+ const paramName = patternParts[i].slice(1);
139
+ params[paramName] = pathParts[i];
140
+ }
141
+ }
142
+ return params;
143
+ }
144
+ /**
145
+ * 处理 OPTIONS 请求
146
+ */
147
+ handleOptions(pathname, routes) {
148
+ const availableMethods = [];
149
+ for (const route of routes) {
150
+ const path = route.fullPath || route.path;
151
+ const method = route.method || "GET";
152
+ if (this.matchPath(path, pathname)) {
153
+ availableMethods.push(method);
154
+ }
155
+ }
156
+ // 去重并排序
157
+ const uniqueMethods = [...new Set(availableMethods)].sort();
158
+ return new Response(null, {
159
+ status: 204,
160
+ headers: {
161
+ Allow: uniqueMethods.join(", "),
162
+ "Access-Control-Allow-Methods": uniqueMethods.join(", "),
163
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
164
+ },
165
+ });
166
+ }
167
+ }
@@ -0,0 +1,32 @@
1
+ import type { ComponentRoute, NestedComponentRoute } from "../types/component-route";
2
+ import { BaseServer } from "./base-server";
3
+ import { DependencyManager } from "../utils/dependency-manager";
4
+ /**
5
+ * 组件路由服务器
6
+ * 专门处理声明式组件路由
7
+ */
8
+ export declare class ComponentServer extends BaseServer {
9
+ private routes;
10
+ private dependencyManager;
11
+ constructor(routes: (ComponentRoute | NestedComponentRoute)[]);
12
+ /**
13
+ * 处理请求
14
+ */
15
+ fetch(req: Request): Promise<Response>;
16
+ /**
17
+ * 执行中间件链
18
+ */
19
+ private executeMiddlewareChain;
20
+ /**
21
+ * 渲染 Vue 组件
22
+ */
23
+ private renderVueComponent;
24
+ /**
25
+ * 渲染 React 组件
26
+ */
27
+ private renderReactComponent;
28
+ /**
29
+ * 获取依赖管理器(用于外部访问)
30
+ */
31
+ getDependencyManager(): DependencyManager;
32
+ }
@@ -0,0 +1,146 @@
1
+ import { flattenComponentRoutes } from "../middleware/component-router";
2
+ import { BaseServer } from "./base-server";
3
+ import { PathMatcher } from "../utils/path-matcher";
4
+ import { HtmlRenderer } from "../utils/html-renderer";
5
+ import { DependencyManager } from "../utils/dependency-manager";
6
+ /**
7
+ * 组件路由服务器
8
+ * 专门处理声明式组件路由
9
+ */
10
+ export class ComponentServer extends BaseServer {
11
+ routes;
12
+ dependencyManager;
13
+ constructor(routes) {
14
+ super();
15
+ this.routes = flattenComponentRoutes(routes);
16
+ this.dependencyManager = new DependencyManager();
17
+ // 检测路由冲突
18
+ this.detectRouteConflicts(this.routes);
19
+ this.logFlattenedRoutes(this.routes, "组件路由");
20
+ console.log("🚀 依赖按需加载,服务器启动完成");
21
+ }
22
+ /**
23
+ * 处理请求
24
+ */
25
+ async fetch(req) {
26
+ const url = new URL(req.url);
27
+ const pathname = url.pathname;
28
+ const method = req.method;
29
+ // 只支持 GET 请求
30
+ if (method !== "GET") {
31
+ return new Response("Method Not Allowed", { status: 405 });
32
+ }
33
+ // 查找匹配的路由
34
+ let matchedRoute = null;
35
+ for (const route of this.routes) {
36
+ if (PathMatcher.matchPath(route.fullPath, pathname)) {
37
+ matchedRoute = route;
38
+ break;
39
+ }
40
+ }
41
+ if (!matchedRoute) {
42
+ return new Response("Not Found", { status: 404 });
43
+ }
44
+ try {
45
+ // 创建中间件上下文
46
+ const context = {
47
+ req,
48
+ params: PathMatcher.extractParams(matchedRoute.fullPath, pathname),
49
+ query: Object.fromEntries(url.searchParams),
50
+ pathname,
51
+ };
52
+ // 执行中间件链,中间件会处理组件渲染
53
+ return await this.executeMiddlewareChain(matchedRoute.middlewareChain, context, matchedRoute.component);
54
+ }
55
+ catch (error) {
56
+ console.error("组件渲染失败:", error);
57
+ return new Response("Internal Server Error", { status: 500 });
58
+ }
59
+ }
60
+ /**
61
+ * 执行中间件链
62
+ */
63
+ async executeMiddlewareChain(middlewareChain, context, componentImport) {
64
+ // 创建最终的渲染函数
65
+ const renderComponent = async () => {
66
+ const componentModule = await componentImport();
67
+ const component = componentModule.default || componentModule;
68
+ // 自动检测组件类型
69
+ const componentType = this.dependencyManager.detectComponentType(component);
70
+ // 按需加载依赖
71
+ const deps = await this.dependencyManager.getFrameworkDeps(componentType);
72
+ // 根据组件类型渲染
73
+ if (componentType === "vue") {
74
+ return await this.renderVueComponent(component, context, deps);
75
+ }
76
+ else if (componentType === "react") {
77
+ return await this.renderReactComponent(component, context, deps);
78
+ }
79
+ else {
80
+ throw new Error(`不支持的组件类型: ${componentType}`);
81
+ }
82
+ };
83
+ // 执行中间件链
84
+ let index = 0;
85
+ const next = async () => {
86
+ if (index >= middlewareChain.length) {
87
+ return await renderComponent();
88
+ }
89
+ const middleware = middlewareChain[index++];
90
+ return await middleware(context.req, next);
91
+ };
92
+ return await next();
93
+ }
94
+ /**
95
+ * 渲染 Vue 组件
96
+ */
97
+ async renderVueComponent(component, context, deps) {
98
+ try {
99
+ const [vue, renderer] = deps;
100
+ const app = vue.createSSRApp(component);
101
+ // 提供路由信息
102
+ app.provide("routeInfo", {
103
+ params: context.params || {},
104
+ query: context.query || {},
105
+ pathname: context.pathname,
106
+ });
107
+ const html = await renderer.renderToString(app);
108
+ const fullHtml = HtmlRenderer.generateVueHtml(html, context);
109
+ return new Response(fullHtml, {
110
+ headers: { "Content-Type": "text/html; charset=utf-8" },
111
+ });
112
+ }
113
+ catch (error) {
114
+ console.error("Vue 组件渲染失败:", error);
115
+ return new Response("Vue Component Render Error", { status: 500 });
116
+ }
117
+ }
118
+ /**
119
+ * 渲染 React 组件
120
+ */
121
+ async renderReactComponent(component, context, deps) {
122
+ try {
123
+ const [react, renderer] = deps;
124
+ const content = react.createElement(component, {
125
+ req: context.req,
126
+ params: context.params || {},
127
+ query: context.query || {},
128
+ });
129
+ const html = renderer.renderToString(content);
130
+ const fullHtml = HtmlRenderer.generateReactHtml(html, context);
131
+ return new Response(fullHtml, {
132
+ headers: { "Content-Type": "text/html; charset=utf-8" },
133
+ });
134
+ }
135
+ catch (error) {
136
+ console.error("React 组件渲染失败:", error);
137
+ return new Response("React Component Render Error", { status: 500 });
138
+ }
139
+ }
140
+ /**
141
+ * 获取依赖管理器(用于外部访问)
142
+ */
143
+ getDependencyManager() {
144
+ return this.dependencyManager;
145
+ }
146
+ }
@@ -0,0 +1,7 @@
1
+ export { Server } from "./server";
2
+ export { ComponentServer } from "./component-server";
3
+ export { BaseServer } from "./base-server";
4
+ export { ServerFactory } from "./server-factory";
5
+ export { PathMatcher } from "../utils/path-matcher";
6
+ export { HtmlRenderer } from "../utils/html-renderer";
7
+ export { DependencyManager } from "../utils/dependency-manager";
@@ -0,0 +1,9 @@
1
+ // 导出所有服务器相关的类和工具
2
+ export { Server } from "./server";
3
+ export { ComponentServer } from "./component-server";
4
+ export { BaseServer } from "./base-server";
5
+ export { ServerFactory } from "./server-factory";
6
+ // 导出工具类
7
+ export { PathMatcher } from "../utils/path-matcher";
8
+ export { HtmlRenderer } from "../utils/html-renderer";
9
+ export { DependencyManager } from "../utils/dependency-manager";
@@ -0,0 +1,42 @@
1
+ import type { Route, NestedRoute } from "../types";
2
+ import type { ComponentRoute, NestedComponentRoute } from "../types/component-route";
3
+ import { Server } from "../server";
4
+ import { ComponentServer } from "./component-server";
5
+ /**
6
+ * 服务器工厂类
7
+ * 用于创建和管理不同类型的服务器
8
+ */
9
+ export declare class ServerFactory {
10
+ private servers;
11
+ /**
12
+ * 创建标准REST API服务器
13
+ */
14
+ createRestServer(routes: (Route | NestedRoute)[]): Server;
15
+ /**
16
+ * 创建组件服务器
17
+ */
18
+ createComponentServer(routes: (ComponentRoute | NestedComponentRoute)[]): ComponentServer;
19
+ /**
20
+ * 获取指定类型的服务器
21
+ */
22
+ getServer(type: "rest" | "component"): Server | ComponentServer | undefined;
23
+ /**
24
+ * 获取所有服务器
25
+ */
26
+ getAllServers(): Map<string, Server | ComponentServer>;
27
+ /**
28
+ * 移除指定类型的服务器
29
+ */
30
+ removeServer(type: string): boolean;
31
+ /**
32
+ * 清除所有服务器
33
+ */
34
+ clearServers(): void;
35
+ /**
36
+ * 获取服务器状态信息
37
+ */
38
+ getServerStatus(): Record<string, {
39
+ type: string;
40
+ routes: number;
41
+ }>;
42
+ }
@@ -0,0 +1,70 @@
1
+ import { Server } from "../server";
2
+ import { ComponentServer } from "./component-server";
3
+ /**
4
+ * 服务器工厂类
5
+ * 用于创建和管理不同类型的服务器
6
+ */
7
+ export class ServerFactory {
8
+ servers = new Map();
9
+ /**
10
+ * 创建标准REST API服务器
11
+ */
12
+ createRestServer(routes) {
13
+ const server = new Server(routes);
14
+ this.servers.set("rest", server);
15
+ return server;
16
+ }
17
+ /**
18
+ * 创建组件服务器
19
+ */
20
+ createComponentServer(routes) {
21
+ const server = new ComponentServer(routes);
22
+ this.servers.set("component", server);
23
+ return server;
24
+ }
25
+ /**
26
+ * 获取指定类型的服务器
27
+ */
28
+ getServer(type) {
29
+ return this.servers.get(type);
30
+ }
31
+ /**
32
+ * 获取所有服务器
33
+ */
34
+ getAllServers() {
35
+ return this.servers;
36
+ }
37
+ /**
38
+ * 移除指定类型的服务器
39
+ */
40
+ removeServer(type) {
41
+ return this.servers.delete(type);
42
+ }
43
+ /**
44
+ * 清除所有服务器
45
+ */
46
+ clearServers() {
47
+ this.servers.clear();
48
+ }
49
+ /**
50
+ * 获取服务器状态信息
51
+ */
52
+ getServerStatus() {
53
+ const status = {};
54
+ for (const [name, server] of this.servers) {
55
+ if (server instanceof Server) {
56
+ status[name] = {
57
+ type: "REST API",
58
+ routes: server.routes?.length || 0,
59
+ };
60
+ }
61
+ else if (server instanceof ComponentServer) {
62
+ status[name] = {
63
+ type: "Component",
64
+ routes: server.routes?.length || 0,
65
+ };
66
+ }
67
+ }
68
+ return status;
69
+ }
70
+ }
@@ -0,0 +1,7 @@
1
+ import type { Route, NestedRoute } from "../types";
2
+ import { BaseServer } from "./base-server";
3
+ export declare class Server extends BaseServer {
4
+ private routes;
5
+ constructor(routes: (Route | NestedRoute)[]);
6
+ fetch: (req: Request) => Promise<Response>;
7
+ }
@@ -0,0 +1,73 @@
1
+ import { matchPath, flattenNestedRoutes } from "../router";
2
+ import { composeMiddleware } from "../middleware";
3
+ import { json } from "../utils/response";
4
+ import { BaseServer } from "./base-server";
5
+ import { PathMatcher } from "../utils/path-matcher";
6
+ export class Server extends BaseServer {
7
+ routes;
8
+ constructor(routes) {
9
+ super();
10
+ // 扁平化嵌套路由,计算完整的中间件链
11
+ this.routes = flattenNestedRoutes(routes);
12
+ // 在构造时按路由"特异性"排序:静态 > 动态(:param) > 通配符(*)
13
+ this.routes = this.routes.sort((a, b) => PathMatcher.calculatePathScore(b.fullPath) -
14
+ PathMatcher.calculatePathScore(a.fullPath));
15
+ // 检测路由冲突
16
+ this.detectRouteConflicts(this.routes);
17
+ // 打印扁平化后的路由信息
18
+ this.logFlattenedRoutes(this.routes);
19
+ }
20
+ fetch = async (req) => {
21
+ const { pathname } = new URL(req.url);
22
+ const method = req.method;
23
+ // 自动处理 OPTIONS 请求
24
+ if (method === "OPTIONS") {
25
+ return this.handleOptions(pathname, this.routes);
26
+ }
27
+ let matched;
28
+ let params = {};
29
+ let availableMethods = [];
30
+ for (const route of this.routes) {
31
+ const result = matchPath(route.fullPath, pathname);
32
+ if (result.matched) {
33
+ if (route.method === method) {
34
+ matched = route;
35
+ params = result.params;
36
+ break;
37
+ }
38
+ else {
39
+ // 路径匹配但方法不匹配,收集可用方法
40
+ availableMethods.push(route.method);
41
+ }
42
+ }
43
+ }
44
+ const handler = async (req) => {
45
+ if (matched) {
46
+ // 将路径参数设置到 req 对象上,以便 TypedRoute 处理器能够访问
47
+ req.params = params;
48
+ return await matched.handler(req, params);
49
+ }
50
+ else if (availableMethods.length > 0) {
51
+ // 路径存在但方法不匹配,返回 405 Method Not Allowed
52
+ return json({
53
+ success: false,
54
+ error: "Method Not Allowed",
55
+ message: `Method ${method} not allowed for this endpoint`,
56
+ allowedMethods: availableMethods,
57
+ }, 405, {
58
+ Allow: availableMethods.join(", "),
59
+ });
60
+ }
61
+ else {
62
+ // 路径不存在,返回 404 Not Found
63
+ return json({ success: false, error: "Not Found" }, 404);
64
+ }
65
+ };
66
+ const middlewareChain = matched?.middlewareChain
67
+ ? [...this.globalMiddleware, ...matched.middlewareChain]
68
+ : this.globalMiddleware;
69
+ // 使用 composeMiddleware 来确保错误处理中间件被应用
70
+ const composedHandler = composeMiddleware(middlewareChain, handler);
71
+ return await composedHandler(req);
72
+ };
73
+ }
@@ -0,0 +1,25 @@
1
+ import type { Middleware } from "./route";
2
+ /**
3
+ * 组件路由配置
4
+ * 支持声明式的组件关联
5
+ */
6
+ export interface ComponentRoute {
7
+ path: string;
8
+ component: () => Promise<any>;
9
+ middleware?: Middleware[];
10
+ }
11
+ /**
12
+ * 嵌套组件路由配置
13
+ */
14
+ export interface NestedComponentRoute {
15
+ path: string;
16
+ middleware?: Middleware[];
17
+ children?: (ComponentRoute | NestedComponentRoute)[];
18
+ }
19
+ /**
20
+ * 扁平化后的组件路由
21
+ */
22
+ export interface FlattenedComponentRoute extends ComponentRoute {
23
+ fullPath: string;
24
+ middlewareChain: Middleware[];
25
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import { Route } from "..";
2
+ export interface Middleware {
3
+ (req: Request, next: () => Promise<Response>): Promise<Response>;
4
+ }
5
+ export interface BaseRouteConfig {
6
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD";
7
+ path: string;
8
+ handler: (req: Request) => Response | Promise<Response>;
9
+ }
10
+ export interface ExtendedRouteConfig extends BaseRouteConfig {
11
+ middleware?: Middleware[];
12
+ body?: any;
13
+ query?: any;
14
+ params?: any;
15
+ headers?: any;
16
+ cookies?: any;
17
+ docs?: {
18
+ description?: string;
19
+ tags?: string[];
20
+ security?: any[];
21
+ responses?: Record<string, any>;
22
+ };
23
+ timeout?: number;
24
+ maxBodySize?: string;
25
+ [key: string]: any;
26
+ }
27
+ export interface NestedRouteConfig {
28
+ path: string;
29
+ middleware?: Middleware[];
30
+ children?: (NestedRouteConfig | ExtendedRouteConfig)[];
31
+ }
32
+ export type TypedRoute = ExtendedRouteConfig;
33
+ export type CompatibleRoute = Route | TypedRoute;
34
+ export interface FlattenedRoute extends ExtendedRouteConfig {
35
+ fullPath: string;
36
+ middlewareChain: Middleware[];
37
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ export type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD";
2
+ export type Handler = (req: Request, params?: Record<string, string>, user?: Record<string, any>) => Response | Promise<Response>;
3
+ export type Middleware = (req: Request, next: () => Promise<Response>) => Promise<Response>;
4
+ export interface Route {
5
+ method: Method;
6
+ path: string;
7
+ handler: Handler;
8
+ middleware?: Middleware[];
9
+ }
10
+ export interface NestedRoute {
11
+ path: string;
12
+ middleware?: Middleware[];
13
+ children?: (NestedRoute | Route)[];
14
+ }
15
+ export interface FlattenedRoute extends Route {
16
+ fullPath: string;
17
+ middlewareChain: Middleware[];
18
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function base64urlEncode(str: string): string;
2
+ export declare function base64urlDecode(str: string): string;
@@ -0,0 +1,11 @@
1
+ export function base64urlEncode(str) {
2
+ return btoa(str)
3
+ .replace(/=/g, "") // ✅ 删除填充
4
+ .replace(/\+/g, "-")
5
+ .replace(/\//g, "_");
6
+ }
7
+ export function base64urlDecode(str) {
8
+ const pad = str.length % 4 === 0 ? "" : "=".repeat(4 - (str.length % 4));
9
+ const base64 = str.replace(/-/g, "+").replace(/_/g, "/") + pad;
10
+ return atob(base64);
11
+ }