@gaias/basenode 1.0.12 → 1.0.13

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 (228) hide show
  1. package/CLAUDE.md +757 -0
  2. package/SECURITY.md +296 -0
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/libs/apisix/ApisixTemplate.d.ts +1 -0
  6. package/dist/libs/apisix/ApisixTemplate.d.ts.map +1 -0
  7. package/dist/libs/apisix/ApisixTemplate.js +120 -74
  8. package/dist/libs/apisix/ApisixTemplate.js.map +1 -1
  9. package/dist/libs/apisix/HttpPutter.d.ts +11 -1
  10. package/dist/libs/apisix/HttpPutter.d.ts.map +1 -0
  11. package/dist/libs/apisix/HttpPutter.js +44 -31
  12. package/dist/libs/apisix/HttpPutter.js.map +1 -1
  13. package/dist/libs/apisix/index.d.ts +1 -0
  14. package/dist/libs/apisix/index.d.ts.map +1 -0
  15. package/dist/libs/cache/CacheService.d.ts +1 -0
  16. package/dist/libs/cache/CacheService.d.ts.map +1 -0
  17. package/dist/libs/cache/CacheService.js +79 -109
  18. package/dist/libs/cache/CacheService.js.map +1 -1
  19. package/dist/libs/cache/Timer.d.ts +1 -0
  20. package/dist/libs/cache/Timer.d.ts.map +1 -0
  21. package/dist/libs/cache/Timer.js +1 -1
  22. package/dist/libs/cache/Timer.js.map +1 -1
  23. package/dist/libs/cache/index.d.ts +1 -0
  24. package/dist/libs/cache/index.d.ts.map +1 -0
  25. package/dist/libs/configure/ApplicationConfig.d.ts +4 -1
  26. package/dist/libs/configure/ApplicationConfig.d.ts.map +1 -0
  27. package/dist/libs/configure/ConfigManager.d.ts +1 -0
  28. package/dist/libs/configure/ConfigManager.d.ts.map +1 -0
  29. package/dist/libs/configure/ConfigManager.js.map +1 -1
  30. package/dist/libs/configure/index.d.ts +1 -0
  31. package/dist/libs/configure/index.d.ts.map +1 -0
  32. package/dist/libs/deps/Libs.d.ts +5 -5
  33. package/dist/libs/deps/Libs.d.ts.map +1 -0
  34. package/dist/libs/deps/Libs.js +5 -6
  35. package/dist/libs/deps/Libs.js.map +1 -1
  36. package/dist/libs/deps/index.d.ts +1 -0
  37. package/dist/libs/deps/index.d.ts.map +1 -0
  38. package/dist/libs/error/BizError.d.ts +1 -0
  39. package/dist/libs/error/BizError.d.ts.map +1 -0
  40. package/dist/libs/error/BizError.js.map +1 -1
  41. package/dist/libs/error/index.d.ts +1 -0
  42. package/dist/libs/error/index.d.ts.map +1 -0
  43. package/dist/libs/gateway/ApiGatewayLoader.d.ts +4 -2
  44. package/dist/libs/gateway/ApiGatewayLoader.d.ts.map +1 -0
  45. package/dist/libs/gateway/ApiGatewayLoader.js +114 -42
  46. package/dist/libs/gateway/ApiGatewayLoader.js.map +1 -1
  47. package/dist/libs/gateway/index.d.ts +1 -0
  48. package/dist/libs/gateway/index.d.ts.map +1 -0
  49. package/dist/libs/generator/IdGenerator.d.ts +1 -0
  50. package/dist/libs/generator/IdGenerator.d.ts.map +1 -0
  51. package/dist/libs/generator/IdGenerator.js +6 -1
  52. package/dist/libs/generator/IdGenerator.js.map +1 -1
  53. package/dist/libs/generator/IndexCreator.d.ts +2 -0
  54. package/dist/libs/generator/IndexCreator.d.ts.map +1 -0
  55. package/dist/libs/generator/IndexCreator.js +49 -17
  56. package/dist/libs/generator/IndexCreator.js.map +1 -1
  57. package/dist/libs/generator/index.d.ts +1 -0
  58. package/dist/libs/generator/index.d.ts.map +1 -0
  59. package/dist/libs/healthcheck/HealthCheckController.d.ts +1 -0
  60. package/dist/libs/healthcheck/HealthCheckController.d.ts.map +1 -0
  61. package/dist/libs/healthcheck/HealthCheckController.js +30 -41
  62. package/dist/libs/healthcheck/HealthCheckController.js.map +1 -1
  63. package/dist/libs/healthcheck/index.d.ts +1 -0
  64. package/dist/libs/healthcheck/index.d.ts.map +1 -0
  65. package/dist/libs/index.d.ts +1 -0
  66. package/dist/libs/index.d.ts.map +1 -0
  67. package/dist/libs/koa/KoaControllerReturnHandler.d.ts +1 -0
  68. package/dist/libs/koa/KoaControllerReturnHandler.d.ts.map +1 -0
  69. package/dist/libs/koa/KoaControllerReturnHandler.js +35 -23
  70. package/dist/libs/koa/KoaControllerReturnHandler.js.map +1 -1
  71. package/dist/libs/koa/KoaLoader.d.ts +1 -0
  72. package/dist/libs/koa/KoaLoader.d.ts.map +1 -0
  73. package/dist/libs/koa/KoaLoader.js +21 -27
  74. package/dist/libs/koa/KoaLoader.js.map +1 -1
  75. package/dist/libs/koa/KoaLoaderOption.d.ts +1 -0
  76. package/dist/libs/koa/KoaLoaderOption.d.ts.map +1 -0
  77. package/dist/libs/koa/KoaLoaderOption.js.map +1 -1
  78. package/dist/libs/koa/index.d.ts +1 -0
  79. package/dist/libs/koa/index.d.ts.map +1 -0
  80. package/dist/libs/koa/setupRestfulControllers.d.ts +1 -0
  81. package/dist/libs/koa/setupRestfulControllers.d.ts.map +1 -0
  82. package/dist/libs/koa/setupRestfulControllers.js +59 -58
  83. package/dist/libs/koa/setupRestfulControllers.js.map +1 -1
  84. package/dist/libs/koa/setupSocketControllers.d.ts +1 -0
  85. package/dist/libs/koa/setupSocketControllers.d.ts.map +1 -0
  86. package/dist/libs/koa/setupSocketControllers.js +56 -33
  87. package/dist/libs/koa/setupSocketControllers.js.map +1 -1
  88. package/dist/libs/leader/Leader.d.ts +1 -0
  89. package/dist/libs/leader/Leader.d.ts.map +1 -0
  90. package/dist/libs/leader/Leader.js +46 -63
  91. package/dist/libs/leader/Leader.js.map +1 -1
  92. package/dist/libs/leader/LeaderOptions.d.ts +1 -0
  93. package/dist/libs/leader/LeaderOptions.d.ts.map +1 -0
  94. package/dist/libs/leader/index.d.ts +1 -0
  95. package/dist/libs/leader/index.d.ts.map +1 -0
  96. package/dist/libs/logger/Logger.d.ts +2 -1
  97. package/dist/libs/logger/Logger.d.ts.map +1 -0
  98. package/dist/libs/logger/Logger.js +9 -3
  99. package/dist/libs/logger/Logger.js.map +1 -1
  100. package/dist/libs/logger/index.d.ts +1 -0
  101. package/dist/libs/logger/index.d.ts.map +1 -0
  102. package/dist/libs/network/getLocalIpAddress.d.ts +1 -0
  103. package/dist/libs/network/getLocalIpAddress.d.ts.map +1 -0
  104. package/dist/libs/network/getLocalIpAddress.js +18 -19
  105. package/dist/libs/network/getLocalIpAddress.js.map +1 -1
  106. package/dist/libs/network/index.d.ts +1 -0
  107. package/dist/libs/network/index.d.ts.map +1 -0
  108. package/dist/libs/orm/BaseRepository.d.ts +1 -0
  109. package/dist/libs/orm/BaseRepository.d.ts.map +1 -0
  110. package/dist/libs/orm/BaseRepository.js +12 -33
  111. package/dist/libs/orm/BaseRepository.js.map +1 -1
  112. package/dist/libs/orm/TypeormLoader.d.ts +1 -0
  113. package/dist/libs/orm/TypeormLoader.d.ts.map +1 -0
  114. package/dist/libs/orm/TypeormLoader.js +6 -15
  115. package/dist/libs/orm/TypeormLoader.js.map +1 -1
  116. package/dist/libs/orm/index.d.ts +1 -0
  117. package/dist/libs/orm/index.d.ts.map +1 -0
  118. package/dist/libs/pagination/Pagination.d.ts +1 -0
  119. package/dist/libs/pagination/Pagination.d.ts.map +1 -0
  120. package/dist/libs/pagination/Pagination.js +1 -2
  121. package/dist/libs/pagination/Pagination.js.map +1 -1
  122. package/dist/libs/pagination/index.d.ts +1 -0
  123. package/dist/libs/pagination/index.d.ts.map +1 -0
  124. package/dist/libs/rabbitmq/DistributedEvents.d.ts +1 -0
  125. package/dist/libs/rabbitmq/DistributedEvents.d.ts.map +1 -0
  126. package/dist/libs/rabbitmq/DistributedEvents.js +49 -63
  127. package/dist/libs/rabbitmq/DistributedEvents.js.map +1 -1
  128. package/dist/libs/rabbitmq/DistributedEventsLoader.d.ts +1 -0
  129. package/dist/libs/rabbitmq/DistributedEventsLoader.d.ts.map +1 -0
  130. package/dist/libs/rabbitmq/DistributedEventsLoader.js +2 -11
  131. package/dist/libs/rabbitmq/DistributedEventsLoader.js.map +1 -1
  132. package/dist/libs/rabbitmq/EventsManager.d.ts +5 -4
  133. package/dist/libs/rabbitmq/EventsManager.d.ts.map +1 -0
  134. package/dist/libs/rabbitmq/EventsManager.js +17 -26
  135. package/dist/libs/rabbitmq/EventsManager.js.map +1 -1
  136. package/dist/libs/rabbitmq/index.d.ts +1 -0
  137. package/dist/libs/rabbitmq/index.d.ts.map +1 -0
  138. package/dist/libs/redis/RedisClient.d.ts +1 -0
  139. package/dist/libs/redis/RedisClient.d.ts.map +1 -0
  140. package/dist/libs/redis/RedisClient.js +41 -62
  141. package/dist/libs/redis/RedisClient.js.map +1 -1
  142. package/dist/libs/redis/RedisLoader.d.ts +1 -0
  143. package/dist/libs/redis/RedisLoader.d.ts.map +1 -0
  144. package/dist/libs/redis/RedisLoader.js +1 -10
  145. package/dist/libs/redis/RedisLoader.js.map +1 -1
  146. package/dist/libs/redis/index.d.ts +1 -0
  147. package/dist/libs/redis/index.d.ts.map +1 -0
  148. package/dist/libs/register/ApiRegisterController.d.ts +1 -0
  149. package/dist/libs/register/ApiRegisterController.d.ts.map +1 -0
  150. package/dist/libs/register/ApiRegisterController.js +73 -98
  151. package/dist/libs/register/ApiRegisterController.js.map +1 -1
  152. package/dist/libs/register/Converter.d.ts +1 -0
  153. package/dist/libs/register/Converter.d.ts.map +1 -0
  154. package/dist/libs/register/Converter.js.map +1 -1
  155. package/dist/libs/register/HttpMethods.d.ts +1 -0
  156. package/dist/libs/register/HttpMethods.d.ts.map +1 -0
  157. package/dist/libs/register/HttpMethods.js +8 -3
  158. package/dist/libs/register/HttpMethods.js.map +1 -1
  159. package/dist/libs/register/ResRegTypes.d.ts +1 -0
  160. package/dist/libs/register/ResRegTypes.d.ts.map +1 -0
  161. package/dist/libs/register/index.d.ts +1 -0
  162. package/dist/libs/register/index.d.ts.map +1 -0
  163. package/dist/libs/type/builder.d.ts +1 -0
  164. package/dist/libs/type/builder.d.ts.map +1 -0
  165. package/dist/libs/type/builder.js.map +1 -1
  166. package/dist/libs/type/index.d.ts +1 -0
  167. package/dist/libs/type/index.d.ts.map +1 -0
  168. package/dist/libs/type/types.d.ts +1 -0
  169. package/dist/libs/type/types.d.ts.map +1 -0
  170. package/dist/libs/universal/UniversalController.d.ts +1 -0
  171. package/dist/libs/universal/UniversalController.d.ts.map +1 -0
  172. package/dist/libs/universal/UniversalController.js.map +1 -1
  173. package/dist/libs/universal/UniversalService.d.ts +1 -0
  174. package/dist/libs/universal/UniversalService.d.ts.map +1 -0
  175. package/dist/libs/universal/UniversalService.js +126 -138
  176. package/dist/libs/universal/UniversalService.js.map +1 -1
  177. package/dist/libs/universal/index.d.ts +1 -0
  178. package/dist/libs/universal/index.d.ts.map +1 -0
  179. package/dist/libs/validator/SafeUrlValidator.d.ts +17 -0
  180. package/dist/libs/validator/SafeUrlValidator.d.ts.map +1 -0
  181. package/dist/libs/validator/SafeUrlValidator.js +88 -0
  182. package/dist/libs/validator/SafeUrlValidator.js.map +1 -0
  183. package/dist/libs/validator/ValidationHelper.d.ts +1 -0
  184. package/dist/libs/validator/ValidationHelper.d.ts.map +1 -0
  185. package/dist/libs/validator/ValidationHelper.js +40 -57
  186. package/dist/libs/validator/ValidationHelper.js.map +1 -1
  187. package/dist/libs/validator/i18nValidator.d.ts +1 -0
  188. package/dist/libs/validator/i18nValidator.d.ts.map +1 -0
  189. package/dist/libs/validator/i18nValidator.js +1 -1
  190. package/dist/libs/validator/i18nValidator.js.map +1 -1
  191. package/dist/libs/validator/index.d.ts +2 -0
  192. package/dist/libs/validator/index.d.ts.map +1 -0
  193. package/dist/libs/validator/index.js +1 -0
  194. package/dist/libs/validator/index.js.map +1 -1
  195. package/dist/server/BootstrapLoader.d.ts +1 -0
  196. package/dist/server/BootstrapLoader.d.ts.map +1 -0
  197. package/dist/server/BootstrapOption.d.ts +1 -0
  198. package/dist/server/BootstrapOption.d.ts.map +1 -0
  199. package/dist/server/bootstrap.d.ts +1 -0
  200. package/dist/server/bootstrap.d.ts.map +1 -0
  201. package/dist/server/bootstrap.js +5 -14
  202. package/dist/server/bootstrap.js.map +1 -1
  203. package/dist/server/index.d.ts +1 -0
  204. package/dist/server/index.d.ts.map +1 -0
  205. package/dist/utils/YamlUtil.d.ts +1 -0
  206. package/dist/utils/YamlUtil.d.ts.map +1 -0
  207. package/dist/utils/YamlUtil.js +12 -3
  208. package/dist/utils/YamlUtil.js.map +1 -1
  209. package/dist/utils/crypto.d.ts +1 -0
  210. package/dist/utils/crypto.d.ts.map +1 -0
  211. package/dist/utils/crypto.js.map +1 -1
  212. package/dist/utils/index.d.ts +1 -0
  213. package/dist/utils/index.d.ts.map +1 -0
  214. package/dist/utils/jwtUtil.d.ts +1 -0
  215. package/dist/utils/jwtUtil.d.ts.map +1 -0
  216. package/dist/utils/jwtUtil.js.map +1 -1
  217. package/dist/utils/transformer.d.ts +1 -0
  218. package/dist/utils/transformer.d.ts.map +1 -0
  219. package/dist/utils/transformer.js.map +1 -1
  220. package/package.json +50 -28
  221. package/.dockerignore +0 -12
  222. package/.drone.yml +0 -54
  223. package/.eslintignore +0 -4
  224. package/.github/workflows/docker-image.yml +0 -69
  225. package/.ncurc.json +0 -8
  226. package/Dockerfile +0 -47
  227. package/gen_db.json +0 -7
  228. package/open.json +0 -104
package/CLAUDE.md ADDED
@@ -0,0 +1,757 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Project Overview](#project-overview)
8
+ - [Quick Start](#quick-start)
9
+ - [Development Commands](#development-commands)
10
+ - [Database Code Generation](#database-code-generation)
11
+ - [Architecture](#architecture)
12
+ - [Bootstrap System](#bootstrap-system)
13
+ - [Configuration Management](#configuration-management)
14
+ - [Dependency Injection](#dependency-injection)
15
+ - [Controller Pattern](#controller-pattern)
16
+ - [Data Layer](#data-layer)
17
+ - [Validation and Transformation](#validation-and-transformation)
18
+ - [Health Check](#health-check)
19
+ - [Pagination](#pagination)
20
+ - [Caching](#caching)
21
+ - [Distributed Events](#distributed-events)
22
+ - [Leader Election](#leader-election)
23
+ - [API Gateway Integration](#api-gateway-integration)
24
+ - [Error Handling](#error-handling)
25
+ - [Logging](#logging)
26
+ - [TypeScript Configuration](#typescript-configuration)
27
+ - [Project Structure](#project-structure)
28
+ - [Key Dependencies](#key-dependencies)
29
+ - [Entry Point](#entry-point)
30
+ - [Best Practices](#best-practices)
31
+ - [Module References](#module-references)
32
+ - [Publishing](#publishing)
33
+
34
+ ## Project Overview
35
+
36
+ `@gaias/basenode` (v1.0.13) is a Node.js API development framework built on Koa, TypeORM, TypeDI, and routing-controllers. It provides a microframework architecture with built-in support for RESTful APIs, WebSocket controllers, database ORM, distributed events via RabbitMQ, Redis caching, and API gateway integration with APISIX.
37
+
38
+ **Requirements:**
39
+ - Node.js: >=18.0.0
40
+ - Yarn: >=1.22.x
41
+ - MariaDB/MySQL: 5.7+ or 8.0+ (for production use)
42
+ - Redis: 6.0+ (optional, for caching and leader election)
43
+ - RabbitMQ: 3.8+ (optional, for distributed events)
44
+
45
+ ## Quick Start
46
+
47
+ 1. **Install dependencies:**
48
+ ```bash
49
+ yarn install
50
+ ```
51
+
52
+ 2. **Configure database:**
53
+ - Edit `cfg/database.yml` with your MariaDB/MySQL connection details
54
+ - Edit `cfg/redis.yml` for Redis (if using caching)
55
+ - Edit `cfg/rabbitmq.yml` for RabbitMQ (if using distributed events)
56
+
57
+ 3. **Set environment variables (optional):**
58
+ ```bash
59
+ # Create .env file or export variables
60
+ NODE_ENV=development # Environment: development, production, test
61
+ ENABLE_API_GATEWAY=true # Enable APISIX gateway registration
62
+ API_GATEWAY_HOST_PORT=192.168.1.100:9180 # Gateway admin API address
63
+ DOMAINS=example.com,*.example.com # Allowed domains for gateway
64
+ ```
65
+
66
+ 4. **Generate database code (optional):**
67
+ ```bash
68
+ # Define tables in gen_db.json, then:
69
+ yarn gen:db
70
+ ```
71
+
72
+ 5. **Run development server:**
73
+ ```bash
74
+ yarn dev
75
+ # App starts on http://localhost:3000 (or configured port)
76
+ # Health check: http://localhost:3000/_healthcheck
77
+ ```
78
+
79
+ 6. **Run tests and linting:**
80
+ ```bash
81
+ yarn test
82
+ yarn lint
83
+ ```
84
+
85
+ ## Development Commands
86
+
87
+ ### Running the Application
88
+ ```bash
89
+ # Development mode with hot reload
90
+ yarn dev
91
+
92
+ # Development mode with API gateway enabled (production-like)
93
+ yarn devPro
94
+
95
+ # Run compiled example app using ncc
96
+ yarn ncc:run
97
+ ```
98
+
99
+ ### Building
100
+ ```bash
101
+ # Build for publishing (transpiles src/ to dist/)
102
+ yarn prepublish
103
+
104
+ # Build single-file executable with ncc
105
+ yarn ncc:build
106
+ ```
107
+
108
+ ### Linting
109
+ ```bash
110
+ # Type check and lint
111
+ yarn lint
112
+
113
+ # Auto-fix linting issues
114
+ yarn lint:fix
115
+ ```
116
+
117
+ ### Security
118
+ ```bash
119
+ # Run security audit on dependencies
120
+ yarn security
121
+
122
+ # Show audit summary only
123
+ yarn security:summary
124
+
125
+ # Output audit results in JSON format
126
+ yarn security:json
127
+
128
+ # Generate detailed security report
129
+ yarn security:report
130
+ ```
131
+
132
+ **Security Policy:** See `SECURITY.md` for comprehensive security guidelines, vulnerability reporting procedures, and mitigation strategies. The project includes automated security auditing via `yarn audit` and custom reporting tools.
133
+
134
+ ### Testing
135
+ ```bash
136
+ # Run all tests
137
+ yarn test
138
+
139
+ # Run tests in watch mode
140
+ yarn test:watch
141
+
142
+ # Run tests with coverage report
143
+ yarn test:coverage
144
+ ```
145
+
146
+ **Testing Framework:** Jest is configured for unit and integration testing. Test files should use `*.test.ts` or `*.spec.ts` naming convention.
147
+
148
+ ### Dependency Management
149
+ ```bash
150
+ # Check for outdated dependencies
151
+ yarn deps:check
152
+
153
+ # Update dependencies to latest versions
154
+ yarn deps:update
155
+
156
+ # Update dependencies (alternative command)
157
+ yarn upver
158
+ ```
159
+
160
+ ### Database Code Generation
161
+
162
+ The framework includes automated code generation tools for database entities and repositories:
163
+
164
+ ```bash
165
+ # Generate entities from database schema
166
+ yarn gen:db-schema
167
+
168
+ # Generate repository classes from entities
169
+ yarn gen:db-repo
170
+
171
+ # Generate both entities and repositories, then fix linting
172
+ yarn gen:db
173
+
174
+ # Generate index.ts files for all modules
175
+ yarn gen:idx
176
+ ```
177
+
178
+ **Important:** Before running database generation:
179
+ 1. Ensure MariaDB/MySQL is running and accessible
180
+ 2. Configure database connection in `cfg/database.yml`
181
+ 3. Define which tables to generate in `gen_db.json` (array of table names)
182
+
183
+ The generators use `typeorm-model-generator` with custom Mustache templates (`tools/repository.mst`) to create:
184
+ - **Entities** in `example/entities/` (or configured output path)
185
+ - **Repositories** in `example/repositories/` with `Repo` suffix
186
+
187
+ Generated repositories extend `BaseRepository<T>` and won't be overwritten if they already exist.
188
+
189
+ ### Other Commands
190
+ ```bash
191
+ # Generate RSA keys for JWT (stored in ./keys/)
192
+ yarn gen:keys
193
+
194
+ # Update build number
195
+ yarn buildNum
196
+
197
+ # Pre-commit hook (runs linting)
198
+ yarn precommit
199
+ ```
200
+
201
+ ## Architecture
202
+
203
+ ### Bootstrap System
204
+
205
+ The application uses a microframework loader pattern orchestrated by `src/server/bootstrap.ts`. The bootstrap function accepts a `BootstrapOption` that combines multiple loader configurations and sequentially initializes:
206
+
207
+ 1. **TypeORM Loader** - Database connection and entity registration
208
+ 2. **Redis Loader** - Redis client initialization
209
+ 3. **RabbitMQ Loader** - Distributed event system setup
210
+ 4. **Koa Loader** - Web server with RESTful and WebSocket controllers
211
+ 5. **API Gateway Loader** - APISIX integration for service registration
212
+
213
+ Each loader can be disabled via flags (`disableDatabase`, `disableRedis`, `disableEvent`).
214
+
215
+ ### Configuration Management
216
+
217
+ Configuration is managed through YAML files in the `cfg/` directory, loaded by `ConfigManager`:
218
+
219
+ - `application.yml` - App name, version, port, and general settings
220
+ - `database.yml` - MariaDB/MySQL connection configuration
221
+ - `redis.yml` - Redis connection settings (host, port, password, db)
222
+ - `rabbitmq.yml` - RabbitMQ connection URL and settings
223
+ - `logger.yml` - Pino logger configuration (level, pretty print)
224
+ - `apisix.yml` - API gateway settings (admin URL, credentials)
225
+ - `openapiCfg.yml` - OpenAPI/Swagger documentation configuration
226
+
227
+ Configuration files support environment-specific overrides (e.g., `application.development.yml`, `application.production.yml`). The system automatically loads the base config and merges environment-specific settings based on `NODE_ENV`.
228
+
229
+ Access configuration via:
230
+ ```typescript
231
+ import { ConfigManager } from '@/libs/configure';
232
+
233
+ const appConfig = ConfigManager.getConfig<ApplicationConfig>('application');
234
+ const dbConfig = ConfigManager.getConfig<DatabaseConfig>('database');
235
+ ```
236
+
237
+ ### Dependency Injection
238
+
239
+ The framework uses TypeDI for IoC. Services and repositories are decorated with `@Service()` and injected via `@Inject()` or constructor injection. The `Container` is automatically configured during bootstrap.
240
+
241
+ **Simplified Imports via `deps` Module:**
242
+
243
+ The framework provides a unified dependency export module (`src/libs/deps`) with short namespace aliases for cleaner imports. See `src/libs/deps/README.md` for comprehensive documentation.
244
+
245
+ ```typescript
246
+ import { rest, di, orm, cv, ct, ws, api, tx } from '@/libs/deps';
247
+
248
+ // Instead of:
249
+ // import { Service } from 'typedi';
250
+ // import { JsonController, Get, Post, Body } from 'routing-controllers';
251
+ // import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
252
+ // import { IsString, IsEmail } from 'class-validator';
253
+
254
+ @rest.JsonController('/users') // routing-controllers
255
+ @di.Service() // typedi
256
+ class UserController {
257
+ @rest.Get('/')
258
+ async getAll() { return []; }
259
+
260
+ @rest.Post('/')
261
+ async create(@rest.Body() data: CreateUserDto) {
262
+ // rest.Body auto-enables excludeExtraneousValues for security
263
+ return {};
264
+ }
265
+ }
266
+ ```
267
+
268
+ **Namespace Aliases:**
269
+ - `ct` = class-transformer
270
+ - `cv` = class-validator
271
+ - `di` = typedi
272
+ - `orm` = typeorm
273
+ - `tx` = typeorm-transactional
274
+ - `rest` = routing-controllers (enhanced with secure Body decorator)
275
+ - `ws` = socket-controllers
276
+ - `api` = routing-controllers-openapi
277
+
278
+ ### Controller Pattern
279
+
280
+ **RESTful Controllers** extend `UniversalController` and use `routing-controllers` decorators:
281
+ - `@JsonController()` - Define controller class
282
+ - `@Get()`, `@Post()`, `@Put()`, `@Delete()` - HTTP methods with optional scopes
283
+ - Method signature: `@Method(path, scope?, module?)`
284
+ - `UniversalController` provides CRUD operations for entities via `getUniversalService(Entity)`
285
+
286
+ **WebSocket Controllers** use `socket-controllers`:
287
+ - Use `@OnConnect`, `@OnDisconnect`, `@OnMessage` decorators
288
+ - Registered via `wsControllers` in bootstrap options
289
+
290
+ ### Data Layer
291
+
292
+ **Entities** are TypeORM entities with decorators (`@Entity`, `@Column`, `@PrimaryGeneratedColumn`, etc.). Auto-generated from database schema.
293
+
294
+ **Repositories** extend `BaseRepository<Entity>` providing:
295
+ - `find()`, `findOne()`, `findById()`
296
+ - `save()`, `update()`, `delete()`
297
+
298
+ **UniversalService** provides high-level CRUD with transformation:
299
+ - `create()`, `readById()`, `update()`, `remove()`
300
+ - `getAll(VoClass)`, `query(search, options)` - With pagination support
301
+ - Automatic VO transformation using `class-transformer`
302
+
303
+ ### Validation and Transformation
304
+
305
+ Use `class-validator` decorators on VO (Value Object) classes wrapped with `@i18n()` for internationalized error messages:
306
+ ```typescript
307
+ class UserVo {
308
+ @i18n(IsString)
309
+ @i18n(MaxLength, 50)
310
+ userName: string;
311
+ }
312
+ ```
313
+
314
+ **⚠️ Security - URL Validation:**
315
+ Use `@IsSafeUrl()` instead of `@IsUrl()` to avoid CVE-2025-56200 in validator.js:
316
+ ```typescript
317
+ import { IsSafeUrl } from '@/libs/validator';
318
+
319
+ class UserVo {
320
+ @IsSafeUrl() // ✅ Secure
321
+ website: string;
322
+
323
+ @IsSafeUrl({ protocols: ['https'] })
324
+ secureUrl: string;
325
+ }
326
+ ```
327
+ See `src/libs/validator/README.md` and `SECURITY.md` for details.
328
+
329
+ Transform responses with `@Transform(VoClass)` decorator on controller methods.
330
+
331
+ ### Health Check
332
+
333
+ Built-in health check endpoint at `/_healthcheck` provided by `HealthCheckController`:
334
+
335
+ ```typescript
336
+ // Basic health check
337
+ GET /_healthcheck
338
+ // Response: { healthy: true, dbAlive: true }
339
+
340
+ // Detailed health check with OS info
341
+ GET /_healthcheck?os=true
342
+ // Response includes system info: hostname, platform, CPU, memory, network
343
+ ```
344
+
345
+ The health check automatically:
346
+ - Tests database connectivity
347
+ - Reports server network information
348
+ - Optionally provides OS-level metrics (CPU, memory, uptime)
349
+
350
+ ### Pagination
351
+
352
+ Complete pagination solution in `src/libs/pagination` with TypeORM integration:
353
+
354
+ **PaginationIn** - Standardized pagination request parameters:
355
+ ```typescript
356
+ class PaginationIn {
357
+ pageIndex?: number; // Page number (starts from 1)
358
+ recordIndex?: number; // Record offset (starts from 0) - for infinite scroll
359
+ pageSize: number = 25; // Items per page
360
+ search?: string; // Search keyword
361
+ sort?: string; // Sort fields (e.g., "!createdAt" for DESC)
362
+ }
363
+ ```
364
+
365
+ **PaginationOut** - Pagination response with auto-transformation:
366
+ ```typescript
367
+ // Service example
368
+ async search(pagination: PaginationIn): Promise<PaginationOut<UserVo, User>> {
369
+ const qb = this.userRepo.createQueryBuilder('user');
370
+
371
+ // Add search conditions
372
+ if (pagination.search) {
373
+ qb.where('user.name LIKE :search', { search: `%${pagination.search}%` });
374
+ }
375
+
376
+ // Add sorting (auto-converts camelCase to snake_case)
377
+ setSorting(qb, 'user', ...pagination.sort?.split(',') || []);
378
+
379
+ // Calculate pagination
380
+ const total = await qb.getCount();
381
+ const { skip, take } = skipAndTake(total, pagination);
382
+ const data = await qb.skip(skip).take(take).getMany();
383
+
384
+ // Return with auto-transformation to VO
385
+ return new PaginationOut(total, pagination.pageSize, UserVo, data);
386
+ }
387
+ ```
388
+
389
+ **Sorting features:**
390
+ - Single/multiple field sorting: `"createdAt"` or `"status,!createdAt"`
391
+ - Descending order: prefix with `!` (e.g., `"!updatedAt"`)
392
+ - Auto-converts camelCase to snake_case for database columns
393
+ - Helper functions: `setSorting()`, `getSorting()`, `skipAndTake()`
394
+
395
+ ### Caching
396
+
397
+ Two-level caching system:
398
+
399
+ **L1 Cache** - In-memory with TTL:
400
+ ```typescript
401
+ @Get('/path')
402
+ @L1Cache({ ttlSeconds: 60 })
403
+ async method() { }
404
+ ```
405
+
406
+ **L2 Cache** - Redis-backed via `CacheService`:
407
+ ```typescript
408
+ @Inject()
409
+ private cacheService: CacheService;
410
+
411
+ await this.cacheService.set('key', value, ttl);
412
+ await this.cacheService.get('key');
413
+ ```
414
+
415
+ ### Distributed Events
416
+
417
+ RabbitMQ-based pub/sub system via `DistributedEvents`:
418
+
419
+ **Publishing events:**
420
+ ```typescript
421
+ events.pub('eventName', { data });
422
+ ```
423
+
424
+ **Subscribing to events:**
425
+ ```typescript
426
+ events.sub(['event.pattern.*']);
427
+ events.on('RemoteEvent', (eventName, data) => { });
428
+ ```
429
+
430
+ Event handlers are classes decorated with `@Service()` registered in `eventsHandlers` bootstrap option.
431
+
432
+ ### Leader Election
433
+
434
+ Redis-based leader election for distributed systems using the `Leader` service:
435
+ ```typescript
436
+ await Container.get(Leader).config({ project: 'ProjectName' }).elect();
437
+ ```
438
+
439
+ Emits `elected` and `revoked` events. Useful for scheduled tasks that should only run on one instance.
440
+
441
+ ### API Gateway Integration
442
+
443
+ Automatic service registration with APISIX when `ENABLE_API_GATEWAY=true`. Routes are auto-discovered and registered with the gateway on startup.
444
+
445
+ ### Error Handling
446
+
447
+ Use `BizError` for business logic errors with i18n support:
448
+ ```typescript
449
+ throw new BizError('error.key');
450
+ // or with params
451
+ throw new BizError({ key: 'error.key', param: { name: 'value' } });
452
+ ```
453
+
454
+ Use `ValidationHelper.check()` for custom validation logic.
455
+
456
+ ### Logging
457
+
458
+ Pino-based logging via `Logger.getLogger(context)`:
459
+ ```typescript
460
+ private logger = Logger.getLogger(MyClass);
461
+ this.logger.info('message');
462
+ this.logger.error('error', err);
463
+ ```
464
+
465
+ ## TypeScript Configuration
466
+
467
+ - Outputs to `temp/` during development
468
+ - Uses path alias `@/*` for `src/*`
469
+ - Decorators enabled (`experimentalDecorators`, `emitDecoratorMetadata`)
470
+ - Strict mode enabled
471
+
472
+ ## Project Structure
473
+
474
+ ```
475
+ src/
476
+ libs/ # Framework components
477
+ apisix/ # APISIX HTTP client and templates
478
+ cache/ # Two-level caching (L1/L2)
479
+ configure/ # YAML configuration management
480
+ deps/ # Dependency library exports (ct, cv, di, orm, rest, ws, api, tx)
481
+ error/ # Error handling (BizError, ErrorHandler)
482
+ gateway/ # API Gateway integration loader
483
+ generator/ # ID generation (nanoid, snowflake)
484
+ healthcheck/ # Health check endpoint controller
485
+ koa/ # Koa server setup and middleware
486
+ leader/ # Redis-based leader election
487
+ logger/ # Pino logger wrapper
488
+ network/ # Network utilities (local IP detection)
489
+ orm/ # TypeORM extensions (BaseRepository)
490
+ pagination/ # Pagination utilities (PaginationIn/Out, sorting)
491
+ rabbitmq/ # RabbitMQ distributed events
492
+ redis/ # Redis client wrapper
493
+ register/ # API route registration and metadata
494
+ type/ # Type definitions and builders
495
+ universal/ # UniversalController/Service for CRUD
496
+ validator/ # Validation helpers (i18n, SafeUrlValidator)
497
+ server/ # Bootstrap logic
498
+ utils/ # Utilities (JWT, crypto, YAML, transformer)
499
+
500
+ example/ # Example application
501
+ app.ts # Entry point
502
+ controllers/ # RESTful controllers
503
+ wsControllers/ # WebSocket controllers
504
+ entities/ # TypeORM entities (auto-generated)
505
+ repositories/ # Repository classes (auto-generated)
506
+ services/ # Business logic services
507
+ vo/ # Value Objects (DTOs)
508
+ events/ # Distributed event handlers
509
+
510
+ cfg/ # YAML configuration files
511
+ application.yml # App settings (name, version, port)
512
+ database.yml # Database connection
513
+ redis.yml # Redis connection
514
+ rabbitmq.yml # RabbitMQ connection
515
+ logger.yml # Logger settings
516
+ apisix.yml # API gateway settings
517
+ openapiCfg.yml # OpenAPI/Swagger config
518
+
519
+ tools/ # Development tools
520
+ DBSchemaGenerator.ts # Generate entities from DB schema
521
+ RepositoryGenerator.ts # Generate repository classes
522
+ repository.mst # Mustache template for repos
523
+ ```
524
+
525
+ ## Key Dependencies
526
+
527
+ ### Core Framework
528
+ - **Koa** (^3.0.3) - Lightweight web framework
529
+ - **routing-controllers** (^0.11.3) - Decorator-based RESTful API routing
530
+ - **socket-controllers** (^0.3.1) - Decorator-based WebSocket controllers
531
+ - **TypeDI** (^0.10.0) - Dependency injection container
532
+ - **microframework** (^0.6.4) - Loader pattern for modular bootstrap
533
+
534
+ ### Data Layer
535
+ - **TypeORM** (^0.3.27) - SQL ORM with full TypeScript support
536
+ - **typeorm-transactional** (^0.5.0) - Declarative transaction management
537
+ - **mysql2** (^3.15.2) - MySQL/MariaDB driver
538
+ - **class-validator** (^0.14.2) - Decorator-based validation
539
+ - **class-transformer** (^0.5.1) - Object-to-class transformation
540
+
541
+ ### Caching & Messaging
542
+ - **ioredis** (^5.8.1) - Redis client with clustering support
543
+ - **amqplib** (^0.10.9) - RabbitMQ client for distributed events
544
+
545
+ ### API Documentation
546
+ - **routing-controllers-openapi** (^5.0.0) - OpenAPI/Swagger spec generation
547
+ - **class-validator-jsonschema** (^5.1.0) - JSON Schema from validators
548
+
549
+ ### Utilities
550
+ - **pino** (^10.0.0) + **pino-pretty** (^11.0.0) - High-performance logger
551
+ - **jsonwebtoken** (^9.0.2) - JWT authentication
552
+ - **lodash** (^4.17.21) - Utility functions
553
+ - **nanoid** (^5.1.6) - Compact unique ID generator
554
+ - **axios** (^1.12.2) - HTTP client
555
+ - **js-yaml** (^4.1.0) - YAML parser for configuration
556
+
557
+ ### Recent Dependency Updates & Migration Notes
558
+
559
+ **TypeORM Transaction Management:** The project has migrated from `typeorm-transactional-cls-hooked` to `typeorm-transactional` (v0.5.0). The new library:
560
+ - No longer depends on `cls-hooked`, improving performance and compatibility
561
+ - Provides the same `@Transactional()` decorator API (no code changes needed)
562
+ - Requires `addTransactionalDataSource(dataSource)` during TypeORM initialization
563
+ - Better support for async/await and modern Node.js versions
564
+
565
+ **Repository Injection:** `typeorm-typedi-extensions` has been removed. Use direct TypeDI injection instead:
566
+ ```typescript
567
+ // Old way (deprecated)
568
+ // import { OrmRepository } from 'typeorm-typedi-extensions';
569
+ // @OrmRepository(User) private userRepo: Repository<User>;
570
+
571
+ // New way (current)
572
+ @Service()
573
+ class UserService {
574
+ @Inject(() => UserRepo)
575
+ private userRepo: UserRepo;
576
+ }
577
+ ```
578
+
579
+ **Security Updates:** The project uses Yarn resolutions to enforce secure versions of transitive dependencies:
580
+ - `validator` (^13.12.0) - Addresses CVE-2025-56200 (mitigated via SafeUrlValidator)
581
+ - `xml2js` (^0.6.2) - Fixes XML parsing vulnerabilities
582
+ - `tmp` (^0.2.4) - Secure temporary file handling
583
+ - `axios` (^1.12.2+) - Latest security patches
584
+ - See `package.json` resolutions and `SECURITY.md` for complete list
585
+
586
+ ## Entry Point
587
+
588
+ Example app entry: `example/app.ts`
589
+
590
+ Import and call `bootstrap()` with configuration:
591
+ ```typescript
592
+ bootstrap({
593
+ restfulControllers: [...controllers],
594
+ wsControllers: [...wsControllers],
595
+ entities: [...entities],
596
+ eventsHandlers: [...handlers],
597
+ })
598
+ ```
599
+
600
+ ## Best Practices
601
+
602
+ ### Controller Design
603
+ - Extend `UniversalController` for standard CRUD operations
604
+ - Use `@rest.Body()` for request body (auto-enables security filtering)
605
+ - Apply `@Transform(VoClass)` decorator for response transformation
606
+ - Group related endpoints under a single controller
607
+ - Use scopes for role-based access control (e.g., `@Get('/', 'admin')`)
608
+
609
+ ### Service Layer
610
+ - Keep controllers thin, business logic in services
611
+ - Use `UniversalService` for common CRUD operations
612
+ - Apply `@Transactional()` decorator for database transactions
613
+ - Inject repositories via TypeDI: `@Inject(() => UserRepo)`
614
+
615
+ ### Data Validation
616
+ - Always validate input with `class-validator` decorators
617
+ - Wrap validators with `@i18n()` for internationalized error messages
618
+ - Use `@IsSafeUrl()` instead of `@IsUrl()` to avoid CVE-2025-56200
619
+ - Mark optional fields with `@IsOptional()`
620
+
621
+ ### Database Operations
622
+ - Use TypeORM query builder for complex queries
623
+ - Apply pagination with `PaginationIn` and `PaginationOut`
624
+ - Use `setSorting()` helper for dynamic sorting
625
+ - Never concatenate user input into SQL queries (use parameterized queries)
626
+
627
+ ### Error Handling
628
+ - Throw `BizError` for business logic errors with i18n keys
629
+ - Let the framework handle routing-controllers validation errors
630
+ - Use `ValidationHelper.check()` for custom validation logic
631
+ - Log errors with context: `this.logger.error('message', error)`
632
+
633
+ ### Performance
634
+ - Use L1 cache (`@L1Cache`) for frequently accessed, rarely changing data
635
+ - Use L2 cache (Redis) for shared state across instances
636
+ - Implement pagination for list endpoints
637
+ - Use leader election for scheduled tasks in distributed systems
638
+
639
+ ### Security
640
+ - Review `SECURITY.md` before adding dependencies
641
+ - Run `yarn security:report` regularly
642
+ - Never commit sensitive data (use `.env` files)
643
+ - Use `@Authorized()` decorator for protected endpoints
644
+ - Validate all user input, sanitize output
645
+
646
+ ## Module References
647
+
648
+ For detailed documentation on specific modules:
649
+ - **deps module**: `src/libs/deps/README.md` - Unified dependency exports
650
+ - **validator**: `src/libs/validator/README.md` - Validation helpers and SafeUrlValidator
651
+ - **apisix**: `src/libs/apisix/README.md` - API gateway integration
652
+ - **gateway**: `src/libs/gateway/README.md` - Gateway loader
653
+ - **generator**: `src/libs/generator/README.md` - ID generation
654
+ - **koa**: `src/libs/koa/README.md` - Koa server setup
655
+ - **network**: `src/libs/network/README.md` - Network utilities
656
+ - **rabbitmq**: `src/libs/rabbitmq/README.md` - Distributed events
657
+ - **register**: `src/libs/register/README.md` - API route registration
658
+ - **type**: `src/libs/type/README.md` - Type utilities
659
+ - **universal**: `src/libs/universal/README.md` - Universal CRUD patterns
660
+ - **Security**: `SECURITY.md` - Comprehensive security guidelines
661
+
662
+ ## Publishing
663
+
664
+ This is a private npm package (`UNLICENSED`). Publishing requires authentication:
665
+ ```bash
666
+ npm_config__auth=<base64_token> yarn publish --access restricted
667
+ ```
668
+
669
+ Before publishing:
670
+ 1. Update version in `package.json`
671
+ 2. Run `yarn buildNum` to update build number
672
+ 3. Run `yarn security:report` to check for vulnerabilities
673
+ 4. Run `yarn test` to ensure all tests pass
674
+ 5. Run `yarn lint` to check code quality
675
+ 6. Update changelog/release notes
676
+
677
+ ## Contributing Guidelines
678
+
679
+ ### Code Style
680
+ - Follow existing code conventions
681
+ - Use TypeScript strict mode
682
+ - Run `yarn lint:fix` before committing
683
+ - Use meaningful variable and function names
684
+ - Add JSDoc comments for public APIs
685
+
686
+ ### Git Workflow
687
+ 1. Create feature branch from `develope`
688
+ 2. Make changes with descriptive commits
689
+ 3. Run tests and linting
690
+ 4. Create pull request to `develope` (not `main`)
691
+ 5. Wait for code review
692
+
693
+ ### Pre-commit Hooks
694
+ The project uses Husky for git hooks:
695
+ - Automatic linting on commit
696
+ - Tests run before push (if configured)
697
+
698
+ ### Adding New Dependencies
699
+ 1. Check for security vulnerabilities: `npm info <package>`
700
+ 2. Add dependency: `yarn add <package>`
701
+ 3. Run security audit: `yarn security:report`
702
+ 4. Document breaking changes or new features
703
+
704
+ ## Troubleshooting
705
+
706
+ ### Common Issues
707
+
708
+ **Issue: Database connection fails**
709
+ - Verify `cfg/database.yml` connection string
710
+ - Check MariaDB/MySQL is running
711
+ - Ensure database user has proper permissions
712
+
713
+ **Issue: Redis connection fails**
714
+ - Check Redis is running: `redis-cli ping`
715
+ - Verify `cfg/redis.yml` settings
716
+ - Can disable Redis by setting `disableRedis: true` in bootstrap
717
+
718
+ **Issue: TypeORM entity not found**
719
+ - Ensure entity is registered in bootstrap `entities` array
720
+ - Check entity file has `@Entity()` decorator
721
+ - Verify import path is correct
722
+
723
+ **Issue: Validation errors not showing**
724
+ - Ensure DTO uses `@i18n()` wrapper for validators
725
+ - Check `class-validator` decorators are applied
726
+ - Verify `class-transformer` is properly configured
727
+
728
+ **Issue: Build fails with decorator errors**
729
+ - Check `tsconfig.json` has `experimentalDecorators: true`
730
+ - Ensure `emitDecoratorMetadata: true` is set
731
+ - Verify `reflect-metadata` is imported at app entry
732
+
733
+ ## Additional Resources
734
+
735
+ ### Framework Documentation
736
+ - [TypeORM Documentation](https://typeorm.io/)
737
+ - [routing-controllers Guide](https://github.com/typestack/routing-controllers)
738
+ - [TypeDI Documentation](https://github.com/typestack/typedi)
739
+ - [class-validator Decorators](https://github.com/typestack/class-validator)
740
+ - [class-transformer Guide](https://github.com/typestack/class-transformer)
741
+
742
+ ### Infrastructure
743
+ - [Koa.js Website](https://koajs.com/)
744
+ - [Redis Documentation](https://redis.io/docs/)
745
+ - [RabbitMQ Tutorials](https://www.rabbitmq.com/tutorials)
746
+ - [APISIX Documentation](https://apisix.apache.org/docs/)
747
+
748
+ ### Tools
749
+ - [Pino Logger](https://github.com/pinojs/pino)
750
+ - [Jest Testing](https://jestjs.io/)
751
+ - [ESLint Rules](https://eslint.org/docs/rules/)
752
+
753
+ ---
754
+
755
+ **Last Updated:** 2025-10-19
756
+ **Framework Version:** 1.0.13
757
+ **Maintainer:** FOT Team