@bymax-one/nest-realtime 1.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.
@@ -0,0 +1,245 @@
1
+ import * as react from 'react';
2
+ import { PropsWithChildren } from 'react';
3
+
4
+ /** Accumulated event shape returned by the hook. */
5
+ type SseEventEntry<TEvents extends Record<string, unknown>> = {
6
+ type: keyof TEvents;
7
+ data: TEvents[keyof TEvents];
8
+ id: string;
9
+ };
10
+
11
+ /** Accumulated event shape returned by the hook. */
12
+ type WsEventEntry<TEvents extends Record<string, unknown>> = {
13
+ type: keyof TEvents;
14
+ data: TEvents[keyof TEvents];
15
+ };
16
+
17
+ /** Transport mode for the universal hook. */
18
+ type UseRealtimeTransport = 'auto' | 'sse' | 'websocket';
19
+ /** Options for {@link useRealtime}. */
20
+ interface UseRealtimeOptions {
21
+ /**
22
+ * Realtime endpoint URL.
23
+ *
24
+ * - `ws://` / `wss://` prefix → WebSocket transport is selected automatically.
25
+ * - Any other value → SSE transport is selected automatically.
26
+ *
27
+ * Use the `transport` field to override the auto-detection.
28
+ */
29
+ url: string;
30
+ /**
31
+ * Override automatic transport detection.
32
+ * - `'auto'` (default) — detect from the URL scheme.
33
+ * - `'sse'` — always use EventSource, regardless of the URL.
34
+ * - `'websocket'` — always use socket.io-client, regardless of the URL.
35
+ */
36
+ transport?: UseRealtimeTransport;
37
+ /** Forward cookies for cross-origin SSE. */
38
+ withCredentials?: boolean;
39
+ /** Auth credentials for the WebSocket handshake. */
40
+ auth?: {
41
+ ticket?: string;
42
+ token?: string;
43
+ };
44
+ /** socket.io path (WebSocket only). Default `/socket.io`. */
45
+ path?: string;
46
+ /**
47
+ * SSE-only: extra named SSE events to subscribe to.
48
+ *
49
+ * `EventSource` never routes a named event to `onmessage`, so an
50
+ * application-level name such as `order.created` is invisible unless it is
51
+ * listed here. Names the hook already handles (`message`, `open`, `error`, and
52
+ * the reserved catalog) are ignored. Ignored entirely on the WebSocket branch,
53
+ * where `onAny` already receives every event name.
54
+ */
55
+ eventNames?: readonly string[];
56
+ /** SSE-only: initial reconnect backoff in ms. Default 1000. */
57
+ reconnectInitialMs?: number;
58
+ /** SSE-only: maximum reconnect backoff in ms. Default 30000. */
59
+ reconnectMaxMs?: number;
60
+ /**
61
+ * SSE-only: give up and close the stream after this many consecutive failed
62
+ * connection attempts (the initial connection counts, so `1` means "never
63
+ * retry"). Unset retries indefinitely. Ignored on WebSocket, where Socket.IO
64
+ * owns the policy.
65
+ */
66
+ maxAttempts?: number;
67
+ }
68
+ /**
69
+ * Universal realtime hook — auto-detects SSE vs WebSocket from the URL scheme.
70
+ *
71
+ * - `http(s)://` or a relative path → SSE via native `EventSource`
72
+ * - `ws(s)://` → WebSocket via socket.io-client (dynamic import)
73
+ *
74
+ * Override with `transport: 'sse' | 'websocket'` when needed.
75
+ *
76
+ * Both internal hooks are always invoked (Rules of Hooks compliance); only the
77
+ * one matching the detected transport is active.
78
+ *
79
+ * The returned shape is identical across transports, but two fields are
80
+ * transport-specific: `emit` works only on WebSocket, and `reconnectAttempts` is
81
+ * always `0` on WebSocket because Socket.IO owns its own retry policy and does not
82
+ * report the count.
83
+ *
84
+ * @example
85
+ * function MyComponent() {
86
+ * const { connected, events } = useRealtime<{ 'invoice.paid': { id: string } }>({
87
+ * url: '/realtime/sse',
88
+ * })
89
+ * return <div>{connected ? 'live' : 'disconnected'}</div>
90
+ * }
91
+ */
92
+ declare function useRealtime<TEvents extends Record<string, unknown> = Record<string, unknown>>(opts: UseRealtimeOptions): {
93
+ connected: boolean;
94
+ events: WsEventEntry<TEvents>[];
95
+ lastEvent: WsEventEntry<TEvents> | undefined;
96
+ error: Error | undefined;
97
+ emit: (event: string, data: unknown) => void;
98
+ reconnect: () => void;
99
+ transport: "websocket";
100
+ reconnectAttempts: number;
101
+ } | {
102
+ emit: never;
103
+ connected: boolean;
104
+ events: SseEventEntry<TEvents>[];
105
+ lastEvent: SseEventEntry<TEvents> | undefined;
106
+ error: Error | undefined;
107
+ reconnectAttempts: number;
108
+ reconnect: () => void;
109
+ transport: "sse";
110
+ };
111
+
112
+ /**
113
+ * Connection-state view — returns `connected`, `error`, `reconnectAttempts`, and
114
+ * `reconnect`.
115
+ *
116
+ * Useful for status indicators, connection guards, or simple error-handling UI.
117
+ * The shared underlying `useRealtime` connection still processes events; this
118
+ * hook intentionally omits the `events` array from what it returns to keep the
119
+ * surface small and focused on connection status. `reconnectAttempts` is included
120
+ * because a status indicator is exactly where a climbing retry count belongs — but
121
+ * only the SSE transport reports it. On WebSocket it stays `0`, since Socket.IO
122
+ * owns its retry policy and exposes no count.
123
+ *
124
+ * @example
125
+ * function ConnectionStatus() {
126
+ * const { connected } = useRealtimeConnection({ url: '/realtime/sse' })
127
+ * return <span>{connected ? '🟢 live' : '🔴 disconnected'}</span>
128
+ * }
129
+ */
130
+ declare function useRealtimeConnection(opts: UseRealtimeOptions): {
131
+ connected: boolean;
132
+ error: Error | undefined;
133
+ reconnectAttempts: number;
134
+ reconnect: (() => void) | (() => void);
135
+ };
136
+
137
+ /** Return value of {@link usePresence}. */
138
+ interface UsePresenceReturn {
139
+ /** Sorted array of user IDs currently online. */
140
+ onlineUserIds: string[];
141
+ /**
142
+ * Returns `true` when the given user is currently online.
143
+ *
144
+ * @param userId - The user ID to check.
145
+ */
146
+ isOnline: (userId: string) => boolean;
147
+ /** Total count of users online. */
148
+ count: number;
149
+ }
150
+ /**
151
+ * Tracks online / offline users based on presence events from the realtime backend.
152
+ *
153
+ * Must be used inside a `<RealtimeProvider>`. The hook is a pure subscriber —
154
+ * it does not open its own connection.
155
+ *
156
+ * @example
157
+ * function OnlineBadge() {
158
+ * const { count, isOnline } = usePresence()
159
+ * return <span>{count} online</span>
160
+ * }
161
+ */
162
+ declare function usePresence(): UsePresenceReturn;
163
+
164
+ /** Context shape: the full return value of `useRealtime`. */
165
+ type RealtimeContextValue = ReturnType<typeof useRealtime>;
166
+ /**
167
+ * Provides a shared realtime connection to all descendant consumers.
168
+ *
169
+ * Mount once near the root of your component tree (or inside a layout that
170
+ * requires realtime) and consume the shared state with `useRealtimeContext`.
171
+ *
172
+ * @example
173
+ * <RealtimeProvider options={{ url: '/realtime/sse', withCredentials: true }}>
174
+ * <App />
175
+ * </RealtimeProvider>
176
+ */
177
+ declare function RealtimeProvider({ options, children, }: PropsWithChildren<{
178
+ options: UseRealtimeOptions;
179
+ }>): react.JSX.Element;
180
+ /**
181
+ * Returns the realtime state from the nearest `<RealtimeProvider>`.
182
+ *
183
+ * @throws {Error} When called outside a `<RealtimeProvider>`.
184
+ *
185
+ * @example
186
+ * function EventList() {
187
+ * const { connected, events } = useRealtimeContext()
188
+ * return <ul>{events.map(e => <li key={e.id}>{JSON.stringify(e.data)}</li>)}</ul>
189
+ * }
190
+ */
191
+ declare function useRealtimeContext(): RealtimeContextValue;
192
+
193
+ /**
194
+ * @fileoverview Config-level transport mode selection.
195
+ * @layer shared
196
+ */
197
+ /**
198
+ * Transport mode chosen by the consumer at module configuration time.
199
+ *
200
+ * - `sse` — Server-Sent Events only. HTTP-based, server → client push.
201
+ * - `websocket` — Socket.IO only. Full duplex.
202
+ * - `both` — Compose SSE and WebSocket. Useful during migrations or when
203
+ * different product surfaces need different transports.
204
+ *
205
+ * Distinct from `ITransport.kind` (`'sse' | 'websocket'`), which identifies a
206
+ * single concrete transport implementation. See
207
+ * `docs/technical_specification.md` §1.3 for selection criteria.
208
+ *
209
+ * @example
210
+ * ```ts
211
+ * const mode: TransportMode = 'sse'
212
+ * ```
213
+ */
214
+ type TransportMode = 'sse' | 'websocket' | 'both';
215
+
216
+ /**
217
+ * @fileoverview Generic realtime event shape shared across transports and the client.
218
+ * @layer shared
219
+ */
220
+ /**
221
+ * Generic shape of an event traveling over a realtime transport.
222
+ *
223
+ * Consumers typically declare a mapped type describing their own events and layer
224
+ * it on top of this generic for end-to-end type safety:
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * interface MyAppEvents {
229
+ * 'invoice.paid': { id: string; amount: number }
230
+ * 'webhook.dlq': { webhookId: string; reason: string }
231
+ * }
232
+ *
233
+ * type InvoicePaid = RealtimeEvent<MyAppEvents['invoice.paid']>
234
+ * ```
235
+ */
236
+ interface RealtimeEvent<TData = unknown> {
237
+ /** Monotonically increasing event id — used for `Last-Event-ID` replay. */
238
+ readonly id: string;
239
+ /** Event name (matches the consumer's mapped-type key). */
240
+ readonly type: string;
241
+ /** Free-form payload. */
242
+ readonly data: TData;
243
+ }
244
+
245
+ export { type RealtimeEvent, RealtimeProvider, type TransportMode, type UsePresenceReturn, type UseRealtimeOptions, usePresence, useRealtime, useRealtimeConnection, useRealtimeContext };
@@ -0,0 +1,268 @@
1
+ import { createContext, useContext, useState, useEffect, useRef, useCallback } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+
4
+ // src/shared/constants/reserved-events.constants.ts
5
+ var RESERVED_EVENT_NAMES = {
6
+ CONNECTION_ESTABLISHED: "connection:established",
7
+ CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed",
8
+ CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring",
9
+ ROOM_JOINED: "room:joined",
10
+ ROOM_LEFT: "room:left",
11
+ ERROR: "error"
12
+ };
13
+ var PRESENCE_EVENT_NAMES = {
14
+ ONLINE: "presence:online",
15
+ OFFLINE: "presence:offline"
16
+ };
17
+ var NAMED_SSE_EVENTS = [
18
+ RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
19
+ RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED,
20
+ RESERVED_EVENT_NAMES.CONNECTION_CREDENTIAL_EXPIRING,
21
+ RESERVED_EVENT_NAMES.ROOM_JOINED,
22
+ RESERVED_EVENT_NAMES.ROOM_LEFT,
23
+ PRESENCE_EVENT_NAMES.ONLINE,
24
+ PRESENCE_EVENT_NAMES.OFFLINE
25
+ ];
26
+ var BROWSER_SSE_EVENT_NAMES = ["message", "open", RESERVED_EVENT_NAMES.ERROR];
27
+ function useRealtimeSse(opts) {
28
+ const [connected, setConnected] = useState(false);
29
+ const [events, setEvents] = useState([]);
30
+ const [lastEvent, setLastEvent] = useState(void 0);
31
+ const [error, setError] = useState(void 0);
32
+ const [reconnectAttempts, setReconnectAttempts] = useState(0);
33
+ const sourceRef = useRef(null);
34
+ const reconnectMsRef = useRef(opts.reconnectInitialMs ?? 1e3);
35
+ const attemptsRef = useRef(0);
36
+ const timerRef = useRef(null);
37
+ const extraEventNames = (opts.eventNames ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
38
+ const clearReconnectTimer = useCallback(() => {
39
+ if (timerRef.current !== null) {
40
+ clearTimeout(timerRef.current);
41
+ timerRef.current = null;
42
+ }
43
+ }, []);
44
+ const connect = useCallback(() => {
45
+ if (opts.enabled === false) return;
46
+ sourceRef.current?.close();
47
+ clearReconnectTimer();
48
+ const source = new EventSource(opts.url, { withCredentials: opts.withCredentials ?? false });
49
+ sourceRef.current = source;
50
+ source.onopen = () => {
51
+ setConnected(true);
52
+ setError(void 0);
53
+ clearReconnectTimer();
54
+ reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
55
+ attemptsRef.current = 0;
56
+ setReconnectAttempts(0);
57
+ };
58
+ source.onerror = () => {
59
+ setConnected(false);
60
+ setError(new Error("SSE connection error"));
61
+ attemptsRef.current += 1;
62
+ setReconnectAttempts(attemptsRef.current);
63
+ if (opts.maxAttempts !== void 0 && attemptsRef.current >= opts.maxAttempts) {
64
+ source.close();
65
+ return;
66
+ }
67
+ clearReconnectTimer();
68
+ const delay = Math.min(reconnectMsRef.current * 2, opts.reconnectMaxMs ?? 3e4);
69
+ reconnectMsRef.current = delay;
70
+ timerRef.current = setTimeout(connect, delay);
71
+ };
72
+ const handleEvent = (e) => {
73
+ let data;
74
+ try {
75
+ data = JSON.parse(e.data);
76
+ } catch {
77
+ setError(new Error(`Malformed SSE payload on "${e.type}"`));
78
+ return;
79
+ }
80
+ const entry = {
81
+ type: e.type,
82
+ data,
83
+ id: e.lastEventId
84
+ };
85
+ setEvents((prev) => [...prev, entry].slice(-100));
86
+ setLastEvent(entry);
87
+ };
88
+ source.onmessage = handleEvent;
89
+ for (const name of NAMED_SSE_EVENTS) {
90
+ source.addEventListener(name, handleEvent);
91
+ }
92
+ for (const name of extraEventNames === "" ? [] : extraEventNames.split("\n")) {
93
+ source.addEventListener(name, handleEvent);
94
+ }
95
+ }, [
96
+ opts.enabled,
97
+ opts.url,
98
+ opts.withCredentials,
99
+ opts.reconnectInitialMs,
100
+ opts.reconnectMaxMs,
101
+ opts.maxAttempts,
102
+ extraEventNames,
103
+ clearReconnectTimer
104
+ ]);
105
+ useEffect(() => {
106
+ if (opts.enabled === false) return;
107
+ connect();
108
+ return () => {
109
+ clearReconnectTimer();
110
+ sourceRef.current?.close();
111
+ sourceRef.current = null;
112
+ };
113
+ }, [connect, opts.enabled, clearReconnectTimer]);
114
+ const reconnect = useCallback(() => {
115
+ reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
116
+ attemptsRef.current = 0;
117
+ setReconnectAttempts(0);
118
+ connect();
119
+ }, [connect, opts.reconnectInitialMs]);
120
+ return { connected, events, lastEvent, error, reconnectAttempts, reconnect };
121
+ }
122
+ var MAX_EVENTS2 = 100;
123
+ function useRealtimeWs(opts) {
124
+ const [connected, setConnected] = useState(false);
125
+ const [events, setEvents] = useState([]);
126
+ const [lastEvent, setLastEvent] = useState(void 0);
127
+ const [error, setError] = useState(void 0);
128
+ const socketRef = useRef(null);
129
+ const disposeSocket = useCallback(() => {
130
+ const sock = socketRef.current;
131
+ if (sock) {
132
+ sock.removeAllListeners();
133
+ sock.disconnect();
134
+ }
135
+ socketRef.current = null;
136
+ }, []);
137
+ const authTicket = opts.auth?.ticket;
138
+ const authToken = opts.auth?.token;
139
+ const connect = useCallback(async () => {
140
+ if (opts.enabled === false) return;
141
+ disposeSocket();
142
+ setConnected(false);
143
+ try {
144
+ const { io } = await import('socket.io-client');
145
+ const auth = {
146
+ ...authTicket !== void 0 ? { ticket: authTicket } : {},
147
+ ...authToken !== void 0 ? { token: authToken } : {}
148
+ };
149
+ const socket = io(opts.url, {
150
+ path: opts.path ?? "/socket.io",
151
+ ...authTicket !== void 0 || authToken !== void 0 ? { auth } : {},
152
+ withCredentials: true
153
+ });
154
+ socketRef.current = socket;
155
+ socket.on("connect", () => {
156
+ setConnected(true);
157
+ setError(void 0);
158
+ });
159
+ socket.on("disconnect", () => setConnected(false));
160
+ socket.on("error", (e) => setError(e instanceof Error ? e : new Error(String(e))));
161
+ socket.onAny((eventName, payload) => {
162
+ const entry = {
163
+ type: eventName,
164
+ data: payload
165
+ };
166
+ setEvents((prev) => [...prev, entry].slice(-MAX_EVENTS2));
167
+ setLastEvent(entry);
168
+ });
169
+ } catch (e) {
170
+ setError(e instanceof Error ? e : new Error(String(e)));
171
+ }
172
+ }, [opts.enabled, opts.url, authTicket, authToken, opts.path, disposeSocket]);
173
+ useEffect(() => {
174
+ if (opts.enabled === false) return;
175
+ void connect();
176
+ return () => disposeSocket();
177
+ }, [connect, opts.enabled, disposeSocket]);
178
+ const emit = useCallback((event, data) => {
179
+ const sock = socketRef.current;
180
+ sock?.emit(event, data);
181
+ }, []);
182
+ const reconnect = useCallback(() => {
183
+ void connect();
184
+ }, [connect]);
185
+ return { connected, events, lastEvent, error, emit, reconnect };
186
+ }
187
+
188
+ // src/react/hooks/use-realtime.ts
189
+ function detectTransport(url) {
190
+ if (url.startsWith("ws://") || url.startsWith("wss://")) return "websocket";
191
+ return "sse";
192
+ }
193
+ function useRealtime(opts) {
194
+ const detected = opts.transport !== void 0 && opts.transport !== "auto" ? opts.transport : detectTransport(opts.url);
195
+ const isWs = detected === "websocket";
196
+ const sseResult = useRealtimeSse({
197
+ url: opts.url,
198
+ ...opts.withCredentials !== void 0 ? { withCredentials: opts.withCredentials } : {},
199
+ ...opts.eventNames !== void 0 ? { eventNames: opts.eventNames } : {},
200
+ ...opts.reconnectInitialMs !== void 0 ? { reconnectInitialMs: opts.reconnectInitialMs } : {},
201
+ ...opts.reconnectMaxMs !== void 0 ? { reconnectMaxMs: opts.reconnectMaxMs } : {},
202
+ ...opts.maxAttempts !== void 0 ? { maxAttempts: opts.maxAttempts } : {},
203
+ enabled: !isWs
204
+ });
205
+ const wsResult = useRealtimeWs({
206
+ url: opts.url,
207
+ ...opts.auth !== void 0 ? { auth: opts.auth } : {},
208
+ ...opts.path !== void 0 ? { path: opts.path } : {},
209
+ enabled: isWs
210
+ });
211
+ if (isWs) {
212
+ return { transport: "websocket", reconnectAttempts: 0, ...wsResult };
213
+ }
214
+ return {
215
+ transport: "sse",
216
+ ...sseResult,
217
+ // `emit` is WebSocket-exclusive; typed as `never` to prevent accidental use on SSE.
218
+ emit: void 0
219
+ };
220
+ }
221
+
222
+ // src/react/hooks/use-realtime-connection.ts
223
+ function useRealtimeConnection(opts) {
224
+ const { connected, error, reconnectAttempts, reconnect } = useRealtime(opts);
225
+ return { connected, error, reconnectAttempts, reconnect };
226
+ }
227
+ var RealtimeContext = createContext(null);
228
+ function RealtimeProvider({
229
+ options,
230
+ children
231
+ }) {
232
+ const value = useRealtime(options);
233
+ return /* @__PURE__ */ jsx(RealtimeContext.Provider, { value, children });
234
+ }
235
+ function useRealtimeContext() {
236
+ const ctx = useContext(RealtimeContext);
237
+ if (!ctx) throw new Error("useRealtimeContext must be used within <RealtimeProvider>");
238
+ return ctx;
239
+ }
240
+
241
+ // src/react/hooks/use-presence.ts
242
+ function usePresence() {
243
+ const { events } = useRealtimeContext();
244
+ const [online, setOnline] = useState(/* @__PURE__ */ new Set());
245
+ useEffect(() => {
246
+ const lastEv = events[events.length - 1];
247
+ if (!lastEv) return;
248
+ if (lastEv.type === PRESENCE_EVENT_NAMES.ONLINE) {
249
+ const payload = lastEv.data;
250
+ setOnline((prev) => new Set(prev).add(payload.userId));
251
+ } else if (lastEv.type === PRESENCE_EVENT_NAMES.OFFLINE) {
252
+ const payload = lastEv.data;
253
+ setOnline((prev) => {
254
+ const next = new Set(prev);
255
+ next.delete(payload.userId);
256
+ return next;
257
+ });
258
+ }
259
+ }, [events]);
260
+ return {
261
+ // Sorted for stable, deterministic rendering (matches UsePresenceReturn docs).
262
+ onlineUserIds: Array.from(online).sort(),
263
+ isOnline: (userId) => online.has(userId),
264
+ count: online.size
265
+ };
266
+ }
267
+
268
+ export { RealtimeProvider, usePresence, useRealtime, useRealtimeConnection, useRealtimeContext };