@gravito/ripple 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +432 -18
  2. package/README.zh-TW.md +104 -2
  3. package/dist/atlas/src/DB.d.ts +301 -0
  4. package/dist/atlas/src/OrbitAtlas.d.ts +9 -0
  5. package/dist/atlas/src/config/defineConfig.d.ts +14 -0
  6. package/dist/atlas/src/config/index.d.ts +7 -0
  7. package/dist/atlas/src/config/loadConfig.d.ts +48 -0
  8. package/dist/atlas/src/connection/Connection.d.ts +108 -0
  9. package/dist/atlas/src/connection/ConnectionManager.d.ts +111 -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 +66 -0
  14. package/dist/atlas/src/drivers/PostgresDriver.d.ts +83 -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 +67 -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 +11 -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/index.d.ts +5 -0
  35. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +121 -0
  36. package/dist/atlas/src/orm/model/Model.d.ts +449 -0
  37. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +20 -0
  38. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +136 -0
  39. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +36 -0
  40. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +87 -0
  41. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +117 -0
  42. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +64 -0
  43. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +15 -0
  44. package/dist/atlas/src/orm/model/concerns/index.d.ts +12 -0
  45. package/dist/atlas/src/orm/model/decorators.d.ts +109 -0
  46. package/dist/atlas/src/orm/model/errors.d.ts +52 -0
  47. package/dist/atlas/src/orm/model/index.d.ts +10 -0
  48. package/dist/atlas/src/orm/model/relationships.d.ts +207 -0
  49. package/dist/atlas/src/orm/model/types.d.ts +12 -0
  50. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +123 -0
  51. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +54 -0
  52. package/dist/atlas/src/orm/schema/index.d.ts +6 -0
  53. package/dist/atlas/src/orm/schema/types.d.ts +85 -0
  54. package/dist/atlas/src/query/Expression.d.ts +60 -0
  55. package/dist/atlas/src/query/NPlusOneDetector.d.ts +10 -0
  56. package/dist/atlas/src/query/QueryBuilder.d.ts +573 -0
  57. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +51 -0
  58. package/dist/atlas/src/query/clauses/HavingClause.d.ts +70 -0
  59. package/dist/atlas/src/query/clauses/JoinClause.d.ts +87 -0
  60. package/dist/atlas/src/query/clauses/LimitClause.d.ts +82 -0
  61. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +69 -0
  62. package/dist/atlas/src/query/clauses/SelectClause.d.ts +71 -0
  63. package/dist/atlas/src/query/clauses/WhereClause.d.ts +167 -0
  64. package/dist/atlas/src/query/clauses/index.d.ts +11 -0
  65. package/dist/atlas/src/schema/Blueprint.d.ts +276 -0
  66. package/dist/atlas/src/schema/ColumnDefinition.d.ts +154 -0
  67. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +37 -0
  68. package/dist/atlas/src/schema/Schema.d.ts +131 -0
  69. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +23 -0
  70. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +26 -0
  71. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +28 -0
  72. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +97 -0
  73. package/dist/atlas/src/schema/grammars/index.d.ts +7 -0
  74. package/dist/atlas/src/schema/index.d.ts +8 -0
  75. package/dist/atlas/src/seed/Factory.d.ts +90 -0
  76. package/dist/atlas/src/seed/Seeder.d.ts +28 -0
  77. package/dist/atlas/src/seed/SeederRunner.d.ts +74 -0
  78. package/dist/atlas/src/seed/index.d.ts +6 -0
  79. package/dist/atlas/src/types/index.d.ts +1100 -0
  80. package/dist/atlas/src/utils/levenshtein.d.ts +9 -0
  81. package/dist/core/src/Application.d.ts +43 -17
  82. package/dist/core/src/CommandKernel.d.ts +33 -0
  83. package/dist/core/src/Container.d.ts +78 -14
  84. package/dist/core/src/HookManager.d.ts +422 -8
  85. package/dist/core/src/PlanetCore.d.ts +52 -7
  86. package/dist/core/src/Router.d.ts +41 -7
  87. package/dist/core/src/ServiceProvider.d.ts +14 -8
  88. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  89. package/dist/core/src/adapters/PhotonAdapter.d.ts +1 -0
  90. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  91. package/dist/core/src/adapters/types.d.ts +39 -0
  92. package/dist/core/src/engine/AOTRouter.d.ts +1 -11
  93. package/dist/core/src/engine/FastContext.d.ts +4 -2
  94. package/dist/core/src/engine/Gravito.d.ts +1 -1
  95. package/dist/core/src/engine/MinimalContext.d.ts +4 -2
  96. package/dist/core/src/engine/types.d.ts +6 -1
  97. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  98. package/dist/core/src/events/DeadLetterQueue.d.ts +145 -0
  99. package/dist/core/src/events/EventBackend.d.ts +11 -0
  100. package/dist/core/src/events/EventOptions.d.ts +109 -0
  101. package/dist/core/src/events/EventPriorityQueue.d.ts +202 -0
  102. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  103. package/dist/core/src/events/index.d.ts +14 -0
  104. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  105. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  106. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  107. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +240 -0
  108. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  109. package/dist/core/src/events/observability/index.d.ts +20 -0
  110. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  111. package/dist/core/src/events/types.d.ts +75 -0
  112. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  113. package/dist/core/src/exceptions/index.d.ts +1 -0
  114. package/dist/core/src/http/cookie.d.ts +29 -0
  115. package/dist/core/src/http/types.d.ts +21 -0
  116. package/dist/core/src/index.d.ts +13 -3
  117. package/dist/core/src/instrumentation/index.d.ts +35 -0
  118. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  119. package/dist/core/src/instrumentation/types.d.ts +182 -0
  120. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +316 -0
  121. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  122. package/dist/core/src/reliability/index.d.ts +6 -0
  123. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  124. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  125. package/dist/index.js +6487 -9562
  126. package/dist/index.js.map +68 -62
  127. package/dist/photon/src/index.d.ts +69 -5
  128. package/dist/photon/src/middleware/binary.d.ts +12 -15
  129. package/dist/photon/src/middleware/htmx.d.ts +39 -0
  130. package/dist/photon/src/middleware/ratelimit.d.ts +157 -0
  131. package/dist/photon/src/openapi.d.ts +19 -0
  132. package/dist/proto/ripple.proto +120 -0
  133. package/dist/ripple/src/OrbitRipple.d.ts +34 -12
  134. package/dist/ripple/src/RippleServer.d.ts +76 -63
  135. package/dist/ripple/src/channels/ChannelManager.d.ts +132 -22
  136. package/dist/ripple/src/drivers/LocalDriver.d.ts +43 -11
  137. package/dist/ripple/src/drivers/NATSDriver.d.ts +87 -0
  138. package/dist/ripple/src/drivers/RedisDriver.d.ts +135 -28
  139. package/dist/ripple/src/drivers/index.d.ts +1 -0
  140. package/dist/ripple/src/engines/BunEngine.d.ts +98 -0
  141. package/dist/ripple/src/engines/IRippleEngine.d.ts +205 -0
  142. package/dist/ripple/src/engines/index.d.ts +11 -0
  143. package/dist/ripple/src/errors/RippleError.d.ts +48 -0
  144. package/dist/ripple/src/errors/index.d.ts +1 -0
  145. package/dist/ripple/src/events/BroadcastEvent.d.ts +78 -6
  146. package/dist/ripple/src/events/BroadcastManager.d.ts +100 -0
  147. package/dist/ripple/src/events/Broadcaster.d.ts +211 -14
  148. package/dist/ripple/src/events/index.d.ts +1 -0
  149. package/dist/ripple/src/health/HealthChecker.d.ts +93 -0
  150. package/dist/ripple/src/health/index.d.ts +1 -0
  151. package/dist/ripple/src/index.d.ts +42 -17
  152. package/dist/ripple/src/logging/Logger.d.ts +99 -0
  153. package/dist/ripple/src/logging/index.d.ts +1 -0
  154. package/dist/ripple/src/middleware/InterceptorManager.d.ts +21 -0
  155. package/dist/ripple/src/observability/RippleMetrics.d.ts +24 -0
  156. package/dist/ripple/src/reliability/AckManager.d.ts +48 -0
  157. package/dist/ripple/src/serializers/ISerializer.d.ts +39 -0
  158. package/dist/ripple/src/serializers/JsonSerializer.d.ts +19 -0
  159. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +38 -0
  160. package/dist/ripple/src/serializers/index.d.ts +3 -0
  161. package/dist/ripple/src/tracking/ConnectionTracker.d.ts +116 -0
  162. package/dist/ripple/src/tracking/SessionManager.d.ts +104 -0
  163. package/dist/ripple/src/tracking/index.d.ts +2 -0
  164. package/dist/ripple/src/types.d.ts +766 -28
  165. package/dist/ripple/src/utils/MessageSerializer.d.ts +54 -0
  166. package/dist/ripple/src/utils/TokenBucket.d.ts +25 -0
  167. package/dist/ripple/src/utils/index.d.ts +1 -0
  168. package/package.json +25 -7
@@ -5,98 +5,99 @@
5
5
  *
6
6
  * @module @gravito/ripple
7
7
  */
8
- import type { Server } from 'bun';
9
- import type { ClientData, RippleConfig, RippleWebSocket, WebSocketHandlerConfig } from './types';
8
+ import type { RippleSocket } from './engines/IRippleEngine';
9
+ import type { RippleConfig, RippleInterceptor, WebSocketHandlerConfig } from './types';
10
10
  /**
11
11
  * Ripple WebSocket Server
12
12
  *
13
- * Provides channel-based real-time communication using Bun's native WebSocket.
13
+ * Provides channel-based real-time communication with multi-runtime support.
14
+ * Can run on Bun (native WebSocket), Node.js (uWebSockets.js or ws).
14
15
  *
15
- * @example
16
- * ```typescript
17
- * const ripple = new RippleServer({
18
- * path: '/ws',
19
- * authorizer: async (channel, userId) => {
20
- * // Custom authorization logic
21
- * return true
22
- * }
23
- * })
24
- *
25
- * Bun.serve({
26
- * fetch: (req, server) => {
27
- * if (ripple.upgrade(req, server)) return
28
- * return new Response('Not found', { status: 404 })
29
- * },
30
- * websocket: ripple.getHandler()
31
- * })
32
- * ```
16
+ * @since 5.0.0 - Multi-runtime support via engine abstraction
33
17
  */
34
18
  export declare class RippleServer {
35
19
  private channels;
36
20
  private driver;
21
+ private engine;
37
22
  private authorizer?;
38
23
  private pingInterval?;
39
24
  private eventListeners;
25
+ private logger;
26
+ private tracker;
27
+ private healthChecker;
28
+ private serializer;
29
+ private whisperLimiters;
30
+ private sessionManager?;
31
+ private ackManager;
32
+ private rippleMetrics?;
33
+ private interceptors;
34
+ private clientSockets;
40
35
  readonly config: Required<Pick<RippleConfig, 'path' | 'authEndpoint' | 'pingInterval'>> & RippleConfig;
41
36
  constructor(config?: RippleConfig);
42
37
  /**
43
- * Register an event listener for client messages.
44
- *
45
- * @param event - The event name to listen for.
46
- * @param handler - The callback function.
38
+ * Create the appropriate WebSocket engine based on configuration.
47
39
  */
48
- on(event: string, handler: (socket: RippleWebSocket, data: any) => void): void;
40
+ private createEngine;
49
41
  /**
50
- * Fluent API for broadcasting to a channel.
51
- *
52
- * @param channel - The channel name.
42
+ * Auto-detect the current JavaScript runtime.
43
+ */
44
+ private detectRuntime;
45
+ /**
46
+ * Setup engine event handlers.
47
+ */
48
+ private setupEngineHandlers;
49
+ private emit;
50
+ on(event: string, handler: (socket: RippleSocket, data: any) => void): void;
51
+ /**
52
+ * Get the name of the active message driver.
53
53
  */
54
+ get driverName(): string;
54
55
  to(channel: string): {
55
- emit: (event: string, data: unknown) => void;
56
+ emit: (event: string, data: unknown, options?: {
57
+ needAck?: boolean;
58
+ timeout?: number;
59
+ }) => void;
56
60
  };
57
61
  /**
58
- * Attempt to upgrade an HTTP request to WebSocket.
62
+ * Upgrade an HTTP request to WebSocket (Bun/uWS only).
59
63
  *
60
- * @param req - The HTTP request.
61
- * @param server - The Bun server instance.
62
- * @returns True if the request was upgraded, false otherwise.
64
+ * @deprecated Use engine-based initialization via init() instead.
65
+ * This method is kept for backward compatibility with v4.x.
63
66
  */
64
- upgrade(req: Request, server: Server<ClientData>): boolean;
67
+ upgrade(req: Request, options?: {
68
+ userId?: string;
69
+ }): boolean;
65
70
  /**
66
- * Get WebSocket handler configuration for Bun.serve.
71
+ * Get WebSocket handler configuration (Bun only).
67
72
  *
68
- * @returns An object containing the WebSocket event handlers.
73
+ * @deprecated Use engine-based initialization via init() instead.
74
+ * This method is kept for backward compatibility with v4.x.
69
75
  */
70
76
  getHandler(): WebSocketHandlerConfig;
71
77
  private handleOpen;
72
78
  private handleMessage;
79
+ private handleBinaryMessage;
80
+ private broadcastBinaryToChannel;
81
+ broadcastBinary(channel: string, event: string, data: ArrayBuffer): void;
73
82
  private handleClose;
74
83
  private handleDrain;
75
84
  private handleSubscribe;
76
85
  private handleUnsubscribe;
77
86
  private handleWhisper;
78
- /**
79
- * Broadcast an event to a channel.
80
- *
81
- * @param channel - The channel name.
82
- * @param event - The event name.
83
- * @param data - The event data.
84
- */
85
- broadcast(channel: string, event: string, data: unknown): void;
86
- /**
87
- * Broadcast to specific client IDs.
88
- *
89
- * @param clientIds - An array of client IDs.
90
- * @param event - The event name.
91
- * @param data - The event data.
92
- */
87
+ broadcast(channel: string, event: string, data: unknown, options?: {
88
+ needAck?: boolean;
89
+ timeout?: number;
90
+ }): void;
93
91
  broadcastToClients(clientIds: string[], event: string, data: unknown): void;
94
92
  private broadcastToChannel;
93
+ private sendRaw;
95
94
  private send;
96
95
  /**
97
- * Get server statistics.
98
- *
99
- * @returns An object containing connection and channel statistics.
96
+ * Add a middleware interceptor (v4.0+).
97
+ */
98
+ use(interceptor: RippleInterceptor): this;
99
+ /**
100
+ * Get real-time server statistics.
100
101
  */
101
102
  getStats(): {
102
103
  totalClients: number;
@@ -107,19 +108,31 @@ export declare class RippleServer {
107
108
  }[];
108
109
  };
109
110
  /**
110
- * Initialize the server.
111
+ * Get Prometheus metrics (v3.7+).
112
+ */
113
+ getMetrics(): string;
114
+ /**
115
+ * Get server health status.
116
+ */
117
+ getHealth(): Promise<import(".").HealthCheckResult>;
118
+ /**
119
+ * Initialize and start the RippleServer.
111
120
  *
112
- * Initializes the driver and starts the ping interval.
121
+ * This method:
122
+ * 1. Initializes the driver (Redis/NATS/Local)
123
+ * 2. Initializes the serializer (JSON/Protobuf)
124
+ * 3. Starts the WebSocket engine (Bun/uWS/ws)
125
+ * 4. Starts the ping interval
113
126
  *
114
- * @returns A promise that resolves when initialization is complete.
127
+ * @since 5.0.0
115
128
  */
116
- init(): Promise<void>;
129
+ start(): Promise<void>;
117
130
  /**
118
- * Shutdown the server.
131
+ * Initialize the RippleServer without starting the engine.
119
132
  *
120
- * Clears the ping interval and shuts down the driver.
121
- *
122
- * @returns A promise that resolves when shutdown is complete.
133
+ * @deprecated Use start() instead. This method is kept for backward compatibility.
134
+ * @since 3.0.0
123
135
  */
136
+ init(): Promise<void>;
124
137
  shutdown(): Promise<void>;
125
138
  }
@@ -5,9 +5,40 @@
5
5
  *
6
6
  * @module @gravito/ripple/channels
7
7
  */
8
- import type { PresenceUserInfo, RippleWebSocket } from '../types';
8
+ import type { RippleSocket } from '../engines/IRippleEngine';
9
+ import type { PresenceUserInfo, RippleDriver } from '../types';
9
10
  /**
10
- * Manages all channel subscriptions and presence tracking
11
+ * Manages all channel subscriptions and presence tracking.
12
+ *
13
+ * The ChannelManager is the central coordinator for WebSocket channel subscriptions.
14
+ * It maintains mappings between clients, channels, and presence information, providing
15
+ * efficient lookups for broadcasting and presence tracking.
16
+ *
17
+ * **Internal Use**: This class is primarily used internally by RippleServer. Most developers
18
+ * interact with channels through RippleServer's public API instead.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * // Typically used internally by RippleServer
23
+ * const manager = new ChannelManager()
24
+ *
25
+ * // Add a client when they connect
26
+ * manager.addClient(ws)
27
+ *
28
+ * // Subscribe them to a channel
29
+ * manager.subscribe(ws.data.id, 'news')
30
+ *
31
+ * // Get all subscribers for broadcasting
32
+ * const subscribers = manager.getSubscribers('news')
33
+ * subscribers.forEach(ws => ws.send(message))
34
+ *
35
+ * // For presence channels with user info
36
+ * manager.subscribe(ws.data.id, 'presence-chat.room1', {
37
+ * id: 'user-123',
38
+ * info: { name: 'John Doe', avatar: '/avatars/john.jpg' }
39
+ * })
40
+ * const members = manager.getPresenceMembers('presence-chat.room1')
41
+ * ```
11
42
  */
12
43
  export declare class ChannelManager {
13
44
  /** Map of channel name -> Set of client IDs */
@@ -16,56 +47,135 @@ export declare class ChannelManager {
16
47
  private clients;
17
48
  /** Map of presence channel -> Map of user ID -> user info */
18
49
  private presenceMembers;
50
+ /** Optional driver for distributed presence tracking */
51
+ private driver?;
52
+ /**
53
+ * Create a new ChannelManager.
54
+ *
55
+ * @param driver - Optional driver for distributed presence tracking
56
+ */
57
+ constructor(driver?: RippleDriver);
19
58
  /**
20
- * Register a new client connection
59
+ * Register a new client WebSocket connection.
60
+ *
61
+ * Adds the client to the internal clients map, making it available for channel subscriptions
62
+ * and broadcasts. This should be called immediately when a WebSocket connection is established.
63
+ *
64
+ * @param ws - The WebSocket connection with client data
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * // Called internally by RippleServer on connection
69
+ * private handleOpen(ws: RippleWebSocket): void {
70
+ * this.channels.addClient(ws)
71
+ * // ... other connection logic
72
+ * }
73
+ * ```
21
74
  */
22
- addClient(ws: RippleWebSocket): void;
75
+ addClient(ws: RippleSocket): void;
23
76
  /**
24
- * Remove a client and all its subscriptions
77
+ * Remove a client and unsubscribe from all channels.
78
+ *
79
+ * Performs cleanup when a client disconnects, removing them from all channel subscriptions
80
+ * and the client registry. Returns the list of channels the client was subscribed to,
81
+ * useful for sending presence leave events.
82
+ *
83
+ * @param clientId - The unique client identifier (ws.data.id)
84
+ * @returns Array of channel names the client was subscribed to before removal
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * // Called internally by RippleServer on disconnect
89
+ * private handleClose(ws: RippleWebSocket): void {
90
+ * const leftChannels = this.channels.removeClient(ws.data.id)
91
+ *
92
+ * // Notify presence channels about user leaving
93
+ * for (const channel of leftChannels) {
94
+ * if (channel.startsWith('presence-')) {
95
+ * this.broadcast(channel, 'presence', { event: 'leave', data: ... })
96
+ * }
97
+ * }
98
+ * }
99
+ * ```
25
100
  */
26
101
  removeClient(clientId: string): string[];
27
102
  /**
28
- * Get a client by ID
103
+ * Get a client WebSocket by ID.
104
+ *
105
+ * @param clientId - The client identifier
106
+ * @returns The WebSocket connection, or undefined if not found
29
107
  */
30
- getClient(clientId: string): RippleWebSocket | undefined;
108
+ getClient(clientId: string): RippleSocket | undefined;
31
109
  /**
32
- * Get all connected clients
110
+ * Get all currently connected WebSocket clients.
111
+ *
112
+ * @returns Array of all connected WebSocket instances
33
113
  */
34
- getAllClients(): RippleWebSocket[];
114
+ getAllClients(): RippleSocket[];
35
115
  /**
36
- * Subscribe a client to a channel
116
+ * Subscribe a client to a channel.
117
+ *
118
+ * @param clientId - The client identifier
119
+ * @param channel - The channel name
120
+ * @param userInfo - User information for presence channels (required for presence-* channels)
121
+ * @returns true if subscription succeeded, false if client not found
37
122
  */
38
- subscribe(clientId: string, channel: string, userInfo?: PresenceUserInfo): boolean;
123
+ subscribe(clientId: string, channel: string, userInfo?: PresenceUserInfo): Promise<boolean>;
39
124
  /**
40
- * Unsubscribe a client from a channel
125
+ * Unsubscribe a client from a channel.
126
+ *
127
+ * @param clientId - The client identifier
128
+ * @param channel - The channel name
129
+ * @returns true if unsubscription succeeded, false if client not found
41
130
  */
42
- unsubscribe(clientId: string, channel: string): boolean;
131
+ unsubscribe(clientId: string, channel: string): Promise<boolean>;
43
132
  /**
44
- * Get all subscribers of a channel
133
+ * Get all WebSocket subscribers of a channel.
134
+ *
135
+ * @param channel - The channel name
136
+ * @returns Array of WebSocket connections subscribed to the channel
45
137
  */
46
- getSubscribers(channel: string): RippleWebSocket[];
138
+ getSubscribers(channel: string): RippleSocket[];
47
139
  /**
48
- * Check if a client is subscribed to a channel
140
+ * Check if a client is subscribed to a channel.
141
+ *
142
+ * @param clientId - The client identifier
143
+ * @param channel - The channel name
144
+ * @returns true if subscribed, false otherwise
49
145
  */
50
146
  isSubscribed(clientId: string, channel: string): boolean;
51
147
  /**
52
- * Add a member to a presence channel
148
+ * Add a member to a presence channel.
149
+ *
150
+ * Uses driver for distributed tracking if available.
53
151
  */
54
152
  private addPresenceMember;
55
153
  /**
56
- * Remove a member from a presence channel
154
+ * Remove a member from a presence channel.
155
+ *
156
+ * Uses driver for distributed tracking if available.
57
157
  */
58
158
  private removePresenceMember;
59
159
  /**
60
- * Get all members of a presence channel
160
+ * Get all members of a presence channel.
161
+ *
162
+ * Queries driver if available for distributed presence data.
163
+ *
164
+ * @param channel - The presence channel name
165
+ * @returns Array of user information for all members in the channel
61
166
  */
62
- getPresenceMembers(channel: string): PresenceUserInfo[];
167
+ getPresenceMembers(channel: string): Promise<PresenceUserInfo[]>;
63
168
  /**
64
- * Get member count for a channel
169
+ * Get subscriber count for a channel.
170
+ *
171
+ * @param channel - The channel name
172
+ * @returns Number of clients subscribed to the channel
65
173
  */
66
174
  getMemberCount(channel: string): number;
67
175
  /**
68
- * Get channel statistics
176
+ * Get comprehensive channel statistics.
177
+ *
178
+ * @returns Statistics object containing total clients, channels, and per-channel subscriber counts
69
179
  */
70
180
  getStats(): {
71
181
  totalClients: number;
@@ -1,29 +1,61 @@
1
1
  /**
2
2
  * @fileoverview Local (in-memory) driver for @gravito/ripple
3
3
  *
4
- * Suitable for single-instance deployments. For horizontal scaling,
5
- * use the Redis driver.
6
- *
7
4
  * @module @gravito/ripple/drivers
8
5
  */
9
- import type { RippleDriver } from '../types';
6
+ import type { DriverStatus, RippleDriver } from '../types';
10
7
  /**
11
- * In-memory driver for single-instance deployments
8
+ * Local (in-memory) driver for Ripple.
9
+ *
10
+ * This driver is intended for development and single-server deployments.
11
+ * It distributes messages directly within the current process memory.
12
12
  *
13
- * This driver keeps all state in memory and is suitable for:
14
- * - Development
15
- * - Single-server deployments
16
- * - Serverless functions (with caveats)
13
+ * @example
14
+ * ```typescript
15
+ * import { RippleServer, LocalDriver } from '@gravito/ripple'
17
16
  *
18
- * For multi-server deployments, use RedisDriver instead.
17
+ * const server = new RippleServer({
18
+ * driver: 'local' // Uses LocalDriver internally
19
+ * })
20
+ * ```
19
21
  */
20
22
  export declare class LocalDriver implements RippleDriver {
23
+ /** Driver name identifier */
21
24
  readonly name = "local";
22
- /** Event callbacks per channel */
25
+ /** In-memory map of channel subscribers: channel -> set of callbacks */
23
26
  private listeners;
27
+ private _initialized;
28
+ /**
29
+ * Publish a message to a channel within the current process.
30
+ *
31
+ * @param channel - Target channel name
32
+ * @param event - Event name
33
+ * @param data - Event payload
34
+ */
24
35
  publish(channel: string, event: string, data: unknown): Promise<void>;
36
+ /**
37
+ * Subscribe to a channel in memory.
38
+ *
39
+ * @param channel - Channel name
40
+ * @param callback - Function called when a message is published to this channel
41
+ */
25
42
  subscribe(channel: string, callback: (event: string, data: unknown) => void): Promise<void>;
43
+ /**
44
+ * Unsubscribe from a channel in memory.
45
+ *
46
+ * @param channel - Channel name
47
+ */
26
48
  unsubscribe(channel: string): Promise<void>;
49
+ /**
50
+ * Initialize the local driver.
51
+ */
27
52
  init(): Promise<void>;
53
+ /**
54
+ * Shutdown the local driver and clear all listeners.
55
+ */
28
56
  shutdown(): Promise<void>;
57
+ /**
58
+ * Get the current status of the local driver.
59
+ */
60
+ getStatus(): DriverStatus;
29
61
  }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @fileoverview NATS driver for @gravito/ripple
3
+ *
4
+ * @module @gravito/ripple/drivers
5
+ */
6
+ import type { ConnectionOptions } from 'nats';
7
+ import type { RippleLogger } from '../logging/Logger';
8
+ import type { DriverStatus, PresenceUserInfo, RippleDriver } from '../types';
9
+ /**
10
+ * Configuration for the NATSDriver.
11
+ */
12
+ export interface NATSDriverConfig {
13
+ /** NATS server URL (default: 'nats://localhost:4222') */
14
+ servers?: string | string[];
15
+ /** Credentials for authentication */
16
+ user?: string;
17
+ password?: string;
18
+ token?: string;
19
+ /** Prefix for Ripple NATS subjects (default: 'ripple.') */
20
+ subjectPrefix?: string;
21
+ /** Custom logger instance */
22
+ logger?: RippleLogger;
23
+ /** Optional NATS connection options */
24
+ connectionOptions?: ConnectionOptions;
25
+ }
26
+ /**
27
+ * NATS driver for Ripple, offering high-performance distributed broadcasting.
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * import { RippleServer, NATSDriver } from '@gravito/ripple'
32
+ *
33
+ * const server = new RippleServer({
34
+ * driver: 'nats',
35
+ * nats: {
36
+ * servers: 'nats://localhost:4222'
37
+ * }
38
+ * })
39
+ * ```
40
+ */
41
+ export declare class NATSDriver implements RippleDriver {
42
+ private config;
43
+ readonly name = "nats";
44
+ private nats?;
45
+ private subjectPrefix;
46
+ private subscriptions;
47
+ private callbacks;
48
+ private _initialized;
49
+ private _connected;
50
+ private _lastError?;
51
+ private logger;
52
+ constructor(config?: NATSDriverConfig);
53
+ get isInitialized(): boolean;
54
+ init(): Promise<void>;
55
+ publish(channel: string, event: string, data: unknown): Promise<void>;
56
+ subscribe(channel: string, callback: (event: string, data: unknown) => void): Promise<void>;
57
+ unsubscribe(channel: string): Promise<void>;
58
+ shutdown(): Promise<void>;
59
+ getStatus(): DriverStatus;
60
+ /**
61
+ * Track presence member using NATS KV Store.
62
+ *
63
+ * Creates or updates a bucket for the channel and stores user info with TTL.
64
+ *
65
+ * @param channel - Presence channel name
66
+ * @param userInfo - User information to store
67
+ * @since 4.0.0-alpha
68
+ */
69
+ trackPresence(channel: string, userInfo: PresenceUserInfo): Promise<void>;
70
+ /**
71
+ * Remove presence member from NATS KV Store.
72
+ *
73
+ * @param channel - Presence channel name
74
+ * @param userId - User ID to remove
75
+ * @since 4.0.0-alpha
76
+ */
77
+ untrackPresence(channel: string, userId: string | number): Promise<void>;
78
+ /**
79
+ * Get all presence members from NATS KV Store.
80
+ *
81
+ * @param channel - Presence channel name
82
+ * @returns Array of presence user information
83
+ * @since 4.0.0-alpha
84
+ */
85
+ getPresenceMembers(channel: string): Promise<PresenceUserInfo[]>;
86
+ private handleError;
87
+ }