@gravito/core 2.0.6 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +64 -25
  2. package/dist/Application.d.ts +2 -9
  3. package/dist/Container.d.ts +18 -1
  4. package/dist/GravitoServer.d.ts +8 -8
  5. package/dist/HookManager.d.ts +36 -34
  6. package/dist/PlanetCore.d.ts +54 -0
  7. package/dist/Route.d.ts +5 -0
  8. package/dist/Router.d.ts +14 -1
  9. package/dist/adapters/bun/BunContext.d.ts +1 -1
  10. package/dist/adapters/bun/BunNativeAdapter.d.ts +11 -1
  11. package/dist/adapters/bun/FastPathRegistry.d.ts +31 -0
  12. package/dist/adapters/bun/RadixNode.d.ts +4 -3
  13. package/dist/adapters/bun/RadixRouter.d.ts +2 -2
  14. package/dist/adapters/bun/types.d.ts +7 -0
  15. package/dist/adapters/types.d.ts +20 -0
  16. package/dist/compat/async-local-storage.d.ts +5 -1
  17. package/dist/compat/async-local-storage.js.map +2 -2
  18. package/dist/compat/crypto.d.ts +6 -1
  19. package/dist/compat/crypto.js.map +2 -2
  20. package/dist/engine/AOTRouter.d.ts +1 -1
  21. package/dist/engine/FastContext.d.ts +4 -4
  22. package/dist/engine/MinimalContext.d.ts +3 -3
  23. package/dist/engine/index.js +29 -8
  24. package/dist/engine/index.js.map +10 -10
  25. package/dist/engine/types.d.ts +5 -5
  26. package/dist/events/CircuitBreaker.d.ts +12 -0
  27. package/dist/events/MessageQueueBridge.d.ts +2 -1
  28. package/dist/events/observability/EventMetrics.d.ts +1 -2
  29. package/dist/events/observability/ObservableHookManager.d.ts +1 -1
  30. package/dist/exceptions/AuthException.d.ts +19 -0
  31. package/dist/exceptions/AuthenticationException.d.ts +9 -3
  32. package/dist/exceptions/AuthorizationException.d.ts +2 -2
  33. package/dist/exceptions/CacheException.d.ts +9 -0
  34. package/dist/exceptions/CircularDependencyException.d.ts +2 -1
  35. package/dist/exceptions/ConfigurationException.d.ts +9 -0
  36. package/dist/exceptions/ContainerBindingCollisionException.d.ts +10 -0
  37. package/dist/exceptions/DatabaseException.d.ts +9 -0
  38. package/dist/exceptions/DomainException.d.ts +9 -0
  39. package/dist/exceptions/InfrastructureException.d.ts +17 -0
  40. package/dist/exceptions/MiddlewareDriftException.d.ts +10 -0
  41. package/dist/exceptions/QueueException.d.ts +9 -0
  42. package/dist/exceptions/StorageException.d.ts +9 -0
  43. package/dist/exceptions/StreamException.d.ts +9 -0
  44. package/dist/exceptions/SystemException.d.ts +9 -0
  45. package/dist/exceptions/ValidationException.d.ts +2 -2
  46. package/dist/exceptions/index.d.ts +12 -0
  47. package/dist/ffi/NativeAccelerator.js.map +3 -3
  48. package/dist/ffi/NativeHasher.d.ts +14 -0
  49. package/dist/ffi/NativeHasher.js +24 -1
  50. package/dist/ffi/NativeHasher.js.map +4 -4
  51. package/dist/ffi/cbor-fallback.js.map +1 -1
  52. package/dist/ffi/hash-fallback.d.ts +15 -0
  53. package/dist/ffi/hash-fallback.js +12 -1
  54. package/dist/ffi/hash-fallback.js.map +3 -3
  55. package/dist/ffi/types.d.ts +13 -0
  56. package/dist/ffi/types.js.map +1 -1
  57. package/dist/hooks/types.d.ts +7 -3
  58. package/dist/http/types.d.ts +2 -2
  59. package/dist/index.browser.d.ts +5 -5
  60. package/dist/index.browser.js +190 -47
  61. package/dist/index.browser.js.map +50 -46
  62. package/dist/index.d.ts +17 -7
  63. package/dist/index.js +613 -202
  64. package/dist/index.js.map +82 -68
  65. package/dist/runtime/NativeOrbitDetector.d.ts +59 -0
  66. package/dist/runtime/index.browser.d.ts +1 -1
  67. package/dist/runtime/index.d.ts +7 -0
  68. package/dist/runtime.d.ts +1 -1
  69. package/dist/testing/HttpTester.d.ts +4 -4
  70. package/dist/testing/TestResponse.d.ts +4 -4
  71. package/dist/types.d.ts +3 -3
  72. package/package.json +4 -3
package/README.md CHANGED
@@ -135,23 +135,7 @@ core.hooks.addAction('user_registered', async (userId: string) => {
135
135
  await core.hooks.doAction('user_registered', 'user_123');
136
136
  ```
137
137
 
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
138
+ ### 5. Mount an Orbit
155
139
 
156
140
  Orbits are just standard Photon applications that plug into the core.
157
141
 
@@ -165,14 +149,14 @@ blogOrbit.get('/posts', (c) => c.json({ posts: [] }));
165
149
  core.mountOrbit('/api/blog', blogOrbit);
166
150
  ```
167
151
 
168
- ### 7. Liftoff! 🚀
152
+ ### 6. Liftoff! 🚀
169
153
 
170
154
  ```typescript
171
155
  // Export for Bun.serve
172
156
  export default core.liftoff(); // Automatically uses PORT from config/env
173
157
  ```
174
158
 
175
- ### 8. Process-level Error Handling (Recommended)
159
+ ### 7. Process-level Error Handling (Recommended)
176
160
 
177
161
  Request-level errors are handled by `PlanetCore` automatically, but background jobs and startup code can still fail outside the request lifecycle.
178
162
 
@@ -301,15 +285,19 @@ const logger = container.make('logger'); // inferred as Logger
301
285
  ### `HookManager`
302
286
 
303
287
  - **`addFilter(hook, callback)`**: Register a filter.
304
- - **`applyFilters(hook, initialValue, ...args)`**: Execute filters sequentially.
305
- - **`addAction(hook, callback)`**: Register an action.
306
- - **`doAction(hook, ...args)`**: Execute actions.
288
+ - **`applyFilters(hook, initialValue, ...args)`**: Apply all registered filters sequentially.
289
+ - **`addAction(hook, callback, options?)`**: Register an action hook.
290
+ - **`doAction(hook, args, options?)`**: Execute action hooks asynchronously.
291
+ - **`doActionSync(hook, args)`**: Execute action hooks synchronously.
292
+ - **`doActionAsync(hook, args, options)`**: Execute action hooks via priority queue.
307
293
 
308
294
  ### `EventManager`
309
295
 
310
- - **`emit(event, ...args)`**: Dispatch an event.
311
- - **`on(event, callback)`**: Listen to an event.
312
- - **`off(event, callback)`**: Remove a listener.
296
+ - **`dispatch(event)`**: Dispatch an event asynchronously.
297
+ - **`listen(event, listener, options?)`**: Register an event listener.
298
+ - **`unlisten(event, listener)`**: Remove an event listener.
299
+ - **`clear()`**: Remove all event listeners.
300
+ - **`getListeners(event?)`**: Get registered listeners.
313
301
 
314
302
  ### `ConfigManager`
315
303
 
@@ -317,6 +305,57 @@ const logger = container.make('logger'); // inferred as Logger
317
305
  - **`set(key, value)`**: Set a config value.
318
306
  - **`has(key)`**: Check if a config key exists.
319
307
 
308
+ ## When to use orbit() vs register() vs use()
309
+
310
+ ### `orbit(orbitInstance)` — Infrastructure Plugins
311
+
312
+ Use when integrating a **GravitoOrbit** that implements `install()`.
313
+ Orbits are infrastructure-level plugins that extend core capabilities.
314
+
315
+ ```typescript
316
+ import { OrbitDatabase } from '@gravito/atlas'
317
+ import { OrbitAuth } from '@gravito/sentinel'
318
+
319
+ const app = await PlanetCore.boot()
320
+ await app.orbit(new OrbitDatabase({ connection: 'sqlite' }))
321
+ await app.orbit(new OrbitAuth({ driver: 'session' }))
322
+ ```
323
+
324
+ ### `register(provider)` — Service Providers
325
+
326
+ Use when adding a **ServiceProvider** to the IoC container.
327
+ Providers register bindings and boot services synchronously.
328
+
329
+ ```typescript
330
+ import { CacheServiceProvider } from './providers/CacheServiceProvider'
331
+
332
+ const app = await PlanetCore.boot()
333
+ app.register(new CacheServiceProvider())
334
+ ```
335
+
336
+ ### `use(satelliteOrFn)` — Satellites & Setup Functions
337
+
338
+ Use when adding a **satellite module** or a **one-off setup function**.
339
+ Accepts either a ServiceProvider (delegates to register()) or an async function.
340
+
341
+ ```typescript
342
+ // Satellite module
343
+ import { CartSatellite } from '@gravito/satellite-cart'
344
+ await app.use(new CartSatellite())
345
+
346
+ // Setup function
347
+ await app.use(async (core) => {
348
+ core.register(new MyProvider())
349
+ await core.orbit(new MyOrbit())
350
+ })
351
+ ```
352
+
353
+ ### Decision Tree
354
+
355
+ 1. Does it implement `GravitoOrbit.install()`? → Use `orbit()`
356
+ 2. Does it implement `ServiceProvider.register()`? → Use `register()`
357
+ 3. Is it a function or satellite module? → Use `use()`
358
+
320
359
  ## 🤝 Contributing
321
360
 
322
361
  Contributions, issues and feature requests are welcome!
@@ -19,12 +19,13 @@ import { Container } from './Container';
19
19
  import type { EventManager } from './EventManager';
20
20
  import type { Logger } from './Logger';
21
21
  import { PlanetCore } from './PlanetCore';
22
+ import type { GravitoConfig } from './PlanetCore';
22
23
  import type { ServiceProvider } from './ServiceProvider';
23
24
  /**
24
25
  * Application Config options for the Application class.
25
26
  * @public
26
27
  */
27
- export interface ApplicationConfig {
28
+ export interface ApplicationConfig extends Pick<GravitoConfig, 'logger' | 'config'> {
28
29
  /**
29
30
  * Base path of the application
30
31
  */
@@ -43,14 +44,6 @@ export interface ApplicationConfig {
43
44
  * Environment (development, production, testing)
44
45
  */
45
46
  env?: 'development' | 'production' | 'testing';
46
- /**
47
- * Logger instance
48
- */
49
- logger?: Logger;
50
- /**
51
- * Initial configuration values
52
- */
53
- config?: Record<string, unknown>;
54
47
  /**
55
48
  * Service providers to register
56
49
  */
@@ -17,7 +17,8 @@ export type Factory<T> = (container: Container) => T;
17
17
  * }
18
18
  * ```
19
19
  */
20
- export type ServiceMap = {};
20
+ export interface ServiceMap {
21
+ }
21
22
  /**
22
23
  * ServiceKey represents the allowed keys for service resolution.
23
24
  * Includes keys from ServiceMap, generic strings, or symbols.
@@ -85,6 +86,22 @@ export declare class Container {
85
86
  * ```
86
87
  */
87
88
  singleton<T>(key: ServiceKey, factory: Factory<T>): void;
89
+ /**
90
+ * Bind a shared service with a namespace prefix (e.g., 'inline:my-plugin:service').
91
+ * Used by Lite Satellites to prevent global namespace pollution.
92
+ *
93
+ * @template T - The type of the service being bound.
94
+ * @param namespace - The namespace for the service (e.g., plugin name).
95
+ * @param key - The unique identifier for the service within the namespace.
96
+ * @param factory - The factory function that creates the service instance.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * container.singletonInline('ping', 'service', (c) => new PingService());
101
+ * // Resulting key: 'inline:ping:service'
102
+ * ```
103
+ */
104
+ singletonInline<T>(namespace: string, key: string, factory: Factory<T>): void;
88
105
  /**
89
106
  * Bind a request-scoped service to the container.
90
107
  *
@@ -1,4 +1,4 @@
1
- import { type GravitoConfig, PlanetCore } from './PlanetCore';
1
+ import { type GravitoConfig, type GravitoOrbit, PlanetCore } from './PlanetCore';
2
2
  /**
3
3
  * Manifest describing a Gravito application structure.
4
4
  * @public
@@ -13,16 +13,16 @@ export interface GravitoManifest {
13
13
  * Function type for asynchronous module resolution.
14
14
  * @public
15
15
  */
16
- export type ModuleResolver = () => Promise<any>;
16
+ export type ModuleResolver = () => Promise<unknown>;
17
17
  /**
18
- * Gravito 核心啟動引擎 (已解耦)
18
+ * Gravito core boot engine (decoupled).
19
19
  */
20
20
  export declare class GravitoServer {
21
21
  /**
22
- * 一鍵建立並組裝伺服器
23
- * @param manifest 站點描述清單
24
- * @param resolvers 模組解析器字典
25
- * @param baseOrbits 基礎軌道模組 (例如 OrbitMonolith)
22
+ * Create and assemble a server in one step.
23
+ * @param manifest - Application manifest describing the site structure.
24
+ * @param resolvers - Dictionary of module resolvers.
25
+ * @param baseOrbits - Base orbit modules (e.g., OrbitMonolith).
26
26
  */
27
- static create(manifest: GravitoManifest, resolvers: Record<string, ModuleResolver>, baseOrbits?: any[]): Promise<PlanetCore>;
27
+ static create(manifest: GravitoManifest, resolvers: Record<string, ModuleResolver>, baseOrbits?: (GravitoOrbit | (new () => GravitoOrbit))[]): Promise<PlanetCore>;
28
28
  }
@@ -2,17 +2,18 @@ import { DeadLetterQueue } from './events/DeadLetterQueue';
2
2
  import type { EventBackend } from './events/EventBackend';
3
3
  import type { EventOptions } from './events/EventOptions';
4
4
  import { EventPriorityQueue } from './events/EventPriorityQueue';
5
+ import type { EventStatus } from './events/MessageQueueBridge';
5
6
  import { DeadLetterQueueManager } from './reliability/DeadLetterQueueManager';
6
7
  export type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions, } from './hooks/types';
7
8
  import type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions } from './hooks/types';
8
9
  /**
9
10
  * Manager for WordPress-style hooks (actions and filters).
10
11
  *
11
- * 此為 facade 類別,將職責委派給專門的管理器:
12
- * - FilterManager:處理 filter hook 的登記與執行
13
- * - ActionManager:處理 action hook 的登記與執行
14
- * - AsyncDetector:非同步偵測快取
15
- * - MigrationWarner:遷移警告管理
12
+ * This is a facade class that delegates responsibilities to specialized managers:
13
+ * - FilterManager: handles filter hook registration and execution
14
+ * - ActionManager: handles action hook registration and execution
15
+ * - AsyncDetector: caches async detection results
16
+ * - MigrationWarner: manages migration warnings
16
17
  *
17
18
  * @public
18
19
  */
@@ -88,8 +89,9 @@ export declare class HookManager {
88
89
  * This method supports both synchronous and asynchronous dispatch based on configuration.
89
90
  * In hybrid mode, it auto-detects async listeners and uses async dispatch.
90
91
  *
91
- * 注意:dispatch 模式決策在此層級完成,以確保子類別(如 ObservableHookManager)
92
- * 可透過多型覆寫正確攔截 doActionSync / doActionAsync 的呼叫。
92
+ * Note: Dispatch mode decisions are made at this level to ensure that subclasses
93
+ * (e.g., ObservableHookManager) can correctly intercept doActionSync / doActionAsync
94
+ * calls via polymorphic overrides.
93
95
  *
94
96
  * @template TArgs - The type of arguments passed to the action.
95
97
  * @param hook - The name of the hook.
@@ -363,20 +365,20 @@ export declare class HookManager {
363
365
  failed: number;
364
366
  }>;
365
367
  /**
366
- * Dispatch an event through Bull Queue(分佈式異步處理).
368
+ * Dispatch an event through Bull Queue (distributed async processing).
367
369
  *
368
- * doActionAsync() 不同:
369
- * - doActionAsync() 使用 EventPriorityQueue (Memory-based)
370
- * - dispatchQueued() 使用 Bull Queue (Redis-backed, 分佈式)
370
+ * Unlike doActionAsync():
371
+ * - doActionAsync() uses EventPriorityQueue (memory-based)
372
+ * - dispatchQueued() uses Bull Queue (Redis-backed, distributed)
371
373
  *
372
- * 適用於需要持久化和跨進程處理的事件。
374
+ * Use this for events that require persistence and cross-process handling.
373
375
  *
374
- * @template TArgs - 事件參數類型
375
- * @param event - 事件名稱
376
- * @param args - 事件參數
377
- * @param options - 事件選項(可選)
378
- * @returns Job ID
379
- * @throws 如果未配置 MessageQueueBridge 或沒有 listeners
376
+ * @template TArgs - The type of event arguments.
377
+ * @param event - Event name.
378
+ * @param args - Event arguments.
379
+ * @param options - Event options (optional).
380
+ * @returns Job ID.
381
+ * @throws If MessageQueueBridge is not configured or there are no listeners.
380
382
  *
381
383
  * @example
382
384
  * ```typescript
@@ -388,21 +390,21 @@ export declare class HookManager {
388
390
  *
389
391
  * @public
390
392
  */
391
- dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: any): Promise<string>;
393
+ dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: EventOptions): Promise<string>;
392
394
  /**
393
- * Dispatch an event through Bull Queue with delay(延遲隊列分發).
395
+ * Dispatch an event through Bull Queue with a delay (deferred distributed dispatch).
394
396
  *
395
- * @template TArgs - 事件參數類型
396
- * @param event - 事件名稱
397
- * @param args - 事件參數
398
- * @param delay - 延遲時間(毫秒)
399
- * @param options - 事件選項(可選)
400
- * @returns Job ID
401
- * @throws 如果未配置 MessageQueueBridge
397
+ * @template TArgs - The type of event arguments.
398
+ * @param event - Event name.
399
+ * @param args - Event arguments.
400
+ * @param delay - Delay in milliseconds.
401
+ * @param options - Event options (optional).
402
+ * @returns Job ID.
403
+ * @throws If MessageQueueBridge is not configured.
402
404
  *
403
405
  * @example
404
406
  * ```typescript
405
- * // 延遲 5 秒後處理
407
+ * // Delay processing by 5 seconds
406
408
  * const jobId = await hookManager.dispatchDeferredQueued(
407
409
  * 'reminder:send',
408
410
  * { userId: '123' },
@@ -412,19 +414,19 @@ export declare class HookManager {
412
414
  *
413
415
  * @public
414
416
  */
415
- dispatchDeferredQueued<TArgs = unknown>(event: string, args: TArgs, delay: number, options?: any): Promise<string>;
417
+ dispatchDeferredQueued<TArgs = unknown>(event: string, args: TArgs, delay: number, options?: EventOptions): Promise<string>;
416
418
  /**
417
419
  * Get the execution status of an event.
418
420
  *
419
- * 查詢事件執行狀態,支持查詢 Bull Queue DLQ 中的事件。
421
+ * Queries event execution status from Bull Queue and DLQ.
420
422
  *
421
- * @param eventId - 事件 ID (task.id jobId)
422
- * @returns 事件狀態信息
423
- * @throws 如果未配置 MessageQueueBridge
423
+ * @param eventId - Event ID (task.id or jobId).
424
+ * @returns Event status information.
425
+ * @throws If MessageQueueBridge is not configured.
424
426
  *
425
427
  * @public
426
428
  */
427
- getEventStatus(eventId: string): Promise<any>;
429
+ getEventStatus(eventId: string): Promise<EventStatus>;
428
430
  /**
429
431
  * Get persistent DLQ statistics.
430
432
  *
@@ -61,6 +61,18 @@ export type ErrorHandlerContext = {
61
61
  * @public
62
62
  */
63
63
  export interface GravitoOrbit {
64
+ /**
65
+ * The unique name of the orbit.
66
+ * Required for Lite Satellites to enable namespaced service injection.
67
+ * @since 2.2.0
68
+ */
69
+ name?: string;
70
+ /**
71
+ * List of other orbit names this orbit depends on.
72
+ * Used for dependency graph generation.
73
+ * @since 2.2.0
74
+ */
75
+ dependencies?: string[];
64
76
  install(core: PlanetCore): void | Promise<void>;
65
77
  }
66
78
  /**
@@ -68,7 +80,17 @@ export interface GravitoOrbit {
68
80
  * @public
69
81
  */
70
82
  export type GravitoConfig = {
83
+ /**
84
+ * Logger instance for the application.
85
+ * Used by both PlanetCore and Application. Defaults to ConsoleLogger if not provided.
86
+ * @since 2.0.0
87
+ */
71
88
  logger?: Logger;
89
+ /**
90
+ * Initial configuration values, loaded into ConfigManager on boot.
91
+ * Accessible via `core.config` or `app.config` after booting.
92
+ * @since 2.0.0
93
+ */
72
94
  config?: Record<string, unknown>;
73
95
  orbits?: (new () => GravitoOrbit)[] | GravitoOrbit[];
74
96
  /**
@@ -174,6 +196,14 @@ export declare class PlanetCore {
174
196
  services: Map<string, unknown>;
175
197
  encrypter?: Encrypter;
176
198
  hasher: BunHasher;
199
+ /**
200
+ * Track installed orbits and their dependencies.
201
+ * @since 2.2.0
202
+ */
203
+ readonly installedOrbits: Array<{
204
+ name: string;
205
+ dependencies: string[];
206
+ }>;
177
207
  /**
178
208
  * Observability provider for distributed tracing and metrics.
179
209
  * @since 2.2.0
@@ -183,6 +213,12 @@ export declare class PlanetCore {
183
213
  private deferredProviders;
184
214
  private bootedProviders;
185
215
  private isShuttingDown;
216
+ /**
217
+ * Global shutdown timeout in milliseconds (D-10).
218
+ * If the entire shutdown sequence does not complete within this limit,
219
+ * a warning is logged and shutdown is force-completed so the process can exit.
220
+ */
221
+ private static readonly GLOBAL_SHUTDOWN_TIMEOUT;
186
222
  /**
187
223
  * Initialize observability asynchronously (metrics, tracing, Prometheus).
188
224
  * This is called from constructor but doesn't block initialization.
@@ -293,6 +329,24 @@ export declare class PlanetCore {
293
329
  * @internal
294
330
  */
295
331
  private setupSignalHandlers;
332
+ /**
333
+ * Register a Lite Satellite (Anonymous Plugin) as an object literal.
334
+ * This is a simplified alternative to full-featured Orbits.
335
+ *
336
+ * @param config - The plugin configuration object.
337
+ * @returns The PlanetCore instance for chaining.
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * await core.plugin({
342
+ * name: 'ping',
343
+ * install(core) {
344
+ * core.router.get('/ping', (c) => c.text('pong'))
345
+ * }
346
+ * });
347
+ * ```
348
+ */
349
+ plugin(config: GravitoOrbit): Promise<this>;
296
350
  /**
297
351
  * Programmatically register an infrastructure module (Orbit).
298
352
  * @since 2.0.0
package/dist/Route.d.ts CHANGED
@@ -15,6 +15,11 @@ export declare class Route {
15
15
  * Name the route
16
16
  */
17
17
  name(name: string): this;
18
+ /**
19
+ * Attach Zod schemas to the route for validation and OpenAPI generation.
20
+ * @since 2.2.0
21
+ */
22
+ schema(schemas: NonNullable<RouteOptions['schema']>): this;
18
23
  static get(path: string, handler: RouteHandler): Route;
19
24
  static get(path: string, request: FormRequestClass, handler: RouteHandler): Route;
20
25
  static get(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
package/dist/Router.d.ts CHANGED
@@ -5,7 +5,7 @@ import { Route } from './Route';
5
5
  * Type for Controller Class Constructor
6
6
  * @public
7
7
  */
8
- export type ControllerClass = new (core: PlanetCore) => any;
8
+ export type ControllerClass = new (core: PlanetCore) => unknown;
9
9
  /**
10
10
  * Handler can be a function or [Class, 'methodName']
11
11
  * @public
@@ -54,6 +54,17 @@ export interface RouteOptions {
54
54
  domain?: string;
55
55
  /** Middleware stack for the route */
56
56
  middleware?: GravitoMiddleware[];
57
+ /**
58
+ * Zod schemas for request validation and response documentation.
59
+ * Used for OpenAPI generation.
60
+ * @since 2.2.0
61
+ */
62
+ schema?: {
63
+ body?: unknown;
64
+ params?: unknown;
65
+ query?: unknown;
66
+ response?: unknown;
67
+ };
57
68
  }
58
69
  /**
59
70
  * Common routing handler argument definition
@@ -140,6 +151,7 @@ export declare class Router {
140
151
  method: string;
141
152
  path: string;
142
153
  domain?: string;
154
+ options?: RouteOptions;
143
155
  }>;
144
156
  private dispatcher;
145
157
  private namedRoutes;
@@ -153,6 +165,7 @@ export declare class Router {
153
165
  path: string;
154
166
  name?: string;
155
167
  domain?: string | undefined;
168
+ schema?: RouteOptions["schema"];
156
169
  }[];
157
170
  /**
158
171
  * Register a named route
@@ -13,7 +13,7 @@ export declare class BunContext<V extends GravitoVariables = GravitoVariables> i
13
13
  /**
14
14
  * URL generator helper
15
15
  */
16
- route: (name: string, params?: Record<string, any>, query?: Record<string, any>) => string;
16
+ route: (name: string, params?: Record<string, string | number>, query?: Record<string, string | number | boolean | null | undefined>) => string;
17
17
  private _status;
18
18
  private _headers;
19
19
  private _executionCtx?;
@@ -1,6 +1,7 @@
1
1
  import type { GravitoContext, GravitoErrorHandler, GravitoHandler, GravitoMiddleware, GravitoNotFoundHandler, HttpMethod } from '../../http/types';
2
2
  import type { HttpAdapter, RouteDefinition } from '../types';
3
3
  import type { WebSocketRouteHandlers } from './BunWebSocketHandler';
4
+ import type { BunRouteOptions } from './types';
4
5
  /**
5
6
  * Native Bun-optimized HTTP Adapter for Gravito.
6
7
  * Uses Bun's standard Request/Response classes and efficient router.
@@ -10,7 +11,9 @@ export declare class BunNativeAdapter implements HttpAdapter {
10
11
  readonly name = "bun-native";
11
12
  readonly version = "0.0.1";
12
13
  get native(): unknown;
14
+ private isSnapshotLocked;
13
15
  private router;
16
+ private fastPathRegistry;
14
17
  private middlewares;
15
18
  private errorHandler;
16
19
  private notFoundHandler;
@@ -18,7 +21,8 @@ export declare class BunNativeAdapter implements HttpAdapter {
18
21
  private readonly maxPoolSize;
19
22
  private middlewareChainCache;
20
23
  private wsHandler;
21
- route(method: HttpMethod, path: string, ...handlers: (GravitoHandler | GravitoMiddleware)[]): void;
24
+ private checkLock;
25
+ route(method: HttpMethod, path: string, ...handlers: (GravitoHandler | GravitoMiddleware | BunRouteOptions)[]): void;
22
26
  routes(routes: RouteDefinition[]): void;
23
27
  use(path: string, ...middleware: GravitoMiddleware[]): void;
24
28
  useGlobal(...middleware: GravitoMiddleware[]): void;
@@ -44,6 +48,12 @@ export declare class BunNativeAdapter implements HttpAdapter {
44
48
  createContext(request: Request): GravitoContext;
45
49
  onError(handler: GravitoErrorHandler): void;
46
50
  onNotFound(handler: GravitoNotFoundHandler): void;
51
+ registerFastPath(method: string, path: string, handler: (req: Request) => Response | Promise<Response>): void;
52
+ /**
53
+ * Generate configuration for Bun.serve().
54
+ * Offloads fast-path GET routes to Bun's native router.
55
+ */
56
+ serveConfig(baseConfig?: Record<string, unknown>): Record<string, unknown>;
47
57
  /**
48
58
  * 註冊 WebSocket 路由
49
59
  */
@@ -0,0 +1,31 @@
1
+ /**
2
+ * FastPathRegistry.ts
3
+ *
4
+ * Lightweight registry for ultra-low latency routes that bypass the Gravito engine.
5
+ * Matches routes using exact string comparison for maximum speed.
6
+ *
7
+ * @module @gravito/core/adapters/bun
8
+ * @since 2.2.0
9
+ */
10
+ export declare class FastPathRegistry {
11
+ private routes;
12
+ /**
13
+ * Register a fast-path handler.
14
+ * @param method HTTP method (GET, POST, etc.)
15
+ * @param path Exact path string (e.g., '/health')
16
+ * @param handler Handler that takes raw Request and returns Response
17
+ */
18
+ register(method: string, path: string, handler: (req: Request) => Response | Promise<Response>): void;
19
+ /**
20
+ * Match a request to a registered fast-path handler.
21
+ * @param method HTTP method
22
+ * @param path Pathname
23
+ * @returns The handler if found, otherwise undefined
24
+ */
25
+ match(method: string, path: string): ((req: Request) => Response | Promise<Response>) | undefined;
26
+ /**
27
+ * Get all registered fast-path routes.
28
+ * Useful for Bun.serve routes integration.
29
+ */
30
+ getAll(): Map<string, Map<string, (req: Request) => Response | Promise<Response>>>;
31
+ }
@@ -1,5 +1,5 @@
1
1
  import type { HttpMethod } from '../../http/types';
2
- import { NodeType, type RouteHandler } from './types';
2
+ import { NodeType, type RouteHandler, type BunRouteOptions } from './types';
3
3
  /**
4
4
  * Node in the Radix Router tree.
5
5
  * @internal
@@ -11,9 +11,10 @@ export declare class RadixNode {
11
11
  paramChild: RadixNode | null;
12
12
  wildcardChild: RadixNode | null;
13
13
  handlers: Map<HttpMethod, RouteHandler[]>;
14
+ options: Map<HttpMethod, BunRouteOptions>;
14
15
  paramName: string | null;
15
16
  regex: RegExp | null;
16
17
  constructor(segment?: string, type?: NodeType);
17
- toJSON(): any;
18
- static fromJSON(json: any): RadixNode;
18
+ toJSON(): Record<string, unknown>;
19
+ static fromJSON(json: Record<string, unknown>): RadixNode;
19
20
  }
@@ -1,5 +1,5 @@
1
1
  import type { HttpMethod } from '../../http/types';
2
- import { type RouteHandler, type RouteMatch } from './types';
2
+ import { type RouteHandler, type RouteMatch, type BunRouteOptions } from './types';
3
3
  /**
4
4
  * High-performance Radix Tree Router for Bun
5
5
  */
@@ -14,7 +14,7 @@ export declare class RadixRouter {
14
14
  /**
15
15
  * Register a route
16
16
  */
17
- add(method: HttpMethod, path: string, handlers: RouteHandler[]): void;
17
+ add(method: HttpMethod, path: string, handlers: RouteHandler[], options?: BunRouteOptions): void;
18
18
  /**
19
19
  * Match a request
20
20
  */
@@ -9,6 +9,13 @@ export type RouteHandler = Function;
9
9
  export interface RouteMatch {
10
10
  handlers: RouteHandler[];
11
11
  params: Record<string, string>;
12
+ options?: BunRouteOptions;
13
+ }
14
+ /**
15
+ * Route Options (Metadata)
16
+ */
17
+ export interface BunRouteOptions {
18
+ excludeMiddleware?: string[];
12
19
  }
13
20
  /**
14
21
  * Radix Node Type
@@ -224,6 +224,26 @@ export interface HttpAdapter<V extends GravitoVariables = GravitoVariables> {
224
224
  * @returns Gravito context
225
225
  */
226
226
  createContext(request: Request): GravitoContext<V>;
227
+ /**
228
+ * Register an ultra-low latency route that bypasses the Gravito engine.
229
+ *
230
+ * @param method - HTTP method
231
+ * @param path - Exact route path (no wildcards or parameters)
232
+ * @param handler - Native fetch handler (Request => Response)
233
+ * @since 2.2.0
234
+ */
235
+ registerFastPath?(method: string, path: string, handler: (req: Request) => Response | Promise<Response>): void;
236
+ /**
237
+ * Generate configuration for the native HTTP engine.
238
+ *
239
+ * This allows offloading fast-path routes to the runtime's native router
240
+ * (e.g., Bun.serve({ routes: { ... } })).
241
+ *
242
+ * @param baseConfig - Base configuration to merge
243
+ * @returns Optimized engine configuration
244
+ * @since 2.2.0
245
+ */
246
+ serveConfig?(baseConfig?: Record<string, unknown>): Record<string, unknown>;
227
247
  }
228
248
  /**
229
249
  * Factory function type for creating adapters
@@ -3,5 +3,9 @@
3
3
  * Automatically switches between node:async_hooks and a browser mock.
4
4
  */
5
5
  export declare const AsyncLocalStorage: {
6
- new <_T>(): any;
6
+ new <T>(): {
7
+ run<R>(store: T, fn: () => R): R;
8
+ getStore(): T | undefined;
9
+ disable(): void;
10
+ };
7
11
  };