@gravito/core 1.6.1 → 2.0.0
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.
- package/README.md +100 -6
- package/README.zh-TW.md +101 -6
- package/dist/Application.d.ts +256 -0
- package/dist/CommandKernel.d.ts +33 -0
- package/dist/ConfigManager.d.ts +65 -0
- package/dist/Container/RequestScopeManager.d.ts +62 -0
- package/dist/Container/RequestScopeMetrics.d.ts +144 -0
- package/dist/Container.d.ts +153 -0
- package/dist/ErrorHandler.d.ts +66 -0
- package/dist/Event.d.ts +5 -0
- package/dist/EventManager.d.ts +123 -0
- package/dist/GlobalErrorHandlers.d.ts +47 -0
- package/dist/GravitoServer.d.ts +28 -0
- package/dist/HookManager.d.ts +435 -0
- package/dist/Listener.d.ts +4 -0
- package/dist/Logger.d.ts +20 -0
- package/dist/PlanetCore.d.ts +402 -0
- package/dist/RequestContext.d.ts +97 -0
- package/dist/Route.d.ts +36 -0
- package/dist/Router.d.ts +270 -0
- package/dist/ServiceProvider.d.ts +178 -0
- package/dist/adapters/GravitoEngineAdapter.d.ts +27 -0
- package/dist/adapters/bun/AdaptiveAdapter.d.ts +99 -0
- package/dist/adapters/bun/BunContext.d.ts +54 -0
- package/dist/adapters/bun/BunNativeAdapter.d.ts +66 -0
- package/dist/adapters/bun/BunRequest.d.ts +31 -0
- package/dist/adapters/bun/BunWebSocketHandler.d.ts +48 -0
- package/dist/adapters/bun/RadixNode.d.ts +19 -0
- package/dist/adapters/bun/RadixRouter.d.ts +32 -0
- package/dist/adapters/bun/index.d.ts +7 -0
- package/dist/adapters/bun/types.d.ts +20 -0
- package/dist/adapters/index.d.ts +12 -0
- package/dist/adapters/types.d.ts +235 -0
- package/dist/binary/BinaryUtils.d.ts +105 -0
- package/dist/binary/index.d.ts +5 -0
- package/dist/cli/queue-commands.d.ts +6 -0
- package/dist/compat/async-local-storage.browser.d.ts +9 -0
- package/dist/compat/async-local-storage.d.ts +7 -0
- package/dist/compat/crypto.browser.d.ts +5 -0
- package/dist/compat/crypto.d.ts +6 -0
- package/dist/compat.cjs +42 -11
- package/dist/compat.cjs.map +9 -0
- package/dist/compat.d.ts +23 -1
- package/dist/compat.js +3 -0
- package/dist/compat.js.map +9 -0
- package/dist/engine/AOTRouter.d.ts +139 -0
- package/dist/engine/FastContext.d.ts +141 -0
- package/dist/engine/Gravito.d.ts +131 -0
- package/dist/engine/MinimalContext.d.ts +102 -0
- package/dist/engine/analyzer.d.ts +113 -0
- package/dist/engine/constants.d.ts +23 -0
- package/dist/engine/index.cjs +576 -647
- package/dist/engine/index.cjs.map +22 -0
- package/dist/engine/index.d.ts +14 -910
- package/dist/engine/index.js +576 -623
- package/dist/engine/index.js.map +22 -0
- package/dist/engine/path.d.ts +26 -0
- package/dist/engine/pool.d.ts +83 -0
- package/dist/engine/types.d.ts +149 -0
- package/dist/error-handling/RequestScopeErrorContext.d.ts +126 -0
- package/dist/events/BackpressureManager.d.ts +215 -0
- package/dist/events/CircuitBreaker.d.ts +229 -0
- package/dist/events/DeadLetterQueue.d.ts +219 -0
- package/dist/events/EventBackend.d.ts +12 -0
- package/dist/events/EventOptions.d.ts +204 -0
- package/dist/events/EventPriorityQueue.d.ts +63 -0
- package/dist/events/FlowControlStrategy.d.ts +109 -0
- package/dist/events/IdempotencyCache.d.ts +60 -0
- package/dist/events/MessageQueueBridge.d.ts +184 -0
- package/dist/events/PriorityEscalationManager.d.ts +82 -0
- package/dist/events/RetryScheduler.d.ts +104 -0
- package/dist/events/WorkerPool.d.ts +98 -0
- package/dist/events/WorkerPoolConfig.d.ts +153 -0
- package/dist/events/WorkerPoolMetrics.d.ts +65 -0
- package/dist/events/aggregation/AggregationWindow.d.ts +77 -0
- package/dist/events/aggregation/DeduplicationManager.d.ts +135 -0
- package/dist/events/aggregation/EventAggregationManager.d.ts +108 -0
- package/dist/events/aggregation/EventBatcher.d.ts +99 -0
- package/dist/events/aggregation/index.d.ts +10 -0
- package/dist/events/aggregation/types.d.ts +117 -0
- package/dist/events/index.d.ts +26 -0
- package/dist/events/observability/EventMetrics.d.ts +132 -0
- package/dist/events/observability/EventTracer.d.ts +68 -0
- package/dist/events/observability/EventTracing.d.ts +161 -0
- package/dist/events/observability/OTelEventMetrics.d.ts +332 -0
- package/dist/events/observability/ObservableHookManager.d.ts +108 -0
- package/dist/events/observability/StreamWorkerMetrics.d.ts +76 -0
- package/dist/events/observability/index.d.ts +24 -0
- package/dist/events/observability/metrics-types.d.ts +16 -0
- package/dist/events/queue-core.d.ts +77 -0
- package/dist/events/task-executor.d.ts +51 -0
- package/dist/events/types.d.ts +134 -0
- package/dist/exceptions/AuthenticationException.d.ts +8 -0
- package/dist/exceptions/AuthorizationException.d.ts +8 -0
- package/dist/exceptions/CircularDependencyException.d.ts +9 -0
- package/dist/exceptions/GravitoException.d.ts +23 -0
- package/dist/exceptions/HttpException.d.ts +9 -0
- package/dist/exceptions/ModelNotFoundException.d.ts +10 -0
- package/dist/exceptions/ValidationException.d.ts +22 -0
- package/dist/exceptions/index.d.ts +7 -0
- package/dist/ffi/NativeAccelerator.d.ts +69 -0
- package/dist/ffi/NativeHasher.d.ts +139 -0
- package/dist/ffi/cbor-fallback.d.ts +96 -0
- package/dist/ffi/hash-fallback.d.ts +33 -0
- package/dist/ffi/index.cjs +621 -0
- package/dist/ffi/index.cjs.map +14 -0
- package/dist/ffi/index.d.ts +10 -0
- package/dist/ffi/index.js +602 -0
- package/dist/ffi/index.js.map +14 -0
- package/dist/ffi/types.d.ts +135 -0
- package/dist/health/HealthProvider.d.ts +67 -0
- package/dist/helpers/Arr.d.ts +19 -0
- package/dist/helpers/Str.d.ts +38 -0
- package/dist/helpers/data.d.ts +25 -0
- package/dist/helpers/errors.d.ts +34 -0
- package/dist/helpers/response.d.ts +41 -0
- package/dist/helpers.d.ts +338 -0
- package/dist/hooks/ActionManager.d.ts +132 -0
- package/dist/hooks/AsyncDetector.d.ts +84 -0
- package/dist/hooks/FilterManager.d.ts +71 -0
- package/dist/hooks/MigrationWarner.d.ts +24 -0
- package/dist/hooks/dlq-operations.d.ts +60 -0
- package/dist/hooks/index.d.ts +11 -0
- package/dist/hooks/types.d.ts +107 -0
- package/dist/http/CookieJar.d.ts +51 -0
- package/dist/http/cookie.d.ts +29 -0
- package/dist/http/index.d.ts +12 -0
- package/dist/{compat-CI8hiulX.d.cts → http/types.d.ts} +29 -16
- package/dist/index.browser.d.ts +34 -0
- package/dist/index.cjs +10525 -11171
- package/dist/index.cjs.map +168 -0
- package/dist/index.d.ts +58 -10981
- package/dist/index.js +10861 -10997
- package/dist/index.js.map +168 -0
- package/dist/observability/QueueDashboard.d.ts +136 -0
- package/dist/observability/contracts.d.ts +137 -0
- package/dist/observability/index.d.ts +13 -0
- package/dist/reliability/DeadLetterQueueManager.d.ts +349 -0
- package/dist/reliability/RetryPolicy.d.ts +217 -0
- package/dist/reliability/index.d.ts +6 -0
- package/dist/router/ControllerDispatcher.d.ts +12 -0
- package/dist/router/RequestValidator.d.ts +20 -0
- package/dist/runtime/adapter-bun.d.ts +12 -0
- package/dist/runtime/adapter-deno.d.ts +12 -0
- package/dist/runtime/adapter-node.d.ts +12 -0
- package/dist/runtime/adapter-unknown.d.ts +13 -0
- package/dist/runtime/archive.d.ts +17 -0
- package/dist/runtime/compression.d.ts +21 -0
- package/dist/runtime/deep-equals.d.ts +56 -0
- package/dist/runtime/detection.d.ts +22 -0
- package/dist/runtime/escape.d.ts +34 -0
- package/dist/runtime/index.browser.d.ts +20 -0
- package/dist/runtime/index.d.ts +44 -0
- package/dist/runtime/markdown.d.ts +44 -0
- package/dist/runtime/types.d.ts +436 -0
- package/dist/runtime-helpers.d.ts +67 -0
- package/dist/runtime.d.ts +11 -0
- package/dist/security/Encrypter.d.ts +33 -0
- package/dist/security/Hasher.d.ts +29 -0
- package/dist/testing/HttpTester.d.ts +39 -0
- package/dist/testing/TestResponse.d.ts +78 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/transpiler-utils.d.ts +170 -0
- package/dist/types/events.d.ts +94 -0
- package/dist/types.d.ts +13 -0
- package/package.json +21 -52
- package/src/ffi/native/cbor.c +1148 -0
- package/dist/Metrics-VOWWRNNR.js +0 -219
- package/dist/chunk-R5U7XKVJ.js +0 -16
- package/dist/compat-CI8hiulX.d.ts +0 -376
- package/dist/compat.d.cts +0 -1
- package/dist/engine/index.d.cts +0 -922
- package/dist/index.d.cts +0 -11008
package/README.md
CHANGED
|
@@ -20,11 +20,16 @@
|
|
|
20
20
|
- 🛰️ **Orbit Mounting** - Easily mount external Photon applications (Orbits) to specific paths.
|
|
21
21
|
- 📝 **Logger System** - PSR-3 style logger interface with default standard output implementation.
|
|
22
22
|
- ⚙️ **Config Manager** - Unified configuration management supporting environment variables, runtime injection, and file-based config loading.
|
|
23
|
-
- 🛡️ **Security Middleware** - Built-in protection
|
|
23
|
+
- 🛡️ **Security Middleware** - Built-in protection (deprecated in v1.7.0, moved to `@gravito/photon`).
|
|
24
24
|
- 🔌 **Runtime Adapters** - Abstraction layer for underlying runtimes (Bun, Node.js) and HTTP engines.
|
|
25
25
|
- 🛡️ **Error Handling** - Built-in standardized JSON error responses, 404 handling, and process-level error management.
|
|
26
|
+
- 🧠 **Request Context** - Global access to request data via `AsyncLocalStorage` (requestId, userId, etc.).
|
|
27
|
+
- 🛠️ **CLI Commands** - CommandKernel for building artisan-style CLI tools.
|
|
28
|
+
- 🏥 **Health Probes** - Cloud-native Liveness and Readiness probes.
|
|
29
|
+
- ⚡ **Native Accelerators** - FFI-powered CBOR and hashing for peak performance.
|
|
26
30
|
- 🚀 **Modern** - Built for **Bun** runtime with native TypeScript support.
|
|
27
31
|
- 🪶 **Lightweight** - Zero external dependencies (except `@gravito/photon`).
|
|
32
|
+
- 📈 **Performance Audited** - Full [2026 Performance & Debt Audit](../../docs/optimization/CORE_AUDIT_2026.md) completed.
|
|
28
33
|
|
|
29
34
|
## 📦 Installation
|
|
30
35
|
|
|
@@ -64,7 +69,19 @@ const core = new PlanetCore({
|
|
|
64
69
|
});
|
|
65
70
|
```
|
|
66
71
|
|
|
67
|
-
### 2.
|
|
72
|
+
### 2. Request Context (AsyncLocalStorage)
|
|
73
|
+
|
|
74
|
+
Access request-scoped data anywhere in your application without parameter drilling:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { RequestContext } from '@gravito/core';
|
|
78
|
+
|
|
79
|
+
// In a deep service layer
|
|
80
|
+
const userId = RequestContext.get()?.userId;
|
|
81
|
+
const requestId = RequestContext.get()?.requestId;
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### 3. Dependency Injection
|
|
68
85
|
|
|
69
86
|
Use the IoC Container to manage your application services:
|
|
70
87
|
|
|
@@ -95,7 +112,7 @@ await core.bootstrap();
|
|
|
95
112
|
const cache = core.container.make('cache');
|
|
96
113
|
```
|
|
97
114
|
|
|
98
|
-
###
|
|
115
|
+
### 4. Register Hooks
|
|
99
116
|
|
|
100
117
|
Use **Filters** to modify data:
|
|
101
118
|
|
|
@@ -118,7 +135,23 @@ core.hooks.addAction('user_registered', async (userId: string) => {
|
|
|
118
135
|
await core.hooks.doAction('user_registered', 'user_123');
|
|
119
136
|
```
|
|
120
137
|
|
|
121
|
-
###
|
|
138
|
+
### 5. Reliability & Distributed Retries
|
|
139
|
+
|
|
140
|
+
Built-in support for distributed retries via Bull Queue:
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { RetryScheduler } from '@gravito/core';
|
|
144
|
+
|
|
145
|
+
const scheduler = new RetryScheduler({
|
|
146
|
+
initialDelayMs: 1000,
|
|
147
|
+
multiplier: 2,
|
|
148
|
+
maxRetries: 5
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
core.hooks.setRetryScheduler(scheduler);
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### 6. Mount an Orbit
|
|
122
155
|
|
|
123
156
|
Orbits are just standard Photon applications that plug into the core.
|
|
124
157
|
|
|
@@ -132,14 +165,14 @@ blogOrbit.get('/posts', (c) => c.json({ posts: [] }));
|
|
|
132
165
|
core.mountOrbit('/api/blog', blogOrbit);
|
|
133
166
|
```
|
|
134
167
|
|
|
135
|
-
###
|
|
168
|
+
### 7. Liftoff! 🚀
|
|
136
169
|
|
|
137
170
|
```typescript
|
|
138
171
|
// Export for Bun.serve
|
|
139
172
|
export default core.liftoff(); // Automatically uses PORT from config/env
|
|
140
173
|
```
|
|
141
174
|
|
|
142
|
-
###
|
|
175
|
+
### 8. Process-level Error Handling (Recommended)
|
|
143
176
|
|
|
144
177
|
Request-level errors are handled by `PlanetCore` automatically, but background jobs and startup code can still fail outside the request lifecycle.
|
|
145
178
|
|
|
@@ -154,6 +187,65 @@ core.hooks.addAction('processError:report', async (ctx) => {
|
|
|
154
187
|
})
|
|
155
188
|
```
|
|
156
189
|
|
|
190
|
+
## 📊 Observability & Metrics
|
|
191
|
+
|
|
192
|
+
### Route Pattern Support
|
|
193
|
+
|
|
194
|
+
To prevent high cardinality in Prometheus metrics caused by dynamic paths (e.g., `/users/123`, `/users/456`), Gravito automatically detects the `routePattern`:
|
|
195
|
+
|
|
196
|
+
- **Path**: `/users/123`
|
|
197
|
+
- **Pattern**: `/users/:id`
|
|
198
|
+
|
|
199
|
+
The `routePattern` is available on the request object and used by the monitoring system.
|
|
200
|
+
|
|
201
|
+
## 🩺 Health Probes
|
|
202
|
+
|
|
203
|
+
Built-in support for cloud-native health checks:
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import { HealthProvider } from '@gravito/core';
|
|
207
|
+
|
|
208
|
+
app.register(new HealthProvider());
|
|
209
|
+
|
|
210
|
+
// Check: http://localhost:3000/health/liveness
|
|
211
|
+
// Check: http://localhost:3000/health/readiness
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## 🛠️ CLI Commands
|
|
215
|
+
|
|
216
|
+
Easily build artisan-style CLI tools:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
import { CommandKernel } from '@gravito/core';
|
|
220
|
+
|
|
221
|
+
const kernel = new CommandKernel(container);
|
|
222
|
+
kernel.register('greet', async (args) => {
|
|
223
|
+
console.log('Hello', args[0]);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
await kernel.handle(process.argv.slice(2));
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## ⚡ Native Accelerators (FFI)
|
|
230
|
+
|
|
231
|
+
Gravito Core leverages FFI to use high-performance C implementations for critical tasks:
|
|
232
|
+
|
|
233
|
+
- **CBOR**: Efficient binary serialization.
|
|
234
|
+
- **Hashing**: SIMD-accelerated SHA-256 and HMAC via Bun primitives.
|
|
235
|
+
|
|
236
|
+
## 🛡️ Security Middleware Migration
|
|
237
|
+
|
|
238
|
+
As of v1.7.0, all HTTP security middleware has been migrated to `@gravito/photon` for better engine alignment. Existing exports in `@gravito/core` are marked as `@deprecated` and will be removed in v2.0.0.
|
|
239
|
+
|
|
240
|
+
**Migration:**
|
|
241
|
+
```typescript
|
|
242
|
+
// Before
|
|
243
|
+
import { cors } from '@gravito/core';
|
|
244
|
+
|
|
245
|
+
// After
|
|
246
|
+
import { cors } from '@gravito/photon/middleware/security';
|
|
247
|
+
```
|
|
248
|
+
|
|
157
249
|
## 📖 API Reference
|
|
158
250
|
|
|
159
251
|
### `Application` (Enterprise Container)
|
|
@@ -186,6 +278,8 @@ core.hooks.addAction('processError:report', async (ctx) => {
|
|
|
186
278
|
- **`instance(key, instance)`**: Register an existing object instance.
|
|
187
279
|
- **`has(key)`**: Check if a service is bound.
|
|
188
280
|
|
|
281
|
+
The container includes built-in **circular dependency detection** to help identify architectural issues during development.
|
|
282
|
+
|
|
189
283
|
#### Type Safety (ServiceMap)
|
|
190
284
|
|
|
191
285
|
You can extend the `ServiceMap` interface to get automatic type inference for `container.make()`:
|
package/README.zh-TW.md
CHANGED
|
@@ -20,9 +20,13 @@
|
|
|
20
20
|
- 🛰️ **Orbit Mounting** - 輕鬆將外部 Photon 應用程式(Orbits)掛載到特定路徑。
|
|
21
21
|
- 📝 **Logger System** - PSR-3 風格的日誌介面,內建標準輸出實作。
|
|
22
22
|
- ⚙️ **Config Manager** - 統一的配置管理,支援環境變數、運行時注入與基於檔案的配置載入。
|
|
23
|
-
- 🛡️ **Security Middleware** -
|
|
23
|
+
- 🛡️ **Security Middleware** - 內建保護功能(自 v1.7.0 起標記為棄用,已遷移至 `@gravito/photon`)。
|
|
24
24
|
- 🔌 **Runtime Adapters** - 底層運行時(Bun, Node.js)與 HTTP 引擎的抽象層。
|
|
25
25
|
- 🛡️ **Error Handling** - 內建標準化 JSON 錯誤回應、404 處理與進程級別錯誤管理。
|
|
26
|
+
- 🧠 **Request Context** - 透過 `AsyncLocalStorage` 全域存取請求資料(requestId, userId 等)。
|
|
27
|
+
- 🛠️ **CLI Commands** - 使用 CommandKernel 構建 Artisan 風格的命令行工具。
|
|
28
|
+
- 🏥 **Health Probes** - 雲原生 Liveness 與 Readiness 探針支援。
|
|
29
|
+
- ⚡ **Native Accelerators** - 基於 FFI 的高效能 CBOR 與雜湊計算(雜湊加速)。
|
|
26
30
|
- 🚀 **Modern** - 專為 **Bun** 運行時設計,原生支援 TypeScript。
|
|
27
31
|
- 🪶 **Lightweight** - 除了 `@gravito/photon` 外零外部依賴。
|
|
28
32
|
|
|
@@ -64,7 +68,19 @@ const core = new PlanetCore({
|
|
|
64
68
|
});
|
|
65
69
|
```
|
|
66
70
|
|
|
67
|
-
### 2.
|
|
71
|
+
### 2. 請求上下文 (AsyncLocalStorage)
|
|
72
|
+
|
|
73
|
+
在應用程式的任何地方存取請求範圍內的資料,無需透過參數逐層傳遞:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
import { RequestContext } from '@gravito/core';
|
|
77
|
+
|
|
78
|
+
// 在深層 Service 中
|
|
79
|
+
const userId = RequestContext.get()?.userId;
|
|
80
|
+
const requestId = RequestContext.get()?.requestId;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### 3. 依賴注入
|
|
68
84
|
|
|
69
85
|
使用 IoC 容器管理應用程式服務:
|
|
70
86
|
|
|
@@ -95,7 +111,7 @@ await core.bootstrap();
|
|
|
95
111
|
const cache = core.container.make('cache');
|
|
96
112
|
```
|
|
97
113
|
|
|
98
|
-
###
|
|
114
|
+
### 4. 註冊 Hooks
|
|
99
115
|
|
|
100
116
|
使用 **Filters** 修改資料:
|
|
101
117
|
|
|
@@ -118,7 +134,23 @@ core.hooks.addAction('user_registered', async (userId: string) => {
|
|
|
118
134
|
await core.hooks.doAction('user_registered', 'user_123');
|
|
119
135
|
```
|
|
120
136
|
|
|
121
|
-
###
|
|
137
|
+
### 5. 可靠性與分佈式重試
|
|
138
|
+
|
|
139
|
+
內建透過 Bull Queue 實作的分佈式重試支援:
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
import { RetryScheduler } from '@gravito/core';
|
|
143
|
+
|
|
144
|
+
const scheduler = new RetryScheduler({
|
|
145
|
+
initialDelayMs: 1000,
|
|
146
|
+
multiplier: 2,
|
|
147
|
+
maxRetries: 5
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
core.hooks.setRetryScheduler(scheduler);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 6. 掛載 Orbit
|
|
122
154
|
|
|
123
155
|
Orbits 是標準的 Photon 應用程式,可以插入核心中。
|
|
124
156
|
|
|
@@ -132,14 +164,14 @@ blogOrbit.get('/posts', (c) => c.json({ posts: [] }));
|
|
|
132
164
|
core.mountOrbit('/api/blog', blogOrbit);
|
|
133
165
|
```
|
|
134
166
|
|
|
135
|
-
###
|
|
167
|
+
### 7. Liftoff! 🚀
|
|
136
168
|
|
|
137
169
|
```typescript
|
|
138
170
|
// 為 Bun.serve 導出
|
|
139
171
|
export default core.liftoff(); // 自動使用來自配置或環境變數的 PORT
|
|
140
172
|
```
|
|
141
173
|
|
|
142
|
-
###
|
|
174
|
+
### 8. 進程級別錯誤處理(推薦)
|
|
143
175
|
|
|
144
176
|
請求級別的錯誤由 `PlanetCore` 自動處理,但背景工作與啟動代碼仍可能在請求生命週期外失敗。
|
|
145
177
|
|
|
@@ -154,6 +186,67 @@ core.hooks.addAction('processError:report', async (ctx) => {
|
|
|
154
186
|
})
|
|
155
187
|
```
|
|
156
188
|
|
|
189
|
+
## 📊 可觀測性與指標
|
|
190
|
+
|
|
191
|
+
### 路由模式(Route Pattern)支援
|
|
192
|
+
|
|
193
|
+
為了防止因動態路徑(如 `/users/123`, `/users/456`)導致 Prometheus 指標基數(cardinality)爆炸,Gravito 會自動偵測 `routePattern`:
|
|
194
|
+
|
|
195
|
+
- **Path**: `/users/123`
|
|
196
|
+
- **Pattern**: `/users/:id`
|
|
197
|
+
|
|
198
|
+
`routePattern` 可在請求物件中取得,並由監控系統自動使用。
|
|
199
|
+
|
|
200
|
+
## 🩺 健康檢查(Health Probes)
|
|
201
|
+
|
|
202
|
+
內建雲原生健康檢查支援:
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import { HealthProvider } from '@gravito/core';
|
|
206
|
+
|
|
207
|
+
app.register(new HealthProvider());
|
|
208
|
+
|
|
209
|
+
// 檢查: http://localhost:3000/health/liveness
|
|
210
|
+
// 檢查: http://localhost:3000/health/readiness
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## 🛠️ 命令行工具(CLI Commands)
|
|
214
|
+
|
|
215
|
+
輕鬆構建 Artisan 風格的 CLI 工具:
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { CommandKernel } from '@gravito/core';
|
|
219
|
+
|
|
220
|
+
const kernel = new CommandKernel(container);
|
|
221
|
+
kernel.register('greet', async (args) => {
|
|
222
|
+
console.log('Hello', args[0]);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
await kernel.handle(process.argv.slice(2));
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## ⚡ 原生加速器(Native Accelerators)
|
|
229
|
+
|
|
230
|
+
Gravito Core 深度利用 Bun 的原生特性與 FFI (Foreign Function Interface) 來處理關鍵任務,實現極限效能:
|
|
231
|
+
|
|
232
|
+
- **原生 Web 引擎 (Bun 1.39+)**: 專為 Bun 優化的獨立 HTTP 引擎,支援 SIMD 加速路由、中介軟體預編譯與 AOT 卸載。
|
|
233
|
+
- **物件池化 (Object Pooling)**: 透過 `FastContext` 回收機制,達成請求處理過程中的「零 JS 堆分配」,極大化吞吐量。
|
|
234
|
+
- **FFI 加速**: 高效能的二進位序列化 (CBOR) 與雜湊計算。
|
|
235
|
+
- **雜湊(Hashing)**: 使用 Bun 原生指令集加速的 SHA-256 與 HMAC 計算。
|
|
236
|
+
|
|
237
|
+
## 🛡️ 安全中介軟體遷移
|
|
238
|
+
|
|
239
|
+
自 v1.7.0 起,所有 HTTP 安全相關的中介軟體已遷移至 `@gravito/photon` 以獲得更好的引擎適配。`@gravito/core` 中的現有匯出已被標記為 `@deprecated`,並將於 v2.0.0 中移除。
|
|
240
|
+
|
|
241
|
+
**遷移方式:**
|
|
242
|
+
```typescript
|
|
243
|
+
// 之前
|
|
244
|
+
import { cors } from '@gravito/core';
|
|
245
|
+
|
|
246
|
+
// 之後
|
|
247
|
+
import { cors } from '@gravito/photon/middleware/security';
|
|
248
|
+
```
|
|
249
|
+
|
|
157
250
|
## 📖 API 參考
|
|
158
251
|
|
|
159
252
|
### `Application` (企業級容器)
|
|
@@ -186,6 +279,8 @@ core.hooks.addAction('processError:report', async (ctx) => {
|
|
|
186
279
|
- **`instance(key, instance)`**: 註冊現有的物件實例。
|
|
187
280
|
- **`has(key)`**: 檢查服務是否已綁定。
|
|
188
281
|
|
|
282
|
+
容器內建 **循環依賴偵測(Circular Dependency Detection)**,幫助您在開發階段及時發現架構設計問題。
|
|
283
|
+
|
|
189
284
|
### `HookManager`
|
|
190
285
|
|
|
191
286
|
- **`addFilter(hook, callback)`**: 註冊過濾器。
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Application - Enterprise Application Container
|
|
3
|
+
*
|
|
4
|
+
* A high-level application class that orchestrates the entire framework.
|
|
5
|
+
* Provides a centralized entry point for enterprise applications with
|
|
6
|
+
* auto-discovery of providers, config loading, and lifecycle management.
|
|
7
|
+
*
|
|
8
|
+
* Phase 4 優化:Provider 預掃描 + 平行載入
|
|
9
|
+
* - Phase 1:預掃描所有 Provider 文件(語法驗證)
|
|
10
|
+
* - Phase 2:篩選有效 Provider(跳過無效的)
|
|
11
|
+
* - Phase 3:平行 import 所有有效 Provider
|
|
12
|
+
* - Phase 4:註冊到容器
|
|
13
|
+
*
|
|
14
|
+
* @module @gravito/core
|
|
15
|
+
* @since 2.0.0
|
|
16
|
+
*/
|
|
17
|
+
import { ConfigManager } from './ConfigManager';
|
|
18
|
+
import { Container } from './Container';
|
|
19
|
+
import type { EventManager } from './EventManager';
|
|
20
|
+
import type { Logger } from './Logger';
|
|
21
|
+
import { PlanetCore } from './PlanetCore';
|
|
22
|
+
import type { ServiceProvider } from './ServiceProvider';
|
|
23
|
+
/**
|
|
24
|
+
* Application Config options for the Application class.
|
|
25
|
+
* @public
|
|
26
|
+
*/
|
|
27
|
+
export interface ApplicationConfig {
|
|
28
|
+
/**
|
|
29
|
+
* Base path of the application
|
|
30
|
+
*/
|
|
31
|
+
basePath: string;
|
|
32
|
+
/**
|
|
33
|
+
* Path to the config directory (relative to basePath)
|
|
34
|
+
* @default 'config'
|
|
35
|
+
*/
|
|
36
|
+
configPath?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Path to the providers directory (relative to basePath)
|
|
39
|
+
* @default 'src/Providers'
|
|
40
|
+
*/
|
|
41
|
+
providersPath?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Environment (development, production, testing)
|
|
44
|
+
*/
|
|
45
|
+
env?: 'development' | 'production' | 'testing';
|
|
46
|
+
/**
|
|
47
|
+
* Logger instance
|
|
48
|
+
*/
|
|
49
|
+
logger?: Logger;
|
|
50
|
+
/**
|
|
51
|
+
* Initial configuration values
|
|
52
|
+
*/
|
|
53
|
+
config?: Record<string, unknown>;
|
|
54
|
+
/**
|
|
55
|
+
* Service providers to register
|
|
56
|
+
*/
|
|
57
|
+
providers?: ServiceProvider[];
|
|
58
|
+
/**
|
|
59
|
+
* Whether to auto-discover providers from providersPath
|
|
60
|
+
* @default true
|
|
61
|
+
*/
|
|
62
|
+
autoDiscoverProviders?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Application - Enterprise-grade application container.
|
|
66
|
+
*
|
|
67
|
+
* Provides a higher-level abstraction over PlanetCore for building
|
|
68
|
+
* enterprise applications with convention-over-configuration patterns.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* // Create application
|
|
73
|
+
* const app = new Application({
|
|
74
|
+
* basePath: import.meta.dir,
|
|
75
|
+
* env: process.env.NODE_ENV as 'development' | 'production',
|
|
76
|
+
* });
|
|
77
|
+
*
|
|
78
|
+
* // Boot the application
|
|
79
|
+
* await app.boot();
|
|
80
|
+
*
|
|
81
|
+
* // Access core
|
|
82
|
+
* export default app.core.liftoff();
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
export declare class Application {
|
|
86
|
+
/**
|
|
87
|
+
* The underlying PlanetCore instance.
|
|
88
|
+
*/
|
|
89
|
+
readonly core: PlanetCore;
|
|
90
|
+
/**
|
|
91
|
+
* The IoC container.
|
|
92
|
+
*/
|
|
93
|
+
readonly container: Container;
|
|
94
|
+
/**
|
|
95
|
+
* The configuration manager.
|
|
96
|
+
*/
|
|
97
|
+
readonly config: ConfigManager;
|
|
98
|
+
/**
|
|
99
|
+
* The event manager.
|
|
100
|
+
*/
|
|
101
|
+
readonly events: EventManager;
|
|
102
|
+
/**
|
|
103
|
+
* The logger instance.
|
|
104
|
+
*/
|
|
105
|
+
readonly logger: Logger;
|
|
106
|
+
/**
|
|
107
|
+
* Application base path.
|
|
108
|
+
*/
|
|
109
|
+
readonly basePath: string;
|
|
110
|
+
/**
|
|
111
|
+
* Environment mode.
|
|
112
|
+
*/
|
|
113
|
+
readonly env: 'development' | 'production' | 'testing';
|
|
114
|
+
/**
|
|
115
|
+
* Configuration options.
|
|
116
|
+
*/
|
|
117
|
+
private readonly options;
|
|
118
|
+
/**
|
|
119
|
+
* Whether the application has been booted.
|
|
120
|
+
*/
|
|
121
|
+
private booted;
|
|
122
|
+
constructor(options: ApplicationConfig);
|
|
123
|
+
/**
|
|
124
|
+
* Boot the application and its dependencies.
|
|
125
|
+
*
|
|
126
|
+
* This method orchestrates the full application lifecycle:
|
|
127
|
+
* 1. Configuration: Loads all config files from the config directory.
|
|
128
|
+
* 2. Discovery: Auto-discovers ServiceProviders from the providers directory.
|
|
129
|
+
* 3. Registration: Registers all discovered and explicit providers.
|
|
130
|
+
* 4. Bootstrapping: Triggers the PlanetCore bootstrap sequence.
|
|
131
|
+
*
|
|
132
|
+
* @returns Promise that resolves to the application instance for chaining.
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```typescript
|
|
136
|
+
* const app = new Application({ basePath: import.meta.dir });
|
|
137
|
+
* await app.boot();
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
boot(): Promise<this>;
|
|
141
|
+
/**
|
|
142
|
+
* Load configuration files from the config directory.
|
|
143
|
+
*
|
|
144
|
+
* @internal
|
|
145
|
+
*/
|
|
146
|
+
private loadConfiguration;
|
|
147
|
+
/**
|
|
148
|
+
* Discover and register providers from the providers directory.
|
|
149
|
+
*
|
|
150
|
+
* Phase 4 優化版本:採用 4-Phase 載入策略
|
|
151
|
+
* - Phase 1:預掃描所有候選 Provider 檔案(語法驗證)
|
|
152
|
+
* - Phase 2:篩選有效 Provider 檔案(跳過語法錯誤的)
|
|
153
|
+
* - Phase 3:平行 import 所有有效 Provider(從循序 → 並行)
|
|
154
|
+
* - Phase 4:逐一註冊到容器
|
|
155
|
+
*
|
|
156
|
+
* 效能改進:N 個 Provider 從 O(N * importTime) 降至 O(importTime + overhead)
|
|
157
|
+
*
|
|
158
|
+
* @internal
|
|
159
|
+
*/
|
|
160
|
+
private discoverProviders;
|
|
161
|
+
/**
|
|
162
|
+
* Phase 1+2:預掃描 Provider 目錄中的所有候選檔案。
|
|
163
|
+
*
|
|
164
|
+
* 使用輕量語法驗證(嘗試讀取 + 基本結構檢查)篩選有效的 Provider 檔案,
|
|
165
|
+
* 讓語法錯誤在 import 之前被發現,提供更清晰的錯誤訊息。
|
|
166
|
+
*
|
|
167
|
+
* 策略:
|
|
168
|
+
* 1. 使用 Bun.Transpiler 進行 import 掃描(在 Bun 環境下)
|
|
169
|
+
* 2. Fallback 至基本檔案讀取驗證(在 Node/Deno 環境下)
|
|
170
|
+
*
|
|
171
|
+
* @param providersPath - Provider 目錄絕對路徑
|
|
172
|
+
* @returns 掃描結果陣列(含有效/無效標記)
|
|
173
|
+
* @internal
|
|
174
|
+
*/
|
|
175
|
+
private prescribeProviders;
|
|
176
|
+
/**
|
|
177
|
+
* Phase 3:平行 import 所有有效的 Provider 檔案。
|
|
178
|
+
*
|
|
179
|
+
* 使用 Promise.all() 同時 import 所有通過預掃描的 Provider 檔案,
|
|
180
|
+
* 從循序載入(O(N))改善為平行載入(O(1) 理論上),
|
|
181
|
+
* 實際效能受 I/O、CPU 和 V8 模組解析限制。
|
|
182
|
+
*
|
|
183
|
+
* @param validProviders - 通過預掃描的 Provider 掃描結果
|
|
184
|
+
* @returns 模組載入結果陣列
|
|
185
|
+
* @internal
|
|
186
|
+
*/
|
|
187
|
+
private loadProvidersInParallel;
|
|
188
|
+
/**
|
|
189
|
+
* Resolve a service instance from the IoC container.
|
|
190
|
+
*
|
|
191
|
+
* This is a convenience wrapper around `container.make()`.
|
|
192
|
+
*
|
|
193
|
+
* @template T - The expected type of the service.
|
|
194
|
+
* @param key - The unique identifier or class name of the service.
|
|
195
|
+
* @returns The resolved service instance.
|
|
196
|
+
* @throws Error if the service is not bound in the container.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```typescript
|
|
200
|
+
* const db = app.make<Database>('db');
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
make<T>(key: string): T;
|
|
204
|
+
/**
|
|
205
|
+
* Check if a service is bound.
|
|
206
|
+
*
|
|
207
|
+
* @param key - The service key
|
|
208
|
+
* @returns True if bound
|
|
209
|
+
*/
|
|
210
|
+
has(key: string): boolean;
|
|
211
|
+
/**
|
|
212
|
+
* Retrieve a configuration value using dot notation.
|
|
213
|
+
*
|
|
214
|
+
* @template T - The expected type of the configuration value.
|
|
215
|
+
* @param key - The configuration key (e.g., 'app.name', 'database.connections.mysql').
|
|
216
|
+
* @param defaultValue - Optional value to return if the key is not found.
|
|
217
|
+
* @returns The configuration value or the default value.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```typescript
|
|
221
|
+
* const port = app.getConfig<number>('app.port', 3000);
|
|
222
|
+
* ```
|
|
223
|
+
*/
|
|
224
|
+
getConfig<T>(key: string, defaultValue?: T): T;
|
|
225
|
+
/**
|
|
226
|
+
* Resolve an absolute path relative to the application base path.
|
|
227
|
+
*
|
|
228
|
+
* @param segments - Path segments to join with the base path.
|
|
229
|
+
* @returns The absolute path string.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* const storagePath = app.path('storage', 'logs');
|
|
234
|
+
* ```
|
|
235
|
+
*/
|
|
236
|
+
path(...segments: string[]): string;
|
|
237
|
+
/**
|
|
238
|
+
* Get the config path.
|
|
239
|
+
*
|
|
240
|
+
* @param segments - Additional path segments
|
|
241
|
+
* @returns Absolute path to config directory
|
|
242
|
+
*/
|
|
243
|
+
configPath(...segments: string[]): string;
|
|
244
|
+
/**
|
|
245
|
+
* Check if running in production.
|
|
246
|
+
*/
|
|
247
|
+
isProduction(): boolean;
|
|
248
|
+
/**
|
|
249
|
+
* Check if running in development.
|
|
250
|
+
*/
|
|
251
|
+
isDevelopment(): boolean;
|
|
252
|
+
/**
|
|
253
|
+
* Check if running in testing.
|
|
254
|
+
*/
|
|
255
|
+
isTesting(): boolean;
|
|
256
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Container } from './Container';
|
|
2
|
+
/**
|
|
3
|
+
* CommandHandler type for custom CLI commands.
|
|
4
|
+
*/
|
|
5
|
+
export type CommandHandler = (args: string[], container: Container) => Promise<void> | void;
|
|
6
|
+
/**
|
|
7
|
+
* CommandKernel - Structured CLI Command handling.
|
|
8
|
+
*
|
|
9
|
+
* Manages registration and execution of custom CLI commands that can
|
|
10
|
+
* reuse the application container and providers.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const kernel = new CommandKernel(container);
|
|
15
|
+
* kernel.register('greet', (args) => console.log('Hello', args[0]));
|
|
16
|
+
* await kernel.handle(['greet', 'Universe']);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare class CommandKernel {
|
|
20
|
+
private container;
|
|
21
|
+
private commands;
|
|
22
|
+
constructor(container: Container);
|
|
23
|
+
/**
|
|
24
|
+
* Register a new command handler.
|
|
25
|
+
*/
|
|
26
|
+
register(name: string, handler: CommandHandler): void;
|
|
27
|
+
/**
|
|
28
|
+
* Handle an incoming CLI command.
|
|
29
|
+
*
|
|
30
|
+
* @param argv - Array of command line arguments (e.g. process.argv.slice(2))
|
|
31
|
+
*/
|
|
32
|
+
handle(argv: string[]): Promise<void>;
|
|
33
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration manager (ConfigManager)
|
|
3
|
+
*
|
|
4
|
+
* Unifies environment variables and application configuration access.
|
|
5
|
+
*/
|
|
6
|
+
import type { ZodSchema } from 'zod';
|
|
7
|
+
/**
|
|
8
|
+
* ConfigManager - Central configuration store.
|
|
9
|
+
* Supports loading from environment variables and initial objects.
|
|
10
|
+
* @public
|
|
11
|
+
*/
|
|
12
|
+
export declare class ConfigManager {
|
|
13
|
+
private config;
|
|
14
|
+
private schema;
|
|
15
|
+
constructor(initialConfig?: Record<string, unknown>);
|
|
16
|
+
/**
|
|
17
|
+
* Load all environment variables from the active runtime.
|
|
18
|
+
*/
|
|
19
|
+
private loadEnv;
|
|
20
|
+
/**
|
|
21
|
+
* Get a configuration value (generic return type supported).
|
|
22
|
+
* Supports dot notation for deep access (e.g. 'app.name').
|
|
23
|
+
*/
|
|
24
|
+
get<T = unknown>(key: string, defaultValue?: T): T;
|
|
25
|
+
/**
|
|
26
|
+
* Set a configuration value.
|
|
27
|
+
*/
|
|
28
|
+
set(key: string, value: unknown): void;
|
|
29
|
+
/**
|
|
30
|
+
* Check whether a key exists.
|
|
31
|
+
*/
|
|
32
|
+
has(key: string): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Define a Zod schema for configuration validation.
|
|
35
|
+
*
|
|
36
|
+
* @param schema - Zod schema for validation
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* config.defineSchema(z.object({
|
|
41
|
+
* DATABASE_URL: z.string().url(),
|
|
42
|
+
* PORT: z.number().default(3000),
|
|
43
|
+
* }))
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
defineSchema(schema: ZodSchema): void;
|
|
47
|
+
/**
|
|
48
|
+
* Validate configuration against the defined schema.
|
|
49
|
+
*
|
|
50
|
+
* Should be called during bootstrap to catch configuration errors early.
|
|
51
|
+
*
|
|
52
|
+
* @throws Error if validation fails with details about missing/invalid fields
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* try {
|
|
57
|
+
* config.validate()
|
|
58
|
+
* } catch (error) {
|
|
59
|
+
* console.error('Config validation failed:', error.message)
|
|
60
|
+
* process.exit(1)
|
|
61
|
+
* }
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
validate(): void;
|
|
65
|
+
}
|