befly 3.10.18 → 3.11.1

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 (223) hide show
  1. package/README.md +83 -307
  2. package/dist/befly.config.d.ts +7 -0
  3. package/{befly.config.ts → dist/befly.config.js} +11 -36
  4. package/dist/befly.js +15621 -0
  5. package/dist/befly.min.js +21 -0
  6. package/dist/checks/checkApi.d.ts +1 -0
  7. package/{checks/checkApi.ts → dist/checks/checkApi.js} +12 -30
  8. package/dist/checks/checkHook.d.ts +1 -0
  9. package/dist/checks/checkHook.js +86 -0
  10. package/dist/checks/checkMenu.d.ts +7 -0
  11. package/{checks/checkMenu.ts → dist/checks/checkMenu.js} +18 -53
  12. package/dist/checks/checkPlugin.d.ts +1 -0
  13. package/dist/checks/checkPlugin.js +86 -0
  14. package/dist/checks/checkTable.d.ts +6 -0
  15. package/{checks/checkTable.ts → dist/checks/checkTable.js} +17 -41
  16. package/dist/configs/presetFields.d.ts +4 -0
  17. package/{configs/presetFields.ts → dist/configs/presetFields.js} +1 -1
  18. package/dist/configs/presetRegexp.d.ts +145 -0
  19. package/{utils/regex.ts → dist/configs/presetRegexp.js} +8 -31
  20. package/dist/hooks/auth.d.ts +7 -0
  21. package/{hooks/auth.ts → dist/hooks/auth.js} +8 -10
  22. package/dist/hooks/cors.d.ts +11 -0
  23. package/{hooks/cors.ts → dist/hooks/cors.js} +5 -13
  24. package/dist/hooks/parser.d.ts +14 -0
  25. package/{hooks/parser.ts → dist/hooks/parser.js} +31 -45
  26. package/dist/hooks/permission.d.ts +14 -0
  27. package/{hooks/permission.ts → dist/hooks/permission.js} +16 -25
  28. package/dist/hooks/validator.d.ts +11 -0
  29. package/{hooks/validator.ts → dist/hooks/validator.js} +9 -14
  30. package/dist/index.d.ts +26 -0
  31. package/{main.ts → dist/index.js} +61 -100
  32. package/dist/lib/asyncContext.d.ts +21 -0
  33. package/dist/lib/asyncContext.js +27 -0
  34. package/dist/lib/cacheHelper.d.ts +95 -0
  35. package/{lib/cacheHelper.ts → dist/lib/cacheHelper.js} +45 -105
  36. package/dist/lib/cacheKeys.d.ts +23 -0
  37. package/{lib/cacheKeys.ts → dist/lib/cacheKeys.js} +5 -10
  38. package/dist/lib/cipher.d.ts +153 -0
  39. package/{lib/cipher.ts → dist/lib/cipher.js} +23 -44
  40. package/dist/lib/connect.d.ts +91 -0
  41. package/{lib/connect.ts → dist/lib/connect.js} +47 -88
  42. package/dist/lib/dbDialect.d.ts +87 -0
  43. package/{lib/dbDialect.ts → dist/lib/dbDialect.js} +32 -112
  44. package/dist/lib/dbHelper.d.ts +204 -0
  45. package/{lib/dbHelper.ts → dist/lib/dbHelper.js} +82 -241
  46. package/dist/lib/dbUtils.d.ts +68 -0
  47. package/{lib/dbUtils.ts → dist/lib/dbUtils.js} +51 -126
  48. package/dist/lib/jwt.d.ts +13 -0
  49. package/{lib/jwt.ts → dist/lib/jwt.js} +11 -32
  50. package/dist/lib/logger.d.ts +42 -0
  51. package/dist/lib/logger.js +1144 -0
  52. package/dist/lib/redisHelper.d.ts +185 -0
  53. package/{lib/redisHelper.ts → dist/lib/redisHelper.js} +97 -141
  54. package/dist/lib/sqlBuilder.d.ts +160 -0
  55. package/{lib/sqlBuilder.ts → dist/lib/sqlBuilder.js} +132 -278
  56. package/dist/lib/sqlCheck.d.ts +23 -0
  57. package/{lib/sqlCheck.ts → dist/lib/sqlCheck.js} +24 -41
  58. package/dist/lib/validator.d.ts +45 -0
  59. package/{lib/validator.ts → dist/lib/validator.js} +44 -61
  60. package/dist/loader/loadApis.d.ts +12 -0
  61. package/{loader/loadApis.ts → dist/loader/loadApis.js} +10 -20
  62. package/dist/loader/loadHooks.d.ts +7 -0
  63. package/dist/loader/loadHooks.js +35 -0
  64. package/dist/loader/loadPlugins.d.ts +8 -0
  65. package/{loader/loadPlugins.ts → dist/loader/loadPlugins.js} +14 -26
  66. package/dist/paths.d.ts +93 -0
  67. package/{paths.ts → dist/paths.js} +6 -19
  68. package/dist/plugins/cache.d.ts +16 -0
  69. package/{plugins/cache.ts → dist/plugins/cache.js} +7 -12
  70. package/dist/plugins/cipher.d.ts +12 -0
  71. package/{plugins/cipher.ts → dist/plugins/cipher.js} +4 -6
  72. package/dist/plugins/config.d.ts +12 -0
  73. package/dist/plugins/config.js +8 -0
  74. package/dist/plugins/db.d.ts +16 -0
  75. package/{plugins/db.ts → dist/plugins/db.js} +11 -17
  76. package/dist/plugins/jwt.d.ts +12 -0
  77. package/dist/plugins/jwt.js +12 -0
  78. package/dist/plugins/logger.d.ts +32 -0
  79. package/{plugins/logger.ts → dist/plugins/logger.js} +5 -8
  80. package/dist/plugins/redis.d.ts +16 -0
  81. package/{plugins/redis.ts → dist/plugins/redis.js} +9 -12
  82. package/dist/plugins/tool.d.ts +81 -0
  83. package/{plugins/tool.ts → dist/plugins/tool.js} +9 -30
  84. package/dist/router/api.d.ts +14 -0
  85. package/dist/router/api.js +107 -0
  86. package/dist/router/static.d.ts +9 -0
  87. package/{router/static.ts → dist/router/static.js} +20 -34
  88. package/dist/scripts/ensureDist.d.ts +1 -0
  89. package/dist/scripts/ensureDist.js +296 -0
  90. package/dist/sync/syncApi.d.ts +3 -0
  91. package/{sync/syncApi.ts → dist/sync/syncApi.js} +35 -55
  92. package/dist/sync/syncCache.d.ts +2 -0
  93. package/{sync/syncCache.ts → dist/sync/syncCache.js} +1 -6
  94. package/dist/sync/syncDev.d.ts +6 -0
  95. package/{sync/syncDev.ts → dist/sync/syncDev.js} +29 -62
  96. package/dist/sync/syncMenu.d.ts +14 -0
  97. package/{sync/syncMenu.ts → dist/sync/syncMenu.js} +65 -125
  98. package/dist/sync/syncTable.d.ts +151 -0
  99. package/{sync/syncTable.ts → dist/sync/syncTable.js} +172 -379
  100. package/{types → dist/types}/api.d.ts +12 -51
  101. package/dist/types/api.js +4 -0
  102. package/{types → dist/types}/befly.d.ts +32 -227
  103. package/dist/types/befly.js +4 -0
  104. package/{types → dist/types}/cache.d.ts +7 -15
  105. package/dist/types/cache.js +4 -0
  106. package/dist/types/cipher.d.ts +27 -0
  107. package/dist/types/cipher.js +7 -0
  108. package/{types → dist/types}/common.d.ts +8 -33
  109. package/dist/types/common.js +5 -0
  110. package/{types → dist/types}/context.d.ts +3 -5
  111. package/dist/types/context.js +4 -0
  112. package/{types → dist/types}/crypto.d.ts +0 -3
  113. package/dist/types/crypto.js +4 -0
  114. package/dist/types/database.d.ts +138 -0
  115. package/dist/types/database.js +4 -0
  116. package/dist/types/hook.d.ts +17 -0
  117. package/dist/types/hook.js +6 -0
  118. package/dist/types/jwt.d.ts +75 -0
  119. package/dist/types/jwt.js +4 -0
  120. package/dist/types/logger.d.ts +59 -0
  121. package/dist/types/logger.js +6 -0
  122. package/dist/types/plugin.d.ts +16 -0
  123. package/dist/types/plugin.js +6 -0
  124. package/dist/types/redis.d.ts +71 -0
  125. package/dist/types/redis.js +4 -0
  126. package/{types/roleApisCache.ts → dist/types/roleApisCache.d.ts} +0 -2
  127. package/dist/types/roleApisCache.js +8 -0
  128. package/dist/types/sync.d.ts +92 -0
  129. package/dist/types/sync.js +4 -0
  130. package/dist/types/table.d.ts +34 -0
  131. package/dist/types/table.js +4 -0
  132. package/dist/types/validate.d.ts +67 -0
  133. package/dist/types/validate.js +4 -0
  134. package/dist/utils/calcPerfTime.d.ts +4 -0
  135. package/{utils/calcPerfTime.ts → dist/utils/calcPerfTime.js} +3 -3
  136. package/dist/utils/convertBigIntFields.d.ts +11 -0
  137. package/{utils/convertBigIntFields.ts → dist/utils/convertBigIntFields.js} +5 -9
  138. package/dist/utils/cors.d.ts +8 -0
  139. package/{utils/cors.ts → dist/utils/cors.js} +1 -3
  140. package/dist/utils/disableMenusGlob.d.ts +13 -0
  141. package/{utils/disableMenusGlob.ts → dist/utils/disableMenusGlob.js} +9 -29
  142. package/dist/utils/fieldClear.d.ts +11 -0
  143. package/{utils/fieldClear.ts → dist/utils/fieldClear.js} +15 -33
  144. package/dist/utils/getClientIp.d.ts +6 -0
  145. package/{utils/getClientIp.ts → dist/utils/getClientIp.js} +1 -7
  146. package/dist/utils/importDefault.d.ts +1 -0
  147. package/dist/utils/importDefault.js +29 -0
  148. package/dist/utils/isDirentDirectory.d.ts +2 -0
  149. package/{utils/isDirentDirectory.ts → dist/utils/isDirentDirectory.js} +3 -8
  150. package/dist/utils/loadMenuConfigs.d.ts +29 -0
  151. package/{utils/loadMenuConfigs.ts → dist/utils/loadMenuConfigs.js} +66 -52
  152. package/dist/utils/mergeAndConcat.d.ts +7 -0
  153. package/dist/utils/mergeAndConcat.js +72 -0
  154. package/dist/utils/processAtSymbol.d.ts +4 -0
  155. package/{utils/processFields.ts → dist/utils/processAtSymbol.js} +5 -9
  156. package/dist/utils/processInfo.d.ts +24 -0
  157. package/{utils/process.ts → dist/utils/processInfo.js} +2 -18
  158. package/dist/utils/response.d.ts +20 -0
  159. package/{utils/response.ts → dist/utils/response.js} +28 -49
  160. package/dist/utils/scanAddons.d.ts +17 -0
  161. package/{utils/scanAddons.ts → dist/utils/scanAddons.js} +7 -41
  162. package/dist/utils/scanConfig.d.ts +26 -0
  163. package/{utils/scanConfig.ts → dist/utils/scanConfig.js} +28 -66
  164. package/dist/utils/scanCoreBuiltins.d.ts +3 -0
  165. package/dist/utils/scanCoreBuiltins.js +65 -0
  166. package/dist/utils/scanFiles.d.ts +30 -0
  167. package/{utils/scanFiles.ts → dist/utils/scanFiles.js} +44 -71
  168. package/dist/utils/scanSources.d.ts +10 -0
  169. package/dist/utils/scanSources.js +46 -0
  170. package/dist/utils/sortModules.d.ts +28 -0
  171. package/{utils/sortModules.ts → dist/utils/sortModules.js} +26 -66
  172. package/dist/utils/util.d.ts +84 -0
  173. package/dist/utils/util.js +262 -0
  174. package/package.json +26 -34
  175. package/.gitignore +0 -0
  176. package/bunfig.toml +0 -3
  177. package/checks/checkHook.ts +0 -48
  178. package/checks/checkPlugin.ts +0 -48
  179. package/configs/presetRegexp.ts +0 -225
  180. package/docs/README.md +0 -98
  181. package/docs/api/api.md +0 -1921
  182. package/docs/guide/examples.md +0 -926
  183. package/docs/guide/quickstart.md +0 -354
  184. package/docs/hooks/auth.md +0 -38
  185. package/docs/hooks/cors.md +0 -28
  186. package/docs/hooks/hook.md +0 -838
  187. package/docs/hooks/parser.md +0 -19
  188. package/docs/hooks/rateLimit.md +0 -47
  189. package/docs/infra/redis.md +0 -628
  190. package/docs/plugins/cipher.md +0 -61
  191. package/docs/plugins/database.md +0 -189
  192. package/docs/plugins/plugin.md +0 -986
  193. package/docs/reference/addon.md +0 -510
  194. package/docs/reference/config.md +0 -573
  195. package/docs/reference/logger.md +0 -495
  196. package/docs/reference/sync.md +0 -478
  197. package/docs/reference/table.md +0 -763
  198. package/docs/reference/validator.md +0 -620
  199. package/lib/asyncContext.ts +0 -43
  200. package/lib/logger.ts +0 -811
  201. package/loader/loadHooks.ts +0 -51
  202. package/plugins/config.ts +0 -13
  203. package/plugins/jwt.ts +0 -15
  204. package/router/api.ts +0 -130
  205. package/tsconfig.json +0 -8
  206. package/types/database.d.ts +0 -541
  207. package/types/hook.d.ts +0 -25
  208. package/types/jwt.d.ts +0 -118
  209. package/types/logger.d.ts +0 -65
  210. package/types/plugin.d.ts +0 -19
  211. package/types/redis.d.ts +0 -83
  212. package/types/sync.d.ts +0 -398
  213. package/types/table.d.ts +0 -216
  214. package/types/validate.d.ts +0 -69
  215. package/utils/arrayKeysToCamel.ts +0 -18
  216. package/utils/configTypes.ts +0 -3
  217. package/utils/genShortId.ts +0 -12
  218. package/utils/importDefault.ts +0 -21
  219. package/utils/keysToCamel.ts +0 -22
  220. package/utils/keysToSnake.ts +0 -22
  221. package/utils/pickFields.ts +0 -19
  222. package/utils/scanSources.ts +0 -64
  223. package/utils/sqlLog.ts +0 -37
package/lib/logger.ts DELETED
@@ -1,811 +0,0 @@
1
- /**
2
- * 日志系统 - 基于 pino 实现
3
- */
4
-
5
- import type { LoggerConfig } from "../types/logger.ts";
6
-
7
- import { existsSync, mkdirSync } from "node:fs";
8
- import { readdir, stat, unlink } from "node:fs/promises";
9
- import { isAbsolute as nodePathIsAbsolute, join as nodePathJoin, resolve as nodePathResolve } from "node:path";
10
-
11
- import { isPlainObject } from "es-toolkit/compat";
12
- import { escapeRegExp } from "es-toolkit/string";
13
- import { join } from "pathe";
14
- import pino from "pino";
15
-
16
- import { getCtx } from "./asyncContext.ts";
17
-
18
- // 注意:Logger 可能在运行时/测试中被 process.chdir() 影响。
19
- // 为避免相对路径的 logs 目录随着 cwd 变化,使用模块加载时的初始 cwd 作为锚点。
20
- const INITIAL_CWD = process.cwd();
21
-
22
- const DEFAULT_LOG_STRING_LEN = 100;
23
- const DEFAULT_LOG_ARRAY_ITEMS = 100;
24
-
25
- let maxLogStringLen = DEFAULT_LOG_STRING_LEN;
26
- let maxLogArrayItems = DEFAULT_LOG_ARRAY_ITEMS;
27
-
28
- // 为避免递归导致栈溢出/性能抖动:使用非递归遍历,并对深度/节点数做硬限制。
29
- // 说明:这不是业务数据结构的“真实深度”,而是日志清洗的最大深入层级(越大越重)。
30
- const DEFAULT_LOG_SANITIZE_DEPTH = 3;
31
- const DEFAULT_LOG_OBJECT_KEYS = 100;
32
- const DEFAULT_LOG_SANITIZE_NODES = 500;
33
-
34
- let sanitizeDepthLimit = DEFAULT_LOG_SANITIZE_DEPTH;
35
- let sanitizeObjectKeysLimit = DEFAULT_LOG_OBJECT_KEYS;
36
- let sanitizeNodesLimit = DEFAULT_LOG_SANITIZE_NODES;
37
-
38
- const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
39
-
40
- const BUILTIN_SENSITIVE_KEYS = ["*password*", "pass", "pwd", "*token*", "access_token", "refresh_token", "accessToken", "refreshToken", "authorization", "cookie", "set-cookie", "*secret*", "apiKey", "api_key", "privateKey", "private_key"];
41
-
42
- let sensitiveKeySet: Set<string> = new Set();
43
- let sensitiveSuffixMatchers: string[] = [];
44
- let sensitivePrefixMatchers: string[] = [];
45
- let sensitiveContainsMatchers: string[] = [];
46
- let sensitiveContainsRegex: RegExp | null = null;
47
-
48
- let instance: pino.Logger | null = null;
49
- let slowInstance: pino.Logger | null = null;
50
- let errorInstance: pino.Logger | null = null;
51
- let mockInstance: pino.Logger | null = null;
52
- let didPruneOldLogFiles: boolean = false;
53
- let didEnsureLogDir: boolean = false;
54
- let config: LoggerConfig = {
55
- debug: 0,
56
- dir: "./logs",
57
- console: 1,
58
- maxSize: 10
59
- };
60
-
61
- function normalizePositiveInt(value: any, fallback: number, min: number, max: number): number {
62
- if (typeof value !== "number") return fallback;
63
- if (!Number.isFinite(value)) return fallback;
64
- const v = Math.floor(value);
65
- if (v < min) return fallback;
66
- if (v > max) return max;
67
- return v;
68
- }
69
-
70
- function resolveLogDir(): string {
71
- const rawDir = config.dir || "./logs";
72
- if (nodePathIsAbsolute(rawDir)) {
73
- return rawDir;
74
- }
75
- return nodePathResolve(INITIAL_CWD, rawDir);
76
- }
77
-
78
- function ensureLogDirExists(): void {
79
- if (didEnsureLogDir) return;
80
- didEnsureLogDir = true;
81
-
82
- const dir = resolveLogDir();
83
- try {
84
- if (!existsSync(dir)) {
85
- mkdirSync(dir, { recursive: true });
86
- }
87
- } catch (error: any) {
88
- // 不能在 Logger 初始化前调用 Logger 本身,直接抛错即可
89
- throw new Error(`创建 logs 目录失败: ${dir}. ${error?.message || error}`);
90
- }
91
- }
92
-
93
- async function pruneOldLogFiles(): Promise<void> {
94
- if (didPruneOldLogFiles) return;
95
- didPruneOldLogFiles = true;
96
-
97
- const dir = resolveLogDir();
98
- const now = Date.now();
99
- const cutoff = now - ONE_YEAR_MS;
100
-
101
- try {
102
- const entries = await readdir(dir, { withFileTypes: true });
103
- for (const entry of entries) {
104
- if (!entry.isFile()) continue;
105
-
106
- const name = entry.name;
107
-
108
- // 只处理本项目的日志文件前缀
109
- const isTarget = name.startsWith("app.") || name.startsWith("slow.") || name.startsWith("error.");
110
- if (!isTarget) continue;
111
-
112
- const fullPath = nodePathJoin(dir, name);
113
-
114
- let st: any;
115
- try {
116
- st = await stat(fullPath);
117
- } catch {
118
- continue;
119
- }
120
-
121
- const mtimeMs = typeof st.mtimeMs === "number" ? st.mtimeMs : 0;
122
- if (mtimeMs > 0 && mtimeMs < cutoff) {
123
- try {
124
- await unlink(fullPath);
125
- } catch {
126
- // 忽略删除失败(权限/占用等),避免影响服务启动
127
- }
128
- }
129
- }
130
- } catch {
131
- // 忽略:目录不存在或无权限等
132
- }
133
- }
134
-
135
- /**
136
- * 配置日志
137
- */
138
- export function configure(cfg: LoggerConfig): void {
139
- config = { ...config, ...cfg };
140
- instance = null;
141
- slowInstance = null;
142
- errorInstance = null;
143
- didPruneOldLogFiles = false;
144
- didEnsureLogDir = false;
145
-
146
- // 运行时清洗上限(可配置)
147
- sanitizeDepthLimit = normalizePositiveInt(config.sanitizeDepth, DEFAULT_LOG_SANITIZE_DEPTH, 1, 10);
148
- sanitizeNodesLimit = normalizePositiveInt(config.sanitizeNodes, DEFAULT_LOG_SANITIZE_NODES, 50, 20000);
149
- sanitizeObjectKeysLimit = normalizePositiveInt(config.sanitizeObjectKeys, DEFAULT_LOG_OBJECT_KEYS, 10, 5000);
150
-
151
- // 运行时截断上限(可配置)
152
- maxLogStringLen = normalizePositiveInt(config.maxStringLen, DEFAULT_LOG_STRING_LEN, 20, 200000);
153
- maxLogArrayItems = normalizePositiveInt(config.maxArrayItems, DEFAULT_LOG_ARRAY_ITEMS, 10, 5000);
154
-
155
- // 仅支持数组配置:excludeFields?: string[]
156
- const userPatterns = Array.isArray(config.excludeFields) ? config.excludeFields : [];
157
- const patterns = [...BUILTIN_SENSITIVE_KEYS, ...userPatterns]
158
- .map((item) => String(item).trim())
159
- .filter((item) => item.length > 0)
160
- .map((item) => item.toLowerCase());
161
-
162
- const exactSet = new Set<string>();
163
- const suffixMatchers: string[] = [];
164
- const prefixMatchers: string[] = [];
165
- const containsMatchers: string[] = [];
166
-
167
- for (const pat of patterns) {
168
- // 支持通配符:
169
- // - *secret -> 后缀匹配
170
- // - secret* -> 前缀匹配
171
- // - *secret* -> 包含匹配
172
- // - 无 * -> 精确匹配(建议用 *x* 显式开启模糊匹配)
173
- const hasStar = pat.includes("*");
174
- if (!hasStar) {
175
- exactSet.add(pat);
176
- continue;
177
- }
178
-
179
- const trimmed = pat.replace(/\*+/g, "*");
180
- const startsStar = trimmed.startsWith("*");
181
- const endsStar = trimmed.endsWith("*");
182
- const core = trimmed.replace(/^\*+|\*+$/g, "");
183
- if (!core) {
184
- continue;
185
- }
186
-
187
- if (startsStar && !endsStar) {
188
- suffixMatchers.push(core);
189
- continue;
190
- }
191
- if (!startsStar && endsStar) {
192
- prefixMatchers.push(core);
193
- continue;
194
- }
195
-
196
- // *core* 或类似 a*b:都降级为包含匹配
197
- containsMatchers.push(core);
198
- }
199
-
200
- sensitiveKeySet = exactSet;
201
- sensitiveSuffixMatchers = suffixMatchers;
202
- sensitivePrefixMatchers = prefixMatchers;
203
- sensitiveContainsMatchers = containsMatchers;
204
-
205
- // 预编译包含匹配:减少每次 isSensitiveKey 的循环开销
206
- // 注意:patterns 已全部 lowerCase,因此 regex 不需要 i 标志
207
- if (containsMatchers.length > 0) {
208
- const escaped = containsMatchers.map((item) => escapeRegExp(item)).filter((item) => item.length > 0);
209
- if (escaped.length > 0) {
210
- sensitiveContainsRegex = new RegExp(escaped.join("|"));
211
- } else {
212
- sensitiveContainsRegex = null;
213
- }
214
- } else {
215
- sensitiveContainsRegex = null;
216
- }
217
- }
218
-
219
- /**
220
- * 设置 Mock Logger(用于测试)
221
- * @param mock - Mock pino 实例,传 null 清除 mock
222
- */
223
- export function setMockLogger(mock: pino.Logger | null): void {
224
- mockInstance = mock;
225
- }
226
-
227
- /**
228
- * 获取 pino 日志实例
229
- */
230
- export function getLogger(): pino.Logger {
231
- // 优先返回 mock 实例(用于测试)
232
- if (mockInstance) return mockInstance;
233
-
234
- if (instance) return instance;
235
-
236
- ensureLogDirExists();
237
-
238
- // 启动时清理过期日志(异步,不阻塞初始化)
239
- void pruneOldLogFiles();
240
-
241
- const level = config.debug === 1 ? "debug" : "info";
242
- const targets: pino.TransportTargetOptions[] = [];
243
-
244
- // 文件输出
245
- targets.push({
246
- target: "pino-roll",
247
- level: level,
248
- options: {
249
- file: join(resolveLogDir(), "app"),
250
- frequency: "daily",
251
- size: `${config.maxSize || 10}m`,
252
- mkdir: true,
253
- dateFormat: "yyyy-MM-dd"
254
- }
255
- });
256
-
257
- // 控制台输出
258
- if (config.console === 1) {
259
- targets.push({
260
- target: "pino/file",
261
- level: level,
262
- options: { destination: 1 }
263
- });
264
- }
265
-
266
- instance = pino({
267
- level: level,
268
- transport: { targets: targets }
269
- });
270
-
271
- return instance;
272
- }
273
-
274
- function getSlowLogger(): pino.Logger {
275
- if (mockInstance) return mockInstance;
276
- if (slowInstance) return slowInstance;
277
-
278
- ensureLogDirExists();
279
-
280
- void pruneOldLogFiles();
281
-
282
- const level = config.debug === 1 ? "debug" : "info";
283
- slowInstance = pino({
284
- level: level,
285
- transport: {
286
- targets: [
287
- {
288
- target: "pino-roll",
289
- level: level,
290
- options: {
291
- file: join(resolveLogDir(), "slow"),
292
- // 只按大小分割(frequency 默认不启用)
293
- size: `${config.maxSize || 10}m`,
294
- mkdir: true
295
- }
296
- }
297
- ]
298
- }
299
- });
300
-
301
- return slowInstance;
302
- }
303
-
304
- function getErrorLogger(): pino.Logger {
305
- if (mockInstance) return mockInstance;
306
- if (errorInstance) return errorInstance;
307
-
308
- ensureLogDirExists();
309
-
310
- void pruneOldLogFiles();
311
-
312
- // error 专属文件:只关注 error 及以上
313
- errorInstance = pino({
314
- level: "error",
315
- transport: {
316
- targets: [
317
- {
318
- target: "pino-roll",
319
- level: "error",
320
- options: {
321
- file: join(resolveLogDir(), "error"),
322
- // 只按大小分割(frequency 默认不启用)
323
- size: `${config.maxSize || 10}m`,
324
- mkdir: true
325
- }
326
- }
327
- ]
328
- }
329
- });
330
-
331
- return errorInstance;
332
- }
333
-
334
- function truncateString(val: string, stats: Record<string, number>): string {
335
- if (val.length <= maxLogStringLen) return val;
336
- stats.truncatedStrings = (stats.truncatedStrings || 0) + 1;
337
- return val.slice(0, maxLogStringLen);
338
- }
339
-
340
- function isSensitiveKey(key: string): boolean {
341
- const lower = String(key).toLowerCase();
342
- if (sensitiveKeySet.has(lower)) return true;
343
-
344
- for (const suffix of sensitiveSuffixMatchers) {
345
- if (lower.endsWith(suffix)) return true;
346
- }
347
- for (const prefix of sensitivePrefixMatchers) {
348
- if (lower.startsWith(prefix)) return true;
349
- }
350
-
351
- if (sensitiveContainsRegex) {
352
- return sensitiveContainsRegex.test(lower);
353
- }
354
-
355
- for (const part of sensitiveContainsMatchers) {
356
- if (lower.includes(part)) return true;
357
- }
358
-
359
- return false;
360
- }
361
-
362
- function safeToStringMasked(val: any, visited: WeakSet<object>, stats: Record<string, number>): string {
363
- if (typeof val === "string") return val;
364
-
365
- if (val instanceof Error) {
366
- const name = val.name || "Error";
367
- const message = val.message || "";
368
- const stack = typeof val.stack === "string" ? val.stack : "";
369
- const errObj: Record<string, any> = {
370
- name: name,
371
- message: message,
372
- stack: stack
373
- };
374
- try {
375
- return JSON.stringify(errObj);
376
- } catch {
377
- return `${name}: ${message}`;
378
- }
379
- }
380
-
381
- if (val && typeof val === "object") {
382
- if (visited.has(val as object)) {
383
- stats.circularRefs = (stats.circularRefs || 0) + 1;
384
- return "[Circular]";
385
- }
386
- }
387
-
388
- try {
389
- const localVisited = visited;
390
- const replacer = (k: string, v: any) => {
391
- // JSON.stringify 的根节点 key 为空字符串
392
- if (k && isSensitiveKey(k)) {
393
- stats.maskedKeys = (stats.maskedKeys || 0) + 1;
394
- return "[MASKED]";
395
- }
396
-
397
- if (v && typeof v === "object") {
398
- if (localVisited.has(v as object)) {
399
- stats.circularRefs = (stats.circularRefs || 0) + 1;
400
- return "[Circular]";
401
- }
402
- localVisited.add(v as object);
403
- }
404
- return v;
405
- };
406
- return JSON.stringify(val, replacer);
407
- } catch {
408
- try {
409
- return String(val);
410
- } catch {
411
- return "[Unserializable]";
412
- }
413
- }
414
- }
415
-
416
- function sanitizeErrorValue(err: Error, stats: Record<string, number>): Record<string, any> {
417
- const errObj: Record<string, any> = {
418
- name: err.name || "Error",
419
- message: truncateString(err.message || "", stats)
420
- };
421
- if (typeof err.stack === "string") {
422
- errObj.stack = truncateString(err.stack, stats);
423
- }
424
- return errObj;
425
- }
426
-
427
- function stringifyPreview(val: any, visited: WeakSet<object>, stats: Record<string, number>): string {
428
- stats.valuesStringified = (stats.valuesStringified || 0) + 1;
429
- const str = safeToStringMasked(val, visited, stats);
430
- return truncateString(str, stats);
431
- }
432
-
433
- function sanitizeValueLimited(val: any, visited: WeakSet<object>, stats: Record<string, number>): any {
434
- if (val === null || val === undefined) return val;
435
- if (typeof val === "string") return truncateString(val, stats);
436
- if (typeof val === "number") return val;
437
- if (typeof val === "boolean") return val;
438
- if (typeof val === "bigint") return val;
439
-
440
- if (val instanceof Error) {
441
- return sanitizeErrorValue(val, stats);
442
- }
443
-
444
- // 仅支持数组 + plain object 的结构化清洗,其余类型走字符串预览。
445
- const isArr = Array.isArray(val);
446
- const isObj = isPlainObject(val);
447
- if (!isArr && !isObj) {
448
- return stringifyPreview(val, visited, stats);
449
- }
450
-
451
- // 防环(根节点)
452
- if (visited.has(val as object)) {
453
- stats.circularRefs = (stats.circularRefs || 0) + 1;
454
- return "[Circular]";
455
- }
456
- visited.add(val as object);
457
-
458
- const rootOut: any = isArr ? [] : {};
459
-
460
- type Frame = { src: any; dst: any; depth: number };
461
- const stack: Frame[] = [{ src: val, dst: rootOut, depth: 1 }];
462
-
463
- let nodes = 0;
464
-
465
- const tryAssign = (dst: any, key: string | number, child: any, depth: number) => {
466
- if (child === null || child === undefined) {
467
- dst[key] = child;
468
- return;
469
- }
470
- if (typeof child === "string") {
471
- dst[key] = truncateString(child, stats);
472
- return;
473
- }
474
- if (typeof child === "number" || typeof child === "boolean" || typeof child === "bigint") {
475
- dst[key] = child;
476
- return;
477
- }
478
- if (child instanceof Error) {
479
- dst[key] = sanitizeErrorValue(child, stats);
480
- return;
481
- }
482
-
483
- const childIsArr = Array.isArray(child);
484
- const childIsObj = isPlainObject(child);
485
-
486
- if (!childIsArr && !childIsObj) {
487
- dst[key] = stringifyPreview(child, visited, stats);
488
- return;
489
- }
490
-
491
- // 深度/节点数上限:超出则降级为字符串预览
492
- if (depth >= sanitizeDepthLimit) {
493
- stats.depthLimited = (stats.depthLimited || 0) + 1;
494
- dst[key] = stringifyPreview(child, visited, stats);
495
- return;
496
- }
497
- if (nodes >= sanitizeNodesLimit) {
498
- stats.nodesLimited = (stats.nodesLimited || 0) + 1;
499
- dst[key] = stringifyPreview(child, visited, stats);
500
- return;
501
- }
502
-
503
- // 防环
504
- if (visited.has(child as object)) {
505
- stats.circularRefs = (stats.circularRefs || 0) + 1;
506
- dst[key] = "[Circular]";
507
- return;
508
- }
509
- visited.add(child as object);
510
-
511
- const childOut: any = childIsArr ? [] : {};
512
- dst[key] = childOut;
513
- stack.push({ src: child, dst: childOut, depth: depth + 1 });
514
- };
515
-
516
- while (stack.length > 0) {
517
- const frame = stack.pop() as Frame;
518
- nodes = nodes + 1;
519
- if (nodes > sanitizeNodesLimit) {
520
- // 超出节点上限:不再深入(已入栈的节点会被忽略,留空结构由上层兜底预览)。
521
- stats.nodesLimited = (stats.nodesLimited || 0) + 1;
522
- break;
523
- }
524
-
525
- if (Array.isArray(frame.src)) {
526
- const arr = frame.src as any[];
527
- const len = arr.length;
528
- const limit = len > maxLogArrayItems ? maxLogArrayItems : len;
529
-
530
- for (let i = 0; i < limit; i++) {
531
- tryAssign(frame.dst, i, arr[i], frame.depth);
532
- }
533
-
534
- if (len > maxLogArrayItems) {
535
- stats.arraysTruncated = (stats.arraysTruncated || 0) + 1;
536
- stats.arrayItemsOmitted = (stats.arrayItemsOmitted || 0) + (len - maxLogArrayItems);
537
- }
538
-
539
- continue;
540
- }
541
-
542
- if (isPlainObject(frame.src)) {
543
- const entries = Object.entries(frame.src as Record<string, any>);
544
- const len = entries.length;
545
- const limit = len > sanitizeObjectKeysLimit ? sanitizeObjectKeysLimit : len;
546
-
547
- for (let i = 0; i < limit; i++) {
548
- const key = entries[i][0];
549
- const child = entries[i][1];
550
- if (isSensitiveKey(key)) {
551
- stats.maskedKeys = (stats.maskedKeys || 0) + 1;
552
- frame.dst[key] = "[MASKED]";
553
- continue;
554
- }
555
- tryAssign(frame.dst, key, child, frame.depth);
556
- }
557
-
558
- if (len > sanitizeObjectKeysLimit) {
559
- stats.objectKeysLimited = (stats.objectKeysLimited || 0) + 1;
560
- stats.objectKeysOmitted = (stats.objectKeysOmitted || 0) + (len - sanitizeObjectKeysLimit);
561
- }
562
-
563
- continue;
564
- }
565
-
566
- // 兜底:理论上不会到这里(frame 只会压入 array/plain object)
567
- }
568
-
569
- return rootOut;
570
- }
571
-
572
- function sanitizeTopValue(val: any, visited: WeakSet<object>, stats: Record<string, number>): any {
573
- return sanitizeValueLimited(val, visited, stats);
574
- }
575
-
576
- function sanitizeLogObject(obj: Record<string, any>): Record<string, any> {
577
- const visited = new WeakSet<object>();
578
- const stats: Record<string, number> = {
579
- maskedKeys: 0,
580
- truncatedStrings: 0,
581
- arraysTruncated: 0,
582
- arrayItemsOmitted: 0,
583
- valuesStringified: 0,
584
- circularRefs: 0,
585
- depthLimited: 0,
586
- nodesLimited: 0,
587
- objectKeysLimited: 0,
588
- objectKeysOmitted: 0
589
- };
590
-
591
- const out: Record<string, any> = {};
592
- for (const [key, val] of Object.entries(obj)) {
593
- if (isSensitiveKey(key)) {
594
- stats.maskedKeys = stats.maskedKeys + 1;
595
- out[key] = "[MASKED]";
596
- continue;
597
- }
598
- out[key] = sanitizeTopValue(val, visited, stats);
599
- }
600
-
601
- const hasChanges =
602
- stats.maskedKeys > 0 || stats.truncatedStrings > 0 || stats.arraysTruncated > 0 || stats.arrayItemsOmitted > 0 || stats.valuesStringified > 0 || stats.circularRefs > 0 || stats.depthLimited > 0 || stats.nodesLimited > 0 || stats.objectKeysLimited > 0 || stats.objectKeysOmitted > 0;
603
-
604
- if (hasChanges) {
605
- out.logTrimStats = {
606
- maskedKeys: stats.maskedKeys,
607
- truncatedStrings: stats.truncatedStrings,
608
- arraysTruncated: stats.arraysTruncated,
609
- arrayItemsOmitted: stats.arrayItemsOmitted,
610
- valuesStringified: stats.valuesStringified,
611
- circularRefs: stats.circularRefs,
612
- depthLimited: stats.depthLimited,
613
- nodesLimited: stats.nodesLimited,
614
- objectKeysLimited: stats.objectKeysLimited,
615
- objectKeysOmitted: stats.objectKeysOmitted
616
- };
617
- }
618
-
619
- return out;
620
- }
621
-
622
- function metaToObject(): Record<string, any> | null {
623
- const meta = getCtx();
624
- if (!meta) return null;
625
-
626
- const durationSinceNowMs = Date.now() - meta.now;
627
-
628
- const obj: Record<string, any> = {
629
- requestId: meta.requestId,
630
- method: meta.method,
631
- route: meta.route,
632
- ip: meta.ip,
633
- now: meta.now,
634
- durationSinceNowMs: durationSinceNowMs
635
- };
636
-
637
- // userId / roleCode 默认写入
638
- obj.userId = meta.userId;
639
- obj.roleCode = meta.roleCode;
640
- obj.nickname = (meta as any).nickname;
641
- obj.roleType = (meta as any).roleType;
642
-
643
- return obj;
644
- }
645
-
646
- function mergeMetaIntoObject(input: Record<string, any>, meta: Record<string, any>): Record<string, any> {
647
- const merged: Record<string, any> = {};
648
- for (const [key, value] of Object.entries(input)) {
649
- merged[key] = value;
650
- }
651
-
652
- // 只补齐、不覆盖:允许把 undefined / null / 空字符串写入(由日志底层序列化决定是否展示)
653
- const keys = ["requestId", "method", "route", "ip", "now", "durationSinceNowMs", "userId", "roleCode", "nickname", "roleType"];
654
-
655
- for (const key of keys) {
656
- if (merged[key] === undefined) merged[key] = meta[key];
657
- }
658
-
659
- return merged;
660
- }
661
-
662
- function withRequestMeta(args: any[]): any[] {
663
- const meta = metaToObject();
664
- if (!meta) return args;
665
- if (args.length === 0) return args;
666
-
667
- const first = args[0];
668
- const second = args.length > 1 ? args[1] : undefined;
669
-
670
- // 兼容:Logger.error("xxx", err)
671
- if (typeof first === "string" && second instanceof Error) {
672
- const obj = {
673
- err: second
674
- };
675
- const merged = mergeMetaIntoObject(obj, meta);
676
- return [merged, first, ...args.slice(2)];
677
- }
678
-
679
- // pino 原生:logger.error(err, msg)
680
- if (first instanceof Error) {
681
- const msg = typeof second === "string" ? second : undefined;
682
- const obj = {
683
- err: first
684
- };
685
- const merged = mergeMetaIntoObject(obj, meta);
686
- if (msg) return [merged, msg, ...args.slice(2)];
687
- return [merged, ...args.slice(1)];
688
- }
689
-
690
- // 纯字符串:Logger.info("msg") -> logger.info(meta, "msg")
691
- if (typeof first === "string") {
692
- return [meta, ...args];
693
- }
694
-
695
- // 对象:Logger.info(obj, msg?) -> 合并 meta(不覆盖显式字段)
696
- if (isPlainObject(first)) {
697
- const merged = mergeMetaIntoObject(first as Record<string, any>, meta);
698
- return [merged, ...args.slice(1)];
699
- }
700
-
701
- return args;
702
- }
703
-
704
- function shouldMirrorToSlow(args: any[]): boolean {
705
- // 测试场景:启用 mock 时不做镜像,避免调用次数翻倍
706
- if (mockInstance) return false;
707
- if (!args || args.length === 0) return false;
708
- const first = args[0];
709
- if (!isPlainObject(first)) return false;
710
-
711
- // 优先使用显式标记:event=slow
712
- const event = (first as any).event;
713
- if (event === "slow") return true;
714
-
715
- // 兼容旧写法:仅通过 message emoji 判断(尽量少用)
716
- const msg = args.length > 1 ? args[1] : undefined;
717
- if (typeof msg === "string" && msg.includes("🐌")) return true;
718
-
719
- return false;
720
- }
721
-
722
- type LoggerObject = Record<string, any>;
723
-
724
- // 兼容 pino 常用调用形式 + 本项目的 Logger.error("msg", err)
725
- type LoggerCallArgs = [] | [msg: string, ...args: unknown[]] | [obj: LoggerObject, msg?: string, ...args: unknown[]] | [err: Error, msg?: string, ...args: unknown[]] | [msg: string, err: Error, ...args: unknown[]];
726
-
727
- function withRequestMetaTyped(args: LoggerCallArgs): LoggerCallArgs {
728
- // 复用现有逻辑(保持行为一致),只收敛类型
729
- return withRequestMeta(args as any[]) as unknown as LoggerCallArgs;
730
- }
731
-
732
- /**
733
- * 日志实例(延迟初始化)
734
- */
735
- export const Logger = {
736
- info(...args: LoggerCallArgs) {
737
- if (args.length === 0) return;
738
- const logger = getLogger();
739
- const finalArgs = withRequestMetaTyped(args);
740
- if (finalArgs.length === 0) return;
741
- if (finalArgs.length > 0 && isPlainObject(finalArgs[0])) {
742
- finalArgs[0] = sanitizeLogObject(finalArgs[0] as Record<string, any>);
743
- }
744
- const ret = (logger.info as any).apply(logger, finalArgs);
745
- if (mockInstance) return ret;
746
- if (shouldMirrorToSlow(finalArgs as any[])) {
747
- const slowLogger = getSlowLogger();
748
- (slowLogger.info as any).apply(slowLogger, finalArgs);
749
- }
750
- return ret;
751
- },
752
- warn(...args: LoggerCallArgs) {
753
- if (args.length === 0) return;
754
- const logger = getLogger();
755
- const finalArgs = withRequestMetaTyped(args);
756
- if (finalArgs.length === 0) return;
757
- if (finalArgs.length > 0 && isPlainObject(finalArgs[0])) {
758
- finalArgs[0] = sanitizeLogObject(finalArgs[0] as Record<string, any>);
759
- }
760
- const ret = (logger.warn as any).apply(logger, finalArgs);
761
- if (mockInstance) return ret;
762
- if (shouldMirrorToSlow(finalArgs as any[])) {
763
- const slowLogger = getSlowLogger();
764
- (slowLogger.warn as any).apply(slowLogger, finalArgs);
765
- }
766
- return ret;
767
- },
768
- error(...args: LoggerCallArgs) {
769
- if (args.length === 0) return;
770
- const logger = getLogger();
771
- const finalArgs = withRequestMetaTyped(args);
772
- if (finalArgs.length === 0) return;
773
- if (finalArgs.length > 0 && isPlainObject(finalArgs[0])) {
774
- finalArgs[0] = sanitizeLogObject(finalArgs[0] as Record<string, any>);
775
- }
776
- const ret = (logger.error as any).apply(logger, finalArgs);
777
-
778
- // 测试场景:启用 mock 时不做镜像,避免调用次数翻倍
779
- if (mockInstance) return ret;
780
-
781
- // error 专属文件:始终镜像一份
782
- const errorLogger = getErrorLogger();
783
- (errorLogger.error as any).apply(errorLogger, finalArgs);
784
-
785
- // error 同时也属于 slow?一般不会,但允许显式 event=slow
786
- if (shouldMirrorToSlow(finalArgs as any[])) {
787
- const slowLogger = getSlowLogger();
788
- (slowLogger.error as any).apply(slowLogger, finalArgs);
789
- }
790
-
791
- return ret;
792
- },
793
- debug(...args: LoggerCallArgs) {
794
- if (args.length === 0) return;
795
- const logger = getLogger();
796
- const finalArgs = withRequestMetaTyped(args);
797
- if (finalArgs.length === 0) return;
798
- if (finalArgs.length > 0 && isPlainObject(finalArgs[0])) {
799
- finalArgs[0] = sanitizeLogObject(finalArgs[0] as Record<string, any>);
800
- }
801
- const ret = (logger.debug as any).apply(logger, finalArgs);
802
- if (mockInstance) return ret;
803
- if (shouldMirrorToSlow(finalArgs as any[])) {
804
- const slowLogger = getSlowLogger();
805
- (slowLogger.debug as any).apply(slowLogger, finalArgs);
806
- }
807
- return ret;
808
- },
809
- configure: configure,
810
- setMock: setMockLogger
811
- };