@gravito/ripple 4.0.1 → 5.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 (226) hide show
  1. package/README.md +26 -10
  2. package/dist/{ripple/src/OrbitRipple.d.ts → OrbitRipple.d.ts} +1 -0
  3. package/dist/{ripple/src/RippleServer.d.ts → RippleServer.d.ts} +32 -1
  4. package/dist/core/src/Application.d.ts +41 -0
  5. package/dist/core/src/HookManager.d.ts +33 -189
  6. package/dist/core/src/PlanetCore.d.ts +31 -1
  7. package/dist/core/src/Router.d.ts +32 -46
  8. package/dist/core/src/adapters/bun/BunContext.d.ts +6 -1
  9. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +35 -0
  10. package/dist/core/src/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  11. package/dist/core/src/adapters/bun/RadixRouter.d.ts +1 -0
  12. package/dist/core/src/adapters/bun/index.d.ts +7 -0
  13. package/dist/core/src/binary/BinaryUtils.d.ts +105 -0
  14. package/dist/core/src/binary/index.d.ts +5 -0
  15. package/dist/core/src/compat/async-local-storage.d.ts +7 -0
  16. package/dist/core/src/compat/crypto.d.ts +6 -0
  17. package/dist/core/src/engine/AOTRouter.d.ts +10 -0
  18. package/dist/core/src/engine/FastContext.d.ts +19 -1
  19. package/dist/core/src/engine/Gravito.d.ts +13 -18
  20. package/dist/core/src/engine/MinimalContext.d.ts +2 -0
  21. package/dist/core/src/engine/analyzer.d.ts +92 -6
  22. package/dist/core/src/engine/types.d.ts +3 -0
  23. package/dist/core/src/events/CircuitBreaker.d.ts +12 -0
  24. package/dist/core/src/events/EventPriorityQueue.d.ts +18 -256
  25. package/dist/core/src/events/index.d.ts +12 -11
  26. package/dist/core/src/events/queue-core.d.ts +77 -0
  27. package/dist/core/src/events/task-executor.d.ts +51 -0
  28. package/dist/core/src/exceptions/AuthException.d.ts +10 -0
  29. package/dist/core/src/exceptions/AuthenticationException.d.ts +2 -2
  30. package/dist/core/src/exceptions/AuthorizationException.d.ts +2 -2
  31. package/dist/core/src/exceptions/CacheException.d.ts +9 -0
  32. package/dist/core/src/exceptions/CircularDependencyException.d.ts +2 -1
  33. package/dist/core/src/exceptions/ConfigurationException.d.ts +9 -0
  34. package/dist/core/src/exceptions/DatabaseException.d.ts +9 -0
  35. package/dist/core/src/exceptions/DomainException.d.ts +9 -0
  36. package/dist/core/src/exceptions/InfrastructureException.d.ts +17 -0
  37. package/dist/core/src/exceptions/QueueException.d.ts +9 -0
  38. package/dist/core/src/exceptions/StorageException.d.ts +9 -0
  39. package/dist/core/src/exceptions/StreamException.d.ts +9 -0
  40. package/dist/core/src/exceptions/SystemException.d.ts +9 -0
  41. package/dist/core/src/exceptions/ValidationException.d.ts +2 -2
  42. package/dist/core/src/exceptions/index.d.ts +10 -0
  43. package/dist/core/src/ffi/NativeAccelerator.d.ts +62 -0
  44. package/dist/core/src/ffi/NativeHasher.d.ts +139 -0
  45. package/dist/core/src/ffi/cbor-fallback.d.ts +96 -0
  46. package/dist/core/src/ffi/hash-fallback.d.ts +33 -0
  47. package/dist/core/src/ffi/index.d.ts +10 -0
  48. package/dist/core/src/ffi/types.d.ts +135 -0
  49. package/dist/core/src/helpers/Str.d.ts +15 -0
  50. package/dist/core/src/hooks/ActionManager.d.ts +132 -0
  51. package/dist/core/src/hooks/AsyncDetector.d.ts +84 -0
  52. package/dist/core/src/hooks/FilterManager.d.ts +71 -0
  53. package/dist/core/src/hooks/MigrationWarner.d.ts +24 -0
  54. package/dist/core/src/hooks/dlq-operations.d.ts +60 -0
  55. package/dist/core/src/hooks/types.d.ts +107 -0
  56. package/dist/core/src/http/CookieJar.d.ts +2 -2
  57. package/dist/core/src/http/types.d.ts +24 -3
  58. package/dist/core/src/index.d.ts +491 -14
  59. package/dist/core/src/observability/contracts.d.ts +137 -0
  60. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +2 -3
  61. package/dist/core/src/runtime/adapter-bun.d.ts +12 -0
  62. package/dist/core/src/runtime/adapter-deno.d.ts +12 -0
  63. package/dist/core/src/runtime/adapter-node.d.ts +12 -0
  64. package/dist/core/src/runtime/adapter-unknown.d.ts +13 -0
  65. package/dist/core/src/runtime/archive.d.ts +17 -0
  66. package/dist/core/src/runtime/compression.d.ts +21 -0
  67. package/dist/core/src/runtime/deep-equals.d.ts +56 -0
  68. package/dist/core/src/runtime/detection.d.ts +22 -0
  69. package/dist/core/src/runtime/escape.d.ts +34 -0
  70. package/dist/core/src/runtime/index.d.ts +44 -0
  71. package/dist/core/src/runtime/markdown.d.ts +44 -0
  72. package/dist/core/src/runtime/types.d.ts +436 -0
  73. package/dist/core/src/runtime-helpers.d.ts +67 -0
  74. package/dist/core/src/runtime.d.ts +10 -118
  75. package/dist/core/src/testing/HttpTester.d.ts +1 -0
  76. package/dist/core/src/transpiler-utils.d.ts +170 -0
  77. package/dist/{ripple/src/engines → engines}/BunEngine.d.ts +11 -0
  78. package/dist/errors/RippleError.d.ts +66 -0
  79. package/dist/index.js +1 -7502
  80. package/dist/index.js.map +3 -71
  81. package/package.json +6 -2
  82. package/dist/atlas/src/DB.d.ts +0 -348
  83. package/dist/atlas/src/OrbitAtlas.d.ts +0 -9
  84. package/dist/atlas/src/config/defineConfig.d.ts +0 -14
  85. package/dist/atlas/src/config/index.d.ts +0 -7
  86. package/dist/atlas/src/config/loadConfig.d.ts +0 -41
  87. package/dist/atlas/src/connection/Connection.d.ts +0 -112
  88. package/dist/atlas/src/connection/ConnectionManager.d.ts +0 -180
  89. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +0 -54
  90. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +0 -32
  91. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +0 -118
  92. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +0 -36
  93. package/dist/atlas/src/drivers/MySQLDriver.d.ts +0 -79
  94. package/dist/atlas/src/drivers/PostgresDriver.d.ts +0 -96
  95. package/dist/atlas/src/drivers/RedisDriver.d.ts +0 -43
  96. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +0 -45
  97. package/dist/atlas/src/drivers/types.d.ts +0 -260
  98. package/dist/atlas/src/errors/index.d.ts +0 -45
  99. package/dist/atlas/src/grammar/Grammar.d.ts +0 -342
  100. package/dist/atlas/src/grammar/MongoGrammar.d.ts +0 -47
  101. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +0 -54
  102. package/dist/atlas/src/grammar/NullGrammar.d.ts +0 -35
  103. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +0 -62
  104. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +0 -32
  105. package/dist/atlas/src/index.d.ts +0 -79
  106. package/dist/atlas/src/migration/Migration.d.ts +0 -64
  107. package/dist/atlas/src/migration/MigrationRepository.d.ts +0 -65
  108. package/dist/atlas/src/migration/Migrator.d.ts +0 -110
  109. package/dist/atlas/src/migration/index.d.ts +0 -6
  110. package/dist/atlas/src/observability/AtlasMetrics.d.ts +0 -33
  111. package/dist/atlas/src/observability/AtlasObservability.d.ts +0 -15
  112. package/dist/atlas/src/observability/AtlasTracer.d.ts +0 -12
  113. package/dist/atlas/src/observability/index.d.ts +0 -9
  114. package/dist/atlas/src/orm/Repository.d.ts +0 -247
  115. package/dist/atlas/src/orm/index.d.ts +0 -6
  116. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +0 -121
  117. package/dist/atlas/src/orm/model/Model.d.ts +0 -458
  118. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +0 -20
  119. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +0 -150
  120. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +0 -36
  121. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +0 -92
  122. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +0 -117
  123. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +0 -64
  124. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +0 -15
  125. package/dist/atlas/src/orm/model/concerns/index.d.ts +0 -12
  126. package/dist/atlas/src/orm/model/decorators.d.ts +0 -138
  127. package/dist/atlas/src/orm/model/errors.d.ts +0 -52
  128. package/dist/atlas/src/orm/model/index.d.ts +0 -10
  129. package/dist/atlas/src/orm/model/relationships.d.ts +0 -207
  130. package/dist/atlas/src/orm/model/types.d.ts +0 -12
  131. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +0 -124
  132. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +0 -54
  133. package/dist/atlas/src/orm/schema/index.d.ts +0 -6
  134. package/dist/atlas/src/orm/schema/types.d.ts +0 -85
  135. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +0 -98
  136. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +0 -91
  137. package/dist/atlas/src/pool/PoolStrategy.d.ts +0 -129
  138. package/dist/atlas/src/pool/PoolWarmer.d.ts +0 -92
  139. package/dist/atlas/src/query/Expression.d.ts +0 -60
  140. package/dist/atlas/src/query/NPlusOneDetector.d.ts +0 -10
  141. package/dist/atlas/src/query/QueryBuilder.d.ts +0 -643
  142. package/dist/atlas/src/query/RelationshipResolver.d.ts +0 -23
  143. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +0 -51
  144. package/dist/atlas/src/query/clauses/HavingClause.d.ts +0 -70
  145. package/dist/atlas/src/query/clauses/JoinClause.d.ts +0 -87
  146. package/dist/atlas/src/query/clauses/LimitClause.d.ts +0 -82
  147. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +0 -69
  148. package/dist/atlas/src/query/clauses/SelectClause.d.ts +0 -71
  149. package/dist/atlas/src/query/clauses/WhereClause.d.ts +0 -167
  150. package/dist/atlas/src/query/clauses/index.d.ts +0 -11
  151. package/dist/atlas/src/schema/Blueprint.d.ts +0 -276
  152. package/dist/atlas/src/schema/ColumnDefinition.d.ts +0 -154
  153. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +0 -37
  154. package/dist/atlas/src/schema/MigrationGenerator.d.ts +0 -45
  155. package/dist/atlas/src/schema/Schema.d.ts +0 -131
  156. package/dist/atlas/src/schema/SchemaDiff.d.ts +0 -73
  157. package/dist/atlas/src/schema/TypeGenerator.d.ts +0 -57
  158. package/dist/atlas/src/schema/TypeWriter.d.ts +0 -42
  159. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +0 -23
  160. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +0 -26
  161. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +0 -28
  162. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +0 -97
  163. package/dist/atlas/src/schema/grammars/index.d.ts +0 -7
  164. package/dist/atlas/src/schema/index.d.ts +0 -8
  165. package/dist/atlas/src/seed/Factory.d.ts +0 -90
  166. package/dist/atlas/src/seed/Seeder.d.ts +0 -28
  167. package/dist/atlas/src/seed/SeederRunner.d.ts +0 -74
  168. package/dist/atlas/src/seed/index.d.ts +0 -6
  169. package/dist/atlas/src/sharding/ShardingManager.d.ts +0 -59
  170. package/dist/atlas/src/types/index.d.ts +0 -1182
  171. package/dist/atlas/src/utils/CursorEncoding.d.ts +0 -63
  172. package/dist/atlas/src/utils/levenshtein.d.ts +0 -9
  173. package/dist/core/src/adapters/PhotonAdapter.d.ts +0 -175
  174. package/dist/core/src/adapters/photon-types.d.ts +0 -73
  175. package/dist/core/src/http/middleware/BodySizeLimit.d.ts +0 -16
  176. package/dist/core/src/http/middleware/Cors.d.ts +0 -24
  177. package/dist/core/src/http/middleware/Csrf.d.ts +0 -23
  178. package/dist/core/src/http/middleware/HeaderTokenGate.d.ts +0 -28
  179. package/dist/core/src/http/middleware/SecurityHeaders.d.ts +0 -29
  180. package/dist/core/src/http/middleware/ThrottleRequests.d.ts +0 -18
  181. package/dist/core/src/instrumentation/index.d.ts +0 -35
  182. package/dist/core/src/instrumentation/opentelemetry.d.ts +0 -178
  183. package/dist/core/src/instrumentation/types.d.ts +0 -182
  184. package/dist/core/src/observability/Metrics.d.ts +0 -244
  185. package/dist/photon/src/index.d.ts +0 -89
  186. package/dist/photon/src/middleware/binary.d.ts +0 -31
  187. package/dist/photon/src/middleware/htmx.d.ts +0 -39
  188. package/dist/photon/src/middleware/ratelimit-redis.d.ts +0 -50
  189. package/dist/photon/src/middleware/ratelimit.d.ts +0 -161
  190. package/dist/photon/src/openapi.d.ts +0 -19
  191. package/dist/ripple/src/errors/RippleError.d.ts +0 -48
  192. /package/dist/{ripple/src/channels → channels}/Channel.d.ts +0 -0
  193. /package/dist/{ripple/src/channels → channels}/ChannelManager.d.ts +0 -0
  194. /package/dist/{ripple/src/channels → channels}/index.d.ts +0 -0
  195. /package/dist/{ripple/src/drivers → drivers}/LocalDriver.d.ts +0 -0
  196. /package/dist/{ripple/src/drivers → drivers}/NATSDriver.d.ts +0 -0
  197. /package/dist/{ripple/src/drivers → drivers}/RedisDriver.d.ts +0 -0
  198. /package/dist/{ripple/src/drivers → drivers}/index.d.ts +0 -0
  199. /package/dist/{ripple/src/engines → engines}/IRippleEngine.d.ts +0 -0
  200. /package/dist/{ripple/src/engines → engines}/UWebSocketsEngine.d.ts +0 -0
  201. /package/dist/{ripple/src/engines → engines}/WsEngine.d.ts +0 -0
  202. /package/dist/{ripple/src/engines → engines}/index.d.ts +0 -0
  203. /package/dist/{ripple/src/errors → errors}/index.d.ts +0 -0
  204. /package/dist/{ripple/src/events → events}/BroadcastEvent.d.ts +0 -0
  205. /package/dist/{ripple/src/events → events}/BroadcastManager.d.ts +0 -0
  206. /package/dist/{ripple/src/events → events}/Broadcaster.d.ts +0 -0
  207. /package/dist/{ripple/src/events → events}/index.d.ts +0 -0
  208. /package/dist/{ripple/src/health → health}/HealthChecker.d.ts +0 -0
  209. /package/dist/{ripple/src/health → health}/index.d.ts +0 -0
  210. /package/dist/{ripple/src/index.d.ts → index.d.ts} +0 -0
  211. /package/dist/{ripple/src/logging → logging}/Logger.d.ts +0 -0
  212. /package/dist/{ripple/src/logging → logging}/index.d.ts +0 -0
  213. /package/dist/{ripple/src/middleware → middleware}/InterceptorManager.d.ts +0 -0
  214. /package/dist/{ripple/src/observability → observability}/RippleMetrics.d.ts +0 -0
  215. /package/dist/{ripple/src/reliability → reliability}/AckManager.d.ts +0 -0
  216. /package/dist/{ripple/src/serializers → serializers}/ISerializer.d.ts +0 -0
  217. /package/dist/{ripple/src/serializers → serializers}/JsonSerializer.d.ts +0 -0
  218. /package/dist/{ripple/src/serializers → serializers}/ProtobufSerializer.d.ts +0 -0
  219. /package/dist/{ripple/src/serializers → serializers}/index.d.ts +0 -0
  220. /package/dist/{ripple/src/tracking → tracking}/ConnectionTracker.d.ts +0 -0
  221. /package/dist/{ripple/src/tracking → tracking}/SessionManager.d.ts +0 -0
  222. /package/dist/{ripple/src/tracking → tracking}/index.d.ts +0 -0
  223. /package/dist/{ripple/src/types.d.ts → types.d.ts} +0 -0
  224. /package/dist/{ripple/src/utils → utils}/MessageSerializer.d.ts +0 -0
  225. /package/dist/{ripple/src/utils → utils}/TokenBucket.d.ts +0 -0
  226. /package/dist/{ripple/src/utils → utils}/index.d.ts +0 -0
package/README.md CHANGED
@@ -11,16 +11,32 @@
11
11
 
12
12
  ## Features
13
13
 
14
- - ⚡ **Multi-Runtime Support** - Run on Bun (native WebSocket), Node.js (uWebSockets.js or ws)
15
- - 🚀 **Simplified API** - Single `start()` method to initialize and run your server
16
- - 📡 **Channel-based Broadcasting** - Public, Private, and Presence channels
17
- - 🔒 **Secure Authorization** - Flexible callback-based authorization system
18
- - 📊 **Production Ready** - 95.24% test coverage, battle-tested architecture
19
- - 🌐 **Horizontal Scaling** - Redis or NATS driver for multi-server deployments
20
- - 🔍 **Full Observability** - Built-in logging, health checks, metrics, and connection tracking
21
- - 💪 **Type-Safe** - Comprehensive TypeScript support with runtime-agnostic types
22
- - 🎯 **Laravel Echo Compatible** - Familiar API for Laravel developers
23
- - 🔄 **Backward Compatible** - Seamless upgrade from v4.x
14
+ - ⚡ **Multi-Runtime Support** - Run on Bun (native WebSocket), Node.js (uWebSockets.js or ws).
15
+ - 🚀 **Simplified API** - Single `start()` method to initialize and run your server.
16
+ - 📡 **Real-time Pulse Sync** - Channel-based broadcasting for Public, Private, and Presence channels.
17
+ - 🪐 **Galaxy-Ready Core** - Native integration with PlanetCore for universal WebSocket communication.
18
+ - 🔒 **Secure Authorization** - Flexible callback-based authorization system.
19
+ - 🌐 **Horizontal Scaling** - Redis or NATS driver for multi-server Galaxy deployments.
20
+ - 🔍 **Full Observability** - Built-in logging, health checks, metrics, and connection tracking.
21
+
22
+ ## 🌌 Role in Galaxy Architecture
23
+
24
+ In the **Gravito Galaxy Architecture**, Ripple acts as the **Gravitational Waves (Real-time Pulse)**.
25
+
26
+ - **Instant Propagation**: Propagates state changes from the Galaxy's core to external observers (Users) with sub-millisecond latency.
27
+ - **Satellite Interactivity**: Provides the foundation for real-time collaboration features within and between Satellites.
28
+ - **Bi-directional Channel**: Unlike the one-way `Radiance` broadcast, Ripple provides a bi-directional "Pulse" that allows Clients to interact with the Sensing Layer over a persistent connection.
29
+
30
+ ```mermaid
31
+ graph LR
32
+ Client([Client]) <--> Ripple{Ripple Pulse}
33
+ Ripple <--> Photon[Photon Engine]
34
+ subgraph Galaxy
35
+ Photon <--> S1[Satellite: Chat]
36
+ Photon <--> S2[Satellite: Dashboard]
37
+ end
38
+ Ripple -.-> Plasma[(Plasma: Redis Sync)]
39
+ ```
24
40
 
25
41
  ## Why Ripple?
26
42
 
@@ -36,6 +36,7 @@ export declare class OrbitRipple implements GravitoOrbit {
36
36
  *
37
37
  * - Registers 'ripple' (RippleServer) and 'broadcast' (BroadcastManager) in the container.
38
38
  * - Adds middleware to inject 'ripple' and 'broadcast' into GravitoContext.
39
+ * - Integrates with BunNativeAdapter for same-port WebSocket support.
39
40
  * - Initializes the server and registers shutdown hooks.
40
41
  *
41
42
  * @param core - The PlanetCore instance
@@ -114,6 +114,36 @@ export declare class RippleServer {
114
114
  * Get server health status.
115
115
  */
116
116
  getHealth(): Promise<import(".").HealthCheckResult>;
117
+ /**
118
+ * Initialize driver and serializer without starting the engine.
119
+ *
120
+ * This method:
121
+ * 1. Initializes the driver (Redis/NATS/Local)
122
+ * 2. Initializes the serializer (JSON/Protobuf)
123
+ * 3. Starts the ping interval
124
+ *
125
+ * Used by OrbitRipple for same-port integration with BunNativeAdapter.
126
+ *
127
+ * @since 5.0.0
128
+ */
129
+ initDriver(): Promise<void>;
130
+ /**
131
+ * Start ping interval (internal helper)
132
+ */
133
+ private startPingInterval;
134
+ /**
135
+ * Get WebSocket handler configuration (Bun only).
136
+ *
137
+ * Returns handler object for use with BunNativeAdapter.registerWebSocketRoute().
138
+ *
139
+ * @throws Error if engine is not BunEngine
140
+ */
141
+ getWebSocketConfig(): {
142
+ open: (ws: any) => void;
143
+ message: (ws: any, data: any) => void;
144
+ close: (ws: any, code: number, reason: string) => void;
145
+ drain: (_ws: any) => void;
146
+ };
117
147
  /**
118
148
  * Initialize and start the RippleServer.
119
149
  *
@@ -123,9 +153,10 @@ export declare class RippleServer {
123
153
  * 3. Starts the WebSocket engine (Bun/uWS/ws)
124
154
  * 4. Starts the ping interval
125
155
  *
156
+ * @param port - Optional port override (defaults to config.port or 3000)
126
157
  * @since 5.0.0
127
158
  */
128
- start(): Promise<void>;
159
+ start(port?: number): Promise<void>;
129
160
  /**
130
161
  * Initialize the RippleServer without starting the engine.
131
162
  *
@@ -5,6 +5,12 @@
5
5
  * Provides a centralized entry point for enterprise applications with
6
6
  * auto-discovery of providers, config loading, and lifecycle management.
7
7
  *
8
+ * Phase 4 優化:Provider 預掃描 + 平行載入
9
+ * - Phase 1:預掃描所有 Provider 文件(語法驗證)
10
+ * - Phase 2:篩選有效 Provider(跳過無效的)
11
+ * - Phase 3:平行 import 所有有效 Provider
12
+ * - Phase 4:註冊到容器
13
+ *
8
14
  * @module @gravito/core
9
15
  * @since 2.0.0
10
16
  */
@@ -141,9 +147,44 @@ export declare class Application {
141
147
  /**
142
148
  * Discover and register providers from the providers directory.
143
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
+ *
144
158
  * @internal
145
159
  */
146
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;
147
188
  /**
148
189
  * Resolve a service instance from the IoC container.
149
190
  *
@@ -1,141 +1,32 @@
1
- import type { ConnectionContract } from '@gravito/atlas';
2
- import { type CircuitBreakerOptions } from './events/CircuitBreaker';
3
1
  import { DeadLetterQueue } from './events/DeadLetterQueue';
4
2
  import type { EventBackend } from './events/EventBackend';
5
3
  import type { EventOptions } from './events/EventOptions';
6
- import { EventPriorityQueue, type EventQueueConfig } from './events/EventPriorityQueue';
4
+ import { EventPriorityQueue } from './events/EventPriorityQueue';
7
5
  import { DeadLetterQueueManager } from './reliability/DeadLetterQueueManager';
6
+ export type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions, } from './hooks/types';
7
+ import type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions } from './hooks/types';
8
8
  /**
9
- * Callback function for filters (transforms values).
9
+ * Manager for WordPress-style hooks (actions and filters).
10
+ *
11
+ * 此為 facade 類別,將職責委派給專門的管理器:
12
+ * - FilterManager:處理 filter hook 的登記與執行
13
+ * - ActionManager:處理 action hook 的登記與執行
14
+ * - AsyncDetector:非同步偵測快取
15
+ * - MigrationWarner:遷移警告管理
16
+ *
10
17
  * @public
11
18
  */
12
- export type FilterCallback<T = unknown> = (value: T, ...args: unknown[]) => Promise<T> | T;
13
- /**
14
- * Callback function for actions (side effects).
15
- * @public
16
- */
17
- export type ActionCallback<TArgs = unknown> = (args: TArgs) => Promise<void> | void;
18
- /**
19
- * Options for listener registration.
20
- * @public
21
- */
22
- export interface ListenerOptions {
23
- /**
24
- * Explicitly specify the listener type.
25
- * - 'sync': Force synchronous dispatch for this listener
26
- * - 'async': Force asynchronous dispatch for this listener
27
- * - 'auto': Auto-detect based on function signature (default)
28
- * @default 'auto'
29
- */
30
- type?: 'sync' | 'async' | 'auto';
31
- /**
32
- * Circuit breaker configuration for this listener.
33
- */
34
- circuitBreaker?: CircuitBreakerOptions;
35
- }
36
- /**
37
- * Information about a registered listener.
38
- * @public
39
- */
40
- export interface ListenerInfo {
41
- /**
42
- * The callback function.
43
- */
44
- callback: ActionCallback;
45
- /**
46
- * Whether the listener is considered async.
47
- */
48
- isAsync: boolean;
49
- /**
50
- * The explicit type override, if any.
51
- */
52
- typeOverride?: 'sync' | 'async' | 'auto';
53
- }
54
- /**
55
- * Configuration for HookManager.
56
- * @public
57
- */
58
- export interface HookManagerConfig {
59
- /**
60
- * Enable async event dispatch by default.
61
- * When true, doAction() will automatically use async dispatch if any listener is async.
62
- * @default false
63
- */
64
- asyncByDefault?: boolean;
65
- /**
66
- * Migration mode for backward compatibility.
67
- * - 'sync': All events use synchronous dispatch (legacy mode)
68
- * - 'hybrid': Auto-detect and use async for async listeners (recommended)
69
- * - 'async': All events use async dispatch (future mode)
70
- * @default 'sync'
71
- */
72
- migrationMode?: 'sync' | 'hybrid' | 'async';
73
- /**
74
- * Enable deprecation warnings for synchronous event dispatch.
75
- * @default false
76
- */
77
- showDeprecationWarnings?: boolean;
78
- /**
79
- * Enable Dead Letter Queue for failed events.
80
- * @default true
81
- */
82
- enableDLQ?: boolean;
83
- /**
84
- * Configuration for the event priority queue (Backpressure).
85
- */
86
- queue?: EventQueueConfig;
87
- /**
88
- * Custom event backend for distributed processing.
89
- */
90
- backend?: EventBackend;
91
- /**
92
- * Database connection for persistent DLQ (optional).
93
- * If provided, failed events after max retries will be persisted to database.
94
- */
95
- db?: ConnectionContract;
96
- /**
97
- * Enable persistent DLQ for failed events (requires db).
98
- * @default false
99
- */
100
- enablePersistentDLQ?: boolean;
101
- /**
102
- * Message Queue Bridge for distributed event processing via Bull Queue.
103
- * When provided, enables dispatchQueued() method for routing events to Redis-backed queue.
104
- */
105
- messageQueueBridge?: any;
106
- /**
107
- * Event aggregation configuration (FS-102).
108
- * Enables deduplication and micro-batching for improved throughput.
109
- */
110
- aggregation?: any;
111
- }
112
19
  export declare class HookManager {
113
- private filters;
114
- private actions;
20
+ private filterManager;
21
+ private actionManager;
22
+ private asyncDetector;
23
+ private migrationWarner;
115
24
  private eventQueue;
116
25
  private backend;
117
26
  private dlq?;
118
27
  private persistentDlqManager?;
119
28
  private messageQueueBridge?;
120
- private idempotencyCache;
121
29
  private config;
122
- private migrationWarner;
123
- private aggregationManager?;
124
- /**
125
- * Cache for async detection results (WeakMap for automatic garbage collection).
126
- * @internal
127
- */
128
- private asyncDetectionCache;
129
- /**
130
- * Count of items in the async detection cache (for testing/debugging).
131
- * @internal
132
- */
133
- private asyncDetectionCacheCount;
134
- /**
135
- * Map of listener type overrides (callback -> type).
136
- * @internal
137
- */
138
- private listenerTypeOverrides;
139
30
  constructor(config?: HookManagerConfig);
140
31
  /**
141
32
  * Register a filter hook.
@@ -150,8 +41,8 @@ export declare class HookManager {
150
41
  * @example
151
42
  * ```typescript
152
43
  * core.hooks.addFilter('content', async (content: string) => {
153
- * return content.toUpperCase();
154
- * });
44
+ * return content.toUpperCase()
45
+ * })
155
46
  * ```
156
47
  */
157
48
  addFilter<T = unknown>(hook: string, callback: FilterCallback<T>): void;
@@ -168,7 +59,7 @@ export declare class HookManager {
168
59
  *
169
60
  * @example
170
61
  * ```typescript
171
- * const content = await core.hooks.applyFilters('content', 'hello world');
62
+ * const content = await core.hooks.applyFilters('content', 'hello world')
172
63
  * ```
173
64
  */
174
65
  applyFilters<T = unknown>(hook: string, initialValue: T, ...args: unknown[]): Promise<T>;
@@ -186,11 +77,8 @@ export declare class HookManager {
186
77
  * @example
187
78
  * ```typescript
188
79
  * core.hooks.addAction('user_registered', async (user: User) => {
189
- * await sendWelcomeEmail(user);
190
- * });
191
- *
192
- * // With explicit type override
193
- * core.hooks.addAction('sync_handler', handler, { type: 'async' });
80
+ * await sendWelcomeEmail(user)
81
+ * })
194
82
  * ```
195
83
  */
196
84
  addAction<TArgs = unknown>(hook: string, callback: ActionCallback<TArgs>, options?: ListenerOptions): void;
@@ -200,6 +88,9 @@ export declare class HookManager {
200
88
  * This method supports both synchronous and asynchronous dispatch based on configuration.
201
89
  * In hybrid mode, it auto-detects async listeners and uses async dispatch.
202
90
  *
91
+ * 注意:dispatch 模式決策在此層級完成,以確保子類別(如 ObservableHookManager)
92
+ * 可透過多型覆寫正確攔截 doActionSync / doActionAsync 的呼叫。
93
+ *
203
94
  * @template TArgs - The type of arguments passed to the action.
204
95
  * @param hook - The name of the hook.
205
96
  * @param args - The arguments to pass to the callbacks.
@@ -207,7 +98,7 @@ export declare class HookManager {
207
98
  *
208
99
  * @example
209
100
  * ```typescript
210
- * await core.hooks.doAction('user_registered', user);
101
+ * await core.hooks.doAction('user_registered', user)
211
102
  * ```
212
103
  */
213
104
  doAction<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
@@ -217,18 +108,11 @@ export declare class HookManager {
217
108
  * @template TArgs - The type of arguments passed to the action.
218
109
  * @param hook - The name of the hook.
219
110
  * @param args - The arguments to pass to the callbacks.
220
- * @internal
221
111
  */
222
112
  doActionSync<TArgs = unknown>(hook: string, args: TArgs): Promise<void>;
223
113
  /**
224
114
  * Run all registered actions asynchronously via priority queue.
225
115
  *
226
- * This method uses EventPriorityQueue for async dispatch with support for:
227
- * - Priority-based processing (high > normal > low)
228
- * - Timeout handling
229
- * - Ordering guarantees (strict, partition, none)
230
- * - Idempotency
231
- *
232
116
  * @template TArgs - The type of arguments passed to the action.
233
117
  * @param hook - The name of the hook.
234
118
  * @param args - The arguments to pass to the callbacks.
@@ -241,18 +125,10 @@ export declare class HookManager {
241
125
  * ordering: 'partition',
242
126
  * partitionKey: order.id,
243
127
  * timeout: 5000,
244
- * });
128
+ * })
245
129
  * ```
246
130
  */
247
131
  doActionAsync<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
248
- /**
249
- * Determine if async dispatch should be used.
250
- *
251
- * @param callbacks - Callbacks to check
252
- * @param options - Event options
253
- * @returns True if async dispatch should be used
254
- * @internal
255
- */
256
132
  /**
257
133
  * Determine the dispatch mode for an event.
258
134
  *
@@ -265,28 +141,14 @@ export declare class HookManager {
265
141
  /**
266
142
  * Check if a callback is an async function (with caching).
267
143
  *
268
- * Detection methods:
269
- * 1. Check cache first
270
- * 2. Check type override
271
- * 3. Check constructor.name === 'AsyncFunction'
272
- * 4. Fallback: Check function string representation
273
- *
274
144
  * @param callback - The callback to check
275
145
  * @returns True if the callback is async
276
146
  * @public
277
147
  */
278
148
  isAsyncListener(callback: ActionCallback): boolean;
279
- /**
280
- * Cache async detection result.
281
- * @internal
282
- */
283
- private cacheAsyncResult;
284
149
  /**
285
150
  * Runtime detection for functions that return Promises but aren't declared async.
286
151
  *
287
- * This method executes the callback with test args and checks if the result is a Promise.
288
- * Use with caution as it actually invokes the callback.
289
- *
290
152
  * @param callback - The callback to check
291
153
  * @param testArgs - Arguments to pass to the callback for testing
292
154
  * @returns True if the callback returns a Promise
@@ -314,14 +176,6 @@ export declare class HookManager {
314
176
  * @public
315
177
  */
316
178
  hasAsyncListeners(hook: string): boolean;
317
- /**
318
- * Check if a listener is effectively async (considering type override).
319
- *
320
- * @param callback - The callback to check
321
- * @returns True if the listener should be treated as async
322
- * @internal
323
- */
324
- private isListenerEffectivelyAsync;
325
179
  /**
326
180
  * Get detailed information about all listeners for a hook.
327
181
  *
@@ -330,7 +184,6 @@ export declare class HookManager {
330
184
  * @public
331
185
  */
332
186
  getListenerInfo(hook: string): ListenerInfo[];
333
- private shouldUseAsyncDispatch;
334
187
  /**
335
188
  * Get the current event queue depth.
336
189
  *
@@ -356,9 +209,14 @@ export declare class HookManager {
356
209
  *
357
210
  * @param hook - Hook name
358
211
  * @returns Array of callbacks
359
- * @internal
360
212
  */
361
213
  getListeners(hook: string): ActionCallback[];
214
+ /**
215
+ * Remove all listeners for a specific action hook.
216
+ *
217
+ * @param hook - Hook name
218
+ */
219
+ removeAction(hook: string): void;
362
220
  /**
363
221
  * Update HookManager configuration.
364
222
  *
@@ -466,12 +324,6 @@ export declare class HookManager {
466
324
  * @returns Backpressure metrics snapshot or undefined if not enabled
467
325
  */
468
326
  getBackpressureMetrics(): object | undefined;
469
- /**
470
- * Remove all listeners for a specific action hook.
471
- *
472
- * @param hook - Hook name
473
- */
474
- removeAction(hook: string): void;
475
327
  /**
476
328
  * Get the persistent DLQ manager instance.
477
329
  *
@@ -511,7 +363,7 @@ export declare class HookManager {
511
363
  failed: number;
512
364
  }>;
513
365
  /**
514
- * Dispatch an event through Bull Queue (分佈式異步處理).
366
+ * Dispatch an event through Bull Queue(分佈式異步處理).
515
367
  *
516
368
  * 與 doActionAsync() 不同:
517
369
  * - doActionAsync() 使用 EventPriorityQueue (Memory-based)
@@ -538,9 +390,7 @@ export declare class HookManager {
538
390
  */
539
391
  dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: any): Promise<string>;
540
392
  /**
541
- * Dispatch an event through Bull Queue with delay (延遲隊列分發).
542
- *
543
- * 通過 Bull Queue 的 delayed jobs 功能實現延遲處理。
393
+ * Dispatch an event through Bull Queue with delay(延遲隊列分發).
544
394
  *
545
395
  * @template TArgs - 事件參數類型
546
396
  * @param event - 事件名稱
@@ -572,12 +422,6 @@ export declare class HookManager {
572
422
  * @returns 事件狀態信息
573
423
  * @throws 如果未配置 MessageQueueBridge
574
424
  *
575
- * @example
576
- * ```typescript
577
- * const status = await hookManager.getEventStatus('queue-1707000000000-abc123')
578
- * console.log(status) // { eventId, status, attempts, createdAt, ... }
579
- * ```
580
- *
581
425
  * @public
582
426
  */
583
427
  getEventStatus(eventId: string): Promise<any>;
@@ -16,6 +16,7 @@ import { HookManager } from './HookManager';
16
16
  import type { fail } from './helpers/response';
17
17
  import type { ContentfulStatusCode, GravitoContext } from './http/types';
18
18
  import { type Logger } from './Logger';
19
+ import { type ObservabilityProvider } from './observability/contracts';
19
20
  import type { ServiceProvider } from './ServiceProvider';
20
21
  /**
21
22
  * CacheService interface for orbit-injected cache
@@ -71,7 +72,14 @@ export type GravitoConfig = {
71
72
  config?: Record<string, unknown>;
72
73
  orbits?: (new () => GravitoOrbit)[] | GravitoOrbit[];
73
74
  /**
74
- * HTTP Adapter to use. Defaults to PhotonAdapter.
75
+ * HTTP Adapter to use. Defaults to BunNativeAdapter in Bun environments.
76
+ * In non-Bun environments, must be provided explicitly.
77
+ * @example
78
+ * ```typescript
79
+ * import { PhotonAdapter } from '@gravito/photon/adapter'
80
+ * new PlanetCore({ adapter: new PhotonAdapter() })
81
+ * ```
82
+ * See https://gravito.dev/guides/http-adapters for available adapters.
75
83
  * @since 2.0.0
76
84
  */
77
85
  adapter?: HttpAdapter;
@@ -123,6 +131,12 @@ export type GravitoConfig = {
123
131
  endpoint?: string;
124
132
  };
125
133
  };
134
+ /**
135
+ * Observability provider for distributed tracing and metrics.
136
+ * If provided, this will be used instead of the default OTel setup.
137
+ * @since 2.2.0
138
+ */
139
+ observabilityProvider?: ObservabilityProvider;
126
140
  };
127
141
  import { Router } from './Router';
128
142
  import { Encrypter } from './security/Encrypter';
@@ -160,14 +174,28 @@ export declare class PlanetCore {
160
174
  services: Map<string, unknown>;
161
175
  encrypter?: Encrypter;
162
176
  hasher: BunHasher;
177
+ /**
178
+ * Observability provider for distributed tracing and metrics.
179
+ * @since 2.2.0
180
+ */
181
+ observabilityProvider: ObservabilityProvider;
163
182
  private providers;
164
183
  private deferredProviders;
165
184
  private bootedProviders;
166
185
  private isShuttingDown;
186
+ /**
187
+ * Global shutdown timeout in milliseconds (D-10).
188
+ * If the entire shutdown sequence does not complete within this limit,
189
+ * a warning is logged and shutdown is force-completed so the process can exit.
190
+ */
191
+ private static readonly GLOBAL_SHUTDOWN_TIMEOUT;
167
192
  /**
168
193
  * Initialize observability asynchronously (metrics, tracing, Prometheus).
169
194
  * This is called from constructor but doesn't block initialization.
170
195
  *
196
+ * Phase 2.2 Update: Now uses the observabilityProvider passed from @gravito/monitor
197
+ * or falls back to OTel implementation if available for backward compatibility.
198
+ *
171
199
  * @internal
172
200
  */
173
201
  private initializeObservabilityAsync;
@@ -175,6 +203,7 @@ export declare class PlanetCore {
175
203
  * Initialize Prometheus metrics asynchronously.
176
204
  *
177
205
  * @internal
206
+ * @deprecated Prometheus setup has been moved to @gravito/monitor
178
207
  */
179
208
  private initializePrometheusAsync;
180
209
  /**
@@ -262,6 +291,7 @@ export declare class PlanetCore {
262
291
  config?: Record<string, unknown>;
263
292
  adapter?: HttpAdapter;
264
293
  container?: Container;
294
+ observabilityProvider?: ObservabilityProvider;
265
295
  });
266
296
  /**
267
297
  * Setup process signal handlers for graceful shutdown