@gravito/ripple 3.0.1 → 3.1.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 (39) hide show
  1. package/README.md +179 -6
  2. package/README.zh-TW.md +104 -2
  3. package/dist/core/src/Application.d.ts +43 -17
  4. package/dist/core/src/Container.d.ts +37 -3
  5. package/dist/core/src/HookManager.d.ts +6 -4
  6. package/dist/core/src/PlanetCore.d.ts +52 -7
  7. package/dist/core/src/Router.d.ts +40 -2
  8. package/dist/core/src/ServiceProvider.d.ts +14 -8
  9. package/dist/core/src/adapters/types.d.ts +12 -0
  10. package/dist/core/src/engine/Gravito.d.ts +1 -1
  11. package/dist/core/src/http/cookie.d.ts +29 -0
  12. package/dist/core/src/index.d.ts +1 -0
  13. package/dist/index.js +531 -64
  14. package/dist/index.js.map +16 -10
  15. package/dist/photon/src/index.d.ts +55 -5
  16. package/dist/photon/src/middleware/binary.d.ts +12 -15
  17. package/dist/photon/src/middleware/htmx.d.ts +39 -0
  18. package/dist/ripple/src/OrbitRipple.d.ts +34 -12
  19. package/dist/ripple/src/RippleServer.d.ts +418 -25
  20. package/dist/ripple/src/channels/ChannelManager.d.ts +107 -12
  21. package/dist/ripple/src/drivers/LocalDriver.d.ts +43 -11
  22. package/dist/ripple/src/drivers/RedisDriver.d.ts +106 -28
  23. package/dist/ripple/src/errors/RippleError.d.ts +48 -0
  24. package/dist/ripple/src/errors/index.d.ts +1 -0
  25. package/dist/ripple/src/events/BroadcastEvent.d.ts +78 -6
  26. package/dist/ripple/src/events/BroadcastManager.d.ts +100 -0
  27. package/dist/ripple/src/events/Broadcaster.d.ts +211 -14
  28. package/dist/ripple/src/events/index.d.ts +1 -0
  29. package/dist/ripple/src/health/HealthChecker.d.ts +93 -0
  30. package/dist/ripple/src/health/index.d.ts +1 -0
  31. package/dist/ripple/src/index.d.ts +40 -17
  32. package/dist/ripple/src/logging/Logger.d.ts +99 -0
  33. package/dist/ripple/src/logging/index.d.ts +1 -0
  34. package/dist/ripple/src/tracking/ConnectionTracker.d.ts +116 -0
  35. package/dist/ripple/src/tracking/index.d.ts +1 -0
  36. package/dist/ripple/src/types.d.ts +592 -19
  37. package/dist/ripple/src/utils/MessageSerializer.d.ts +44 -0
  38. package/dist/ripple/src/utils/index.d.ts +1 -0
  39. package/package.json +5 -3
@@ -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
  }
@@ -1,63 +1,141 @@
1
1
  /**
2
2
  * @fileoverview Redis driver for @gravito/ripple
3
3
  *
4
- * Enables horizontal scaling across multiple server instances using
5
- * Redis Pub/Sub for message broadcasting.
6
- *
7
4
  * @module @gravito/ripple/drivers
8
5
  */
9
- import type { RippleDriver } from '../types';
6
+ import type { RippleLogger } from '../logging/Logger';
7
+ import type { DriverStatus, RippleDriver } from '../types';
8
+ /**
9
+ * Configuration for the RedisDriver.
10
+ */
11
+ export interface RedisDriverConfig {
12
+ /** Redis server hostname (default: 'localhost') */
13
+ host?: string;
14
+ /** Redis server port (default: 6379) */
15
+ port?: number;
16
+ /** Redis password for authentication */
17
+ password?: string;
18
+ /** Redis database index (default: 0) */
19
+ db?: number;
20
+ /** Prefix for Ripple Redis channels (default: 'ripple:') */
21
+ keyPrefix?: string;
22
+ /** Custom logger instance */
23
+ logger?: RippleLogger;
24
+ /** Connection timeout in milliseconds (default: 5000) */
25
+ connectTimeout?: number;
26
+ /** Command timeout in milliseconds (default: 3000) */
27
+ commandTimeout?: number;
28
+ /** Whether to enable ready check (default: true) */
29
+ enableReadyCheck?: boolean;
30
+ /** Whether to connect lazily (default: false) */
31
+ lazyConnect?: boolean;
32
+ }
10
33
  /**
11
- * Redis-based driver for multi-server deployments
34
+ * Redis driver for Ripple, enabling horizontal scaling via Redis Pub/Sub.
12
35
  *
13
- * This driver uses Redis Pub/Sub to broadcast messages across multiple
14
- * server instances, enabling horizontal scaling of WebSocket connections.
36
+ * This driver distributes messages across multiple server instances, allowing
37
+ * clients connected to different servers to receive the same broadcasts.
15
38
  *
16
39
  * @example
17
40
  * ```typescript
18
- * const ripple = new RippleServer({
41
+ * import { RippleServer, RedisDriver } from '@gravito/ripple'
42
+ *
43
+ * const server = new RippleServer({
19
44
  * driver: 'redis',
20
45
  * redis: {
21
46
  * host: 'localhost',
22
- * port: 6379
47
+ * port: 6379,
48
+ * password: 'secret_password'
23
49
  * }
24
50
  * })
25
51
  * ```
26
52
  */
27
53
  export declare class RedisDriver implements RippleDriver {
28
54
  private config;
55
+ /** Driver name identifier */
29
56
  readonly name = "redis";
30
- private redis;
31
- private subscriber;
57
+ /** Redis client for publishing messages */
58
+ private redis?;
59
+ /** Redis client for subscribing to messages */
60
+ private subscriber?;
61
+ /** Prefix for Redis channels to avoid collisions */
32
62
  private channelPrefix;
63
+ /** Local subscription map: channel -> callbacks */
33
64
  private subscriptions;
65
+ private _initialized;
66
+ private _connected;
67
+ private _lastError?;
68
+ private logger;
69
+ /**
70
+ * Create a new RedisDriver.
71
+ *
72
+ * @param config - Redis connection and behavior configuration
73
+ */
34
74
  constructor(config?: RedisDriverConfig);
75
+ /**
76
+ * Check if the driver has been initialized.
77
+ */
78
+ get isInitialized(): boolean;
79
+ /**
80
+ * Initialize the Redis connections (Publisher and Subscriber).
81
+ *
82
+ * This method performs dynamic import of 'ioredis' to avoid mandatory
83
+ * dependency on users who only use the local driver.
84
+ *
85
+ * @throws {RippleDriverError} If 'ioredis' is not installed or connection fails
86
+ */
35
87
  init(): Promise<void>;
88
+ /**
89
+ * Publish a message to Redis Pub/Sub.
90
+ *
91
+ * @param channel - Target channel name
92
+ * @param event - Event name
93
+ * @param data - Event payload
94
+ * @throws {RippleDriverError} If driver is not initialized
95
+ */
36
96
  publish(channel: string, event: string, data: unknown): Promise<void>;
97
+ /**
98
+ * Subscribe to a channel via Redis Pub/Sub.
99
+ *
100
+ * Multiple calls for the same channel will only result in one Redis subscription,
101
+ * while maintaining all local callbacks.
102
+ *
103
+ * @param channel - Channel name
104
+ * @param callback - Function called when a message is received from Redis
105
+ * @throws {RippleDriverError} If driver is not initialized
106
+ */
37
107
  subscribe(channel: string, callback: (event: string, data: unknown) => void): Promise<void>;
108
+ /**
109
+ * Unsubscribe from a channel via Redis Pub/Sub.
110
+ *
111
+ * If no local callbacks remain for the channel, the actual Redis unsubscription
112
+ * is performed.
113
+ *
114
+ * @param channel - Channel name
115
+ */
38
116
  unsubscribe(channel: string): Promise<void>;
117
+ /**
118
+ * Shutdown the Redis driver and close all connections.
119
+ */
39
120
  shutdown(): Promise<void>;
40
121
  /**
41
- * Handle incoming Redis messages
122
+ * Get the current status of the Redis driver.
123
+ */
124
+ getStatus(): DriverStatus;
125
+ /**
126
+ * Handle an incoming message from Redis Pub/Sub.
127
+ *
128
+ * Dispatches the message to all local callbacks registered for the channel.
42
129
  */
43
130
  private handleMessage;
44
131
  /**
45
- * Dynamically import ioredis to avoid bundling it if not used
132
+ * Handle Redis client errors.
133
+ */
134
+ private handleError;
135
+ /**
136
+ * Dynamically import ioredis to check if it's available.
137
+ *
138
+ * @throws {RippleDriverError} If ioredis package is missing
46
139
  */
47
140
  private getRedisClient;
48
141
  }
49
- /**
50
- * Configuration options for RedisDriver
51
- */
52
- export interface RedisDriverConfig {
53
- /** Redis host (default: 'localhost') */
54
- host?: string;
55
- /** Redis port (default: 6379) */
56
- port?: number;
57
- /** Redis password (optional) */
58
- password?: string;
59
- /** Redis database number (default: 0) */
60
- db?: number;
61
- /** Key prefix for channels (default: 'ripple:') */
62
- keyPrefix?: string;
63
- }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @fileoverview Ripple error types
3
+ *
4
+ * @module @gravito/ripple/errors
5
+ */
6
+ /**
7
+ * Base error class for Ripple module.
8
+ *
9
+ * Provides structured error handling with error codes and messages.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * throw new RippleError('INVALID_FORMAT', 'Invalid message format')
14
+ * ```
15
+ */
16
+ export declare class RippleError extends Error {
17
+ readonly code: string;
18
+ /**
19
+ * Creates a new RippleError instance.
20
+ *
21
+ * @param code - The error code.
22
+ * @param message - The error message.
23
+ */
24
+ constructor(code: string, message: string);
25
+ }
26
+ /**
27
+ * Error class for driver-related issues.
28
+ *
29
+ * Used specifically for errors that occur in driver implementations
30
+ * (LocalDriver, RedisDriver).
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * throw new RippleDriverError(
35
+ * 'REDIS_NOT_INSTALLED',
36
+ * 'ioredis is required for RedisDriver'
37
+ * )
38
+ * ```
39
+ */
40
+ export declare class RippleDriverError extends RippleError {
41
+ /**
42
+ * Creates a new RippleDriverError instance.
43
+ *
44
+ * @param code - The error code.
45
+ * @param message - The error message.
46
+ */
47
+ constructor(code: string, message: string);
48
+ }
@@ -0,0 +1 @@
1
+ export * from './RippleError';
@@ -31,21 +31,93 @@ import type { Channel } from '../types';
31
31
  */
32
32
  export declare abstract class BroadcastEvent {
33
33
  /**
34
- * The channels to broadcast this event on
34
+ * Define which channel(s) this event should be broadcast on.
35
+ *
36
+ * @returns Single Channel or array of Channels for multi-channel broadcasting
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Broadcast to a single private channel
41
+ * broadcastOn() {
42
+ * return new PrivateChannel(`orders.${this.order.userId}`)
43
+ * }
44
+ *
45
+ * // Broadcast to multiple channels
46
+ * broadcastOn() {
47
+ * return [
48
+ * new PrivateChannel(`user.${this.userId}`),
49
+ * new PublicChannel('notifications')
50
+ * ]
51
+ * }
52
+ * ```
35
53
  */
36
54
  abstract broadcastOn(): Channel | Channel[];
37
55
  /**
38
- * The event name to use when broadcasting
39
- * Defaults to the class name
56
+ * Define the event name for client listeners.
57
+ *
58
+ * @returns The event name (defaults to class name if not overridden)
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * // Use class name (default behavior)
63
+ * class OrderShipped extends BroadcastEvent {
64
+ * // Event name will be 'OrderShipped'
65
+ * }
66
+ *
67
+ * // Custom event name
68
+ * broadcastAs() {
69
+ * return 'order.shipped' // dot notation style
70
+ * }
71
+ * ```
40
72
  */
41
73
  broadcastAs(): string;
42
74
  /**
43
- * Socket IDs to exclude from the broadcast
75
+ * Exclude specific socket IDs from receiving this broadcast.
76
+ *
77
+ * @returns Array of socket IDs to exclude (empty array by default)
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * // Exclude the sender
82
+ * class MessageSent extends BroadcastEvent {
83
+ * constructor(
84
+ * public message: Message,
85
+ * public senderSocketId: string
86
+ * ) { super() }
87
+ *
88
+ * broadcastExcept() {
89
+ * return [this.senderSocketId] // Don't send back to sender
90
+ * }
91
+ * }
92
+ * ```
44
93
  */
45
94
  broadcastExcept(): string[];
46
95
  /**
47
- * Get the event data payload
48
- * Override to customize the broadcast payload
96
+ * Define the event payload data sent to clients.
97
+ *
98
+ * @returns The data object to broadcast (all public properties by default)
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * // Default: All public properties are included
103
+ * class OrderShipped extends BroadcastEvent {
104
+ * constructor(public order: Order) { super() }
105
+ * // Broadcasts: { order: { id, status, ... } }
106
+ * }
107
+ *
108
+ * // Custom payload
109
+ * class OrderShipped extends BroadcastEvent {
110
+ * constructor(public order: Order) { super() }
111
+ *
112
+ * broadcastWith() {
113
+ * return {
114
+ * orderId: this.order.id,
115
+ * trackingNumber: this.order.trackingNumber,
116
+ * // Exclude sensitive data
117
+ * }
118
+ * }
119
+ * }
120
+ * ```
49
121
  */
50
122
  broadcastWith(): Record<string, unknown>;
51
123
  }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @fileoverview Broadcast manager for Ripple
3
+ *
4
+ * @module @gravito/ripple/events
5
+ */
6
+ import type { RippleServer } from '../RippleServer';
7
+ import type { BroadcastEvent } from './BroadcastEvent';
8
+ /**
9
+ * Modern broadcast manager with dependency injection.
10
+ *
11
+ * BroadcastManager is the recommended way to broadcast events in Ripple applications.
12
+ * It accepts RippleServer explicitly through the constructor (dependency injection),
13
+ * making it testable and avoiding global state.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * // Setup with dependency injection
18
+ * const ripple = new RippleServer({ path: '/ws' })
19
+ * const manager = new BroadcastManager(ripple)
20
+ *
21
+ * // Or bind to IoC container
22
+ * container.bind('broadcast').toValue(new BroadcastManager(ripple))
23
+ *
24
+ * // Broadcast BroadcastEvent instances
25
+ * manager.broadcast(new OrderShipped(order))
26
+ *
27
+ * // Fluent API for direct broadcasting
28
+ * manager.to('news').emit('article.published', { id: 123 })
29
+ * manager.toPrivate('orders.456').emit('order.updated', { status: 'shipped' })
30
+ * manager.toPresence('chat.lobby').except('socket-1').emit('message', { text: 'Hi!' })
31
+ * ```
32
+ */
33
+ export declare class BroadcastManager {
34
+ private readonly server;
35
+ constructor(server: RippleServer);
36
+ /**
37
+ * Broadcast a BroadcastEvent to its designated channels.
38
+ *
39
+ * @param event - The BroadcastEvent instance to broadcast
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * class OrderShipped extends BroadcastEvent {
44
+ * constructor(public order: Order) { super() }
45
+ * broadcastOn() { return new PrivateChannel(`orders.${this.order.userId}`) }
46
+ * broadcastAs() { return 'OrderShipped' }
47
+ * }
48
+ *
49
+ * manager.broadcast(new OrderShipped(order))
50
+ * ```
51
+ */
52
+ broadcast(event: BroadcastEvent): void;
53
+ /**
54
+ * Broadcast to a public channel.
55
+ *
56
+ * @param channel - The channel name (without prefix)
57
+ * @returns ChannelBroadcaster for chaining
58
+ */
59
+ to(channel: string): ChannelBroadcaster;
60
+ /**
61
+ * Broadcast to a private channel.
62
+ *
63
+ * @param channel - The channel name (will be prefixed with 'private-')
64
+ * @returns ChannelBroadcaster for chaining
65
+ */
66
+ toPrivate(channel: string): ChannelBroadcaster;
67
+ /**
68
+ * Broadcast to a presence channel.
69
+ *
70
+ * @param channel - The channel name (will be prefixed with 'presence-')
71
+ * @returns ChannelBroadcaster for chaining
72
+ */
73
+ toPresence(channel: string): ChannelBroadcaster;
74
+ }
75
+ /**
76
+ * Fluent broadcaster for channel-specific operations.
77
+ *
78
+ * Returned by BroadcastManager's `to()`, `toPrivate()`, and `toPresence()` methods.
79
+ * Provides a chainable API for broadcasting with optional exclusions.
80
+ */
81
+ export declare class ChannelBroadcaster {
82
+ private readonly server;
83
+ private readonly channel;
84
+ private _except;
85
+ constructor(server: RippleServer, channel: string);
86
+ /**
87
+ * Exclude specific socket IDs from the broadcast.
88
+ *
89
+ * @param socketIds - Single socket ID or array of IDs to exclude
90
+ * @returns this for method chaining
91
+ */
92
+ except(socketIds: string | string[]): this;
93
+ /**
94
+ * Emit the event to the channel.
95
+ *
96
+ * @param event - The event name
97
+ * @param data - The event payload (must be JSON-serializable)
98
+ */
99
+ emit(event: string, data: unknown): void;
100
+ }