@gravito/ripple 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +260 -19
  2. package/dist/atlas/src/DB.d.ts +348 -0
  3. package/dist/atlas/src/OrbitAtlas.d.ts +9 -0
  4. package/dist/atlas/src/config/defineConfig.d.ts +14 -0
  5. package/dist/atlas/src/config/index.d.ts +7 -0
  6. package/dist/atlas/src/config/loadConfig.d.ts +41 -0
  7. package/dist/atlas/src/connection/Connection.d.ts +112 -0
  8. package/dist/atlas/src/connection/ConnectionManager.d.ts +180 -0
  9. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +54 -0
  10. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +32 -0
  11. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +118 -0
  12. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +36 -0
  13. package/dist/atlas/src/drivers/MySQLDriver.d.ts +79 -0
  14. package/dist/atlas/src/drivers/PostgresDriver.d.ts +96 -0
  15. package/dist/atlas/src/drivers/RedisDriver.d.ts +43 -0
  16. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +45 -0
  17. package/dist/atlas/src/drivers/types.d.ts +260 -0
  18. package/dist/atlas/src/errors/index.d.ts +45 -0
  19. package/dist/atlas/src/grammar/Grammar.d.ts +342 -0
  20. package/dist/atlas/src/grammar/MongoGrammar.d.ts +47 -0
  21. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +54 -0
  22. package/dist/atlas/src/grammar/NullGrammar.d.ts +35 -0
  23. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +62 -0
  24. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +32 -0
  25. package/dist/atlas/src/index.d.ts +79 -0
  26. package/dist/atlas/src/migration/Migration.d.ts +64 -0
  27. package/dist/atlas/src/migration/MigrationRepository.d.ts +65 -0
  28. package/dist/atlas/src/migration/Migrator.d.ts +110 -0
  29. package/dist/atlas/src/migration/index.d.ts +6 -0
  30. package/dist/atlas/src/observability/AtlasMetrics.d.ts +33 -0
  31. package/dist/atlas/src/observability/AtlasObservability.d.ts +15 -0
  32. package/dist/atlas/src/observability/AtlasTracer.d.ts +12 -0
  33. package/dist/atlas/src/observability/index.d.ts +9 -0
  34. package/dist/atlas/src/orm/Repository.d.ts +247 -0
  35. package/dist/atlas/src/orm/index.d.ts +6 -0
  36. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +121 -0
  37. package/dist/atlas/src/orm/model/Model.d.ts +458 -0
  38. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +20 -0
  39. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +150 -0
  40. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +36 -0
  41. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +92 -0
  42. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +117 -0
  43. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +64 -0
  44. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +15 -0
  45. package/dist/atlas/src/orm/model/concerns/index.d.ts +12 -0
  46. package/dist/atlas/src/orm/model/decorators.d.ts +138 -0
  47. package/dist/atlas/src/orm/model/errors.d.ts +52 -0
  48. package/dist/atlas/src/orm/model/index.d.ts +10 -0
  49. package/dist/atlas/src/orm/model/relationships.d.ts +207 -0
  50. package/dist/atlas/src/orm/model/types.d.ts +12 -0
  51. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +124 -0
  52. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +54 -0
  53. package/dist/atlas/src/orm/schema/index.d.ts +6 -0
  54. package/dist/atlas/src/orm/schema/types.d.ts +85 -0
  55. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +98 -0
  56. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +91 -0
  57. package/dist/atlas/src/pool/PoolStrategy.d.ts +129 -0
  58. package/dist/atlas/src/pool/PoolWarmer.d.ts +92 -0
  59. package/dist/atlas/src/query/Expression.d.ts +60 -0
  60. package/dist/atlas/src/query/NPlusOneDetector.d.ts +10 -0
  61. package/dist/atlas/src/query/QueryBuilder.d.ts +643 -0
  62. package/dist/atlas/src/query/RelationshipResolver.d.ts +23 -0
  63. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +51 -0
  64. package/dist/atlas/src/query/clauses/HavingClause.d.ts +70 -0
  65. package/dist/atlas/src/query/clauses/JoinClause.d.ts +87 -0
  66. package/dist/atlas/src/query/clauses/LimitClause.d.ts +82 -0
  67. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +69 -0
  68. package/dist/atlas/src/query/clauses/SelectClause.d.ts +71 -0
  69. package/dist/atlas/src/query/clauses/WhereClause.d.ts +167 -0
  70. package/dist/atlas/src/query/clauses/index.d.ts +11 -0
  71. package/dist/atlas/src/schema/Blueprint.d.ts +276 -0
  72. package/dist/atlas/src/schema/ColumnDefinition.d.ts +154 -0
  73. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +37 -0
  74. package/dist/atlas/src/schema/MigrationGenerator.d.ts +45 -0
  75. package/dist/atlas/src/schema/Schema.d.ts +131 -0
  76. package/dist/atlas/src/schema/SchemaDiff.d.ts +73 -0
  77. package/dist/atlas/src/schema/TypeGenerator.d.ts +57 -0
  78. package/dist/atlas/src/schema/TypeWriter.d.ts +42 -0
  79. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +23 -0
  80. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +26 -0
  81. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +28 -0
  82. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +97 -0
  83. package/dist/atlas/src/schema/grammars/index.d.ts +7 -0
  84. package/dist/atlas/src/schema/index.d.ts +8 -0
  85. package/dist/atlas/src/seed/Factory.d.ts +90 -0
  86. package/dist/atlas/src/seed/Seeder.d.ts +28 -0
  87. package/dist/atlas/src/seed/SeederRunner.d.ts +74 -0
  88. package/dist/atlas/src/seed/index.d.ts +6 -0
  89. package/dist/atlas/src/sharding/ShardingManager.d.ts +59 -0
  90. package/dist/atlas/src/types/index.d.ts +1182 -0
  91. package/dist/atlas/src/utils/CursorEncoding.d.ts +63 -0
  92. package/dist/atlas/src/utils/levenshtein.d.ts +9 -0
  93. package/dist/core/src/CommandKernel.d.ts +33 -0
  94. package/dist/core/src/ConfigManager.d.ts +39 -0
  95. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  96. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  97. package/dist/core/src/Container.d.ts +86 -11
  98. package/dist/core/src/ErrorHandler.d.ts +3 -0
  99. package/dist/core/src/HookManager.d.ts +511 -4
  100. package/dist/core/src/PlanetCore.d.ts +89 -0
  101. package/dist/core/src/RequestContext.d.ts +97 -0
  102. package/dist/core/src/Router.d.ts +1 -5
  103. package/dist/core/src/ServiceProvider.d.ts +22 -0
  104. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  105. package/dist/core/src/adapters/PhotonAdapter.d.ts +5 -0
  106. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  107. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  108. package/dist/core/src/adapters/types.d.ts +27 -0
  109. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  110. package/dist/core/src/engine/AOTRouter.d.ts +7 -12
  111. package/dist/core/src/engine/FastContext.d.ts +27 -2
  112. package/dist/core/src/engine/Gravito.d.ts +0 -1
  113. package/dist/core/src/engine/MinimalContext.d.ts +25 -2
  114. package/dist/core/src/engine/types.d.ts +9 -1
  115. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  116. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  117. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  118. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  119. package/dist/core/src/events/EventBackend.d.ts +12 -0
  120. package/dist/core/src/events/EventOptions.d.ts +204 -0
  121. package/dist/core/src/events/EventPriorityQueue.d.ts +301 -0
  122. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  123. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  124. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  125. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  126. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  127. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  128. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  129. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  130. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  131. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  132. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  133. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  134. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  135. package/dist/core/src/events/index.d.ts +25 -0
  136. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  137. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  138. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  139. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  140. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  141. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  142. package/dist/core/src/events/observability/index.d.ts +24 -0
  143. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  144. package/dist/core/src/events/types.d.ts +134 -0
  145. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  146. package/dist/core/src/exceptions/index.d.ts +1 -0
  147. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  148. package/dist/core/src/http/types.d.ts +40 -0
  149. package/dist/core/src/index.d.ts +25 -4
  150. package/dist/core/src/instrumentation/index.d.ts +35 -0
  151. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  152. package/dist/core/src/instrumentation/types.d.ts +182 -0
  153. package/dist/core/src/observability/Metrics.d.ts +244 -0
  154. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  155. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +350 -0
  156. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  157. package/dist/core/src/reliability/index.d.ts +6 -0
  158. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  159. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  160. package/dist/index.js +6709 -9888
  161. package/dist/index.js.map +64 -62
  162. package/dist/photon/src/index.d.ts +19 -0
  163. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  164. package/dist/photon/src/middleware/ratelimit.d.ts +161 -0
  165. package/dist/photon/src/openapi.d.ts +19 -0
  166. package/dist/proto/ripple.proto +120 -0
  167. package/dist/ripple/src/RippleServer.d.ts +64 -445
  168. package/dist/ripple/src/channels/ChannelManager.d.ts +25 -10
  169. package/dist/ripple/src/drivers/NATSDriver.d.ts +87 -0
  170. package/dist/ripple/src/drivers/RedisDriver.d.ts +30 -1
  171. package/dist/ripple/src/drivers/index.d.ts +1 -0
  172. package/dist/ripple/src/engines/BunEngine.d.ts +98 -0
  173. package/dist/ripple/src/engines/IRippleEngine.d.ts +205 -0
  174. package/dist/ripple/src/engines/UWebSocketsEngine.d.ts +97 -0
  175. package/dist/ripple/src/engines/WsEngine.d.ts +69 -0
  176. package/dist/ripple/src/engines/index.d.ts +15 -0
  177. package/dist/ripple/src/index.d.ts +2 -0
  178. package/dist/ripple/src/middleware/InterceptorManager.d.ts +21 -0
  179. package/dist/ripple/src/observability/RippleMetrics.d.ts +24 -0
  180. package/dist/ripple/src/reliability/AckManager.d.ts +48 -0
  181. package/dist/ripple/src/serializers/ISerializer.d.ts +39 -0
  182. package/dist/ripple/src/serializers/JsonSerializer.d.ts +19 -0
  183. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +41 -0
  184. package/dist/ripple/src/serializers/index.d.ts +3 -0
  185. package/dist/ripple/src/tracking/SessionManager.d.ts +104 -0
  186. package/dist/ripple/src/tracking/index.d.ts +1 -0
  187. package/dist/ripple/src/types.d.ts +188 -12
  188. package/dist/ripple/src/utils/MessageSerializer.d.ts +33 -23
  189. package/dist/ripple/src/utils/TokenBucket.d.ts +25 -0
  190. package/package.json +25 -8
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @gravito/atlas - Cursor Encoding Utility
3
+ * @description Base64 encode/decode for cursor-based pagination cursors.
4
+ *
5
+ * Cursor format: base64(JSON({ id, sortValue, sortColumn, direction }))
6
+ * This enables O(1) pagination using tuple comparison SQL:
7
+ * WHERE (sort_col, id) > (val, id_val)
8
+ */
9
+ export interface CursorPayload {
10
+ /**
11
+ * Primary key value of the last/first record in the current page
12
+ */
13
+ id: unknown;
14
+ /**
15
+ * Value of the sort column at the cursor boundary
16
+ */
17
+ sortValue: unknown;
18
+ /**
19
+ * Column name used for sorting
20
+ */
21
+ sortColumn: string;
22
+ /**
23
+ * Sort direction
24
+ */
25
+ direction: 'asc' | 'desc';
26
+ }
27
+ /**
28
+ * Encode a cursor payload to an opaque base64 string.
29
+ *
30
+ * @param payload - Cursor data to encode
31
+ * @returns Base64-encoded cursor string
32
+ *
33
+ * @example
34
+ * const cursor = encodeCursor({ id: 42, sortValue: '2026-01-01', sortColumn: 'created_at', direction: 'asc' })
35
+ */
36
+ export declare function encodeCursor(payload: CursorPayload): string;
37
+ /**
38
+ * Decode a cursor string back to its payload.
39
+ *
40
+ * @param cursor - Base64 cursor string
41
+ * @returns Decoded cursor payload
42
+ * @throws {Error} If the cursor is malformed or tampered with
43
+ *
44
+ * @example
45
+ * const payload = decodeCursor(cursor)
46
+ * // payload.id, payload.sortValue, etc.
47
+ */
48
+ export declare function decodeCursor(cursor: string): CursorPayload;
49
+ /**
50
+ * Build the WHERE clause raw SQL and bindings for cursor pagination.
51
+ *
52
+ * For ascending sort: WHERE (sort_col, id) > (sort_val, id_val)
53
+ * For descending sort: WHERE (sort_col, id) < (sort_val, id_val)
54
+ *
55
+ * Uses tuple comparison which is O(1) on indexed columns in Postgres & MySQL.
56
+ *
57
+ * @param payload - Decoded cursor payload
58
+ * @returns { sql, bindings } ready for whereRaw()
59
+ */
60
+ export declare function buildCursorWhereClause(payload: CursorPayload, idColumn?: string): {
61
+ sql: string;
62
+ bindings: unknown[];
63
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Calculate Levenshtein distance between two strings
3
+ * Used for "Did you mean?" suggestions
4
+ */
5
+ export declare function levenshtein(a: string, b: string): number;
6
+ /**
7
+ * Find similar strings from a list
8
+ */
9
+ export declare function findSimilar(target: string, candidates: string[], maxDistance?: number, maxResults?: number): string[];
@@ -0,0 +1,33 @@
1
+ import type { Container } from './Container';
2
+ /**
3
+ * CommandHandler type for custom CLI commands.
4
+ */
5
+ export type CommandHandler = (args: string[], container: Container) => Promise<void> | void;
6
+ /**
7
+ * CommandKernel - Structured CLI Command handling.
8
+ *
9
+ * Manages registration and execution of custom CLI commands that can
10
+ * reuse the application container and providers.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const kernel = new CommandKernel(container);
15
+ * kernel.register('greet', (args) => console.log('Hello', args[0]));
16
+ * await kernel.handle(['greet', 'Universe']);
17
+ * ```
18
+ */
19
+ export declare class CommandKernel {
20
+ private container;
21
+ private commands;
22
+ constructor(container: Container);
23
+ /**
24
+ * Register a new command handler.
25
+ */
26
+ register(name: string, handler: CommandHandler): void;
27
+ /**
28
+ * Handle an incoming CLI command.
29
+ *
30
+ * @param argv - Array of command line arguments (e.g. process.argv.slice(2))
31
+ */
32
+ handle(argv: string[]): Promise<void>;
33
+ }
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Configuration manager (ConfigManager)
3
+ *
4
+ * Unifies environment variables and application configuration access.
5
+ */
6
+ import type { ZodSchema } from 'zod';
1
7
  /**
2
8
  * ConfigManager - Central configuration store.
3
9
  * Supports loading from environment variables and initial objects.
@@ -5,6 +11,7 @@
5
11
  */
6
12
  export declare class ConfigManager {
7
13
  private config;
14
+ private schema;
8
15
  constructor(initialConfig?: Record<string, unknown>);
9
16
  /**
10
17
  * Load all environment variables from the active runtime.
@@ -23,4 +30,36 @@ export declare class ConfigManager {
23
30
  * Check whether a key exists.
24
31
  */
25
32
  has(key: string): boolean;
33
+ /**
34
+ * Define a Zod schema for configuration validation.
35
+ *
36
+ * @param schema - Zod schema for validation
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * config.defineSchema(z.object({
41
+ * DATABASE_URL: z.string().url(),
42
+ * PORT: z.number().default(3000),
43
+ * }))
44
+ * ```
45
+ */
46
+ defineSchema(schema: ZodSchema): void;
47
+ /**
48
+ * Validate configuration against the defined schema.
49
+ *
50
+ * Should be called during bootstrap to catch configuration errors early.
51
+ *
52
+ * @throws Error if validation fails with details about missing/invalid fields
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * try {
57
+ * config.validate()
58
+ * } catch (error) {
59
+ * console.error('Config validation failed:', error.message)
60
+ * process.exit(1)
61
+ * }
62
+ * ```
63
+ */
64
+ validate(): void;
26
65
  }
@@ -0,0 +1,62 @@
1
+ import type { ServiceKey } from '../Container';
2
+ import { RequestScopeMetrics, type RequestScopeObserver } from './RequestScopeMetrics';
3
+ /**
4
+ * Manages request-scoped service instances within a single HTTP request.
5
+ *
6
+ * Each request gets its own RequestScopeManager instance with isolated state.
7
+ * Services are cached within the request and automatically cleaned up when
8
+ * the request ends.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const scope = new RequestScopeManager()
13
+ * const cache = scope.resolve('productCache', () => new ProductCache())
14
+ * // ... use cache ...
15
+ * await scope.cleanup() // Called automatically by Gravito engine
16
+ * ```
17
+ */
18
+ export declare class RequestScopeManager {
19
+ private scoped;
20
+ private metadata;
21
+ private metrics;
22
+ private observer;
23
+ constructor(observer?: RequestScopeObserver);
24
+ /**
25
+ * Set observer for monitoring scope lifecycle
26
+ */
27
+ setObserver(observer: RequestScopeObserver): void;
28
+ /**
29
+ * Get metrics for this scope
30
+ */
31
+ getMetrics(): RequestScopeMetrics;
32
+ /**
33
+ * Resolve or retrieve a request-scoped service instance.
34
+ *
35
+ * If the service already exists in this scope, returns the cached instance.
36
+ * Otherwise, calls the factory function to create a new instance and caches it.
37
+ *
38
+ * Automatically detects and records services with cleanup methods.
39
+ *
40
+ * @template T - The type of the service.
41
+ * @param key - The service key (for caching).
42
+ * @param factory - Factory function to create the instance if not cached.
43
+ * @returns The cached or newly created instance.
44
+ */
45
+ resolve<T>(key: ServiceKey, factory: () => T): T;
46
+ /**
47
+ * Clean up all request-scoped instances.
48
+ *
49
+ * Calls the cleanup() method on each service that has one.
50
+ * Silently ignores cleanup errors to prevent cascading failures.
51
+ * Called automatically by the Gravito engine in the request finally block.
52
+ *
53
+ * @returns Promise that resolves when all cleanup is complete.
54
+ */
55
+ cleanup(): Promise<void>;
56
+ /**
57
+ * Get the number of services in this scope (for monitoring).
58
+ *
59
+ * @returns The count of cached services.
60
+ */
61
+ size(): number;
62
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * RequestScopeMetrics - Observability for RequestScope lifecycle
3
+ *
4
+ * Tracks cleanup execution time, scope size, and service counts
5
+ * for performance monitoring and diagnostics.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const metrics = new RequestScopeMetrics()
10
+ * metrics.recordCleanupStart()
11
+ * await scope.cleanup()
12
+ * metrics.recordCleanupEnd()
13
+ *
14
+ * console.log(metrics.toJSON())
15
+ * // { cleanupDuration: 2.5, scopeSize: 3, servicesCleaned: 3 }
16
+ * ```
17
+ */
18
+ export declare class RequestScopeMetrics {
19
+ private cleanupStartTime;
20
+ private cleanupDuration;
21
+ private scopeSize;
22
+ private servicesCleaned;
23
+ private errorsOccurred;
24
+ /**
25
+ * Record start of cleanup operation
26
+ */
27
+ recordCleanupStart(): void;
28
+ /**
29
+ * Record end of cleanup operation
30
+ *
31
+ * @param scopeSize - Number of services in the scope
32
+ * @param servicesCleaned - Number of services that had cleanup called
33
+ * @param errorsOccurred - Number of cleanup errors
34
+ */
35
+ recordCleanupEnd(scopeSize: number, servicesCleaned: number, errorsOccurred?: number): void;
36
+ /**
37
+ * Get cleanup duration in milliseconds
38
+ *
39
+ * @returns Duration in ms, or null if cleanup not completed
40
+ */
41
+ getCleanupDuration(): number | null;
42
+ /**
43
+ * Check if cleanup took longer than threshold (default 2ms)
44
+ * Useful for detecting slow cleanups
45
+ *
46
+ * @param thresholdMs - Threshold in milliseconds
47
+ * @returns True if cleanup exceeded threshold
48
+ */
49
+ isSlowCleanup(thresholdMs?: number): boolean;
50
+ /**
51
+ * Export metrics as JSON for logging/monitoring
52
+ */
53
+ toJSON(): {
54
+ cleanupDuration: number | null;
55
+ scopeSize: number;
56
+ servicesCleaned: number;
57
+ errorsOccurred: number;
58
+ hasErrors: boolean;
59
+ isSlowCleanup: boolean;
60
+ };
61
+ /**
62
+ * Export metrics as compact string for logging
63
+ */
64
+ toString(): string;
65
+ }
66
+ /**
67
+ * RequestScopeObserver - Hook for monitoring RequestScope lifecycle
68
+ *
69
+ * Implement this interface to receive callbacks during scope operations
70
+ */
71
+ export interface RequestScopeObserver {
72
+ /**
73
+ * Called when a service is resolved in the scope
74
+ */
75
+ onServiceResolved?(key: string | symbol, isFromCache: boolean): void;
76
+ /**
77
+ * Called when cleanup starts
78
+ */
79
+ onCleanupStart?(): void;
80
+ /**
81
+ * Called when cleanup completes
82
+ */
83
+ onCleanupEnd?(metrics: RequestScopeMetrics): void;
84
+ /**
85
+ * Called when cleanup encounters an error
86
+ */
87
+ onCleanupError?(error: Error): void;
88
+ }
89
+ /**
90
+ * RequestScopeMetricsCollector - Aggregates metrics across multiple scopes
91
+ *
92
+ * Used for application-level monitoring and performance tracking
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const collector = new RequestScopeMetricsCollector()
97
+ *
98
+ * // Record metrics from multiple requests
99
+ * collector.record(metrics1)
100
+ * collector.record(metrics2)
101
+ * collector.record(metrics3)
102
+ *
103
+ * // Get aggregated stats
104
+ * const stats = collector.getStats()
105
+ * console.log(stats.averageCleanupTime) // 3.5ms
106
+ * ```
107
+ */
108
+ export declare class RequestScopeMetricsCollector {
109
+ private metrics;
110
+ /**
111
+ * Record metrics from a request scope
112
+ */
113
+ record(metrics: RequestScopeMetrics): void;
114
+ /**
115
+ * Get aggregated statistics
116
+ */
117
+ getStats(): {
118
+ count: number;
119
+ averageCleanupTime: number | null;
120
+ maxCleanupTime: number | null;
121
+ minCleanupTime: number | null;
122
+ totalErrorCount: number;
123
+ errorRate: number;
124
+ };
125
+ /**
126
+ * Clear collected metrics
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get number of recorded metrics
131
+ */
132
+ size(): number;
133
+ /**
134
+ * Export metrics as JSON array
135
+ */
136
+ toJSON(): {
137
+ cleanupDuration: number | null;
138
+ scopeSize: number;
139
+ servicesCleaned: number;
140
+ errorsOccurred: number;
141
+ hasErrors: boolean;
142
+ isSlowCleanup: boolean;
143
+ }[];
144
+ }
@@ -1,8 +1,28 @@
1
+ import type { RequestScopeManager } from './Container/RequestScopeManager';
1
2
  /**
2
3
  * Factory type for creating service instances
3
4
  */
4
5
  export type Factory<T> = (container: Container) => T;
5
- export type BindingKey = string | symbol;
6
+ /**
7
+ * ServiceMap interface for type-safe IoC resolution.
8
+ *
9
+ * Extend this interface via module augmentation to get type inference:
10
+ * @example
11
+ * ```typescript
12
+ * declare module '@gravito/core' {
13
+ * interface ServiceMap {
14
+ * logger: Logger
15
+ * db: DatabaseConnection
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export type ServiceMap = {};
21
+ /**
22
+ * ServiceKey represents the allowed keys for service resolution.
23
+ * Includes keys from ServiceMap, generic strings, or symbols.
24
+ */
25
+ export type ServiceKey = keyof ServiceMap | (string & {}) | symbol;
6
26
  /**
7
27
  * Container - Simple Dependency Injection Container.
8
28
  * Manages service bindings and singleton instances.
@@ -11,6 +31,28 @@ export type BindingKey = string | symbol;
11
31
  export declare class Container {
12
32
  private bindings;
13
33
  private instances;
34
+ private resolutionStack;
35
+ /**
36
+ * Run a function within a request scope context.
37
+ *
38
+ * All service resolutions within the function will use the provided scope,
39
+ * enabling request-scoped service instances to be properly isolated.
40
+ *
41
+ * @template T - The return type of the function.
42
+ * @param scope - The RequestScopeManager for this request.
43
+ * @param fn - The function to execute within the scope.
44
+ * @returns The result of the function.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const scope = new RequestScopeManager()
49
+ * const result = await Container.runWithScope(scope, async () => {
50
+ * const service = container.make('requestScoped')
51
+ * return service.doSomething()
52
+ * })
53
+ * ```
54
+ */
55
+ static runWithScope<T>(scope: RequestScopeManager, fn: () => T | Promise<T>): T | Promise<T>;
14
56
  /**
15
57
  * Bind a service to the container.
16
58
  *
@@ -26,7 +68,7 @@ export declare class Container {
26
68
  * container.bind('logger', (c) => new ConsoleLogger());
27
69
  * ```
28
70
  */
29
- bind<T>(key: BindingKey, factory: Factory<T>): void;
71
+ bind<T>(key: ServiceKey, factory: Factory<T>): void;
30
72
  /**
31
73
  * Bind a shared service to the container (Singleton).
32
74
  *
@@ -42,11 +84,37 @@ export declare class Container {
42
84
  * container.singleton('db', (c) => new DatabaseConnection());
43
85
  * ```
44
86
  */
45
- singleton<T>(key: BindingKey, factory: Factory<T>): void;
87
+ singleton<T>(key: ServiceKey, factory: Factory<T>): void;
88
+ /**
89
+ * Bind a request-scoped service to the container.
90
+ *
91
+ * A new instance will be created for each request and cached within that request.
92
+ * The service is automatically cleaned up when the request ends.
93
+ *
94
+ * @template T - The type of the service being bound.
95
+ * @param key - The unique identifier for the service.
96
+ * @param factory - The factory function that creates the service instance.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * container.scoped('requestCache', (c) => new RequestProductCache());
101
+ * ```
102
+ */
103
+ scoped<T>(key: ServiceKey, factory: Factory<T>): void;
46
104
  /**
47
- * Register an existing instance as shared service.
105
+ * Register an existing instance as a shared service.
106
+ *
107
+ * @param key - The unique identifier for the service.
108
+ * @param instance - The instance to register.
48
109
  */
49
- instance<T>(key: BindingKey, instance: T): void;
110
+ instance<T>(key: ServiceKey, instance: T): void;
111
+ /**
112
+ * Check if a service is request-scoped.
113
+ *
114
+ * @param key - The service key to check.
115
+ * @returns True if the service is request-scoped.
116
+ */
117
+ isRequestScoped(key: ServiceKey): boolean;
50
118
  /**
51
119
  * Resolve a service instance from the container.
52
120
  *
@@ -62,17 +130,24 @@ export declare class Container {
62
130
  * const logger = container.make<Logger>('logger');
63
131
  * ```
64
132
  */
65
- make<T>(key: BindingKey): T;
133
+ make<K extends keyof ServiceMap>(key: K): ServiceMap[K];
134
+ make<T>(key: ServiceKey): T;
66
135
  /**
67
- * Check if a service is bound.
136
+ * Check if a service is bound or has an instance in the container.
137
+ *
138
+ * @param key - The service key to check.
139
+ * @returns True if the service exists.
68
140
  */
69
- has(key: BindingKey): boolean;
141
+ has(key: ServiceKey): boolean;
70
142
  /**
71
- * Flush all instances and bindings.
143
+ * Flush all instances and bindings from the container.
144
+ * Resets the container to an empty state.
72
145
  */
73
146
  flush(): void;
74
147
  /**
75
- * Forget a specific instance (but keep binding)
148
+ * Forget a specific instance while keeping its binding.
149
+ *
150
+ * @param key - The service key to forget.
76
151
  */
77
- forget(key: BindingKey): void;
152
+ forget(key: ServiceKey): void;
78
153
  }
@@ -42,6 +42,9 @@ export declare class ErrorHandler {
42
42
  constructor(deps: ErrorHandlerDeps);
43
43
  /**
44
44
  * Handle application errors
45
+ *
46
+ * Integrates RequestScope cleanup to ensure proper resource management
47
+ * even when errors occur during request processing.
45
48
  */
46
49
  handleError(err: unknown, c: GravitoContext): Promise<Response>;
47
50
  /**