@gravito/core 1.6.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) 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 +576 -647
  53. package/dist/engine/index.cjs.map +22 -0
  54. package/dist/engine/index.d.ts +14 -910
  55. package/dist/engine/index.js +576 -623
  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-CI8hiulX.d.cts → http/types.d.ts} +29 -16
  129. package/dist/index.browser.d.ts +34 -0
  130. package/dist/index.cjs +10525 -11171
  131. package/dist/index.cjs.map +168 -0
  132. package/dist/index.d.ts +58 -10981
  133. package/dist/index.js +10861 -10997
  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 +21 -52
  167. package/src/ffi/native/cbor.c +1148 -0
  168. package/dist/Metrics-VOWWRNNR.js +0 -219
  169. package/dist/chunk-R5U7XKVJ.js +0 -16
  170. package/dist/compat-CI8hiulX.d.ts +0 -376
  171. package/dist/compat.d.cts +0 -1
  172. package/dist/engine/index.d.cts +0 -922
  173. package/dist/index.d.cts +0 -11008
@@ -0,0 +1,139 @@
1
+ /**
2
+ * @fileoverview AOT (Ahead-of-Time) Router
3
+ *
4
+ * Hybrid routing strategy:
5
+ * - Static routes: O(1) Map lookup
6
+ * - Dynamic routes: Optimized Radix Tree
7
+ *
8
+ * The key optimization is separating static from dynamic routes at registration time,
9
+ * not at match time. This eliminates unnecessary tree traversal for static paths.
10
+ *
11
+ * @module @gravito/core/engine
12
+ */
13
+ import type { HttpMethod } from '../http/types';
14
+ import type { Handler, Middleware, RouteMatch, RouteMetadata } from './types';
15
+ /**
16
+ * Route definition for re-playing routes (mounting)
17
+ */
18
+ interface RouteDefinition {
19
+ method: HttpMethod;
20
+ path: string;
21
+ handler: Handler;
22
+ middleware: Middleware[];
23
+ }
24
+ /**
25
+ * AOT Router - Optimized for Bun
26
+ */
27
+ export declare class AOTRouter {
28
+ /** @internal */
29
+ readonly staticRoutes: Map<string, RouteMetadata>;
30
+ private dynamicRouter;
31
+ /** @internal */
32
+ readonly routeDefinitions: RouteDefinition[];
33
+ /** @internal */
34
+ readonly globalMiddleware: Middleware[];
35
+ /** @internal */
36
+ readonly pathMiddleware: Map<string, Middleware[]>;
37
+ private dynamicRoutePatterns;
38
+ private middlewareCache;
39
+ private cacheMaxSize;
40
+ private _version;
41
+ /**
42
+ * Get the current version for cache invalidation
43
+ * Incremented whenever middleware or routes are modified
44
+ */
45
+ get version(): number;
46
+ /**
47
+ * Register a route
48
+ *
49
+ * Automatically determines if route is static or dynamic.
50
+ * Static routes are stored in a Map for O(1) lookup.
51
+ * Dynamic routes use the Radix Tree.
52
+ *
53
+ * @param method - HTTP method
54
+ * @param path - Route path
55
+ * @param handler - Route handler
56
+ * @param middleware - Route-specific middleware
57
+ */
58
+ add(method: HttpMethod, path: string, handler: Handler, middleware?: Middleware[]): void;
59
+ /**
60
+ * Mount another router at a prefix
61
+ */
62
+ mount(prefix: string, other: AOTRouter): void;
63
+ /**
64
+ * Add global middleware
65
+ *
66
+ * These run for every request, before route-specific middleware.
67
+ *
68
+ * @param middleware - Middleware functions
69
+ */
70
+ use(...middleware: Middleware[]): void;
71
+ /**
72
+ * Add path-based middleware
73
+ *
74
+ * Supports wildcard patterns like '/api/*'
75
+ *
76
+ * @param pattern - Path pattern
77
+ * @param middleware - Middleware functions
78
+ */
79
+ usePattern(pattern: string, ...middleware: Middleware[]): void;
80
+ /**
81
+ * Match a request to a route
82
+ *
83
+ * Returns the handler, params, and all applicable middleware.
84
+ *
85
+ * @param method - HTTP method
86
+ * @param path - Request path
87
+ * @returns Route match or null if not found
88
+ */
89
+ match(method: string, path: string): RouteMatch;
90
+ /**
91
+ * Public wrapper for collectMiddleware (used by Gravito for optimization)
92
+ */
93
+ collectMiddlewarePublic(path: string, routeMiddleware: Middleware[]): Middleware[];
94
+ /**
95
+ * Collect all applicable middleware for a path
96
+ *
97
+ * Order: global -> pattern-based -> route-specific
98
+ *
99
+ * @param path - Request path
100
+ * @param routeMiddleware - Route-specific middleware
101
+ * @returns Combined middleware array
102
+ */
103
+ private collectMiddleware;
104
+ /**
105
+ * Get all static routes optimized for Bun's native router.
106
+ *
107
+ * Unlike basic offloading, this version supports routes with middleware
108
+ * by pre-compiling the middleware chain into a single native handler.
109
+ *
110
+ * @param onMatch - Factory to wrap handler and middleware into a Bun-compatible function
111
+ * @returns Record of path -> Handler (Bun-compatible)
112
+ */
113
+ getNativeRoutes(onMatch: (handler: Handler, middleware: Middleware[], path: string) => (req: Request) => Response | Promise<Response>): Record<string, any>;
114
+ /**
115
+ * Check if a path is static (no parameters or wildcards)
116
+ */
117
+ private isStaticPath;
118
+ /**
119
+ * Match a pattern against a path
120
+ *
121
+ * Supports:
122
+ * - Exact match: '/api/users'
123
+ * - Wildcard suffix: '/api/*'
124
+ *
125
+ * @param pattern - Pattern to match
126
+ * @param path - Path to test
127
+ * @returns True if pattern matches
128
+ */
129
+ private matchPattern;
130
+ /**
131
+ * Get all registered routes (for debugging)
132
+ */
133
+ getRoutes(): Array<{
134
+ method: string;
135
+ path: string;
136
+ type: 'static' | 'dynamic';
137
+ }>;
138
+ }
139
+ export {};
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @fileoverview FastContext - Pooled Request Context
3
+ *
4
+ * Minimal, high-performance context implementation designed for object pooling.
5
+ * Lazy parsing strategy: only parse what's actually accessed.
6
+ *
7
+ * @module @gravito/core/engine
8
+ */
9
+ import { RequestScopeManager } from '../Container/RequestScopeManager';
10
+ import type { FastRequest, FastContext as IFastContext } from './types';
11
+ /**
12
+ * Lazy-parsed request wrapper
13
+ *
14
+ * Delays parsing of query params, headers, and body until accessed.
15
+ * This is a key optimization for requests that don't need all data.
16
+ */
17
+ declare class FastRequestImpl implements FastRequest {
18
+ private _request;
19
+ private _params;
20
+ private _path;
21
+ private _routePattern?;
22
+ private _url;
23
+ private _query;
24
+ private _headers;
25
+ private _cachedJson;
26
+ private _jsonParsed;
27
+ private _cachedText;
28
+ private _textParsed;
29
+ private _cachedFormData;
30
+ private _formDataParsed;
31
+ private _cachedQueries;
32
+ private _cachedCookies;
33
+ private _ctx;
34
+ constructor(ctx: FastContext);
35
+ /**
36
+ * Initialize for new request
37
+ */
38
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
39
+ /**
40
+ * Reset for pooling
41
+ */
42
+ reset(): void;
43
+ private checkReleased;
44
+ get url(): string;
45
+ get method(): string;
46
+ get path(): string;
47
+ get routePattern(): string | undefined;
48
+ param(name: string): string | undefined;
49
+ params(): Record<string, string>;
50
+ private getUrl;
51
+ query(name: string): string | undefined;
52
+ queries(): Record<string, string | string[]>;
53
+ header(name: string): string | undefined;
54
+ headers(): Record<string, string>;
55
+ get cookies(): Record<string, string>;
56
+ json<T = unknown>(): Promise<T>;
57
+ text(): Promise<string>;
58
+ formData(): Promise<FormData>;
59
+ get raw(): Request;
60
+ }
61
+ /**
62
+ * FastContext - Pooled request context
63
+ *
64
+ * Designed for minimal memory allocation and maximum reuse.
65
+ * All response helpers create Response objects directly without intermediate wrappers.
66
+ */
67
+ export declare class FastContext implements IFastContext {
68
+ readonly req: FastRequestImpl;
69
+ private _headers;
70
+ _isReleased: boolean;
71
+ private _requestScope;
72
+ /**
73
+ * Initialize context for a new request
74
+ *
75
+ * This is called when acquiring from the pool.
76
+ */
77
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
78
+ /**
79
+ * Reset context for pooling (Cleanup)
80
+ *
81
+ * This is called when releasing back to the pool.
82
+ * Implements "Deep-Reset Protocol" and "Release Guard".
83
+ */
84
+ reset(): void;
85
+ /**
86
+ * Check if context is released
87
+ */
88
+ private checkReleased;
89
+ json<T>(data: T, status?: number): Response;
90
+ text(text: string, status?: number): Response;
91
+ html(html: string, status?: number): Response;
92
+ /**
93
+ * Escape HTML using Bun's SIMD-accelerated native implementation
94
+ */
95
+ escape(html: string): string;
96
+ redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
97
+ body(data: BodyInit | null, status?: number): Response;
98
+ /**
99
+ * Send high-performance binary response (e.g. CBOR, Protobuf)
100
+ * Utilizing Bun's native ArrayBufferSink for zero-allocation construction.
101
+ */
102
+ binary(data: Uint8Array | ArrayBuffer, status?: number): Response;
103
+ stream(stream: any, status?: number): Response;
104
+ notFound(message?: string): Response;
105
+ forbidden(message?: string): Response;
106
+ unauthorized(message?: string): Response;
107
+ badRequest(message?: string): Response;
108
+ forward(target: string, _options?: any): Promise<Response>;
109
+ header(name: string): string | undefined;
110
+ header(name: string, value: string): void;
111
+ /**
112
+ * Status code setter (no-op)
113
+ *
114
+ * Note: Since all response helpers accept a `status` parameter,
115
+ * this method is not actively used. Status should be set directly
116
+ * in the response helper call (e.g., `ctx.json({}, 201)`).
117
+ */
118
+ status(_code: number): void;
119
+ private _store;
120
+ get<T>(key: string): T;
121
+ set(key: string, value: any): void;
122
+ /**
123
+ * Get the request-scoped service manager for this request.
124
+ *
125
+ * @returns The RequestScopeManager for this request.
126
+ * @throws Error if called before init() or after reset().
127
+ */
128
+ requestScope(): RequestScopeManager;
129
+ /**
130
+ * Resolve a request-scoped service (convenience method).
131
+ *
132
+ * @template T - The service type.
133
+ * @param key - The service key for caching.
134
+ * @param factory - Factory function to create the service.
135
+ * @returns The cached or newly created service instance.
136
+ */
137
+ scoped<T>(key: string | symbol, factory: () => T): T;
138
+ route: (name: string, params?: any, query?: any) => string;
139
+ get native(): this;
140
+ }
141
+ export {};
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @fileoverview Gravito - High-Performance Web Engine for Bun
3
+ *
4
+ * The standalone engine optimized exclusively for Bun runtime.
5
+ * 99% API-compatible with Hono, but faster through Bun-specific optimizations.
6
+ *
7
+ * Key optimizations:
8
+ * 1. Object pooling for zero-allocation request handling
9
+ * 2. AOT router with O(1) static route lookup
10
+ * 3. Lazy parsing - only parse what's accessed
11
+ * 4. Direct Bun.serve integration without wrapper layers
12
+ *
13
+ * @module @gravito/core/engine
14
+ */
15
+ import type { EngineOptions, ErrorHandler, Handler, Middleware, NotFoundHandler, RouteMetadata } from './types';
16
+ /**
17
+ * Gravito - The High-Performance Web Engine
18
+ */
19
+ export declare class Gravito {
20
+ private router;
21
+ private contextPool;
22
+ private errorHandler?;
23
+ private notFoundHandler?;
24
+ /** @internal */
25
+ staticRoutes: Map<string, RouteMetadata>;
26
+ private isPureStaticApp;
27
+ private compiledDynamicRoutes;
28
+ /**
29
+ * Create a new Gravito instance
30
+ *
31
+ * @param options - Engine configuration options
32
+ */
33
+ constructor(options?: EngineOptions);
34
+ /**
35
+ * Register a GET route
36
+ */
37
+ get(path: string, ...handlers: Handler[]): this;
38
+ /**
39
+ * Register a POST route
40
+ */
41
+ post(path: string, ...handlers: Handler[]): this;
42
+ /**
43
+ * Register a PUT route
44
+ */
45
+ put(path: string, ...handlers: Handler[]): this;
46
+ /**
47
+ * Register a DELETE route
48
+ */
49
+ delete(path: string, ...handlers: Handler[]): this;
50
+ /**
51
+ * Register a PATCH route
52
+ */
53
+ patch(path: string, ...handlers: Handler[]): this;
54
+ /**
55
+ * Register an OPTIONS route
56
+ */
57
+ options(path: string, ...handlers: Handler[]): this;
58
+ /**
59
+ * Register a HEAD route
60
+ */
61
+ head(path: string, ...handlers: Handler[]): this;
62
+ /**
63
+ * Register a route for all HTTP methods
64
+ */
65
+ all(path: string, ...handlers: Handler[]): this;
66
+ /**
67
+ * Register global or path-based middleware
68
+ */
69
+ use(path: string, ...middleware: Middleware[]): this;
70
+ use(...middleware: Middleware[]): this;
71
+ /**
72
+ * Mount a sub-application at a path prefix
73
+ */
74
+ route(path: string, app: Gravito): this;
75
+ /**
76
+ * Set custom error handler
77
+ */
78
+ onError(handler: ErrorHandler): this;
79
+ /**
80
+ * Set custom 404 handler
81
+ */
82
+ notFound(handler: NotFoundHandler): this;
83
+ /**
84
+ * Predictive Route Warming (JIT Optimization)
85
+ *
86
+ * Simulates requests to specified routes to trigger JIT compilation (FTL)
87
+ * before real traffic arrives.
88
+ *
89
+ * @param paths List of paths to warm up (e.g. ['/api/users', '/health'])
90
+ */
91
+ warmup(paths: string[]): Promise<void>;
92
+ /**
93
+ * Generate Native Bun.serve Configuration
94
+ *
95
+ * Offloads static routes to Bun's SIMD-accelerated native router.
96
+ * Supports pre-compiled middleware chains for zero runtime lookup.
97
+ */
98
+ serveConfig(baseConfig?: Record<string, unknown>): Record<string, unknown>;
99
+ /**
100
+ * Optimize TLS Configuration for Bun 1.39+
101
+ */
102
+ private optimizeTLS;
103
+ /**
104
+ * Handle an incoming request
105
+ */
106
+ fetch: (request: Request) => Promise<Response>;
107
+ /**
108
+ * Handle dynamic routes with Radix Tree
109
+ */
110
+ private handleDynamicRoute;
111
+ /**
112
+ * Sync error handler (for ultra-fast path)
113
+ */
114
+ private handleErrorSync;
115
+ /**
116
+ * Sync 404 handler (for ultra-fast path)
117
+ */
118
+ private handleNotFoundSync;
119
+ /**
120
+ * Collect middleware for a specific path
121
+ */
122
+ private collectMiddlewareForPath;
123
+ /**
124
+ * Compile routes for optimization
125
+ */
126
+ private compileRoutes;
127
+ /**
128
+ * Add a route to the router
129
+ */
130
+ private addRoute;
131
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @fileoverview MinimalContext - Ultra-lightweight Request Context
3
+ *
4
+ * Designed for zero-middleware static routes where pool overhead
5
+ * exceeds the cost of creating a new object.
6
+ *
7
+ * Key difference from FastContext:
8
+ * - No object pooling (direct instantiation is faster for simple cases)
9
+ * - No Headers object reuse (creates inline)
10
+ * - Minimal memory footprint
11
+ *
12
+ * @module @gravito/core/engine
13
+ */
14
+ import { RequestScopeManager } from '../Container/RequestScopeManager';
15
+ import type { FastRequest, FastContext as IFastContext } from './types';
16
+ /**
17
+ * Minimal request wrapper
18
+ */
19
+ declare class MinimalRequest implements FastRequest {
20
+ private readonly _request;
21
+ private readonly _params;
22
+ private readonly _path;
23
+ private readonly _routePattern?;
24
+ private _searchParams;
25
+ private _cachedQueries;
26
+ private _cachedJsonPromise;
27
+ private _cachedTextPromise;
28
+ private _cachedFormDataPromise;
29
+ constructor(_request: Request, _params: Record<string, string>, _path: string, _routePattern?: string);
30
+ get url(): string;
31
+ get method(): string;
32
+ get path(): string;
33
+ get routePattern(): string | undefined;
34
+ param(name: string): string | undefined;
35
+ params(): Record<string, string>;
36
+ /**
37
+ * Lazy-initialize searchParams, only parse once
38
+ */
39
+ private getSearchParams;
40
+ query(name: string): string | undefined;
41
+ queries(): Record<string, string | string[]>;
42
+ header(name: string): string | undefined;
43
+ headers(): Record<string, string>;
44
+ json<T = unknown>(): Promise<T>;
45
+ text(): Promise<string>;
46
+ formData(): Promise<FormData>;
47
+ get cookies(): Record<string, string>;
48
+ get raw(): Request;
49
+ }
50
+ /**
51
+ * MinimalContext - Optimized for simple, fast responses
52
+ *
53
+ * Use when:
54
+ * - No middleware
55
+ * - Static routes
56
+ * - Simple JSON/text responses
57
+ * - No custom headers needed
58
+ */
59
+ export declare class MinimalContext implements IFastContext {
60
+ readonly req: MinimalRequest;
61
+ private _resHeaders;
62
+ private _requestScope;
63
+ constructor(request: Request, params: Record<string, string>, path: string, routePattern?: string);
64
+ private getHeaders;
65
+ json<T>(data: T, status?: number): Response;
66
+ text(text: string, status?: number): Response;
67
+ html(html: string, status?: number): Response;
68
+ redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
69
+ body(data: BodyInit | null, status?: number): Response;
70
+ header(name: string): string | undefined;
71
+ header(name: string, value: string): void;
72
+ status(_code: number): void;
73
+ stream(stream: ReadableStream, status?: number): Response;
74
+ notFound(message?: string): Response;
75
+ forbidden(message?: string): Response;
76
+ unauthorized(message?: string): Response;
77
+ badRequest(message?: string): Response;
78
+ forward(target: string, _options?: any): Promise<Response>;
79
+ escape(html: string): string;
80
+ get<T>(_key: string): T;
81
+ set(_key: string, _value: any): void;
82
+ /**
83
+ * Get the request-scoped service manager for this request.
84
+ *
85
+ * @returns The RequestScopeManager for this request.
86
+ */
87
+ requestScope(): RequestScopeManager;
88
+ /**
89
+ * Resolve a request-scoped service (convenience method).
90
+ *
91
+ * @template T - The service type.
92
+ * @param key - The service key for caching.
93
+ * @param factory - Factory function to create the service.
94
+ * @returns The cached or newly created service instance.
95
+ */
96
+ scoped<T>(key: string | symbol, factory: () => T): T;
97
+ route: (name: string, params?: any, query?: any) => string;
98
+ get native(): this;
99
+ init(_request: Request, _params?: Record<string, string>, _path?: string): this;
100
+ reset(): void;
101
+ }
102
+ export {};
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @fileoverview Handler 靜態分析器(Elysia-inspired,升級版)
3
+ *
4
+ * 分析 handler 函式,偵測其存取了哪些請求屬性,
5
+ * 以選擇最優化的 Context 類型(minimal/fast/full)。
6
+ *
7
+ * ## 版本歷史
8
+ *
9
+ * ### v2(目前版本)- 使用 Bun.Transpiler
10
+ * - 精確度:~99%(AST 層級分析)
11
+ * - 正確處理假陽性:`const header = '...'` 不再誤判
12
+ * - 支援解構賦值:`const { header } = ctx.req`
13
+ * - 支援 Minified 代碼(transformSync 先標準化)
14
+ * - Fallback:若 Transpiler 失敗,退回字串匹配
15
+ *
16
+ * ### v1(原版本)- 字串匹配
17
+ * - 精確度:~85%
18
+ * - 假陽性:變數名稱包含目標字串會誤判
19
+ * - 假陰性:解構賦值無法偵測
20
+ * - Minified 代碼可能失效
21
+ *
22
+ * @module @gravito/core/engine/analyzer
23
+ * @since 3.0.0
24
+ */
25
+ /**
26
+ * Handler 靜態分析結果
27
+ *
28
+ * 記錄 handler 函式使用了哪些請求屬性,
29
+ * 用於選擇最優化的 Context 類型。
30
+ *
31
+ * @public
32
+ * @since 3.0.0
33
+ */
34
+ export interface HandlerAnalysis {
35
+ /** 是否存取了 request headers */
36
+ usesHeaders: boolean;
37
+ /** 是否存取了 query string 參數 */
38
+ usesQuery: boolean;
39
+ /** 是否存取了 request body */
40
+ usesBody: boolean;
41
+ /** 是否存取了 route 路徑參數 */
42
+ usesParams: boolean;
43
+ /** 是否為非同步函式(含 async/await) */
44
+ isAsync: boolean;
45
+ }
46
+ /**
47
+ * 分析 handler 函式,偵測其使用了哪些請求屬性
48
+ *
49
+ * 使用 Bun.Transpiler 進行 AST 層級的精確分析(精確度 ~99%)。
50
+ * 若 Transpiler 不可用,自動 fallback 到字串匹配(精確度 ~85%)。
51
+ *
52
+ * ## 精確度提升說明
53
+ *
54
+ * **假陽性修復**(原本誤判,現在正確):
55
+ * ```typescript
56
+ * // 這個 handler 原本會誤判 usesHeaders = true
57
+ * // 因為字串 'header' 出現在變數名稱中
58
+ * function handler(ctx) {
59
+ * const header = 'Content-Type' // ← 變數名稱,不是 API 呼叫
60
+ * return ctx.json({ header })
61
+ * }
62
+ * // 現在:usesHeaders = false ✅
63
+ * ```
64
+ *
65
+ * **假陰性修復**(原本漏偵測,現在正確):
66
+ * ```typescript
67
+ * // 這個 handler 原本會漏偵測解構賦值
68
+ * function handler(ctx) {
69
+ * const { header, query } = ctx.req // ← 解構賦值
70
+ * return ctx.json({ header })
71
+ * }
72
+ * // 現在:usesHeaders = true, usesQuery = true ✅
73
+ * ```
74
+ *
75
+ * @param handler - 要分析的 handler 函式
76
+ * @returns HandlerAnalysis 分析結果
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const handler = async (ctx) => {
81
+ * const name = ctx.req.query('name')
82
+ * return ctx.json({ name })
83
+ * }
84
+ *
85
+ * const analysis = analyzeHandler(handler)
86
+ * // analysis.usesQuery === true
87
+ * // analysis.usesHeaders === false
88
+ * // analysis.isAsync === true
89
+ *
90
+ * const type = getOptimalContextType(analysis)
91
+ * // type === 'fast'
92
+ * ```
93
+ */
94
+ export declare function analyzeHandler(handler: Function): HandlerAnalysis;
95
+ /**
96
+ * 根據分析結果決定最優化的 Context 類型
97
+ *
98
+ * Context 類型由輕到重:
99
+ * - `minimal`:僅支援路徑參數與靜態回應,零 overhead
100
+ * - `fast`:支援 headers 與 query,使用物件池
101
+ * - `full`:支援完整功能含 body 解析(async)
102
+ *
103
+ * 選擇邏輯(優先順序):
104
+ * 1. 若存取 headers → `fast`(header 設置需要完整支援)
105
+ * 2. 若不存取任何屬性 → `minimal`
106
+ * 3. 若僅存取 params → `minimal`(params 在 minimal 中也可用)
107
+ * 4. 若存取 body → `full`(async body 解析需要完整 context)
108
+ * 5. 其他 → `fast`
109
+ *
110
+ * @param analysis - HandlerAnalysis 分析結果
111
+ * @returns 最優化的 context 類型
112
+ */
113
+ export declare function getOptimalContextType(analysis: HandlerAnalysis): 'minimal' | 'fast' | 'full';
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @fileoverview Engine Constants & Cached Buffers
3
+ *
4
+ * Pre-allocated resources to minimize runtime allocation overhead.
5
+ * Specifically targets Bun's zero-copy capabilities.
6
+ */
7
+ export declare const CACHED_RESPONSES: {
8
+ readonly NOT_FOUND: Uint8Array<ArrayBuffer>;
9
+ readonly INTERNAL_ERROR: Uint8Array<ArrayBuffer>;
10
+ readonly OK: Uint8Array<ArrayBuffer>;
11
+ readonly EMPTY: Uint8Array<ArrayBuffer>;
12
+ };
13
+ export declare const HEADERS: {
14
+ readonly JSON: {
15
+ readonly 'Content-Type': "application/json; charset=utf-8";
16
+ };
17
+ readonly TEXT: {
18
+ readonly 'Content-Type': "text/plain; charset=utf-8";
19
+ };
20
+ readonly HTML: {
21
+ readonly 'Content-Type': "text/html; charset=utf-8";
22
+ };
23
+ };