befly 3.9.37 → 3.9.39

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 (155) hide show
  1. package/README.md +38 -39
  2. package/befly.config.ts +62 -40
  3. package/checks/checkApi.ts +16 -16
  4. package/checks/checkApp.ts +19 -25
  5. package/checks/checkTable.ts +42 -42
  6. package/docs/README.md +42 -35
  7. package/docs/{api.md → api/api.md} +225 -235
  8. package/docs/cipher.md +71 -69
  9. package/docs/database.md +155 -153
  10. package/docs/{examples.md → guide/examples.md} +181 -181
  11. package/docs/guide/quickstart.md +331 -0
  12. package/docs/hooks/auth.md +38 -0
  13. package/docs/hooks/cors.md +28 -0
  14. package/docs/{hook.md → hooks/hook.md} +140 -57
  15. package/docs/hooks/parser.md +19 -0
  16. package/docs/hooks/rateLimit.md +47 -0
  17. package/docs/{redis.md → infra/redis.md} +84 -93
  18. package/docs/plugins/cipher.md +61 -0
  19. package/docs/plugins/database.md +128 -0
  20. package/docs/{plugin.md → plugins/plugin.md} +83 -81
  21. package/docs/quickstart.md +26 -26
  22. package/docs/{addon.md → reference/addon.md} +46 -46
  23. package/docs/{config.md → reference/config.md} +32 -80
  24. package/docs/{logger.md → reference/logger.md} +52 -52
  25. package/docs/{sync.md → reference/sync.md} +32 -35
  26. package/docs/{table.md → reference/table.md} +7 -7
  27. package/docs/{validator.md → reference/validator.md} +57 -57
  28. package/hooks/auth.ts +8 -4
  29. package/hooks/cors.ts +13 -13
  30. package/hooks/parser.ts +37 -17
  31. package/hooks/permission.ts +26 -14
  32. package/hooks/rateLimit.ts +276 -0
  33. package/hooks/validator.ts +15 -7
  34. package/lib/asyncContext.ts +43 -0
  35. package/lib/cacheHelper.ts +212 -81
  36. package/lib/cacheKeys.ts +38 -0
  37. package/lib/cipher.ts +30 -30
  38. package/lib/connect.ts +28 -28
  39. package/lib/dbHelper.ts +211 -109
  40. package/lib/jwt.ts +16 -16
  41. package/lib/logger.ts +610 -19
  42. package/lib/redisHelper.ts +185 -44
  43. package/lib/sqlBuilder.ts +90 -91
  44. package/lib/validator.ts +59 -39
  45. package/loader/loadApis.ts +53 -47
  46. package/loader/loadHooks.ts +40 -14
  47. package/loader/loadPlugins.ts +16 -17
  48. package/main.ts +57 -47
  49. package/package.json +47 -45
  50. package/paths.ts +15 -14
  51. package/plugins/cache.ts +5 -4
  52. package/plugins/cipher.ts +3 -3
  53. package/plugins/config.ts +2 -2
  54. package/plugins/db.ts +9 -9
  55. package/plugins/jwt.ts +3 -3
  56. package/plugins/logger.ts +8 -12
  57. package/plugins/redis.ts +8 -8
  58. package/plugins/tool.ts +6 -6
  59. package/router/api.ts +85 -56
  60. package/router/static.ts +12 -12
  61. package/sync/syncAll.ts +12 -12
  62. package/sync/syncApi.ts +55 -54
  63. package/sync/syncDb/apply.ts +20 -19
  64. package/sync/syncDb/constants.ts +25 -23
  65. package/sync/syncDb/ddl.ts +35 -36
  66. package/sync/syncDb/helpers.ts +6 -9
  67. package/sync/syncDb/schema.ts +10 -9
  68. package/sync/syncDb/sqlite.ts +7 -8
  69. package/sync/syncDb/table.ts +37 -35
  70. package/sync/syncDb/tableCreate.ts +21 -20
  71. package/sync/syncDb/types.ts +23 -20
  72. package/sync/syncDb/version.ts +10 -10
  73. package/sync/syncDb.ts +43 -36
  74. package/sync/syncDev.ts +74 -66
  75. package/sync/syncMenu.ts +190 -57
  76. package/tests/api-integration-array-number.test.ts +282 -0
  77. package/tests/befly-config-env.test.ts +78 -0
  78. package/tests/cacheHelper.test.ts +135 -104
  79. package/tests/cacheKeys.test.ts +41 -0
  80. package/tests/cipher.test.ts +90 -89
  81. package/tests/dbHelper-advanced.test.ts +140 -134
  82. package/tests/dbHelper-all-array-types.test.ts +316 -0
  83. package/tests/dbHelper-array-serialization.test.ts +258 -0
  84. package/tests/dbHelper-columns.test.ts +56 -55
  85. package/tests/dbHelper-execute.test.ts +45 -44
  86. package/tests/dbHelper-joins.test.ts +124 -119
  87. package/tests/fields-redis-cache.test.ts +29 -27
  88. package/tests/fields-validate.test.ts +38 -38
  89. package/tests/getClientIp.test.ts +54 -0
  90. package/tests/integration.test.ts +69 -67
  91. package/tests/jwt.test.ts +27 -26
  92. package/tests/logger.test.ts +267 -34
  93. package/tests/rateLimit-hook.test.ts +477 -0
  94. package/tests/redisHelper.test.ts +187 -188
  95. package/tests/redisKeys.test.ts +6 -73
  96. package/tests/scanConfig.test.ts +144 -0
  97. package/tests/sqlBuilder-advanced.test.ts +217 -215
  98. package/tests/sqlBuilder.test.ts +92 -91
  99. package/tests/sync-connection.test.ts +29 -29
  100. package/tests/syncDb-apply.test.ts +97 -96
  101. package/tests/syncDb-array-number.test.ts +160 -0
  102. package/tests/syncDb-constants.test.ts +48 -47
  103. package/tests/syncDb-ddl.test.ts +99 -98
  104. package/tests/syncDb-helpers.test.ts +29 -28
  105. package/tests/syncDb-schema.test.ts +61 -60
  106. package/tests/syncDb-types.test.ts +60 -59
  107. package/tests/syncMenu-paths.test.ts +68 -0
  108. package/tests/util.test.ts +42 -41
  109. package/tests/validator-array-number.test.ts +310 -0
  110. package/tests/validator-default.test.ts +373 -0
  111. package/tests/validator.test.ts +271 -266
  112. package/tsconfig.json +4 -5
  113. package/types/api.d.ts +7 -12
  114. package/types/befly.d.ts +60 -13
  115. package/types/cache.d.ts +8 -4
  116. package/types/common.d.ts +17 -9
  117. package/types/context.d.ts +2 -2
  118. package/types/crypto.d.ts +23 -0
  119. package/types/database.d.ts +19 -19
  120. package/types/hook.d.ts +2 -2
  121. package/types/jwt.d.ts +118 -0
  122. package/types/logger.d.ts +30 -0
  123. package/types/plugin.d.ts +4 -4
  124. package/types/redis.d.ts +7 -3
  125. package/types/roleApisCache.ts +23 -0
  126. package/types/sync.d.ts +10 -10
  127. package/types/table.d.ts +50 -9
  128. package/types/validate.d.ts +69 -0
  129. package/utils/addonHelper.ts +90 -0
  130. package/utils/arrayKeysToCamel.ts +18 -0
  131. package/utils/calcPerfTime.ts +13 -0
  132. package/utils/configTypes.ts +3 -0
  133. package/utils/cors.ts +19 -0
  134. package/utils/fieldClear.ts +75 -0
  135. package/utils/genShortId.ts +12 -0
  136. package/utils/getClientIp.ts +45 -0
  137. package/utils/keysToCamel.ts +22 -0
  138. package/utils/keysToSnake.ts +22 -0
  139. package/utils/modules.ts +98 -0
  140. package/utils/pickFields.ts +19 -0
  141. package/utils/process.ts +56 -0
  142. package/utils/regex.ts +225 -0
  143. package/utils/response.ts +115 -0
  144. package/utils/route.ts +23 -0
  145. package/utils/scanConfig.ts +142 -0
  146. package/utils/scanFiles.ts +48 -0
  147. package/.prettierignore +0 -2
  148. package/.prettierrc +0 -12
  149. package/docs/1-/345/237/272/346/234/254/344/273/213/347/273/215.md +0 -35
  150. package/docs/2-/345/210/235/346/255/245/344/275/223/351/252/214.md +0 -64
  151. package/docs/3-/347/254/254/344/270/200/344/270/252/346/216/245/345/217/243.md +0 -46
  152. package/docs/4-/346/223/215/344/275/234/346/225/260/346/215/256/345/272/223.md +0 -172
  153. package/hooks/requestLogger.ts +0 -84
  154. package/types/index.ts +0 -24
  155. package/util.ts +0 -283
package/util.ts DELETED
@@ -1,283 +0,0 @@
1
- /**
2
- * 核心工具函数
3
- */
4
-
5
- // 内部依赖
6
- import { existsSync } from 'node:fs';
7
-
8
- /**
9
- * 进程角色信息
10
- */
11
- export interface ProcessRole {
12
- /** 进程角色:primary(主进程)或 worker(工作进程) */
13
- role: 'primary' | 'worker';
14
- /** 实例 ID(PM2 或 Bun Worker) */
15
- instanceId: string | null;
16
- /** 运行环境:bun-cluster、pm2-cluster 或 standalone */
17
- env: 'bun-cluster' | 'pm2-cluster' | 'standalone';
18
- }
19
-
20
- /**
21
- * 获取当前进程角色信息
22
- * @returns 进程角色、实例 ID 和运行环境
23
- */
24
- export function getProcessRole(): ProcessRole {
25
- const bunWorkerId = process.env.BUN_WORKER_ID;
26
- const pm2InstanceId = process.env.PM2_INSTANCE_ID;
27
-
28
- // Bun 集群模式
29
- if (bunWorkerId !== undefined) {
30
- return {
31
- role: bunWorkerId === '' ? 'primary' : 'worker',
32
- instanceId: bunWorkerId || '0',
33
- env: 'bun-cluster'
34
- };
35
- }
36
-
37
- // PM2 集群模式
38
- if (pm2InstanceId !== undefined) {
39
- return {
40
- role: pm2InstanceId === '0' ? 'primary' : 'worker',
41
- instanceId: pm2InstanceId,
42
- env: 'pm2-cluster'
43
- };
44
- }
45
-
46
- // 单进程模式
47
- return {
48
- role: 'primary',
49
- instanceId: null,
50
- env: 'standalone'
51
- };
52
- }
53
-
54
- /**
55
- * 检测当前进程是否为主进程
56
- * 用于集群模式下避免重复执行同步任务
57
- * - Bun 集群:BUN_WORKER_ID 为空时是主进程
58
- * - PM2 集群:PM2_INSTANCE_ID 为 '0' 或不存在时是主进程
59
- * @returns 是否为主进程
60
- */
61
- export function isPrimaryProcess(): boolean {
62
- return getProcessRole().role === 'primary';
63
- }
64
-
65
- // 外部依赖
66
- import { camelCase } from 'es-toolkit/string';
67
- import { scanFiles } from 'befly-shared/scanFiles';
68
-
69
- // 相对导入
70
- import { Logger } from './lib/logger.js';
71
-
72
- // 类型导入
73
- import type { Plugin } from './types/plugin.js';
74
- import type { Hook } from './types/hook.js';
75
- import type { CorsConfig, BeflyContext } from './types/befly.js';
76
- import type { RequestContext } from './types/context.js';
77
- import type { PluginRequestHook, Next } from './types/plugin.js';
78
-
79
- /**
80
- * 创建错误响应(专用于 Hook 中间件)
81
- * 在钩子中提前拦截请求时使用
82
- * @param ctx - 请求上下文
83
- * @param msg - 错误消息
84
- * @param code - 错误码,默认 1
85
- * @param data - 附加数据,默认 null
86
- * @param detail - 详细信息,用于标记具体提示位置,默认 null
87
- * @returns Response 对象
88
- */
89
- export function ErrorResponse(ctx: RequestContext, msg: string, code: number = 1, data: any = null, detail: any = null): Response {
90
- // 记录拦截日志
91
- if (ctx.requestId) {
92
- const duration = Date.now() - ctx.now;
93
- const user = ctx.user?.id ? `[User:${ctx.user.id} ${ctx.user.nickname}]` : '[Guest]';
94
- Logger.info(`[${ctx.requestId}] ${ctx.route} ${user} ${duration}ms [${msg}]`);
95
- }
96
-
97
- return Response.json(
98
- {
99
- code: code,
100
- msg: msg,
101
- data: data,
102
- detail: detail
103
- },
104
- {
105
- headers: ctx.corsHeaders
106
- }
107
- );
108
- }
109
-
110
- /**
111
- * 创建最终响应(专用于 API 路由结尾)
112
- * 自动处理 ctx.response/ctx.result,并记录请求日志
113
- * @param ctx - 请求上下文
114
- * @returns Response 对象
115
- */
116
- export function FinalResponse(ctx: RequestContext): Response {
117
- // 记录请求日志
118
- if (ctx.api && ctx.requestId) {
119
- const duration = Date.now() - ctx.now;
120
- const user = ctx.user?.id ? `[User:${ctx.user.id} ${ctx.user.nickname}]` : '[Guest]';
121
- Logger.info(`[${ctx.requestId}] ${ctx.route} ${user} ${duration}ms`);
122
- }
123
-
124
- // 1. 如果已经有 response,直接返回
125
- if (ctx.response) {
126
- return ctx.response;
127
- }
128
-
129
- // 2. 如果有 result,格式化为响应
130
- if (ctx.result !== undefined) {
131
- let result = ctx.result;
132
-
133
- // 如果是字符串,自动包裹为成功响应
134
- if (typeof result === 'string') {
135
- result = {
136
- code: 0,
137
- msg: result
138
- };
139
- }
140
- // 如果是对象,自动补充 code: 0
141
- else if (result && typeof result === 'object') {
142
- if (!('code' in result)) {
143
- result = {
144
- code: 0,
145
- ...result
146
- };
147
- }
148
- }
149
-
150
- // 处理 BigInt 序列化问题
151
- if (result && typeof result === 'object') {
152
- const jsonString = JSON.stringify(result, (key, value) => (typeof value === 'bigint' ? value.toString() : value));
153
- return new Response(jsonString, {
154
- headers: {
155
- ...ctx.corsHeaders,
156
- 'Content-Type': 'application/json'
157
- }
158
- });
159
- } else {
160
- return Response.json(result, {
161
- headers: ctx.corsHeaders
162
- });
163
- }
164
- }
165
-
166
- // 3. 默认响应:没有生成响应
167
- return Response.json(
168
- {
169
- code: 1,
170
- msg: '未生成响应'
171
- },
172
- {
173
- headers: ctx.corsHeaders
174
- }
175
- );
176
- }
177
-
178
- /**
179
- * 设置 CORS 响应头
180
- * @param req - 请求对象
181
- * @param config - CORS 配置(可选)
182
- * @returns CORS 响应头对象
183
- */
184
- export function setCorsOptions(req: Request, config: CorsConfig = {}): Record<string, string> {
185
- const origin = config.origin || '*';
186
- return {
187
- 'Access-Control-Allow-Origin': origin === '*' ? req.headers.get('origin') || '*' : origin,
188
- 'Access-Control-Allow-Methods': config.methods || 'GET, POST, PUT, DELETE, OPTIONS',
189
- 'Access-Control-Allow-Headers': config.allowedHeaders || 'Content-Type, Authorization, authorization, token',
190
- 'Access-Control-Expose-Headers': config.exposedHeaders || 'Content-Range, X-Content-Range, Authorization, authorization, token',
191
- 'Access-Control-Max-Age': String(config.maxAge || 86400),
192
- 'Access-Control-Allow-Credentials': config.credentials || 'true'
193
- };
194
- }
195
-
196
- /**
197
- * 扫描模块(插件或钩子)
198
- * @param dir - 目录路径
199
- * @param type - 模块类型(core/addon/app)
200
- * @param moduleLabel - 模块标签(如"插件"、"钩子")
201
- * @param addonName - 组件名称(仅 type='addon' 时需要)
202
- * @returns 模块列表
203
- */
204
- export async function scanModules<T extends Plugin | Hook>(dir: string, type: 'core' | 'addon' | 'app', moduleLabel: string, addonName?: string): Promise<T[]> {
205
- if (!existsSync(dir)) return [];
206
-
207
- const items: T[] = [];
208
- const files = await scanFiles(dir, '*.{ts,js}');
209
-
210
- for (const { filePath, fileName } of files) {
211
- // 生成模块名称
212
- const name = camelCase(fileName);
213
- const moduleName = type === 'core' ? name : type === 'addon' ? `addon_${camelCase(addonName!)}_${name}` : `app_${name}`;
214
-
215
- try {
216
- const normalizedFilePath = filePath.replace(/\\/g, '/');
217
- const moduleImport = await import(normalizedFilePath);
218
- const item = moduleImport.default;
219
-
220
- item.name = moduleName;
221
- // 为 addon 模块记录 addon 名称
222
- if (type === 'addon' && addonName) {
223
- item.addonName = addonName;
224
- }
225
- items.push(item);
226
- } catch (err: any) {
227
- const typeLabel = type === 'core' ? '核心' : type === 'addon' ? `组件${addonName}` : '项目';
228
- Logger.error({ err: err, module: fileName }, `${typeLabel}${moduleLabel} 导入失败`);
229
- process.exit(1);
230
- }
231
- }
232
-
233
- return items;
234
- }
235
-
236
- /**
237
- * 排序模块(根据依赖关系)
238
- * @param modules - 待排序的模块列表
239
- * @returns 排序后的模块列表,如果存在循环依赖或依赖不存在则返回 false
240
- */
241
- export function sortModules<T extends { name?: string; after?: string[] }>(modules: T[]): T[] | false {
242
- const result: T[] = [];
243
- const visited = new Set<string>();
244
- const visiting = new Set<string>();
245
- const moduleMap: Record<string, T> = Object.fromEntries(modules.map((m) => [m.name!, m]));
246
- let isPass = true;
247
-
248
- // 检查依赖是否存在
249
- for (const module of modules) {
250
- if (module.after) {
251
- for (const dep of module.after) {
252
- if (!moduleMap[dep]) {
253
- Logger.error({ module: module.name, dependency: dep }, '依赖的模块未找到');
254
- isPass = false;
255
- }
256
- }
257
- }
258
- }
259
-
260
- if (!isPass) return false;
261
-
262
- const visit = (name: string): void => {
263
- if (visited.has(name)) return;
264
- if (visiting.has(name)) {
265
- Logger.error({ module: name }, '模块循环依赖');
266
- isPass = false;
267
- return;
268
- }
269
-
270
- const module = moduleMap[name];
271
- if (!module) return;
272
-
273
- visiting.add(name);
274
- (module.after || []).forEach(visit);
275
- visiting.delete(name);
276
- visited.add(name);
277
- result.push(module);
278
- };
279
-
280
- modules.forEach((m) => visit(m.name!));
281
-
282
- return isPass ? result : false;
283
- }