@gravito/core 1.2.0 → 1.2.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.
package/dist/index.d.cts DELETED
@@ -1,2623 +0,0 @@
1
- import { Variables as GravitoVariables, HttpMethod, Handler as GravitoHandler, MiddlewareHandler as GravitoMiddleware, GravitoErrorHandler, GravitoNotFoundHandler, Context as GravitoContext, ContentfulStatusCode, GravitoRequest, StatusCode } from './compat.cjs';
2
- export { Next as GravitoNext, ValidationTarget } from './compat.cjs';
3
- import { Photon, Context } from '@gravito/photon';
4
-
5
- /**
6
- * @fileoverview HTTP Adapter Interface for Gravito Framework
7
- *
8
- * This module defines the contract that all HTTP adapters must implement.
9
- * By programming to this interface, Gravito can swap out the underlying
10
- * HTTP engine without changing application code.
11
- *
12
- * @module @gravito/core/adapters
13
- * @since 2.0.0
14
- */
15
-
16
- /**
17
- * Configuration options for HTTP adapters
18
- */
19
- interface AdapterConfig {
20
- /**
21
- * Base path prefix for all routes
22
- * @default ''
23
- */
24
- basePath?: string;
25
- /**
26
- * Whether to enable strict routing (trailing slashes matter)
27
- * @default false
28
- */
29
- strictRouting?: boolean;
30
- /**
31
- * Custom options passed to the underlying HTTP engine
32
- */
33
- engineOptions?: Record<string, unknown>;
34
- }
35
- /**
36
- * Route definition structure
37
- */
38
- interface RouteDefinition {
39
- method: HttpMethod;
40
- path: string;
41
- handlers: (GravitoHandler | GravitoMiddleware)[];
42
- name?: string;
43
- middleware?: GravitoMiddleware[];
44
- }
45
- /**
46
- * HttpAdapter - The core interface for HTTP engine abstraction
47
- *
48
- * Any HTTP engine (Photon, Express, Fastify, custom Bun implementation)
49
- * must implement this interface to be usable with Gravito.
50
- *
51
- * @typeParam V - Context variables type
52
- *
53
- * @example
54
- * ```typescript
55
- * // Using the default Photon adapter
56
- * import { PhotonAdapter } from '@gravito/core/adapters'
57
- *
58
- * const core = new PlanetCore({
59
- * adapter: new PhotonAdapter()
60
- * })
61
- *
62
- * // Using a custom adapter
63
- * import { BunNativeAdapter } from '@gravito/adapter-bun'
64
- *
65
- * const core = new PlanetCore({
66
- * adapter: new BunNativeAdapter()
67
- * })
68
- * ```
69
- */
70
- interface HttpAdapter<V extends GravitoVariables = GravitoVariables> {
71
- /**
72
- * Adapter name for identification
73
- * @example 'photon', 'bun-native', 'express'
74
- */
75
- readonly name: string;
76
- /**
77
- * Adapter version
78
- */
79
- readonly version: string;
80
- /**
81
- * Access the underlying native HTTP engine instance.
82
- *
83
- * ⚠️ WARNING: Using this ties your code to a specific adapter.
84
- *
85
- * @example
86
- * ```typescript
87
- * // For Photon adapter
88
- * const photonApp = adapter.native as Photon
89
- *
90
- * // For custom Bun adapter
91
- * const bunApp = adapter.native as BunApp
92
- * ```
93
- */
94
- readonly native: unknown;
95
- /**
96
- * Register a route with the adapter
97
- *
98
- * @param method - HTTP method
99
- * @param path - Route path (may include parameters like ':id')
100
- * @param handlers - One or more handlers for this route (handlers or middleware)
101
- */
102
- route(method: HttpMethod, path: string, ...handlers: (GravitoHandler<V> | GravitoMiddleware<V>)[]): void;
103
- /**
104
- * Register multiple routes at once
105
- *
106
- * @param routes - Array of route definitions
107
- */
108
- routes(routes: RouteDefinition[]): void;
109
- /**
110
- * Register a middleware for a path
111
- *
112
- * @param path - Path pattern to match
113
- * @param middleware - One or more middleware functions
114
- */
115
- use(path: string, ...middleware: GravitoMiddleware<V>[]): void;
116
- /**
117
- * Register a global middleware (applied to all routes)
118
- *
119
- * @param middleware - Middleware function
120
- */
121
- useGlobal(...middleware: GravitoMiddleware<V>[]): void;
122
- /**
123
- * Mount a sub-adapter at a path
124
- *
125
- * @param path - Mount path
126
- * @param subAdapter - The adapter to mount
127
- */
128
- mount(path: string, subAdapter: HttpAdapter<V>): void;
129
- /**
130
- * Set the error handler
131
- *
132
- * @param handler - Error handler function
133
- */
134
- onError(handler: GravitoErrorHandler<V>): void;
135
- /**
136
- * Set the not-found handler
137
- *
138
- * @param handler - Not-found handler function
139
- */
140
- onNotFound(handler: GravitoNotFoundHandler<V>): void;
141
- /**
142
- * The main fetch handler for serving requests.
143
- *
144
- * This is compatible with `Bun.serve()`, Cloudflare Workers,
145
- * and other fetch-based runtimes.
146
- *
147
- * @param request - Incoming HTTP request
148
- * @param server - Optional server context (Bun.Server, etc.)
149
- * @returns HTTP response
150
- *
151
- * @example
152
- * ```typescript
153
- * // With Bun.serve
154
- * Bun.serve({
155
- * port: 3000,
156
- * fetch: adapter.fetch
157
- * })
158
- * ```
159
- */
160
- fetch(request: Request, server?: unknown): Response | Promise<Response>;
161
- /**
162
- * Initialize the adapter
163
- *
164
- * Called during PlanetCore.boot()
165
- */
166
- init?(): void | Promise<void>;
167
- /**
168
- * Cleanup resources
169
- *
170
- * Called during graceful shutdown
171
- */
172
- shutdown?(): void | Promise<void>;
173
- /**
174
- * Create a GravitoContext from a raw request.
175
- *
176
- * This is used internally for testing and advanced scenarios.
177
- *
178
- * @param request - Raw HTTP request
179
- * @returns Gravito context
180
- */
181
- createContext(request: Request): GravitoContext<V>;
182
- }
183
- /**
184
- * Factory function type for creating adapters
185
- */
186
- type AdapterFactory<V extends GravitoVariables = GravitoVariables> = (config?: AdapterConfig) => HttpAdapter<V>;
187
- /**
188
- * Check if a value is an HttpAdapter
189
- */
190
- declare function isHttpAdapter(value: unknown): value is HttpAdapter;
191
-
192
- declare class ConfigManager {
193
- private config;
194
- constructor(initialConfig?: Record<string, unknown>);
195
- /**
196
- * Load all environment variables from the active runtime.
197
- */
198
- private loadEnv;
199
- /**
200
- * Get a configuration value (generic return type supported).
201
- * Supports dot notation for deep access (e.g. 'app.name').
202
- */
203
- get<T = unknown>(key: string, defaultValue?: T): T;
204
- /**
205
- * Set a configuration value.
206
- */
207
- set(key: string, value: unknown): void;
208
- /**
209
- * Check whether a key exists.
210
- */
211
- has(key: string): boolean;
212
- }
213
-
214
- /**
215
- * Factory type for creating service instances
216
- */
217
- type Factory<T> = (container: Container) => T;
218
- declare class Container {
219
- private bindings;
220
- private instances;
221
- /**
222
- * Bind a service to the container.
223
- * New instance will be created on each resolution.
224
- */
225
- bind<T>(key: string, factory: Factory<T>): void;
226
- /**
227
- * Bind a shared service to the container (Singleton).
228
- * Same instance will be returned on each resolution.
229
- */
230
- singleton<T>(key: string, factory: Factory<T>): void;
231
- /**
232
- * Register an existing instance as shared service.
233
- */
234
- instance<T>(key: string, instance: T): void;
235
- /**
236
- * Resolve a service from the container.
237
- */
238
- make<T>(key: string): T;
239
- /**
240
- * Check if a service is bound.
241
- */
242
- has(key: string): boolean;
243
- /**
244
- * Flush all instances and bindings.
245
- */
246
- flush(): void;
247
- /**
248
- * Forget a specific instance (but keep binding)
249
- */
250
- forget(key: string): void;
251
- }
252
-
253
- /**
254
- * Event system type definitions.
255
- */
256
- /**
257
- * Listener interface.
258
- *
259
- * All event listeners must implement this interface.
260
- */
261
- interface Listener<TEvent extends Event = Event> {
262
- /**
263
- * Handle an event.
264
- * @param event - Event instance
265
- */
266
- handle(event: TEvent): Promise<void> | void;
267
- }
268
- /**
269
- * Marker interface for listeners that should be queued.
270
- *
271
- * Listeners implementing this interface can be dispatched asynchronously via a queue.
272
- */
273
- interface ShouldQueue {
274
- /**
275
- * Queue name (optional).
276
- */
277
- queue?: string;
278
- /**
279
- * Connection name (optional).
280
- */
281
- connection?: string;
282
- /**
283
- * Delay before execution (seconds).
284
- */
285
- delay?: number;
286
- }
287
- /**
288
- * Marker interface for events that should be broadcast.
289
- *
290
- * Events implementing this interface can be automatically broadcast to clients.
291
- */
292
- interface ShouldBroadcast {
293
- /**
294
- * Define the broadcast channel.
295
- * @returns Channel name or channel object
296
- */
297
- broadcastOn(): string | Channel;
298
- /**
299
- * Define broadcast payload (optional).
300
- * If omitted, public event properties will be used.
301
- * @returns Broadcast payload
302
- */
303
- broadcastWith?(): Record<string, unknown>;
304
- /**
305
- * Define the broadcast event name (optional).
306
- * If omitted, the event class name will be used.
307
- * @returns Event name
308
- */
309
- broadcastAs?(): string;
310
- }
311
- /**
312
- * Channel interface.
313
- */
314
- interface Channel {
315
- /**
316
- * Channel name.
317
- */
318
- name: string;
319
- /**
320
- * Channel type.
321
- */
322
- type: 'public' | 'private' | 'presence';
323
- }
324
- /**
325
- * Base event class.
326
- *
327
- * All events should extend this class.
328
- */
329
- declare abstract class Event {
330
- /**
331
- * Whether this event should be broadcast.
332
- */
333
- shouldBroadcast(): boolean;
334
- /**
335
- * Get broadcast channel.
336
- */
337
- getBroadcastChannel(): string | Channel | null;
338
- /**
339
- * Get broadcast payload.
340
- */
341
- getBroadcastData(): Record<string, unknown>;
342
- /**
343
- * Get broadcast event name.
344
- */
345
- getBroadcastEventName(): string;
346
- }
347
-
348
- /**
349
- * Listener registration metadata.
350
- */
351
- interface ListenerRegistration<TEvent extends Event = Event> {
352
- listener: Listener<TEvent> | (new () => Listener<TEvent>);
353
- queue?: string;
354
- connection?: string;
355
- delay?: number;
356
- }
357
- /**
358
- * Event manager.
359
- *
360
- * Provides type-safe event dispatching and listener registration.
361
- * Supports both synchronous listeners and asynchronous (queued) listeners.
362
- *
363
- * @example
364
- * ```typescript
365
- * class UserRegistered extends Event {
366
- * constructor(public user: User) {
367
- * super()
368
- * }
369
- * }
370
- *
371
- * class SendWelcomeEmail implements Listener<UserRegistered> {
372
- * async handle(event: UserRegistered): Promise<void> {
373
- * // send welcome email
374
- * }
375
- * }
376
- *
377
- * // Register listener
378
- * core.events.listen(UserRegistered, SendWelcomeEmail)
379
- *
380
- * // Dispatch event
381
- * await core.events.dispatch(new UserRegistered(user))
382
- * ```
383
- */
384
- declare class EventManager {
385
- private core;
386
- /**
387
- * Listener registry.
388
- * Key: event class or event name
389
- * Value: listener registrations
390
- */
391
- private listeners;
392
- /**
393
- * Broadcast manager (optional, injected by `orbit-broadcasting`).
394
- */
395
- private broadcastManager;
396
- /**
397
- * Queue manager (optional, injected by `orbit-queue`).
398
- */
399
- private queueManager;
400
- constructor(core: PlanetCore);
401
- /**
402
- * Register the broadcast manager (called by `orbit-broadcasting`).
403
- */
404
- setBroadcastManager(manager: EventManager['broadcastManager']): void;
405
- /**
406
- * Register the queue manager (called by `orbit-queue`).
407
- */
408
- setQueueManager(manager: EventManager['queueManager']): void;
409
- /**
410
- * Register an event listener.
411
- *
412
- * @param event - Event class or event name
413
- * @param listener - Listener instance or listener class
414
- * @param options - Optional queue options
415
- *
416
- * @example
417
- * ```typescript
418
- * // Synchronous listener
419
- * core.events.listen(UserRegistered, SendWelcomeEmail)
420
- *
421
- * // Queued listener (async)
422
- * core.events.listen(UserRegistered, SendWelcomeEmail, {
423
- * queue: 'emails',
424
- * delay: 60
425
- * })
426
- * ```
427
- */
428
- listen<TEvent extends Event>(event: string | (new (...args: unknown[]) => TEvent), listener: Listener<TEvent> | (new () => Listener<TEvent>), options?: {
429
- queue?: string;
430
- connection?: string;
431
- delay?: number;
432
- }): void;
433
- /**
434
- * Remove an event listener.
435
- *
436
- * @param event - Event class or event name
437
- * @param listener - Listener to remove
438
- */
439
- unlisten<TEvent extends Event>(event: string | (new (...args: unknown[]) => TEvent), listener: Listener<TEvent> | (new () => Listener<TEvent>)): void;
440
- /**
441
- * Dispatch an event.
442
- *
443
- * Runs all registered listeners. If a listener implements `ShouldQueue` or
444
- * has queue options, the listener will be pushed to the queue for async execution.
445
- *
446
- * @param event - Event instance
447
- *
448
- * @example
449
- * ```typescript
450
- * await core.events.dispatch(new UserRegistered(user))
451
- * ```
452
- */
453
- dispatch<TEvent extends Event>(event: TEvent): Promise<void>;
454
- /**
455
- * Serialize an event (for queueing).
456
- */
457
- private serializeEvent;
458
- /**
459
- * Get all registered listeners.
460
- */
461
- getListeners(event?: string | (new () => Event)): ListenerRegistration[];
462
- /**
463
- * Clear all listeners.
464
- */
465
- clear(): void;
466
- }
467
-
468
- /**
469
- * Standard logger interface.
470
- *
471
- * PSR-3 inspired API for easy swapping (e.g., Winston, Pino).
472
- */
473
- interface Logger {
474
- debug(message: string, ...args: unknown[]): void;
475
- info(message: string, ...args: unknown[]): void;
476
- warn(message: string, ...args: unknown[]): void;
477
- error(message: string, ...args: unknown[]): void;
478
- }
479
- /**
480
- * Default console logger implementation.
481
- */
482
- declare class ConsoleLogger implements Logger {
483
- debug(message: string, ...args: unknown[]): void;
484
- info(message: string, ...args: unknown[]): void;
485
- warn(message: string, ...args: unknown[]): void;
486
- error(message: string, ...args: unknown[]): void;
487
- }
488
-
489
- type GlobalProcessErrorKind = 'unhandledRejection' | 'uncaughtException';
490
- type GlobalProcessErrorHandlerContext = {
491
- core?: PlanetCore;
492
- kind: GlobalProcessErrorKind;
493
- error: unknown;
494
- isProduction: boolean;
495
- timestamp: number;
496
- logLevel?: 'error' | 'warn' | 'info' | 'none';
497
- logMessage?: string;
498
- exit?: boolean;
499
- exitCode?: number;
500
- gracePeriodMs?: number;
501
- };
502
- type GlobalErrorHandlersMode = 'log' | 'exit' | 'exitInProduction';
503
- type RegisterGlobalErrorHandlersOptions = {
504
- core?: PlanetCore;
505
- logger?: Logger;
506
- mode?: GlobalErrorHandlersMode;
507
- exitCode?: number;
508
- gracePeriodMs?: number;
509
- };
510
- /**
511
- * Register process-level error handlers (`unhandledRejection` / `uncaughtException`).
512
- *
513
- * - `mode: "log"`: only log/report
514
- * - `mode: "exit"`: report then `process.exit(exitCode)`
515
- * - `mode: "exitInProduction"`: exit only when `NODE_ENV=production` (default)
516
- */
517
- declare function registerGlobalErrorHandlers(options?: RegisterGlobalErrorHandlersOptions): () => void;
518
-
519
- type FilterCallback<T = unknown> = (value: T, ...args: unknown[]) => Promise<T> | T;
520
- type ActionCallback<TArgs = unknown> = (args: TArgs) => Promise<void> | void;
521
- declare class HookManager {
522
- private filters;
523
- private actions;
524
- /**
525
- * Register a filter hook.
526
- *
527
- * Filters are used to transform a value (input/output).
528
- *
529
- * @template T - The type of value being filtered.
530
- * @param hook - The name of the hook.
531
- * @param callback - The callback function to execute.
532
- *
533
- * @example
534
- * ```typescript
535
- * core.hooks.addFilter('content', async (content: string) => {
536
- * return content.toUpperCase();
537
- * });
538
- * ```
539
- */
540
- addFilter<T = unknown>(hook: string, callback: FilterCallback<T>): void;
541
- /**
542
- * Apply all registered filters sequentially.
543
- *
544
- * Each callback receives the previous callback's return value.
545
- *
546
- * @template T - The type of value being filtered.
547
- * @param hook - The name of the hook.
548
- * @param initialValue - The initial value to filter.
549
- * @param args - Additional arguments to pass to the callbacks.
550
- * @returns The final filtered value.
551
- *
552
- * @example
553
- * ```typescript
554
- * const content = await core.hooks.applyFilters('content', 'hello world');
555
- * ```
556
- */
557
- applyFilters<T = unknown>(hook: string, initialValue: T, ...args: unknown[]): Promise<T>;
558
- /**
559
- * Register an action hook.
560
- *
561
- * Actions are for side effects (no return value).
562
- *
563
- * @template TArgs - The type of arguments passed to the action.
564
- * @param hook - The name of the hook.
565
- * @param callback - The callback function to execute.
566
- *
567
- * @example
568
- * ```typescript
569
- * core.hooks.addAction('user_registered', async (user: User) => {
570
- * await sendWelcomeEmail(user);
571
- * });
572
- * ```
573
- */
574
- addAction<TArgs = unknown>(hook: string, callback: ActionCallback<TArgs>): void;
575
- /**
576
- * Run all registered actions sequentially.
577
- *
578
- * @template TArgs - The type of arguments passed to the action.
579
- * @param hook - The name of the hook.
580
- * @param args - The arguments to pass to the callbacks.
581
- *
582
- * @example
583
- * ```typescript
584
- * await core.hooks.doAction('user_registered', user);
585
- * ```
586
- */
587
- doAction<TArgs = unknown>(hook: string, args: TArgs): Promise<void>;
588
- }
589
-
590
- type ApiSuccess<T> = {
591
- success: true;
592
- data: T;
593
- };
594
- type ApiFailure = {
595
- success: false;
596
- error: {
597
- message: string;
598
- code?: string;
599
- details?: unknown;
600
- };
601
- };
602
- declare function ok<T>(data: T): ApiSuccess<T>;
603
- declare function fail(message: string, code?: string, details?: unknown): ApiFailure;
604
- declare function jsonSuccess<T>(c: GravitoContext, data: T, status?: ContentfulStatusCode): Response;
605
- declare function jsonFail(c: GravitoContext, message: string, status?: ContentfulStatusCode, code?: string, details?: unknown): Response;
606
-
607
- /**
608
- * ServiceProvider - The foundation for modular service registration.
609
- *
610
- * Service providers are the central place to configure your application.
611
- * They bind services to the container and bootstrap application features.
612
- *
613
- * Lifecycle:
614
- * 1. register() - Called during registration phase (sync or async)
615
- * 2. boot() - Called after ALL providers have registered
616
- *
617
- * @since 1.0.0
618
- * @example
619
- * ```typescript
620
- * class DatabaseServiceProvider extends ServiceProvider {
621
- * register(container: Container) {
622
- * container.singleton('db', () => new DatabaseManager());
623
- * }
624
- *
625
- * boot(core: PlanetCore) {
626
- * const db = core.container.make<DatabaseManager>('db');
627
- * db.setDefaultConnection(core.config.get('database.default'));
628
- * }
629
- * }
630
- * ```
631
- */
632
- declare abstract class ServiceProvider {
633
- /**
634
- * Reference to the application core instance.
635
- * Set during provider registration.
636
- */
637
- protected core?: PlanetCore;
638
- /**
639
- * Whether this provider should be deferred.
640
- * Deferred providers are only registered when one of their
641
- * provided services is actually requested from the container.
642
- */
643
- deferred: boolean;
644
- /**
645
- * Get the services provided by this provider.
646
- * Used for deferred loading - provider is only loaded when
647
- * one of these services is requested.
648
- *
649
- * @returns Array of service keys this provider offers
650
- *
651
- * @example
652
- * ```typescript
653
- * provides(): string[] {
654
- * return ['db', 'db.connection'];
655
- * }
656
- * ```
657
- */
658
- provides(): string[];
659
- /**
660
- * Register bindings in the container.
661
- *
662
- * This method is called during the registration phase.
663
- * **Warning**: Do not resolve services from other providers here,
664
- * as they may not be registered yet.
665
- *
666
- * Supports both synchronous and asynchronous registration.
667
- *
668
- * @param container - The IoC container instance
669
- */
670
- abstract register(container: Container): void | Promise<void>;
671
- /**
672
- * Bootstrap any application services.
673
- *
674
- * This method is called after ALL providers have registered.
675
- * You can safely resolve services from the container here.
676
- *
677
- * @param core - The PlanetCore application instance
678
- */
679
- boot?(core: PlanetCore): void | Promise<void>;
680
- /**
681
- * Set the core instance reference.
682
- * Called internally by the application during registration.
683
- *
684
- * @internal
685
- */
686
- setCore(core: PlanetCore): void;
687
- /**
688
- * Merge configuration from a file into the application config.
689
- *
690
- * @param config - The ConfigManager instance
691
- * @param key - The configuration key to set
692
- * @param value - The configuration value or object
693
- *
694
- * @example
695
- * ```typescript
696
- * this.mergeConfig(config, 'database', {
697
- * default: 'mysql',
698
- * connections: { ... }
699
- * });
700
- * ```
701
- */
702
- protected mergeConfig(config: ConfigManager, key: string, value: unknown): void;
703
- /**
704
- * Merge configuration from an async loader.
705
- * Useful for loading config from .ts files dynamically.
706
- *
707
- * @param config - The ConfigManager instance
708
- * @param key - The configuration key
709
- * @param loader - Async function that returns config value
710
- *
711
- * @example
712
- * ```typescript
713
- * await this.mergeConfigFrom(config, 'database', async () => {
714
- * return (await import('./config/database')).default;
715
- * });
716
- * ```
717
- */
718
- protected mergeConfigFrom(config: ConfigManager, key: string, loader: () => Promise<unknown>): Promise<void>;
719
- /**
720
- * Paths that should be published by the CLI.
721
- * Maps source paths to destination paths.
722
- */
723
- private static publishables;
724
- /**
725
- * Register paths to be published.
726
- * Used by CLI commands like `gravito vendor:publish`.
727
- *
728
- * @param paths - Map of source to destination paths
729
- * @param group - Optional group name for selective publishing
730
- *
731
- * @example
732
- * ```typescript
733
- * this.publishes({
734
- * './config/cache.ts': 'config/cache.ts',
735
- * './views/errors': 'resources/views/errors'
736
- * }, 'config');
737
- * ```
738
- */
739
- protected publishes(paths: Record<string, string>, group?: string): void;
740
- /**
741
- * Get all publishable paths for a group.
742
- *
743
- * @param group - The group name (defaults to provider class name)
744
- * @returns Map of source to destination paths
745
- */
746
- static getPublishables(group?: string): Map<string, string>;
747
- /**
748
- * Get all publish groups.
749
- *
750
- * @returns Array of group names
751
- */
752
- static getPublishGroups(): string[];
753
- }
754
-
755
- declare class Route {
756
- private router;
757
- private method;
758
- private path;
759
- private options;
760
- constructor(router: Router, method: string, path: string, options: RouteOptions);
761
- /**
762
- * Name the route
763
- */
764
- name(name: string): this;
765
- static get(path: string, handler: RouteHandler): Route;
766
- static get(path: string, request: FormRequestClass, handler: RouteHandler): Route;
767
- static get(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
768
- static post(path: string, handler: RouteHandler): Route;
769
- static post(path: string, request: FormRequestClass, handler: RouteHandler): Route;
770
- static post(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
771
- static put(path: string, handler: RouteHandler): Route;
772
- static put(path: string, request: FormRequestClass, handler: RouteHandler): Route;
773
- static put(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
774
- static delete(path: string, handler: RouteHandler): Route;
775
- static delete(path: string, request: FormRequestClass, handler: RouteHandler): Route;
776
- static delete(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
777
- static patch(path: string, handler: RouteHandler): Route;
778
- static patch(path: string, request: FormRequestClass, handler: RouteHandler): Route;
779
- static patch(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
780
- static resource(name: string, controller: ControllerClass, options?: ResourceOptions): void;
781
- static prefix(path: string): RouteGroup;
782
- static middleware(...handlers: any[]): RouteGroup;
783
- }
784
-
785
- type ControllerClass = new (core: PlanetCore) => Record<string, unknown>;
786
- type RouteHandler = GravitoHandler | [ControllerClass, string];
787
- /**
788
- * Interface for FormRequest classes (from @gravito/impulse).
789
- * Used for duck-typing detection without hard dependency.
790
- */
791
- interface FormRequestLike {
792
- schema: unknown;
793
- source?: string;
794
- validate?(ctx: unknown): Promise<{
795
- success: boolean;
796
- data?: unknown;
797
- error?: unknown;
798
- }>;
799
- }
800
- /**
801
- * Type for FormRequest class constructor
802
- */
803
- type FormRequestClass = new () => FormRequestLike;
804
- interface RouteOptions {
805
- prefix?: string;
806
- domain?: string;
807
- middleware?: GravitoMiddleware[];
808
- }
809
- /**
810
- * RouteGroup
811
- * Helper class for chained route configuration (prefix, domain, etc.)
812
- */
813
- declare class RouteGroup {
814
- private router;
815
- private options;
816
- constructor(router: Router, options: RouteOptions);
817
- /**
818
- * Add a prefix to the current group
819
- */
820
- prefix(path: string): RouteGroup;
821
- /**
822
- * Add middleware to the current group.
823
- * Accepts individual handlers or arrays of handlers.
824
- */
825
- middleware(...handlers: (GravitoMiddleware | GravitoMiddleware[])[]): RouteGroup;
826
- /**
827
- * Define routes within this group
828
- */
829
- group(callback: (router: Router | RouteGroup) => void): void;
830
- get(path: string, handler: RouteHandler): Route;
831
- get(path: string, request: FormRequestClass, handler: RouteHandler): Route;
832
- get(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
833
- post(path: string, handler: RouteHandler): Route;
834
- post(path: string, request: FormRequestClass, handler: RouteHandler): Route;
835
- post(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
836
- put(path: string, handler: RouteHandler): Route;
837
- put(path: string, request: FormRequestClass, handler: RouteHandler): Route;
838
- put(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
839
- delete(path: string, handler: RouteHandler): Route;
840
- delete(path: string, request: FormRequestClass, handler: RouteHandler): Route;
841
- delete(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
842
- patch(path: string, handler: RouteHandler): Route;
843
- patch(path: string, request: FormRequestClass, handler: RouteHandler): Route;
844
- patch(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
845
- resource(name: string, controller: ControllerClass, options?: ResourceOptions): void;
846
- }
847
- /**
848
- * Gravito Router
849
- *
850
- * Provides a Laravel-like fluent API for defining routes.
851
- * Supports:
852
- * - Controller-based routing: router.get('/', [HomeController, 'index'])
853
- * - Route groups with prefixes: router.prefix('/api').group(...)
854
- * - Domain-based routing: router.domain('api.app').group(...)
855
- * - Middleware chaining: router.middleware(auth).group(...)
856
- * - FormRequest validation: router.post('/users', StoreUserRequest, [UserController, 'store'])
857
- * - Inline Middleware: router.get('/users', authMiddleware, [UserController, 'index'])
858
- */
859
- declare class Router {
860
- private core;
861
- routes: Array<{
862
- method: string;
863
- path: string;
864
- }>;
865
- private controllers;
866
- private namedRoutes;
867
- private bindings;
868
- /**
869
- * Compile all registered routes into a flat array for caching or manifest generation.
870
- */
871
- compile(): {
872
- method: string;
873
- path: string;
874
- name?: string;
875
- domain?: string | undefined;
876
- }[];
877
- /**
878
- * Register a named route
879
- */
880
- registerName(name: string, method: string, path: string, options?: RouteOptions): void;
881
- /**
882
- * Generate a URL from a named route.
883
- */
884
- url(name: string, params?: Record<string, string | number>, query?: Record<string, string | number | boolean | null | undefined>): string;
885
- /**
886
- * Export named routes as a serializable manifest (for caching).
887
- */
888
- exportNamedRoutes(): Record<string, {
889
- method: string;
890
- path: string;
891
- domain?: string;
892
- }>;
893
- /**
894
- * Load named routes from a manifest (for caching).
895
- */
896
- loadNamedRoutes(manifest: Record<string, {
897
- method: string;
898
- path: string;
899
- domain?: string;
900
- }>): void;
901
- /**
902
- * Register a route model binding.
903
- */
904
- bind(param: string, resolver: (id: string) => Promise<unknown>): void;
905
- /**
906
- * Register a route model binding for a Model class.
907
- */
908
- model(param: string, modelClass: unknown): void;
909
- constructor(core: PlanetCore);
910
- /**
911
- * Start a route group with a prefix
912
- */
913
- prefix(path: string): RouteGroup;
914
- /**
915
- * Start a route group with a domain constraint
916
- */
917
- domain(host: string): RouteGroup;
918
- /**
919
- * Start a route group with middleware.
920
- * Accepts individual handlers or arrays of handlers.
921
- */
922
- middleware(...handlers: (GravitoMiddleware | GravitoMiddleware[])[]): RouteGroup;
923
- /**
924
- * Register a GET route.
925
- */
926
- get(path: string, handler: RouteHandler): Route;
927
- get(path: string, request: FormRequestClass, handler: RouteHandler): Route;
928
- get(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
929
- /**
930
- * Register a POST route.
931
- */
932
- post(path: string, handler: RouteHandler): Route;
933
- post(path: string, request: FormRequestClass, handler: RouteHandler): Route;
934
- post(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
935
- /**
936
- * Register a PUT route.
937
- */
938
- put(path: string, handler: RouteHandler): Route;
939
- put(path: string, request: FormRequestClass, handler: RouteHandler): Route;
940
- put(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
941
- /**
942
- * Register a DELETE route.
943
- */
944
- delete(path: string, handler: RouteHandler): Route;
945
- delete(path: string, request: FormRequestClass, handler: RouteHandler): Route;
946
- delete(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
947
- /**
948
- * Register a PATCH route.
949
- */
950
- patch(path: string, handler: RouteHandler): Route;
951
- patch(path: string, request: FormRequestClass, handler: RouteHandler): Route;
952
- patch(path: string, middleware: GravitoMiddleware | GravitoMiddleware[], handler: RouteHandler): Route;
953
- /**
954
- * Register a resource route (Laravel-style).
955
- */
956
- resource(name: string, controller: ControllerClass, options?: ResourceOptions): void;
957
- /**
958
- * Internal Request Registration
959
- */
960
- req(method: HttpMethod, path: string, requestOrHandlerOrMiddleware: FormRequestClass | RouteHandler | GravitoMiddleware | GravitoMiddleware[], handler?: RouteHandler, options?: RouteOptions): Route;
961
- /**
962
- * Resolve Controller Instance and Method
963
- */
964
- private resolveControllerHandler;
965
- }
966
- type ResourceAction = 'index' | 'create' | 'store' | 'show' | 'edit' | 'update' | 'destroy';
967
- interface ResourceOptions {
968
- only?: ResourceAction[];
969
- except?: ResourceAction[];
970
- }
971
-
972
- interface EncrypterOptions {
973
- key: string;
974
- cipher?: string;
975
- }
976
- declare class Encrypter {
977
- private algorithm;
978
- private key;
979
- constructor(options: EncrypterOptions);
980
- /**
981
- * Encrypt a value
982
- */
983
- encrypt(value: unknown, serialize?: boolean): string;
984
- /**
985
- * Decrypt a value
986
- */
987
- decrypt(payload: string, deserialize?: boolean): unknown;
988
- private hash;
989
- private validPayload;
990
- private validMac;
991
- /**
992
- * Generate a new key
993
- */
994
- static generateKey(cipher?: string): string;
995
- }
996
-
997
- /**
998
- * Hashing interface
999
- */
1000
- interface Hasher {
1001
- /**
1002
- * Hash the given value
1003
- */
1004
- make(value: string, options?: Record<string, unknown>): Promise<string>;
1005
- /**
1006
- * Check the given plain value against a hash
1007
- */
1008
- check(value: string, hashedValue: string): Promise<boolean>;
1009
- /**
1010
- * Check if the given hash has been hashed using the given options
1011
- */
1012
- needsRehash(hashedValue: string, options?: Record<string, unknown>): boolean;
1013
- }
1014
- /**
1015
- * Bun Hasher
1016
- * Uses Bun's native password hashing (bcrypt by default)
1017
- */
1018
- declare class BunHasher implements Hasher {
1019
- make(value: string, options?: {
1020
- algorithm?: 'bcrypt' | 'argon2id';
1021
- cost?: number;
1022
- }): Promise<string>;
1023
- check(value: string, hashedValue: string): Promise<boolean>;
1024
- needsRehash(_hashedValue: string, _options?: Record<string, unknown>): boolean;
1025
- }
1026
-
1027
- /**
1028
- * @fileoverview PlanetCore - The Heart of Gravito Framework
1029
- *
1030
- * The micro-kernel that orchestrates the entire Galaxy Architecture.
1031
- * Manages HTTP routing, middleware, error handling, and orbit integration.
1032
- *
1033
- * @module @gravito/core
1034
- * @since 1.0.0
1035
- */
1036
-
1037
- /**
1038
- * CacheService interface for orbit-injected cache
1039
- * Orbits implementing cache should conform to this interface
1040
- */
1041
- interface CacheService {
1042
- get<T = unknown>(key: string): Promise<T | null>;
1043
- set(key: string, value: unknown, ttl?: number): Promise<void>;
1044
- delete(key: string): Promise<void>;
1045
- clear(): Promise<void>;
1046
- remember<T>(key: string, ttl: number, callback: () => Promise<T>): Promise<T>;
1047
- }
1048
- interface ViewService {
1049
- render(view: string, data?: Record<string, unknown>, options?: Record<string, unknown>): string;
1050
- }
1051
- type ErrorHandlerContext = {
1052
- core: PlanetCore;
1053
- c: GravitoContext;
1054
- error: unknown;
1055
- isProduction: boolean;
1056
- accept: string;
1057
- wantsHtml: boolean;
1058
- status: ContentfulStatusCode;
1059
- payload: ReturnType<typeof fail>;
1060
- logLevel?: 'error' | 'warn' | 'info' | 'none';
1061
- logMessage?: string;
1062
- html?: {
1063
- templates: string[];
1064
- data: Record<string, unknown>;
1065
- };
1066
- };
1067
- interface GravitoOrbit {
1068
- install(core: PlanetCore): void | Promise<void>;
1069
- }
1070
- type GravitoConfig = {
1071
- logger?: Logger;
1072
- config?: Record<string, unknown>;
1073
- orbits?: (new () => GravitoOrbit)[] | GravitoOrbit[];
1074
- /**
1075
- * HTTP Adapter to use. Defaults to PhotonAdapter.
1076
- * @since 2.0.0
1077
- */
1078
- adapter?: HttpAdapter;
1079
- };
1080
-
1081
- declare class PlanetCore {
1082
- /**
1083
- * The HTTP adapter used by this core instance.
1084
- * @since 2.0.0
1085
- */
1086
- private _adapter;
1087
- /**
1088
- * Access the underlying Photon app instance.
1089
- * @deprecated Use adapter methods for new code. This property is kept for backward compatibility.
1090
- */
1091
- get app(): unknown;
1092
- /**
1093
- * Get the HTTP adapter instance.
1094
- * @since 2.0.0
1095
- */
1096
- get adapter(): HttpAdapter;
1097
- logger: Logger;
1098
- config: ConfigManager;
1099
- hooks: HookManager;
1100
- events: EventManager;
1101
- router: Router;
1102
- container: Container;
1103
- /** @deprecated Use core.container instead */
1104
- services: Map<string, unknown>;
1105
- encrypter?: Encrypter;
1106
- hasher: BunHasher;
1107
- private providers;
1108
- private deferredProviders;
1109
- private bootedProviders;
1110
- /**
1111
- * Register a service provider.
1112
- *
1113
- * @param provider - The ServiceProvider instance to register.
1114
- * @returns The PlanetCore instance for chaining.
1115
- *
1116
- * @example
1117
- * ```typescript
1118
- * core.register(new DatabaseServiceProvider());
1119
- * ```
1120
- */
1121
- register(provider: ServiceProvider): this;
1122
- /**
1123
- * Bootstrap the application by registering and booting providers.
1124
- *
1125
- * This method must be called before the application starts handling requests.
1126
- * It calls `register()` on all providers first, then `boot()` on all providers.
1127
- *
1128
- * Supports async register() methods.
1129
- *
1130
- * @returns Promise that resolves when bootstrapping is complete.
1131
- */
1132
- bootstrap(): Promise<void>;
1133
- /**
1134
- * Setup deferred provider resolution.
1135
- * Wraps container.make to auto-register deferred providers on first request.
1136
- *
1137
- * @internal
1138
- */
1139
- private setupDeferredProviderResolution;
1140
- /**
1141
- * Register a deferred provider on-demand.
1142
- *
1143
- * @internal
1144
- */
1145
- private registerDeferredProvider;
1146
- /**
1147
- * Boot a single provider if not already booted.
1148
- *
1149
- * @internal
1150
- */
1151
- private bootProvider;
1152
- constructor(options?: {
1153
- logger?: Logger;
1154
- config?: Record<string, unknown>;
1155
- adapter?: HttpAdapter;
1156
- });
1157
- /**
1158
- * Programmatically register an infrastructure module (Orbit).
1159
- * @since 2.0.0
1160
- *
1161
- * @param orbit - The orbit class or instance to register.
1162
- * @returns The PlanetCore instance for chaining.
1163
- *
1164
- * @example
1165
- * ```typescript
1166
- * await core.orbit(OrbitCache);
1167
- * ```
1168
- */
1169
- orbit(orbit: GravitoOrbit | (new () => GravitoOrbit)): Promise<this>;
1170
- /**
1171
- * Programmatically register a feature module (Satellite).
1172
- * Alias for register() with provider support.
1173
- * @since 2.0.0
1174
- *
1175
- * @param satellite - The provider or setup function.
1176
- * @returns The PlanetCore instance for chaining.
1177
- *
1178
- * @example
1179
- * ```typescript
1180
- * await core.use(new AuthProvider());
1181
- * ```
1182
- */
1183
- use(satellite: ServiceProvider | ((core: PlanetCore) => void | Promise<void>)): Promise<this>;
1184
- registerGlobalErrorHandlers(options?: Omit<RegisterGlobalErrorHandlersOptions, 'core'>): () => void;
1185
- /**
1186
- * Boot the application with a configuration object (IoC style default entry)
1187
- *
1188
- * @param config - The Gravito configuration object.
1189
- * @returns A Promise resolving to the booted PlanetCore instance.
1190
- *
1191
- * @example
1192
- * ```typescript
1193
- * const core = await PlanetCore.boot(config);
1194
- * ```
1195
- */
1196
- static boot(config: GravitoConfig): Promise<PlanetCore>;
1197
- /**
1198
- * Mount an Orbit (a Photon app) to a path.
1199
- *
1200
- * @param path - The URL path to mount the orbit at.
1201
- * @param orbitApp - The Photon application instance.
1202
- */
1203
- mountOrbit(path: string, orbitApp: unknown): void;
1204
- /**
1205
- * Start the core (Liftoff).
1206
- *
1207
- * Returns a config object for `Bun.serve`.
1208
- *
1209
- * @param port - Optional port number (defaults to config or 3000).
1210
- * @returns An object compatible with Bun.serve({ ... }).
1211
- *
1212
- * @example
1213
- * ```typescript
1214
- * export default core.liftoff(3000);
1215
- * ```
1216
- */
1217
- liftoff(port?: number): {
1218
- port: number;
1219
- fetch: (request: Request, server?: unknown) => Response | Promise<Response>;
1220
- core: PlanetCore;
1221
- };
1222
- }
1223
-
1224
- /**
1225
- * @fileoverview Photon Adapter Implementation
1226
- *
1227
- * This adapter wraps Photon to implement the Gravito HttpAdapter interface.
1228
- * It serves as the default adapter and reference implementation for others.
1229
- *
1230
- * @module @gravito/core/adapters/photon
1231
- * @since 2.0.0
1232
- */
1233
-
1234
- /**
1235
- * Wraps Photon's request object to implement GravitoRequest
1236
- */
1237
- declare class PhotonRequestWrapper implements GravitoRequest {
1238
- readonly photonCtx: Context;
1239
- constructor(photonCtx: Context);
1240
- /**
1241
- * Create a proxied instance to delegate to Photon's request
1242
- */
1243
- static create(photonCtx: Context): PhotonRequestWrapper;
1244
- get url(): string;
1245
- get method(): string;
1246
- get path(): string;
1247
- param(name: string): string | undefined;
1248
- params(): Record<string, string>;
1249
- query(name: string): string | undefined;
1250
- queries(): Record<string, string | string[]>;
1251
- header(name: string): string | undefined;
1252
- header(): Record<string, string>;
1253
- json<T = unknown>(): Promise<T>;
1254
- text(): Promise<string>;
1255
- formData(): Promise<FormData>;
1256
- arrayBuffer(): Promise<ArrayBuffer>;
1257
- parseBody<T = unknown>(): Promise<T>;
1258
- get raw(): Request;
1259
- valid<T = unknown>(target: string): T;
1260
- }
1261
- /**
1262
- * Wraps Photon's context to implement GravitoContext
1263
- */
1264
- declare class PhotonContextWrapper<V extends GravitoVariables = GravitoVariables> implements GravitoContext<V> {
1265
- private photonCtx;
1266
- private _req;
1267
- constructor(photonCtx: Context);
1268
- /**
1269
- * Create a proxied instance to enable object destructuring of context variables
1270
- * This allows: async list({ userService }: Context)
1271
- */
1272
- static create<V extends GravitoVariables = GravitoVariables>(photonCtx: Context): GravitoContext<V>;
1273
- get req(): GravitoRequest;
1274
- json<T>(data: T, status?: number): Response;
1275
- text(text: string, status?: number): Response;
1276
- html(html: string, status?: number): Response;
1277
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
1278
- body(data: BodyInit | null, status?: number): Response;
1279
- stream(stream: ReadableStream, status?: number): Response;
1280
- notFound(message?: string): Response;
1281
- forbidden(message?: string): Response;
1282
- unauthorized(message?: string): Response;
1283
- badRequest(message?: string): Response;
1284
- header(name: string): string | undefined;
1285
- header(name: string, value: string, options?: {
1286
- append?: boolean;
1287
- }): void;
1288
- status(code: StatusCode): void;
1289
- get<K extends keyof V>(key: K): V[K];
1290
- set<K extends keyof V>(key: K, value: V[K]): void;
1291
- get executionCtx(): ExecutionContext | undefined;
1292
- get env(): Record<string, unknown> | undefined;
1293
- get native(): Context;
1294
- }
1295
- /**
1296
- * Default HTTP adapter using the optimized Gravito Core Engine.
1297
- *
1298
- * This adapter provides a consistent interface that can be
1299
- * swapped out for other implementations without changing application code.
1300
- *
1301
- * @example
1302
- * ```typescript
1303
- * import { GravitoAdapter } from '@gravito/core'
1304
- *
1305
- * const adapter = new GravitoAdapter()
1306
- *
1307
- * // Register routes
1308
- * adapter.route('get', '/hello', async (ctx) => {
1309
- * return ctx.json({ message: 'Hello, World!' })
1310
- * })
1311
- * ```
1312
- */
1313
- declare class PhotonAdapter<V extends GravitoVariables = GravitoVariables> implements HttpAdapter<V> {
1314
- private config;
1315
- readonly name = "photon";
1316
- readonly version = "1.0.0";
1317
- private app;
1318
- constructor(config?: AdapterConfig, photonInstance?: unknown);
1319
- /**
1320
- * Get the underlying Photon app instance
1321
- */
1322
- get native(): Photon;
1323
- /**
1324
- * Set the underlying Photon app instance
1325
- * Used by PlanetCore during initialization
1326
- */
1327
- setNative(app: Photon): void;
1328
- route(method: HttpMethod, path: string, ...handlers: (GravitoHandler<V> | GravitoMiddleware<V>)[]): void;
1329
- routes(routes: RouteDefinition[]): void;
1330
- use(path: string, ...middleware: GravitoMiddleware<V>[]): void;
1331
- useGlobal(...middleware: GravitoMiddleware<V>[]): void;
1332
- mount(path: string, subAdapter: HttpAdapter<V>): void;
1333
- onError(handler: GravitoErrorHandler<V>): void;
1334
- onNotFound(handler: GravitoNotFoundHandler<V>): void;
1335
- fetch: (request: Request, server?: unknown) => Response | Promise<Response>;
1336
- createContext(_request: Request): GravitoContext<V>;
1337
- init(): Promise<void>;
1338
- shutdown(): Promise<void>;
1339
- }
1340
- /**
1341
- * Create a new PhotonAdapter instance
1342
- */
1343
- declare function createPhotonAdapter<V extends GravitoVariables = GravitoVariables>(config?: AdapterConfig): PhotonAdapter<V>;
1344
-
1345
- /**
1346
- * Rebranded alias for PhotonAdapter.
1347
- * @category Rebranding
1348
- */
1349
- declare const GravitoAdapter: typeof PhotonAdapter;
1350
- type GravitoAdapter<V extends GravitoVariables = GravitoVariables> = PhotonAdapter<V>;
1351
- /**
1352
- * Rebranded alias for createPhotonAdapter.
1353
- * @category Rebranding
1354
- */
1355
- declare const createGravitoAdapter: typeof createPhotonAdapter;
1356
-
1357
- /**
1358
- * @fileoverview Application - Enterprise Application Container
1359
- *
1360
- * A high-level application class that orchestrates the entire framework.
1361
- * Provides a centralized entry point for enterprise applications with
1362
- * auto-discovery of providers, config loading, and lifecycle management.
1363
- *
1364
- * @module @gravito/core
1365
- * @since 2.0.0
1366
- */
1367
-
1368
- interface ApplicationConfig {
1369
- /**
1370
- * Base path of the application
1371
- */
1372
- basePath: string;
1373
- /**
1374
- * Path to the config directory (relative to basePath)
1375
- * @default 'config'
1376
- */
1377
- configPath?: string;
1378
- /**
1379
- * Path to the providers directory (relative to basePath)
1380
- * @default 'src/Providers'
1381
- */
1382
- providersPath?: string;
1383
- /**
1384
- * Environment (development, production, testing)
1385
- */
1386
- env?: 'development' | 'production' | 'testing';
1387
- /**
1388
- * Logger instance
1389
- */
1390
- logger?: Logger;
1391
- /**
1392
- * Initial configuration values
1393
- */
1394
- config?: Record<string, unknown>;
1395
- /**
1396
- * Service providers to register
1397
- */
1398
- providers?: ServiceProvider[];
1399
- /**
1400
- * Whether to auto-discover providers from providersPath
1401
- * @default true
1402
- */
1403
- autoDiscoverProviders?: boolean;
1404
- }
1405
- /**
1406
- * Application - Enterprise-grade application container.
1407
- *
1408
- * Provides a higher-level abstraction over PlanetCore for building
1409
- * enterprise applications with convention-over-configuration patterns.
1410
- *
1411
- * @example
1412
- * ```typescript
1413
- * // Create application
1414
- * const app = new Application({
1415
- * basePath: import.meta.dir,
1416
- * env: process.env.NODE_ENV as 'development' | 'production',
1417
- * });
1418
- *
1419
- * // Boot the application
1420
- * await app.boot();
1421
- *
1422
- * // Access core
1423
- * export default app.core.liftoff();
1424
- * ```
1425
- */
1426
- declare class Application {
1427
- /**
1428
- * The underlying PlanetCore instance.
1429
- */
1430
- readonly core: PlanetCore;
1431
- /**
1432
- * The IoC container.
1433
- */
1434
- readonly container: Container;
1435
- /**
1436
- * The configuration manager.
1437
- */
1438
- readonly config: ConfigManager;
1439
- /**
1440
- * The event manager.
1441
- */
1442
- readonly events: EventManager;
1443
- /**
1444
- * The logger instance.
1445
- */
1446
- readonly logger: Logger;
1447
- /**
1448
- * Application base path.
1449
- */
1450
- readonly basePath: string;
1451
- /**
1452
- * Environment mode.
1453
- */
1454
- readonly env: 'development' | 'production' | 'testing';
1455
- /**
1456
- * Configuration options.
1457
- */
1458
- private readonly options;
1459
- /**
1460
- * Whether the application has been booted.
1461
- */
1462
- private booted;
1463
- constructor(options: ApplicationConfig);
1464
- /**
1465
- * Boot the application.
1466
- *
1467
- * This will:
1468
- * 1. Load configuration files
1469
- * 2. Auto-discover providers (if enabled)
1470
- * 3. Register all providers
1471
- * 4. Bootstrap the core
1472
- *
1473
- * @returns Promise that resolves when boot is complete
1474
- */
1475
- boot(): Promise<this>;
1476
- /**
1477
- * Load configuration files from the config directory.
1478
- *
1479
- * @internal
1480
- */
1481
- private loadConfiguration;
1482
- /**
1483
- * Discover and register providers from the providers directory.
1484
- *
1485
- * @internal
1486
- */
1487
- private discoverProviders;
1488
- /**
1489
- * Get a service from the container.
1490
- *
1491
- * @param key - The service key
1492
- * @returns The resolved service
1493
- */
1494
- make<T>(key: string): T;
1495
- /**
1496
- * Check if a service is bound.
1497
- *
1498
- * @param key - The service key
1499
- * @returns True if bound
1500
- */
1501
- has(key: string): boolean;
1502
- /**
1503
- * Get a configuration value.
1504
- *
1505
- * @param key - The config key (supports dot notation)
1506
- * @param defaultValue - Default value if not found
1507
- * @returns The config value
1508
- */
1509
- getConfig<T>(key: string, defaultValue?: T): T;
1510
- /**
1511
- * Create application path helper.
1512
- *
1513
- * @param segments - Path segments relative to base path
1514
- * @returns Absolute path
1515
- */
1516
- path(...segments: string[]): string;
1517
- /**
1518
- * Get the config path.
1519
- *
1520
- * @param segments - Additional path segments
1521
- * @returns Absolute path to config directory
1522
- */
1523
- configPath(...segments: string[]): string;
1524
- /**
1525
- * Check if running in production.
1526
- */
1527
- isProduction(): boolean;
1528
- /**
1529
- * Check if running in development.
1530
- */
1531
- isDevelopment(): boolean;
1532
- /**
1533
- * Check if running in testing.
1534
- */
1535
- isTesting(): boolean;
1536
- }
1537
-
1538
- interface ExceptionOptions {
1539
- message?: string;
1540
- cause?: unknown;
1541
- i18nKey?: string;
1542
- i18nParams?: Record<string, string | number>;
1543
- }
1544
- declare abstract class GravitoException extends Error {
1545
- readonly status: ContentfulStatusCode;
1546
- readonly code: string;
1547
- readonly i18nKey?: string;
1548
- readonly i18nParams?: Record<string, string | number>;
1549
- constructor(status: number, code: string, options?: ExceptionOptions);
1550
- getLocalizedMessage(t: (key: string, params?: Record<string, string | number>) => string): string;
1551
- }
1552
-
1553
- declare class AuthenticationException extends GravitoException {
1554
- constructor(message?: string);
1555
- }
1556
-
1557
- declare class AuthorizationException extends GravitoException {
1558
- constructor(message?: string);
1559
- }
1560
-
1561
- declare class HttpException extends GravitoException {
1562
- constructor(status: ContentfulStatusCode, options?: ExceptionOptions);
1563
- }
1564
-
1565
- declare class ModelNotFoundException extends GravitoException {
1566
- readonly model: string;
1567
- readonly id?: string | number;
1568
- constructor(model: string, id?: string | number);
1569
- }
1570
-
1571
- interface ValidationError {
1572
- field: string;
1573
- message: string;
1574
- code?: string;
1575
- }
1576
- declare class ValidationException extends GravitoException {
1577
- readonly errors: ValidationError[];
1578
- redirectTo?: string;
1579
- input?: unknown;
1580
- constructor(errors: ValidationError[], message?: string);
1581
- withRedirect(url: string): this;
1582
- withInput(input: unknown): this;
1583
- }
1584
-
1585
- interface GravitoManifest {
1586
- name: string;
1587
- version?: string;
1588
- modules: string[];
1589
- config?: GravitoConfig;
1590
- }
1591
- type ModuleResolver = () => Promise<any>;
1592
- /**
1593
- * Gravito 核心啟動引擎 (已解耦)
1594
- */
1595
- declare class GravitoServer {
1596
- /**
1597
- * 一鍵建立並組裝伺服器
1598
- * @param manifest 站點描述清單
1599
- * @param resolvers 模組解析器字典
1600
- * @param baseOrbits 基礎軌道模組 (例如 OrbitMonolith)
1601
- */
1602
- static create(manifest: GravitoManifest, resolvers: Record<string, ModuleResolver>, baseOrbits?: any[]): Promise<PlanetCore>;
1603
- }
1604
-
1605
- type PathSegment = string | number;
1606
- type DataPath = string | readonly PathSegment[];
1607
- declare function dataGet<TDefault = undefined>(target: unknown, path: DataPath | null | undefined, defaultValue?: TDefault): unknown | TDefault;
1608
- declare function dataHas(target: unknown, path: DataPath | null | undefined): boolean;
1609
- declare function dataSet(target: unknown, path: DataPath, setValue: unknown, overwrite?: boolean): unknown;
1610
-
1611
- declare const Arr: {
1612
- readonly get: <TDefault = undefined>(target: unknown, path: DataPath | null | undefined, defaultValue?: TDefault) => unknown | TDefault;
1613
- readonly has: (target: unknown, path: DataPath | null | undefined) => boolean;
1614
- readonly set: (target: unknown, path: DataPath, value: unknown, overwrite?: boolean) => unknown;
1615
- readonly wrap: <T>(value: T | T[] | null | undefined) => T[];
1616
- readonly first: <T>(items: readonly T[], callback?: (value: T, index: number) => boolean) => T | undefined;
1617
- readonly last: <T>(items: readonly T[], callback?: (value: T, index: number) => boolean) => T | undefined;
1618
- readonly only: <T extends Record<string, unknown>>(target: T, keys: readonly string[]) => Partial<T>;
1619
- readonly except: <T extends Record<string, unknown>>(target: T, keys: readonly string[]) => Partial<T>;
1620
- readonly flatten: (items: unknown[], depth?: number) => unknown[];
1621
- readonly pluck: <TItem extends Record<string, unknown>>(items: readonly TItem[], valuePath: DataPath, keyPath?: DataPath) => unknown[] | Record<string, unknown>;
1622
- readonly where: <T>(items: readonly T[], callback: (value: T, index: number) => boolean) => T[];
1623
- };
1624
-
1625
- interface ErrorBag {
1626
- has(field: string): boolean;
1627
- first(field?: string): string | undefined;
1628
- get(field: string): string[];
1629
- all(): Record<string, string[]>;
1630
- any(): boolean;
1631
- count(): number;
1632
- }
1633
- declare function createErrorBag(errors: Record<string, string[]>): ErrorBag;
1634
- declare function errors(c: GravitoContext): ErrorBag;
1635
- declare function old(c: GravitoContext, field: string, defaultValue?: unknown): unknown;
1636
-
1637
- type StartsEndsNeedle = string | readonly string[];
1638
- declare const Str: {
1639
- readonly lower: (value: string) => string;
1640
- readonly upper: (value: string) => string;
1641
- readonly startsWith: (haystack: string, needles: StartsEndsNeedle) => boolean;
1642
- readonly endsWith: (haystack: string, needles: StartsEndsNeedle) => boolean;
1643
- readonly contains: (haystack: string, needles: StartsEndsNeedle) => boolean;
1644
- readonly snake: (value: string) => string;
1645
- readonly kebab: (value: string) => string;
1646
- readonly studly: (value: string) => string;
1647
- readonly camel: (value: string) => string;
1648
- readonly title: (value: string) => string;
1649
- readonly limit: (value: string, limit: number, end?: string) => string;
1650
- readonly slug: (value: string, separator?: string) => string;
1651
- readonly uuid: () => string;
1652
- readonly random: (length?: number) => string;
1653
- };
1654
-
1655
- declare class DumpDieError extends Error {
1656
- readonly values: unknown[];
1657
- name: string;
1658
- constructor(values: unknown[]);
1659
- }
1660
- type DumpOptions = {
1661
- depth?: number | null;
1662
- colors?: boolean;
1663
- };
1664
- declare function dump(...values: unknown[]): void;
1665
- declare function dd(...values: unknown[]): never;
1666
- declare function tap<T>(value: T, callback: (value: T) => unknown): T;
1667
- declare function value<TArgs extends readonly unknown[], TResult>(value: (...args: TArgs) => TResult, ...args: TArgs): TResult;
1668
- declare function value<TResult>(value: TResult): TResult;
1669
- declare function value<TArgs extends readonly unknown[], TResult>(valueOrFactory: TResult | ((...args: TArgs) => TResult), ...args: TArgs): TResult;
1670
- declare function blank(value: unknown): boolean;
1671
- declare function filled(value: unknown): boolean;
1672
- declare function throwIf(condition: unknown, error?: Error | string | (() => Error)): void;
1673
- declare function throwUnless(condition: unknown, error?: Error | string | (() => Error)): void;
1674
- declare function env<TDefault = string | undefined>(key: string, defaultValue?: TDefault): string | TDefault;
1675
- declare function setApp(core: PlanetCore | null): void;
1676
- declare function hasApp(): boolean;
1677
- declare function app(): PlanetCore;
1678
- declare function config<T = unknown>(key: string): T;
1679
- declare function config<T>(key: string, defaultValue: T): T;
1680
- declare function logger(): Logger;
1681
- declare function router(): Router;
1682
- declare function abort(status: ContentfulStatusCode, message?: string): never;
1683
- declare function abortIf(condition: unknown, status: ContentfulStatusCode, message?: string): void;
1684
- declare function abortUnless(condition: unknown, status: ContentfulStatusCode, message?: string): void;
1685
-
1686
- interface CookieOptions {
1687
- path?: string;
1688
- domain?: string;
1689
- secure?: boolean;
1690
- httpOnly?: boolean;
1691
- sameSite?: 'Strict' | 'Lax' | 'None';
1692
- maxAge?: number;
1693
- expires?: Date;
1694
- encrypt?: boolean;
1695
- }
1696
- declare class CookieJar {
1697
- private encrypter?;
1698
- private queued;
1699
- constructor(encrypter?: Encrypter | undefined);
1700
- /**
1701
- * Queue a cookie to be sent with the response
1702
- */
1703
- queue(name: string, value: string, minutes?: number, options?: CookieOptions): void;
1704
- /**
1705
- * Make a cookie that lasts "forever" (5 years)
1706
- */
1707
- forever(name: string, value: string, options?: CookieOptions): void;
1708
- /**
1709
- * Expire a cookie
1710
- */
1711
- forget(name: string, options?: CookieOptions): void;
1712
- /**
1713
- * Serialize a cookie to a Set-Cookie header value
1714
- */
1715
- private serializeCookie;
1716
- /**
1717
- * Attach queued cookies to the context
1718
- */
1719
- attach(c: GravitoContext): void;
1720
- }
1721
-
1722
- type BodySizeLimitOptions = {
1723
- methods?: string[];
1724
- requireContentLength?: boolean;
1725
- };
1726
- declare function bodySizeLimit(maxBytes: number, options?: BodySizeLimitOptions): GravitoMiddleware;
1727
-
1728
- type CorsOrigin = string | string[] | ((origin: string | undefined) => string | false);
1729
- type CorsOptions = {
1730
- origin?: CorsOrigin;
1731
- methods?: string[];
1732
- allowedHeaders?: string[];
1733
- exposedHeaders?: string[];
1734
- credentials?: boolean;
1735
- maxAge?: number;
1736
- optionsSuccessStatus?: number;
1737
- };
1738
- declare function cors(options?: CorsOptions): GravitoMiddleware;
1739
-
1740
- type CsrfOptions = {
1741
- cookieName?: string;
1742
- headerName?: string;
1743
- formFieldName?: string;
1744
- cookie?: CookieOptions;
1745
- safeMethods?: string[];
1746
- };
1747
- declare function getCsrfToken(c: GravitoContext, options?: CsrfOptions): string;
1748
- declare function csrfProtection(options?: CsrfOptions): GravitoMiddleware;
1749
-
1750
- type HeaderTokenGateOptions = {
1751
- headerName?: string;
1752
- token?: string | ((c: GravitoContext) => string | undefined);
1753
- };
1754
- type RequireHeaderTokenOptions = HeaderTokenGateOptions & {
1755
- status?: number;
1756
- message?: string;
1757
- };
1758
- declare function createHeaderGate(options?: HeaderTokenGateOptions): (c: GravitoContext) => Promise<boolean>;
1759
- declare function requireHeaderToken(options?: RequireHeaderTokenOptions): GravitoMiddleware;
1760
-
1761
- type HstsOptions = {
1762
- maxAge: number;
1763
- includeSubDomains?: boolean;
1764
- preload?: boolean;
1765
- };
1766
- type SecurityHeadersOptions = {
1767
- contentSecurityPolicy?: string | false | ((c: GravitoContext) => string | false);
1768
- frameOptions?: string | false;
1769
- referrerPolicy?: string | false;
1770
- noSniff?: boolean;
1771
- hsts?: HstsOptions | false;
1772
- permissionsPolicy?: string | false;
1773
- crossOriginOpenerPolicy?: string | false;
1774
- crossOriginResourcePolicy?: string | false;
1775
- };
1776
- declare function securityHeaders(options?: SecurityHeadersOptions): GravitoMiddleware;
1777
-
1778
- declare class ThrottleRequests {
1779
- private core;
1780
- constructor(core: PlanetCore);
1781
- /**
1782
- * Create the middleware
1783
- * @param maxAttempts - Max requests allowed
1784
- * @param decaySeconds - Time window in seconds
1785
- */
1786
- handle(maxAttempts?: number, decaySeconds?: number): GravitoMiddleware;
1787
- }
1788
-
1789
- /**
1790
- * TestResponse wraps a standard Fetch Response and provides fluent assertion methods
1791
- * inspired by Laravel's TestResponse.
1792
- */
1793
- declare class TestResponse {
1794
- readonly response: Response;
1795
- private _jsonData;
1796
- private _textData;
1797
- constructor(response: Response);
1798
- /**
1799
- * Assert the response status code
1800
- */
1801
- assertStatus(status: number): this;
1802
- /**
1803
- * Assert that the response has a 200 status code
1804
- */
1805
- assertOk(): this;
1806
- /**
1807
- * Assert that the response has a 201 status code
1808
- */
1809
- assertCreated(): this;
1810
- /**
1811
- * Assert that the response has a 404 status code
1812
- */
1813
- assertNotFound(): this;
1814
- /**
1815
- * Assert that the response has a 403 status code
1816
- */
1817
- assertForbidden(): this;
1818
- /**
1819
- * Assert that the response has a 401 status code
1820
- */
1821
- assertUnauthorized(): this;
1822
- /**
1823
- * Assert the response is a redirect
1824
- */
1825
- assertRedirect(uri?: string): this;
1826
- /**
1827
- * Assert that the response contains the given JSON data.
1828
- */
1829
- assertJson(data: any): Promise<this>;
1830
- /**
1831
- * Assert that the response contains exactly the given JSON data.
1832
- */
1833
- assertExactJson(data: any): Promise<this>;
1834
- /**
1835
- * Assert the structure of the JSON response.
1836
- */
1837
- assertJsonStructure(structure: any): Promise<this>;
1838
- /**
1839
- * Assert that the response contains the given string.
1840
- */
1841
- assertSee(value: string): Promise<this>;
1842
- /**
1843
- * Assert that the response does not contain the given string.
1844
- */
1845
- assertDontSee(value: string): Promise<this>;
1846
- /**
1847
- * Assert a header exists and matches value
1848
- */
1849
- assertHeader(header: string, value: string): this;
1850
- /**
1851
- * Assert a header does not exist
1852
- */
1853
- assertHeaderMissing(header: string): this;
1854
- /**
1855
- * Get the JSON content
1856
- */
1857
- getJson(): Promise<any>;
1858
- /**
1859
- * Get the text content
1860
- */
1861
- getText(): Promise<string>;
1862
- /**
1863
- * Alias for getText for standard expectations if needed
1864
- */
1865
- get body(): Promise<string>;
1866
- }
1867
-
1868
- /**
1869
- * HttpTester provides a way to simulate HTTP requests against a PlanetCore instance
1870
- * and returns a TestResponse for assertions.
1871
- */
1872
- declare class HttpTester {
1873
- private core;
1874
- constructor(core: PlanetCore);
1875
- /**
1876
- * Make a GET request
1877
- */
1878
- get(uri: string, headers?: Record<string, string>): Promise<TestResponse>;
1879
- /**
1880
- * Make a POST request
1881
- */
1882
- post(uri: string, data?: any, headers?: Record<string, string>): Promise<TestResponse>;
1883
- /**
1884
- * Make a PUT request
1885
- */
1886
- put(uri: string, data?: any, headers?: Record<string, string>): Promise<TestResponse>;
1887
- /**
1888
- * Make a PATCH request
1889
- */
1890
- patch(uri: string, data?: any, headers?: Record<string, string>): Promise<TestResponse>;
1891
- /**
1892
- * Make a DELETE request
1893
- */
1894
- delete(uri: string, data?: any, headers?: Record<string, string>): Promise<TestResponse>;
1895
- /**
1896
- * Core call method
1897
- */
1898
- private call;
1899
- }
1900
- /**
1901
- * Helper to create an HttpTester for a PlanetCore instance
1902
- */
1903
- declare function createHttpTester(core: PlanetCore): HttpTester;
1904
-
1905
- type RuntimeKind = 'bun' | 'node' | 'deno' | 'unknown';
1906
- interface RuntimeSpawnOptions {
1907
- cwd?: string;
1908
- env?: Record<string, string | undefined>;
1909
- stdin?: 'pipe' | 'inherit' | 'ignore';
1910
- stdout?: 'pipe' | 'inherit' | 'ignore';
1911
- stderr?: 'pipe' | 'inherit' | 'ignore';
1912
- }
1913
- interface RuntimeProcess {
1914
- exited: Promise<number>;
1915
- stdout?: ReadableStream<Uint8Array> | null;
1916
- stderr?: ReadableStream<Uint8Array> | null;
1917
- kill?: (signal?: string | number) => void;
1918
- }
1919
- interface RuntimeFileStat {
1920
- size: number;
1921
- }
1922
- interface RuntimeServeConfig {
1923
- port?: number;
1924
- fetch: (req: Request, server?: unknown) => Response | Promise<Response>;
1925
- websocket?: unknown;
1926
- }
1927
- interface RuntimeServer {
1928
- stop?: () => void;
1929
- }
1930
- interface RuntimeAdapter {
1931
- kind: RuntimeKind;
1932
- spawn(command: string[], options?: RuntimeSpawnOptions): RuntimeProcess;
1933
- writeFile(path: string, data: Blob | Buffer | string | ArrayBuffer | Uint8Array): Promise<void>;
1934
- readFile(path: string): Promise<Uint8Array>;
1935
- readFileAsBlob(path: string): Promise<Blob>;
1936
- exists(path: string): Promise<boolean>;
1937
- stat(path: string): Promise<RuntimeFileStat>;
1938
- deleteFile(path: string): Promise<void>;
1939
- serve(config: RuntimeServeConfig): RuntimeServer;
1940
- }
1941
- interface RuntimePasswordAdapter {
1942
- hash(value: string, options: {
1943
- algorithm: 'bcrypt';
1944
- cost?: number;
1945
- } | {
1946
- algorithm: 'argon2id';
1947
- memoryCost?: number;
1948
- timeCost?: number;
1949
- parallelism?: number;
1950
- }): Promise<string>;
1951
- verify(value: string, hashed: string): Promise<boolean>;
1952
- }
1953
- interface RuntimeSqliteStatement {
1954
- run(params?: Record<string, unknown>): void;
1955
- get(params?: Record<string, unknown>): unknown;
1956
- all(params?: Record<string, unknown>): unknown[];
1957
- }
1958
- interface RuntimeSqliteDatabase {
1959
- run(sql: string): void;
1960
- prepare(sql: string): RuntimeSqliteStatement;
1961
- query(sql: string): RuntimeSqliteStatement;
1962
- close(): void;
1963
- }
1964
- declare const getRuntimeEnv: () => Record<string, string | undefined>;
1965
- declare const getRuntimeAdapter: () => RuntimeAdapter;
1966
- declare const getPasswordAdapter: () => RuntimePasswordAdapter;
1967
- declare const createSqliteDatabase: (path: string) => Promise<RuntimeSqliteDatabase>;
1968
-
1969
- /**
1970
- * @fileoverview Gravito Core Engine Types
1971
- *
1972
- * Minimal, high-performance types for the standalone engine.
1973
- * These are intentionally simpler than the full framework types.
1974
- *
1975
- * @module @gravito/core/engine
1976
- */
1977
-
1978
- /**
1979
- * FastContext - The pooled request context
1980
- */
1981
- interface FastContext$1 {
1982
- /** Request accessor */
1983
- readonly req: FastRequest;
1984
- /** Response helpers */
1985
- json<T>(data: T, status?: number): Response;
1986
- text(text: string, status?: number): Response;
1987
- html(html: string, status?: number): Response;
1988
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
1989
- body(data: BodyInit | null, status?: number): Response;
1990
- /** Header management */
1991
- header(name: string, value: string): void;
1992
- status(code: number): void;
1993
- /** Internal reset for pooling */
1994
- reset(request: Request, params?: Record<string, string>): this;
1995
- }
1996
- /**
1997
- * FastRequest - Minimal request interface
1998
- */
1999
- interface FastRequest {
2000
- /** Full URL */
2001
- readonly url: string;
2002
- /** HTTP method */
2003
- readonly method: string;
2004
- /** Path without query */
2005
- readonly path: string;
2006
- /** Get route parameter */
2007
- param(name: string): string | undefined;
2008
- /** Get all route parameters */
2009
- params(): Record<string, string>;
2010
- /** Get query parameter */
2011
- query(name: string): string | undefined;
2012
- /** Get all query parameters */
2013
- queries(): Record<string, string | string[]>;
2014
- /** Get header */
2015
- header(name: string): string | undefined;
2016
- /** Get all headers */
2017
- headers(): Record<string, string>;
2018
- /** Parse JSON body */
2019
- json<T = unknown>(): Promise<T>;
2020
- /** Parse text body */
2021
- text(): Promise<string>;
2022
- /** Parse form data */
2023
- formData(): Promise<FormData>;
2024
- /** Raw Request object */
2025
- readonly raw: Request;
2026
- }
2027
- /**
2028
- * Route handler function
2029
- */
2030
- type Handler = (ctx: FastContext$1) => Response | Promise<Response>;
2031
- /**
2032
- * Middleware function
2033
- */
2034
- type Middleware = (ctx: FastContext$1, next: () => Promise<Response | undefined>) => Response | undefined | Promise<Response | undefined>;
2035
- /**
2036
- * Error handler function
2037
- */
2038
- type ErrorHandler = (error: Error, ctx: FastContext$1) => Response | Promise<Response>;
2039
- /**
2040
- * Not found handler function
2041
- */
2042
- type NotFoundHandler = (ctx: FastContext$1) => Response | Promise<Response>;
2043
- /**
2044
- * Route match result from router
2045
- */
2046
- interface RouteMatch {
2047
- /** Matched handler */
2048
- handler: Handler | null;
2049
- /** Extracted route parameters */
2050
- params: Record<string, string>;
2051
- /** Middleware to execute */
2052
- middleware: Middleware[];
2053
- }
2054
- /**
2055
- * Engine configuration options
2056
- */
2057
- interface EngineOptions {
2058
- /** Context pool size (default: 256) */
2059
- poolSize?: number;
2060
- /** Enable route compilation optimization (default: true) */
2061
- enableAOT?: boolean;
2062
- /** Custom error handler */
2063
- onError?: ErrorHandler;
2064
- /** Custom 404 handler */
2065
- onNotFound?: NotFoundHandler;
2066
- }
2067
-
2068
- /**
2069
- * @fileoverview Gravito - High-Performance Web Engine for Bun
2070
- *
2071
- * The standalone engine optimized exclusively for Bun runtime.
2072
- * 99% API-compatible with Hono, but faster through Bun-specific optimizations.
2073
- *
2074
- * Key optimizations:
2075
- * 1. Object pooling for zero-allocation request handling
2076
- * 2. AOT router with O(1) static route lookup
2077
- * 3. Lazy parsing - only parse what's accessed
2078
- * 4. Direct Bun.serve integration without wrapper layers
2079
- *
2080
- * @module @gravito/core/engine
2081
- */
2082
-
2083
- /**
2084
- * Gravito - The High-Performance Web Engine
2085
- *
2086
- * @example
2087
- * ```typescript
2088
- * import { Gravito } from '@gravito/core/engine'
2089
- *
2090
- * const app = new Gravito()
2091
- *
2092
- * app.get('/', (c) => c.json({ message: 'Hello, World!' }))
2093
- * app.get('/users/:id', (c) => {
2094
- * const id = c.req.param('id')
2095
- * return c.json({ id })
2096
- * })
2097
- *
2098
- * export default app
2099
- * ```
2100
- */
2101
- declare class Gravito {
2102
- private router;
2103
- private contextPool;
2104
- private errorHandler?;
2105
- private notFoundHandler?;
2106
- private staticRoutes;
2107
- private isPureStaticApp;
2108
- /**
2109
- * Create a new Gravito instance
2110
- *
2111
- * @param options - Engine configuration options
2112
- */
2113
- constructor(options?: EngineOptions);
2114
- /**
2115
- * Register a GET route
2116
- *
2117
- * @param path - Route path (e.g., '/users/:id')
2118
- * @param handlers - Handler and optional middleware
2119
- * @returns This instance for chaining
2120
- */
2121
- get(path: string, ...handlers: Handler[]): this;
2122
- /**
2123
- * Register a POST route
2124
- */
2125
- post(path: string, ...handlers: Handler[]): this;
2126
- /**
2127
- * Register a PUT route
2128
- */
2129
- put(path: string, ...handlers: Handler[]): this;
2130
- /**
2131
- * Register a DELETE route
2132
- */
2133
- delete(path: string, ...handlers: Handler[]): this;
2134
- /**
2135
- * Register a PATCH route
2136
- */
2137
- patch(path: string, ...handlers: Handler[]): this;
2138
- /**
2139
- * Register an OPTIONS route
2140
- */
2141
- options(path: string, ...handlers: Handler[]): this;
2142
- /**
2143
- * Register a HEAD route
2144
- */
2145
- head(path: string, ...handlers: Handler[]): this;
2146
- /**
2147
- * Register a route for all HTTP methods
2148
- */
2149
- all(path: string, ...handlers: Handler[]): this;
2150
- /**
2151
- * Register global or path-based middleware
2152
- *
2153
- * @example
2154
- * ```typescript
2155
- * // Global middleware
2156
- * app.use(async (c, next) => {
2157
- * console.log(`${c.req.method} ${c.req.path}`)
2158
- * await next()
2159
- * })
2160
- *
2161
- * // Path-based middleware
2162
- * app.use('/api/*', async (c, next) => {
2163
- * c.header('X-API-Version', '1.0')
2164
- * await next()
2165
- * })
2166
- * ```
2167
- */
2168
- use(path: string, ...middleware: Middleware[]): this;
2169
- use(...middleware: Middleware[]): this;
2170
- /**
2171
- * Mount a sub-application at a path prefix
2172
- *
2173
- * @example
2174
- * ```typescript
2175
- * const api = new Gravito()
2176
- * api.get('/users', (c) => c.json({ users: [] }))
2177
- *
2178
- * const app = new Gravito()
2179
- * app.route('/api', api)
2180
- * // Now accessible at /api/users
2181
- * ```
2182
- */
2183
- route(_path: string, _app: Gravito): this;
2184
- /**
2185
- * Set custom error handler
2186
- *
2187
- * @example
2188
- * ```typescript
2189
- * app.onError((err, c) => {
2190
- * console.error(err)
2191
- * return c.json({ error: err.message }, 500)
2192
- * })
2193
- * ```
2194
- */
2195
- onError(handler: ErrorHandler): this;
2196
- /**
2197
- * Set custom 404 handler
2198
- *
2199
- * @example
2200
- * ```typescript
2201
- * app.notFound((c) => {
2202
- * return c.json({ error: 'Not Found' }, 404)
2203
- * })
2204
- * ```
2205
- */
2206
- notFound(handler: NotFoundHandler): this;
2207
- /**
2208
- * Handle an incoming request
2209
- *
2210
- * Optimized for minimal allocations and maximum throughput.
2211
- * Uses sync/async dual-path strategy inspired by Hono.
2212
- *
2213
- * @param request - Incoming Request object
2214
- * @returns Response object (sync or async)
2215
- */
2216
- fetch: (request: Request) => Response | Promise<Response>;
2217
- /**
2218
- * Handle routes with middleware (async path)
2219
- */
2220
- private handleWithMiddleware;
2221
- /**
2222
- * Handle dynamic routes (Radix Tree lookup)
2223
- */
2224
- private handleDynamicRoute;
2225
- /**
2226
- * Sync error handler (for ultra-fast path)
2227
- */
2228
- private handleErrorSync;
2229
- /**
2230
- * Sync 404 handler (for ultra-fast path)
2231
- */
2232
- private handleNotFoundSync;
2233
- /**
2234
- * Collect middleware for a specific path
2235
- * (Simplified version - assumes we've already checked for pure static)
2236
- */
2237
- private collectMiddlewareForPath;
2238
- /**
2239
- * Compile routes for optimization
2240
- * Called once during initialization and when routes change
2241
- */
2242
- private compileRoutes;
2243
- /**
2244
- * Add a route to the router
2245
- */
2246
- private addRoute;
2247
- /**
2248
- * Execute middleware chain followed by handler
2249
- *
2250
- * Implements the standard middleware pattern:
2251
- * Each middleware can call next() to continue the chain.
2252
- */
2253
- private executeMiddleware;
2254
- /**
2255
- * Handle errors (Async version for dynamic/middleware paths)
2256
- */
2257
- private handleError;
2258
- }
2259
-
2260
- /**
2261
- * @fileoverview AOT (Ahead-of-Time) Router
2262
- *
2263
- * Hybrid routing strategy:
2264
- * - Static routes: O(1) Map lookup
2265
- * - Dynamic routes: Optimized Radix Tree
2266
- *
2267
- * The key optimization is separating static from dynamic routes at registration time,
2268
- * not at match time. This eliminates unnecessary tree traversal for static paths.
2269
- *
2270
- * @module @gravito/core/engine
2271
- */
2272
-
2273
- /**
2274
- * AOT Router - Optimized for Bun
2275
- *
2276
- * Performance characteristics:
2277
- * - Static routes: O(1) lookup via Map
2278
- * - Dynamic routes: O(log n) via Radix Tree
2279
- * - Middleware: O(m) where m = number of matching middleware
2280
- */
2281
- declare class AOTRouter {
2282
- private staticRoutes;
2283
- private dynamicRouter;
2284
- private globalMiddleware;
2285
- private pathMiddleware;
2286
- /**
2287
- * Register a route
2288
- *
2289
- * Automatically determines if route is static or dynamic.
2290
- * Static routes are stored in a Map for O(1) lookup.
2291
- * Dynamic routes use the Radix Tree.
2292
- *
2293
- * @param method - HTTP method
2294
- * @param path - Route path
2295
- * @param handler - Route handler
2296
- * @param middleware - Route-specific middleware
2297
- */
2298
- add(method: HttpMethod, path: string, handler: Handler, middleware?: Middleware[]): void;
2299
- /**
2300
- * Add global middleware
2301
- *
2302
- * These run for every request, before route-specific middleware.
2303
- *
2304
- * @param middleware - Middleware functions
2305
- */
2306
- use(...middleware: Middleware[]): void;
2307
- /**
2308
- * Add path-based middleware
2309
- *
2310
- * Supports wildcard patterns like '/api/*'
2311
- *
2312
- * @param pattern - Path pattern
2313
- * @param middleware - Middleware functions
2314
- */
2315
- usePattern(pattern: string, ...middleware: Middleware[]): void;
2316
- /**
2317
- * Match a request to a route
2318
- *
2319
- * Returns the handler, params, and all applicable middleware.
2320
- *
2321
- * @param method - HTTP method
2322
- * @param path - Request path
2323
- * @returns Route match or null if not found
2324
- */
2325
- match(method: string, path: string): RouteMatch;
2326
- /**
2327
- * Public wrapper for collectMiddleware (used by Gravito for optimization)
2328
- */
2329
- collectMiddlewarePublic(path: string, routeMiddleware: Middleware[]): Middleware[];
2330
- /**
2331
- * Collect all applicable middleware for a path
2332
- *
2333
- * Order: global -> pattern-based -> route-specific
2334
- *
2335
- * @param path - Request path
2336
- * @param routeMiddleware - Route-specific middleware
2337
- * @returns Combined middleware array
2338
- */
2339
- private collectMiddleware;
2340
- /**
2341
- * Check if a path is static (no parameters or wildcards)
2342
- */
2343
- private isStaticPath;
2344
- /**
2345
- * Match a pattern against a path
2346
- *
2347
- * Supports:
2348
- * - Exact match: '/api/users'
2349
- * - Wildcard suffix: '/api/*'
2350
- *
2351
- * @param pattern - Pattern to match
2352
- * @param path - Path to test
2353
- * @returns True if pattern matches
2354
- */
2355
- private matchPattern;
2356
- /**
2357
- * Find the original route key for a matched dynamic route
2358
- *
2359
- * This is needed to look up route-specific middleware.
2360
- * It's a bit of a hack, but avoids storing duplicate data.
2361
- *
2362
- * @param method - HTTP method
2363
- * @param path - Matched path
2364
- * @returns Route key or null
2365
- */
2366
- private findDynamicRouteKey;
2367
- /**
2368
- * Get all registered routes (for debugging)
2369
- */
2370
- getRoutes(): Array<{
2371
- method: string;
2372
- path: string;
2373
- type: 'static' | 'dynamic';
2374
- }>;
2375
- }
2376
-
2377
- /**
2378
- * @fileoverview FastContext - Pooled Request Context
2379
- *
2380
- * Minimal, high-performance context implementation designed for object pooling.
2381
- * Lazy parsing strategy: only parse what's actually accessed.
2382
- *
2383
- * @module @gravito/core/engine
2384
- */
2385
-
2386
- /**
2387
- * FastContext - Pooled request context
2388
- *
2389
- * Designed for minimal memory allocation and maximum reuse.
2390
- * All response helpers create Response objects directly without intermediate wrappers.
2391
- */
2392
- declare class FastContext implements FastContext$1 {
2393
- private _req;
2394
- private _headers;
2395
- /**
2396
- * Reset context for pooling
2397
- *
2398
- * This is called when acquiring from the pool.
2399
- * Must clear all state from previous request.
2400
- */
2401
- reset(request: Request, params?: Record<string, string>): this;
2402
- get req(): FastRequest;
2403
- json<T>(data: T, status?: number): Response;
2404
- text(text: string, status?: number): Response;
2405
- html(html: string, status?: number): Response;
2406
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
2407
- body(data: BodyInit | null, status?: number): Response;
2408
- header(name: string, value: string): void;
2409
- status(_code: number): void;
2410
- }
2411
-
2412
- /**
2413
- * @fileoverview MinimalContext - Ultra-lightweight Request Context
2414
- *
2415
- * Designed for zero-middleware static routes where pool overhead
2416
- * exceeds the cost of creating a new object.
2417
- *
2418
- * Key difference from FastContext:
2419
- * - No object pooling (direct instantiation is faster for simple cases)
2420
- * - No Headers object reuse (creates inline)
2421
- * - Minimal memory footprint
2422
- *
2423
- * @module @gravito/core/engine
2424
- */
2425
-
2426
- /**
2427
- * MinimalContext - Optimized for simple, fast responses
2428
- *
2429
- * Use when:
2430
- * - No middleware
2431
- * - Static routes
2432
- * - Simple JSON/text responses
2433
- * - No custom headers needed
2434
- */
2435
- declare class MinimalContext implements FastContext$1 {
2436
- private readonly _req;
2437
- constructor(request: Request, params: Record<string, string>, path: string);
2438
- get req(): FastRequest;
2439
- json<T>(data: T, status?: number): Response;
2440
- text(text: string, status?: number): Response;
2441
- html(html: string, status?: number): Response;
2442
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
2443
- body(data: BodyInit | null, status?: number): Response;
2444
- header(_name: string, _value: string): void;
2445
- status(_code: number): void;
2446
- reset(_request: Request, _params?: Record<string, string>): this;
2447
- }
2448
-
2449
- /**
2450
- * @fileoverview Lightweight Path Utilities
2451
- *
2452
- * High-performance path extraction without creating URL objects.
2453
- * Performance critical - every optimization matters.
2454
- *
2455
- * @module @gravito/core/engine
2456
- */
2457
- /**
2458
- * Extract pathname from URL string without creating URL object
2459
- *
2460
- * @param url - Full URL string (e.g., "http://localhost:3000/api/users?id=1")
2461
- * @returns pathname (e.g., "/api/users")
2462
- *
2463
- * @example
2464
- * ```typescript
2465
- * extractPath("http://localhost:3000/api/users?id=1") // "/api/users"
2466
- * extractPath("https://example.com/") // "/"
2467
- * ```
2468
- */
2469
- declare function extractPath(url: string): string;
2470
-
2471
- /**
2472
- * @fileoverview Generic Object Pool Implementation
2473
- *
2474
- * High-performance object pooling to reduce GC pressure.
2475
- * Implements "fixed pool + overflow fallback" strategy.
2476
- *
2477
- * @module @gravito/core/engine
2478
- */
2479
- /**
2480
- * Generic object pool with fixed size and overflow handling
2481
- *
2482
- * @typeParam T - Type of objects to pool
2483
- *
2484
- * @example
2485
- * ```typescript
2486
- * const pool = new ObjectPool(
2487
- * () => new MyObject(),
2488
- * (obj) => obj.reset(),
2489
- * 256
2490
- * )
2491
- *
2492
- * const obj = pool.acquire()
2493
- * try {
2494
- * // Use object
2495
- * } finally {
2496
- * pool.release(obj)
2497
- * }
2498
- * ```
2499
- */
2500
- declare class ObjectPool<T> {
2501
- private pool;
2502
- private readonly factory;
2503
- private readonly reset;
2504
- private readonly maxSize;
2505
- /**
2506
- * Create a new object pool
2507
- *
2508
- * @param factory - Function to create new objects
2509
- * @param reset - Function to reset objects before reuse
2510
- * @param maxSize - Maximum pool size (default: 256)
2511
- */
2512
- constructor(factory: () => T, reset: (obj: T) => void, maxSize?: number);
2513
- /**
2514
- * Acquire an object from the pool
2515
- *
2516
- * If the pool is empty, creates a new object (overflow strategy).
2517
- * This ensures the pool never blocks under high load.
2518
- *
2519
- * @returns Object from pool or newly created
2520
- */
2521
- acquire(): T;
2522
- /**
2523
- * Release an object back to the pool
2524
- *
2525
- * If the pool is full, the object is discarded (will be GC'd).
2526
- * This prevents unbounded memory growth.
2527
- *
2528
- * @param obj - Object to release
2529
- */
2530
- release(obj: T): void;
2531
- /**
2532
- * Clear all objects from the pool
2533
- *
2534
- * Useful for testing or when you need to force a clean slate.
2535
- */
2536
- clear(): void;
2537
- /**
2538
- * Get current pool size
2539
- */
2540
- get size(): number;
2541
- /**
2542
- * Get maximum pool size
2543
- */
2544
- get capacity(): number;
2545
- /**
2546
- * Pre-warm the pool by creating objects in advance
2547
- *
2548
- * This can reduce latency for the first N requests.
2549
- *
2550
- * @param count - Number of objects to pre-create
2551
- */
2552
- prewarm(count: number): void;
2553
- }
2554
-
2555
- /**
2556
- * @fileoverview Gravito Core Engine - Public API
2557
- *
2558
- * The High-Performance Web Engine for Bun
2559
- *
2560
- * @module @gravito/core/engine
2561
- * @packageDocumentation
2562
- *
2563
- * @example
2564
- * ```typescript
2565
- * import { Gravito } from '@gravito/core/engine'
2566
- *
2567
- * const app = new Gravito()
2568
- *
2569
- * app.get('/', (c) => c.json({ message: 'Hello, World!' }))
2570
- *
2571
- * export default app
2572
- * ```
2573
- */
2574
-
2575
- type index_AOTRouter = AOTRouter;
2576
- declare const index_AOTRouter: typeof AOTRouter;
2577
- type index_EngineOptions = EngineOptions;
2578
- type index_ErrorHandler = ErrorHandler;
2579
- type index_FastRequest = FastRequest;
2580
- type index_Gravito = Gravito;
2581
- declare const index_Gravito: typeof Gravito;
2582
- type index_Handler = Handler;
2583
- type index_Middleware = Middleware;
2584
- type index_MinimalContext = MinimalContext;
2585
- declare const index_MinimalContext: typeof MinimalContext;
2586
- type index_NotFoundHandler = NotFoundHandler;
2587
- type index_ObjectPool<T> = ObjectPool<T>;
2588
- declare const index_ObjectPool: typeof ObjectPool;
2589
- type index_RouteMatch = RouteMatch;
2590
- declare const index_extractPath: typeof extractPath;
2591
- declare namespace index {
2592
- export { index_AOTRouter as AOTRouter, type index_EngineOptions as EngineOptions, type index_ErrorHandler as ErrorHandler, type FastContext$1 as FastContext, FastContext as FastContextImpl, type index_FastRequest as FastRequest, index_Gravito as Gravito, type index_Handler as Handler, type index_Middleware as Middleware, index_MinimalContext as MinimalContext, type index_NotFoundHandler as NotFoundHandler, index_ObjectPool as ObjectPool, type index_RouteMatch as RouteMatch, index_extractPath as extractPath };
2593
- }
2594
-
2595
- /**
2596
- * @gravito/core
2597
- *
2598
- * The core micro-kernel for the Galaxy Architecture.
2599
- *
2600
- * @packageDocumentation
2601
- */
2602
-
2603
- declare const VERSION: string;
2604
-
2605
- /**
2606
- * Configure your Gravito application
2607
- *
2608
- * @example
2609
- * ```typescript
2610
- * const config = defineConfig({
2611
- * config: {
2612
- * APP_NAME: 'My App',
2613
- * PORT: 3000,
2614
- * },
2615
- * orbits: [], // Add your orbits here
2616
- * })
2617
- *
2618
- * const core = await PlanetCore.boot(config)
2619
- * ```
2620
- */
2621
- declare function defineConfig(config: GravitoConfig): GravitoConfig;
2622
-
2623
- export { type ActionCallback, type AdapterConfig, type AdapterFactory, type ApiFailure, type ApiSuccess, Application, type ApplicationConfig, Arr, AuthenticationException, AuthorizationException, type BodySizeLimitOptions, type CacheService, type Channel, ConfigManager, ConsoleLogger, Container, ContentfulStatusCode, type ControllerClass, CookieJar, type CookieOptions, type CorsOptions, type CorsOrigin, type CsrfOptions, type DataPath, DumpDieError, type DumpOptions, Encrypter, type EncrypterOptions, type ErrorBag, type ErrorHandlerContext, Event, EventManager, type ExceptionOptions, type Factory, type FilterCallback, type FormRequestClass, type FormRequestLike, type GlobalErrorHandlersMode, type GlobalProcessErrorHandlerContext, type GlobalProcessErrorKind, GravitoAdapter, type GravitoConfig, GravitoContext, GravitoErrorHandler, GravitoException, GravitoHandler, type GravitoManifest, GravitoMiddleware, GravitoNotFoundHandler, type GravitoOrbit, GravitoRequest, GravitoServer, GravitoVariables, type HeaderTokenGateOptions, HookManager, type HstsOptions, type HttpAdapter, HttpException, HttpMethod, HttpTester, type Listener, type Logger, ModelNotFoundException, type PathSegment, PhotonAdapter, PhotonContextWrapper, PhotonRequestWrapper, PlanetCore, type RegisterGlobalErrorHandlersOptions, type RequireHeaderTokenOptions, Route, type RouteDefinition, RouteGroup, type RouteHandler, type RouteOptions, Router, type RuntimeAdapter, type RuntimeFileStat, type RuntimeKind, type RuntimePasswordAdapter, type RuntimeProcess, type RuntimeServeConfig, type RuntimeServer, type RuntimeSpawnOptions, type RuntimeSqliteDatabase, type RuntimeSqliteStatement, type SecurityHeadersOptions, ServiceProvider, type ShouldBroadcast, type ShouldQueue, StatusCode, Str, TestResponse, ThrottleRequests, VERSION, type ValidationError, ValidationException, type ViewService, abort, abortIf, abortUnless, app, blank, bodySizeLimit, config, cors, createErrorBag, createGravitoAdapter, createHeaderGate, createHttpTester, createPhotonAdapter, createSqliteDatabase, csrfProtection, dataGet, dataHas, dataSet, dd, defineConfig, dump, index as engine, env, errors, fail, filled, getCsrfToken, getPasswordAdapter, getRuntimeAdapter, getRuntimeEnv, hasApp, isHttpAdapter, jsonFail, jsonSuccess, logger, ok, old, registerGlobalErrorHandlers, requireHeaderToken, router, securityHeaders, setApp, tap, throwIf, throwUnless, value };