@gravito/core 1.6.0 → 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.
Files changed (171) hide show
  1. package/README.md +100 -6
  2. package/README.zh-TW.md +101 -6
  3. package/dist/Application.d.ts +256 -0
  4. package/dist/CommandKernel.d.ts +33 -0
  5. package/dist/ConfigManager.d.ts +65 -0
  6. package/dist/Container/RequestScopeManager.d.ts +62 -0
  7. package/dist/Container/RequestScopeMetrics.d.ts +144 -0
  8. package/dist/Container.d.ts +153 -0
  9. package/dist/ErrorHandler.d.ts +66 -0
  10. package/dist/Event.d.ts +5 -0
  11. package/dist/EventManager.d.ts +123 -0
  12. package/dist/GlobalErrorHandlers.d.ts +47 -0
  13. package/dist/GravitoServer.d.ts +28 -0
  14. package/dist/HookManager.d.ts +435 -0
  15. package/dist/Listener.d.ts +4 -0
  16. package/dist/Logger.d.ts +20 -0
  17. package/dist/PlanetCore.d.ts +402 -0
  18. package/dist/RequestContext.d.ts +97 -0
  19. package/dist/Route.d.ts +36 -0
  20. package/dist/Router.d.ts +270 -0
  21. package/dist/ServiceProvider.d.ts +178 -0
  22. package/dist/adapters/GravitoEngineAdapter.d.ts +27 -0
  23. package/dist/adapters/bun/AdaptiveAdapter.d.ts +99 -0
  24. package/dist/adapters/bun/BunContext.d.ts +54 -0
  25. package/dist/adapters/bun/BunNativeAdapter.d.ts +66 -0
  26. package/dist/adapters/bun/BunRequest.d.ts +31 -0
  27. package/dist/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  28. package/dist/adapters/bun/RadixNode.d.ts +19 -0
  29. package/dist/adapters/bun/RadixRouter.d.ts +32 -0
  30. package/dist/adapters/bun/index.d.ts +7 -0
  31. package/dist/adapters/bun/types.d.ts +20 -0
  32. package/dist/adapters/index.d.ts +12 -0
  33. package/dist/adapters/types.d.ts +235 -0
  34. package/dist/binary/BinaryUtils.d.ts +105 -0
  35. package/dist/binary/index.d.ts +5 -0
  36. package/dist/cli/queue-commands.d.ts +6 -0
  37. package/dist/compat/async-local-storage.browser.d.ts +9 -0
  38. package/dist/compat/async-local-storage.d.ts +7 -0
  39. package/dist/compat/crypto.browser.d.ts +5 -0
  40. package/dist/compat/crypto.d.ts +6 -0
  41. package/dist/compat.cjs +42 -11
  42. package/dist/compat.cjs.map +9 -0
  43. package/dist/compat.d.ts +23 -1
  44. package/dist/compat.js +3 -0
  45. package/dist/compat.js.map +9 -0
  46. package/dist/engine/AOTRouter.d.ts +139 -0
  47. package/dist/engine/FastContext.d.ts +141 -0
  48. package/dist/engine/Gravito.d.ts +131 -0
  49. package/dist/engine/MinimalContext.d.ts +102 -0
  50. package/dist/engine/analyzer.d.ts +113 -0
  51. package/dist/engine/constants.d.ts +23 -0
  52. package/dist/engine/index.cjs +758 -532
  53. package/dist/engine/index.cjs.map +22 -0
  54. package/dist/engine/index.d.ts +14 -690
  55. package/dist/engine/index.js +758 -508
  56. package/dist/engine/index.js.map +22 -0
  57. package/dist/engine/path.d.ts +26 -0
  58. package/dist/engine/pool.d.ts +83 -0
  59. package/dist/engine/types.d.ts +149 -0
  60. package/dist/error-handling/RequestScopeErrorContext.d.ts +126 -0
  61. package/dist/events/BackpressureManager.d.ts +215 -0
  62. package/dist/events/CircuitBreaker.d.ts +229 -0
  63. package/dist/events/DeadLetterQueue.d.ts +219 -0
  64. package/dist/events/EventBackend.d.ts +12 -0
  65. package/dist/events/EventOptions.d.ts +204 -0
  66. package/dist/events/EventPriorityQueue.d.ts +63 -0
  67. package/dist/events/FlowControlStrategy.d.ts +109 -0
  68. package/dist/events/IdempotencyCache.d.ts +60 -0
  69. package/dist/events/MessageQueueBridge.d.ts +184 -0
  70. package/dist/events/PriorityEscalationManager.d.ts +82 -0
  71. package/dist/events/RetryScheduler.d.ts +104 -0
  72. package/dist/events/WorkerPool.d.ts +98 -0
  73. package/dist/events/WorkerPoolConfig.d.ts +153 -0
  74. package/dist/events/WorkerPoolMetrics.d.ts +65 -0
  75. package/dist/events/aggregation/AggregationWindow.d.ts +77 -0
  76. package/dist/events/aggregation/DeduplicationManager.d.ts +135 -0
  77. package/dist/events/aggregation/EventAggregationManager.d.ts +108 -0
  78. package/dist/events/aggregation/EventBatcher.d.ts +99 -0
  79. package/dist/events/aggregation/index.d.ts +10 -0
  80. package/dist/events/aggregation/types.d.ts +117 -0
  81. package/dist/events/index.d.ts +26 -0
  82. package/dist/events/observability/EventMetrics.d.ts +132 -0
  83. package/dist/events/observability/EventTracer.d.ts +68 -0
  84. package/dist/events/observability/EventTracing.d.ts +161 -0
  85. package/dist/events/observability/OTelEventMetrics.d.ts +332 -0
  86. package/dist/events/observability/ObservableHookManager.d.ts +108 -0
  87. package/dist/events/observability/StreamWorkerMetrics.d.ts +76 -0
  88. package/dist/events/observability/index.d.ts +24 -0
  89. package/dist/events/observability/metrics-types.d.ts +16 -0
  90. package/dist/events/queue-core.d.ts +77 -0
  91. package/dist/events/task-executor.d.ts +51 -0
  92. package/dist/events/types.d.ts +134 -0
  93. package/dist/exceptions/AuthenticationException.d.ts +8 -0
  94. package/dist/exceptions/AuthorizationException.d.ts +8 -0
  95. package/dist/exceptions/CircularDependencyException.d.ts +9 -0
  96. package/dist/exceptions/GravitoException.d.ts +23 -0
  97. package/dist/exceptions/HttpException.d.ts +9 -0
  98. package/dist/exceptions/ModelNotFoundException.d.ts +10 -0
  99. package/dist/exceptions/ValidationException.d.ts +22 -0
  100. package/dist/exceptions/index.d.ts +7 -0
  101. package/dist/ffi/NativeAccelerator.d.ts +69 -0
  102. package/dist/ffi/NativeHasher.d.ts +139 -0
  103. package/dist/ffi/cbor-fallback.d.ts +96 -0
  104. package/dist/ffi/hash-fallback.d.ts +33 -0
  105. package/dist/ffi/index.cjs +621 -0
  106. package/dist/ffi/index.cjs.map +14 -0
  107. package/dist/ffi/index.d.ts +10 -0
  108. package/dist/ffi/index.js +602 -0
  109. package/dist/ffi/index.js.map +14 -0
  110. package/dist/ffi/types.d.ts +135 -0
  111. package/dist/health/HealthProvider.d.ts +67 -0
  112. package/dist/helpers/Arr.d.ts +19 -0
  113. package/dist/helpers/Str.d.ts +38 -0
  114. package/dist/helpers/data.d.ts +25 -0
  115. package/dist/helpers/errors.d.ts +34 -0
  116. package/dist/helpers/response.d.ts +41 -0
  117. package/dist/helpers.d.ts +338 -0
  118. package/dist/hooks/ActionManager.d.ts +132 -0
  119. package/dist/hooks/AsyncDetector.d.ts +84 -0
  120. package/dist/hooks/FilterManager.d.ts +71 -0
  121. package/dist/hooks/MigrationWarner.d.ts +24 -0
  122. package/dist/hooks/dlq-operations.d.ts +60 -0
  123. package/dist/hooks/index.d.ts +11 -0
  124. package/dist/hooks/types.d.ts +107 -0
  125. package/dist/http/CookieJar.d.ts +51 -0
  126. package/dist/http/cookie.d.ts +29 -0
  127. package/dist/http/index.d.ts +12 -0
  128. package/dist/{compat-C4Src6NN.d.cts → http/types.d.ts} +48 -16
  129. package/dist/index.browser.d.ts +34 -0
  130. package/dist/index.cjs +12909 -9492
  131. package/dist/index.cjs.map +168 -0
  132. package/dist/index.d.ts +58 -8707
  133. package/dist/index.js +12906 -9381
  134. package/dist/index.js.map +168 -0
  135. package/dist/observability/QueueDashboard.d.ts +136 -0
  136. package/dist/observability/contracts.d.ts +137 -0
  137. package/dist/observability/index.d.ts +13 -0
  138. package/dist/reliability/DeadLetterQueueManager.d.ts +349 -0
  139. package/dist/reliability/RetryPolicy.d.ts +217 -0
  140. package/dist/reliability/index.d.ts +6 -0
  141. package/dist/router/ControllerDispatcher.d.ts +12 -0
  142. package/dist/router/RequestValidator.d.ts +20 -0
  143. package/dist/runtime/adapter-bun.d.ts +12 -0
  144. package/dist/runtime/adapter-deno.d.ts +12 -0
  145. package/dist/runtime/adapter-node.d.ts +12 -0
  146. package/dist/runtime/adapter-unknown.d.ts +13 -0
  147. package/dist/runtime/archive.d.ts +17 -0
  148. package/dist/runtime/compression.d.ts +21 -0
  149. package/dist/runtime/deep-equals.d.ts +56 -0
  150. package/dist/runtime/detection.d.ts +22 -0
  151. package/dist/runtime/escape.d.ts +34 -0
  152. package/dist/runtime/index.browser.d.ts +20 -0
  153. package/dist/runtime/index.d.ts +44 -0
  154. package/dist/runtime/markdown.d.ts +44 -0
  155. package/dist/runtime/types.d.ts +436 -0
  156. package/dist/runtime-helpers.d.ts +67 -0
  157. package/dist/runtime.d.ts +11 -0
  158. package/dist/security/Encrypter.d.ts +33 -0
  159. package/dist/security/Hasher.d.ts +29 -0
  160. package/dist/testing/HttpTester.d.ts +39 -0
  161. package/dist/testing/TestResponse.d.ts +78 -0
  162. package/dist/testing/index.d.ts +2 -0
  163. package/dist/transpiler-utils.d.ts +170 -0
  164. package/dist/types/events.d.ts +94 -0
  165. package/dist/types.d.ts +13 -0
  166. package/package.json +23 -53
  167. package/src/ffi/native/cbor.c +1148 -0
  168. package/dist/compat-C4Src6NN.d.ts +0 -357
  169. package/dist/compat.d.cts +0 -1
  170. package/dist/engine/index.d.cts +0 -702
  171. package/dist/index.d.cts +0 -8734
@@ -0,0 +1,62 @@
1
+ import type { ServiceKey } from '../Container';
2
+ import { RequestScopeMetrics, type RequestScopeObserver } from './RequestScopeMetrics';
3
+ /**
4
+ * Manages request-scoped service instances within a single HTTP request.
5
+ *
6
+ * Each request gets its own RequestScopeManager instance with isolated state.
7
+ * Services are cached within the request and automatically cleaned up when
8
+ * the request ends.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const scope = new RequestScopeManager()
13
+ * const cache = scope.resolve('productCache', () => new ProductCache())
14
+ * // ... use cache ...
15
+ * await scope.cleanup() // Called automatically by Gravito engine
16
+ * ```
17
+ */
18
+ export declare class RequestScopeManager {
19
+ private scoped;
20
+ private metadata;
21
+ private metrics;
22
+ private observer;
23
+ constructor(observer?: RequestScopeObserver);
24
+ /**
25
+ * Set observer for monitoring scope lifecycle
26
+ */
27
+ setObserver(observer: RequestScopeObserver): void;
28
+ /**
29
+ * Get metrics for this scope
30
+ */
31
+ getMetrics(): RequestScopeMetrics;
32
+ /**
33
+ * Resolve or retrieve a request-scoped service instance.
34
+ *
35
+ * If the service already exists in this scope, returns the cached instance.
36
+ * Otherwise, calls the factory function to create a new instance and caches it.
37
+ *
38
+ * Automatically detects and records services with cleanup methods.
39
+ *
40
+ * @template T - The type of the service.
41
+ * @param key - The service key (for caching).
42
+ * @param factory - Factory function to create the instance if not cached.
43
+ * @returns The cached or newly created instance.
44
+ */
45
+ resolve<T>(key: ServiceKey, factory: () => T): T;
46
+ /**
47
+ * Clean up all request-scoped instances.
48
+ *
49
+ * Calls the cleanup() method on each service that has one.
50
+ * Silently ignores cleanup errors to prevent cascading failures.
51
+ * Called automatically by the Gravito engine in the request finally block.
52
+ *
53
+ * @returns Promise that resolves when all cleanup is complete.
54
+ */
55
+ cleanup(): Promise<void>;
56
+ /**
57
+ * Get the number of services in this scope (for monitoring).
58
+ *
59
+ * @returns The count of cached services.
60
+ */
61
+ size(): number;
62
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * RequestScopeMetrics - Observability for RequestScope lifecycle
3
+ *
4
+ * Tracks cleanup execution time, scope size, and service counts
5
+ * for performance monitoring and diagnostics.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const metrics = new RequestScopeMetrics()
10
+ * metrics.recordCleanupStart()
11
+ * await scope.cleanup()
12
+ * metrics.recordCleanupEnd()
13
+ *
14
+ * console.log(metrics.toJSON())
15
+ * // { cleanupDuration: 2.5, scopeSize: 3, servicesCleaned: 3 }
16
+ * ```
17
+ */
18
+ export declare class RequestScopeMetrics {
19
+ private cleanupStartTime;
20
+ private cleanupDuration;
21
+ private scopeSize;
22
+ private servicesCleaned;
23
+ private errorsOccurred;
24
+ /**
25
+ * Record start of cleanup operation
26
+ */
27
+ recordCleanupStart(): void;
28
+ /**
29
+ * Record end of cleanup operation
30
+ *
31
+ * @param scopeSize - Number of services in the scope
32
+ * @param servicesCleaned - Number of services that had cleanup called
33
+ * @param errorsOccurred - Number of cleanup errors
34
+ */
35
+ recordCleanupEnd(scopeSize: number, servicesCleaned: number, errorsOccurred?: number): void;
36
+ /**
37
+ * Get cleanup duration in milliseconds
38
+ *
39
+ * @returns Duration in ms, or null if cleanup not completed
40
+ */
41
+ getCleanupDuration(): number | null;
42
+ /**
43
+ * Check if cleanup took longer than threshold (default 2ms)
44
+ * Useful for detecting slow cleanups
45
+ *
46
+ * @param thresholdMs - Threshold in milliseconds
47
+ * @returns True if cleanup exceeded threshold
48
+ */
49
+ isSlowCleanup(thresholdMs?: number): boolean;
50
+ /**
51
+ * Export metrics as JSON for logging/monitoring
52
+ */
53
+ toJSON(): {
54
+ cleanupDuration: number;
55
+ scopeSize: number;
56
+ servicesCleaned: number;
57
+ errorsOccurred: number;
58
+ hasErrors: boolean;
59
+ isSlowCleanup: boolean;
60
+ };
61
+ /**
62
+ * Export metrics as compact string for logging
63
+ */
64
+ toString(): string;
65
+ }
66
+ /**
67
+ * RequestScopeObserver - Hook for monitoring RequestScope lifecycle
68
+ *
69
+ * Implement this interface to receive callbacks during scope operations
70
+ */
71
+ export interface RequestScopeObserver {
72
+ /**
73
+ * Called when a service is resolved in the scope
74
+ */
75
+ onServiceResolved?(key: string | symbol, isFromCache: boolean): void;
76
+ /**
77
+ * Called when cleanup starts
78
+ */
79
+ onCleanupStart?(): void;
80
+ /**
81
+ * Called when cleanup completes
82
+ */
83
+ onCleanupEnd?(metrics: RequestScopeMetrics): void;
84
+ /**
85
+ * Called when cleanup encounters an error
86
+ */
87
+ onCleanupError?(error: Error): void;
88
+ }
89
+ /**
90
+ * RequestScopeMetricsCollector - Aggregates metrics across multiple scopes
91
+ *
92
+ * Used for application-level monitoring and performance tracking
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const collector = new RequestScopeMetricsCollector()
97
+ *
98
+ * // Record metrics from multiple requests
99
+ * collector.record(metrics1)
100
+ * collector.record(metrics2)
101
+ * collector.record(metrics3)
102
+ *
103
+ * // Get aggregated stats
104
+ * const stats = collector.getStats()
105
+ * console.log(stats.averageCleanupTime) // 3.5ms
106
+ * ```
107
+ */
108
+ export declare class RequestScopeMetricsCollector {
109
+ private metrics;
110
+ /**
111
+ * Record metrics from a request scope
112
+ */
113
+ record(metrics: RequestScopeMetrics): void;
114
+ /**
115
+ * Get aggregated statistics
116
+ */
117
+ getStats(): {
118
+ count: number;
119
+ averageCleanupTime: number;
120
+ maxCleanupTime: number;
121
+ minCleanupTime: number;
122
+ totalErrorCount: number;
123
+ errorRate: number;
124
+ };
125
+ /**
126
+ * Clear collected metrics
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get number of recorded metrics
131
+ */
132
+ size(): number;
133
+ /**
134
+ * Export metrics as JSON array
135
+ */
136
+ toJSON(): {
137
+ cleanupDuration: number;
138
+ scopeSize: number;
139
+ servicesCleaned: number;
140
+ errorsOccurred: number;
141
+ hasErrors: boolean;
142
+ isSlowCleanup: boolean;
143
+ }[];
144
+ }
@@ -0,0 +1,153 @@
1
+ import type { RequestScopeManager } from './Container/RequestScopeManager';
2
+ /**
3
+ * Factory type for creating service instances
4
+ */
5
+ export type Factory<T> = (container: Container) => T;
6
+ /**
7
+ * ServiceMap interface for type-safe IoC resolution.
8
+ *
9
+ * Extend this interface via module augmentation to get type inference:
10
+ * @example
11
+ * ```typescript
12
+ * declare module '@gravito/core' {
13
+ * interface ServiceMap {
14
+ * logger: Logger
15
+ * db: DatabaseConnection
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export type ServiceMap = {};
21
+ /**
22
+ * ServiceKey represents the allowed keys for service resolution.
23
+ * Includes keys from ServiceMap, generic strings, or symbols.
24
+ */
25
+ export type ServiceKey = keyof ServiceMap | (string & {}) | symbol;
26
+ /**
27
+ * Container - Simple Dependency Injection Container.
28
+ * Manages service bindings and singleton instances.
29
+ * @public
30
+ */
31
+ export declare class Container {
32
+ private bindings;
33
+ private instances;
34
+ private resolutionStack;
35
+ /**
36
+ * Run a function within a request scope context.
37
+ *
38
+ * All service resolutions within the function will use the provided scope,
39
+ * enabling request-scoped service instances to be properly isolated.
40
+ *
41
+ * @template T - The return type of the function.
42
+ * @param scope - The RequestScopeManager for this request.
43
+ * @param fn - The function to execute within the scope.
44
+ * @returns The result of the function.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const scope = new RequestScopeManager()
49
+ * const result = await Container.runWithScope(scope, async () => {
50
+ * const service = container.make('requestScoped')
51
+ * return service.doSomething()
52
+ * })
53
+ * ```
54
+ */
55
+ static runWithScope<T>(scope: RequestScopeManager, fn: () => T | Promise<T>): T | Promise<T>;
56
+ /**
57
+ * Bind a service to the container.
58
+ *
59
+ * A new instance will be created by the factory function every time the
60
+ * service is resolved from the container.
61
+ *
62
+ * @template T - The type of the service being bound.
63
+ * @param key - The unique identifier for the service.
64
+ * @param factory - The factory function that creates the service instance.
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * container.bind('logger', (c) => new ConsoleLogger());
69
+ * ```
70
+ */
71
+ bind<T>(key: ServiceKey, factory: Factory<T>): void;
72
+ /**
73
+ * Bind a shared service to the container (Singleton).
74
+ *
75
+ * The factory function will be called only once, and the same instance
76
+ * will be returned on every subsequent resolution.
77
+ *
78
+ * @template T - The type of the service being bound.
79
+ * @param key - The unique identifier for the service.
80
+ * @param factory - The factory function that creates the service instance.
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * container.singleton('db', (c) => new DatabaseConnection());
85
+ * ```
86
+ */
87
+ singleton<T>(key: ServiceKey, factory: Factory<T>): void;
88
+ /**
89
+ * Bind a request-scoped service to the container.
90
+ *
91
+ * A new instance will be created for each request and cached within that request.
92
+ * The service is automatically cleaned up when the request ends.
93
+ *
94
+ * @template T - The type of the service being bound.
95
+ * @param key - The unique identifier for the service.
96
+ * @param factory - The factory function that creates the service instance.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * container.scoped('requestCache', (c) => new RequestProductCache());
101
+ * ```
102
+ */
103
+ scoped<T>(key: ServiceKey, factory: Factory<T>): void;
104
+ /**
105
+ * Register an existing instance as a shared service.
106
+ *
107
+ * @param key - The unique identifier for the service.
108
+ * @param instance - The instance to register.
109
+ */
110
+ instance<T>(key: ServiceKey, instance: T): void;
111
+ /**
112
+ * Check if a service is request-scoped.
113
+ *
114
+ * @param key - The service key to check.
115
+ * @returns True if the service is request-scoped.
116
+ */
117
+ isRequestScoped(key: ServiceKey): boolean;
118
+ /**
119
+ * Resolve a service instance from the container.
120
+ *
121
+ * Automatically handles singleton caching and factory execution.
122
+ *
123
+ * @template T - The expected type of the service.
124
+ * @param key - The unique identifier for the service.
125
+ * @returns The resolved service instance.
126
+ * @throws Error if the service key is not found in the container.
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * const logger = container.make<Logger>('logger');
131
+ * ```
132
+ */
133
+ make<K extends keyof ServiceMap>(key: K): ServiceMap[K];
134
+ make<T>(key: ServiceKey): T;
135
+ /**
136
+ * Check if a service is bound or has an instance in the container.
137
+ *
138
+ * @param key - The service key to check.
139
+ * @returns True if the service exists.
140
+ */
141
+ has(key: ServiceKey): boolean;
142
+ /**
143
+ * Flush all instances and bindings from the container.
144
+ * Resets the container to an empty state.
145
+ */
146
+ flush(): void;
147
+ /**
148
+ * Forget a specific instance while keeping its binding.
149
+ *
150
+ * @param key - The service key to forget.
151
+ */
152
+ forget(key: ServiceKey): void;
153
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @fileoverview ErrorHandler - Centralized Error Handling for Gravito Framework
3
+ *
4
+ * Extracted from PlanetCore to follow Single Responsibility Principle.
5
+ * Handles HTTP errors, validation errors, and error rendering.
6
+ *
7
+ * @module @gravito/core
8
+ * @since 1.3.0
9
+ */
10
+ import type { HookManager } from './HookManager';
11
+ import type { GravitoContext } from './http/types';
12
+ import type { Logger } from './Logger';
13
+ /**
14
+ * HTTP Status Code to Error Code mapping
15
+ */
16
+ export declare function codeFromStatus(status: number): string;
17
+ /**
18
+ * HTTP Status Code to Message mapping
19
+ */
20
+ export declare function messageFromStatus(status: number): string;
21
+ /**
22
+ * Dependencies injected into ErrorHandler
23
+ * @public
24
+ */
25
+ export interface ErrorHandlerDeps {
26
+ logger: Logger;
27
+ hooks: HookManager;
28
+ getCore: () => unknown;
29
+ }
30
+ /**
31
+ * ErrorHandler - Centralized error handling logic
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * const handler = new ErrorHandler({ logger, hooks, getCore: () => core })
36
+ * adapter.onError(handler.handleError.bind(handler))
37
+ * adapter.onNotFound(handler.handleNotFound.bind(handler))
38
+ * ```
39
+ */
40
+ export declare class ErrorHandler {
41
+ private deps;
42
+ constructor(deps: ErrorHandlerDeps);
43
+ /**
44
+ * Handle application errors
45
+ *
46
+ * Integrates RequestScope cleanup to ensure proper resource management
47
+ * even when errors occur during request processing.
48
+ */
49
+ handleError(err: unknown, c: GravitoContext): Promise<Response>;
50
+ /**
51
+ * Handle 404 Not Found errors
52
+ */
53
+ handleNotFound(c: GravitoContext): Promise<Response>;
54
+ /**
55
+ * Handle validation error redirect for HTML requests
56
+ */
57
+ private handleValidationRedirect;
58
+ /**
59
+ * Log error based on context settings
60
+ */
61
+ private logError;
62
+ /**
63
+ * Render error response (HTML or JSON)
64
+ */
65
+ private renderErrorResponse;
66
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Event base class and related types.
3
+ */
4
+ export type { Channel, ShouldBroadcast } from './types/events';
5
+ export { Event } from './types/events';
@@ -0,0 +1,123 @@
1
+ import { Event } from './Event';
2
+ import type { Listener } from './Listener';
3
+ import type { PlanetCore } from './PlanetCore';
4
+ /**
5
+ * Listener registration metadata.
6
+ */
7
+ interface ListenerRegistration<TEvent extends Event = Event> {
8
+ listener: Listener<TEvent> | (new () => Listener<TEvent>);
9
+ queue?: string;
10
+ connection?: string;
11
+ delay?: number;
12
+ }
13
+ /**
14
+ * Event manager.
15
+ *
16
+ * Provides type-safe event dispatching and listener registration.
17
+ * Supports both synchronous listeners and asynchronous (queued) listeners.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * class UserRegistered extends Event {
22
+ * constructor(public user: User) {
23
+ * super()
24
+ * }
25
+ * }
26
+ *
27
+ * class SendWelcomeEmail implements Listener<UserRegistered> {
28
+ * async handle(event: UserRegistered): Promise<void> {
29
+ * // send welcome email
30
+ * }
31
+ * }
32
+ *
33
+ * // Register listener
34
+ * core.events.listen(UserRegistered, SendWelcomeEmail)
35
+ *
36
+ * // Dispatch event
37
+ * await core.events.dispatch(new UserRegistered(user))
38
+ * ```
39
+ */
40
+ export declare class EventManager {
41
+ private core;
42
+ /**
43
+ * Listener registry.
44
+ * Key: event class or event name
45
+ * Value: listener registrations
46
+ */
47
+ private listeners;
48
+ /**
49
+ * Broadcast manager (optional, injected by `orbit-broadcasting`).
50
+ */
51
+ private broadcastManager;
52
+ /**
53
+ * Queue manager (optional, injected by `orbit-queue`).
54
+ */
55
+ private queueManager;
56
+ constructor(core: PlanetCore);
57
+ /**
58
+ * Register the broadcast manager (called by `orbit-broadcasting`).
59
+ */
60
+ setBroadcastManager(manager: EventManager['broadcastManager']): void;
61
+ /**
62
+ * Register the queue manager (called by `orbit-queue`).
63
+ */
64
+ setQueueManager(manager: EventManager['queueManager']): void;
65
+ /**
66
+ * Register an event listener.
67
+ *
68
+ * @param event - Event class or event name
69
+ * @param listener - Listener instance or listener class
70
+ * @param options - Optional queue options
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * // Synchronous listener
75
+ * core.events.listen(UserRegistered, SendWelcomeEmail)
76
+ *
77
+ * // Queued listener (async)
78
+ * core.events.listen(UserRegistered, SendWelcomeEmail, {
79
+ * queue: 'emails',
80
+ * delay: 60
81
+ * })
82
+ * ```
83
+ */
84
+ listen<TEvent extends Event>(event: string | (new (...args: unknown[]) => TEvent), listener: Listener<TEvent> | (new () => Listener<TEvent>), options?: {
85
+ queue?: string;
86
+ connection?: string;
87
+ delay?: number;
88
+ }): void;
89
+ /**
90
+ * Remove an event listener.
91
+ *
92
+ * @param event - Event class or event name
93
+ * @param listener - Listener to remove
94
+ */
95
+ unlisten<TEvent extends Event>(event: string | (new (...args: unknown[]) => TEvent), listener: Listener<TEvent> | (new () => Listener<TEvent>)): void;
96
+ /**
97
+ * Dispatch an event.
98
+ *
99
+ * Runs all registered listeners. If a listener implements `ShouldQueue` or
100
+ * has queue options, the listener will be pushed to the queue for async execution.
101
+ *
102
+ * @param event - Event instance
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * await core.events.dispatch(new UserRegistered(user))
107
+ * ```
108
+ */
109
+ dispatch<TEvent extends Event>(event: TEvent): Promise<void>;
110
+ /**
111
+ * Serialize an event (for queueing).
112
+ */
113
+ private serializeEvent;
114
+ /**
115
+ * Get all registered listeners.
116
+ */
117
+ getListeners(event?: string | (new () => Event)): ListenerRegistration[];
118
+ /**
119
+ * Clear all listeners.
120
+ */
121
+ clear(): void;
122
+ }
123
+ export {};
@@ -0,0 +1,47 @@
1
+ import type { Logger } from './Logger';
2
+ import type { PlanetCore } from './PlanetCore';
3
+ /**
4
+ * Type of process-level error
5
+ * @public
6
+ */
7
+ export type GlobalProcessErrorKind = 'unhandledRejection' | 'uncaughtException';
8
+ /**
9
+ * Context payload for global error handler filters/actions
10
+ * @public
11
+ */
12
+ export type GlobalProcessErrorHandlerContext = {
13
+ core?: PlanetCore;
14
+ kind: GlobalProcessErrorKind;
15
+ error: unknown;
16
+ isProduction: boolean;
17
+ timestamp: number;
18
+ logLevel?: 'error' | 'warn' | 'info' | 'none';
19
+ logMessage?: string;
20
+ exit?: boolean;
21
+ exitCode?: number;
22
+ gracePeriodMs?: number;
23
+ };
24
+ /**
25
+ * Error handling strategy
26
+ * @public
27
+ */
28
+ export type GlobalErrorHandlersMode = 'log' | 'exit' | 'exitInProduction';
29
+ /**
30
+ * Options for registering global handlers
31
+ * @public
32
+ */
33
+ export type RegisterGlobalErrorHandlersOptions = {
34
+ core?: PlanetCore;
35
+ logger?: Logger;
36
+ mode?: GlobalErrorHandlersMode;
37
+ exitCode?: number;
38
+ gracePeriodMs?: number;
39
+ };
40
+ /**
41
+ * Register process-level error handlers (`unhandledRejection` / `uncaughtException`).
42
+ *
43
+ * - `mode: "log"`: only log/report
44
+ * - `mode: "exit"`: report then `process.exit(exitCode)`
45
+ * - `mode: "exitInProduction"`: exit only when `NODE_ENV=production` (default)
46
+ */
47
+ export declare function registerGlobalErrorHandlers(options?: RegisterGlobalErrorHandlersOptions): () => void;
@@ -0,0 +1,28 @@
1
+ import { type GravitoConfig, PlanetCore } from './PlanetCore';
2
+ /**
3
+ * Manifest describing a Gravito application structure.
4
+ * @public
5
+ */
6
+ export interface GravitoManifest {
7
+ name: string;
8
+ version?: string;
9
+ modules: string[];
10
+ config?: GravitoConfig;
11
+ }
12
+ /**
13
+ * Function type for asynchronous module resolution.
14
+ * @public
15
+ */
16
+ export type ModuleResolver = () => Promise<any>;
17
+ /**
18
+ * Gravito 核心啟動引擎 (已解耦)
19
+ */
20
+ export declare class GravitoServer {
21
+ /**
22
+ * 一鍵建立並組裝伺服器
23
+ * @param manifest 站點描述清單
24
+ * @param resolvers 模組解析器字典
25
+ * @param baseOrbits 基礎軌道模組 (例如 OrbitMonolith)
26
+ */
27
+ static create(manifest: GravitoManifest, resolvers: Record<string, ModuleResolver>, baseOrbits?: any[]): Promise<PlanetCore>;
28
+ }