react-websocket 3.0.0 → 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.
package/dist/index.d.ts CHANGED
@@ -335,6 +335,103 @@ interface WebSocketClient<In = unknown, Out = unknown> {
335
335
  */
336
336
  declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
337
337
 
338
+ /** Options for {@link createWebSocketState}. */
339
+ interface WebSocketStateOptions<S, In> {
340
+ /** The state before any message arrives, and what `reset()` returns to. */
341
+ initialState: S;
342
+ /**
343
+ * Fold one incoming message into the state. Must be pure: return a new object for a
344
+ * change, or the same `state` to ignore the message (subscribers aren't notified).
345
+ */
346
+ reduce: (state: S, message: In) => S;
347
+ }
348
+ /**
349
+ * State derived from a client's messages. Read it with `useWebSocketState(store, selector)`,
350
+ * or with `getState`/`subscribe` outside React.
351
+ *
352
+ * @typeParam S - The state type. Don't use a function type: `setState` treats functions as updaters.
353
+ */
354
+ interface WebSocketState<S> {
355
+ /** The client whose messages this store reduces. Hooks reading the store keep it connected. */
356
+ readonly client: WebSocketClient<any, any>;
357
+ /** The `initialState` it was created with. Used for server rendering and hydration. */
358
+ readonly initialState: S;
359
+ /** The current state. Returns the same object until it changes. */
360
+ getState(): S;
361
+ /** Called whenever the state changes. Compatible with `useSyncExternalStore`. */
362
+ subscribe(listener: () => void): () => void;
363
+ /** Replace the state, or update it from the current one, e.g. for optimistic updates. */
364
+ setState(update: S | ((state: S) => S)): void;
365
+ /** Go back to `initialState`. */
366
+ reset(): void;
367
+ /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */
368
+ dispose(): void;
369
+ }
370
+ /**
371
+ * Keep state derived from a client's messages, like a reducer that runs on every message.
372
+ * It starts listening immediately and keeps the state across reconnects; it doesn't open
373
+ * the connection by itself.
374
+ *
375
+ * @example
376
+ * ```ts
377
+ * const prices = createWebSocket<Tick>('wss://api.example.com/prices', { json: true });
378
+ *
379
+ * export const priceState = createWebSocketState(prices, {
380
+ * initialState: {} as Record<string, number>,
381
+ * reduce: (state, tick) => ({ ...state, [tick.symbol]: tick.price })
382
+ * });
383
+ *
384
+ * // In a component: re-renders only when ACME's price changes.
385
+ * const acme = useWebSocketState(priceState, state => state.ACME);
386
+ * ```
387
+ */
388
+ declare function createWebSocketState<S, In>(client: WebSocketClient<In, any>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
389
+
390
+ /** Options for {@link createWebSocketTopics}: the messages your server expects. */
391
+ interface WebSocketTopicsOptions<Out> {
392
+ /** The message that subscribes to `topic`. */
393
+ subscribe: (topic: string) => Out;
394
+ /** The message that unsubscribes from `topic`. Omit it if your server has none. */
395
+ unsubscribe?: (topic: string) => Out;
396
+ }
397
+ /** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */
398
+ interface WebSocketTopics {
399
+ /** The client the subscription messages are sent on. */
400
+ readonly client: WebSocketClient<any, any>;
401
+ /**
402
+ * Hold a subscription to `topic`, and the client's connection, until the returned
403
+ * function is called. The release function is safe to call more than once.
404
+ */
405
+ acquire(topic: string): () => void;
406
+ /** The topics currently held, in the order they were first acquired. */
407
+ active(): string[];
408
+ /** Stop managing subscriptions. Only needed for managers created dynamically. */
409
+ dispose(): void;
410
+ }
411
+ /**
412
+ * Manage topic subscriptions that survive reconnects.
413
+ *
414
+ * - The first holder of a topic sends `subscribe(topic)`. Later holders share it.
415
+ * - A tick after the last holder releases it, `unsubscribe(topic)` is sent, so StrictMode
416
+ * and route transitions don't churn subscriptions.
417
+ * - After every reconnect, every held topic is subscribed again on the new socket, before
418
+ * messages queued while disconnected are sent.
419
+ *
420
+ * Subscriptions are only sent while the socket is open; nothing is queued for them.
421
+ *
422
+ * @example
423
+ * ```ts
424
+ * export const topics = createWebSocketTopics(live, {
425
+ * subscribe: topic => ({ type: 'subscribe', topic }),
426
+ * unsubscribe: topic => ({ type: 'unsubscribe', topic })
427
+ * });
428
+ *
429
+ * // In a component:
430
+ * useWebSocketTopic(topics, `prices:${symbol}`);
431
+ * ```
432
+ */
433
+ declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>>): WebSocketTopics;
434
+
338
435
  /**
339
436
  * Per-component event handlers. They always see the component's latest props and
340
437
  * state, and changing them never reconnects.
@@ -414,5 +511,31 @@ declare function useWebSocketEvent<In, K extends keyof EventMap<In>>(client: Web
414
511
  * ```
415
512
  */
416
513
  declare function useWebSocketStatus(client: WebSocketClient<any, any> | null | undefined): Status;
514
+ /**
515
+ * Read state built from messages by `createWebSocketState`. Re-renders only when the
516
+ * selected value changes (by `isEqual`, default `Object.is`), however often messages
517
+ * arrive. Keeps the connection open while mounted.
518
+ *
519
+ * On the server, and during hydration, it reads from `initialState`.
520
+ *
521
+ * @example
522
+ * ```tsx
523
+ * const acme = useWebSocketState(priceState, state => state.ACME);
524
+ * ```
525
+ */
526
+ declare function useWebSocketState<S>(store: WebSocketState<S>): S;
527
+ declare function useWebSocketState<S, T>(store: WebSocketState<S>, selector: (state: S) => T, isEqual?: (a: T, b: T) => boolean): T;
528
+ /**
529
+ * Subscribe to one topic (or several) while mounted, through a `createWebSocketTopics`
530
+ * manager. Components holding the same topic share one subscription, and it is sent again
531
+ * after every reconnect. Keeps the connection open while mounted. `null` holds nothing.
532
+ *
533
+ * @example
534
+ * ```tsx
535
+ * useWebSocketTopic(topics, `prices:${symbol}`);
536
+ * useWebSocketTopic(topics, watchlist.map(symbol => `prices:${symbol}`));
537
+ * ```
538
+ */
539
+ declare function useWebSocketTopic(topics: WebSocketTopics | null | undefined, topic: string | readonly string[] | null | undefined): void;
417
540
 
418
- export { type CloseInfo, type EventMap, type HeartbeatOptions, MessageError, type QueueOptions, type ReconnectOptions, type SendData, type Snapshot, type StandardSchemaV1, type Status, type UrlSource, type UseWebSocketOptions, type UseWebSocketResult, type WebSocketClient, type WebSocketHandlers, type WebSocketOptions, createWebSocket, useWebSocket, useWebSocketEvent, useWebSocketStatus };
541
+ export { type CloseInfo, type EventMap, type HeartbeatOptions, MessageError, type QueueOptions, type ReconnectOptions, type SendData, type Snapshot, type StandardSchemaV1, type Status, type UrlSource, type UseWebSocketOptions, type UseWebSocketResult, type WebSocketClient, type WebSocketHandlers, type WebSocketOptions, type WebSocketState, type WebSocketStateOptions, type WebSocketTopics, type WebSocketTopicsOptions, createWebSocket, createWebSocketState, createWebSocketTopics, useWebSocket, useWebSocketEvent, useWebSocketState, useWebSocketStatus, useWebSocketTopic };
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  export * from "./core.js";
5
5
 
6
6
  // src/react.ts
7
- import { useEffect, useInsertionEffect, useRef, useSyncExternalStore } from "react";
7
+ import { useEffect, useInsertionEffect, useMemo, useRef, useSyncExternalStore } from "react";
8
8
  import { createWebSocket } from "./core.js";
9
9
  var IDLE = Object.freeze({ status: "idle", lastMessage: void 0, attempt: 0 });
10
10
  var idleSnapshot = () => IDLE;
@@ -93,9 +93,42 @@ function useWebSocketStatus(client) {
93
93
  useHold(client ?? null, true);
94
94
  return status;
95
95
  }
96
+ var identity = (value) => value;
97
+ function useWebSocketState(store, selector = identity, isEqual = Object.is) {
98
+ const [getSelection, getServerSelection] = useMemo(() => {
99
+ const memoized = (read) => {
100
+ let memo;
101
+ return () => {
102
+ const state = read();
103
+ if (memo && Object.is(memo.state, state)) return memo.selection;
104
+ const selection2 = selector(state);
105
+ if (memo && isEqual(memo.selection, selection2)) {
106
+ memo = { state, selection: memo.selection };
107
+ return memo.selection;
108
+ }
109
+ memo = { state, selection: selection2 };
110
+ return selection2;
111
+ };
112
+ };
113
+ return [memoized(store.getState), memoized(() => store.initialState)];
114
+ }, [store, selector, isEqual]);
115
+ const selection = useSyncExternalStore(store.subscribe, getSelection, getServerSelection);
116
+ useHold(store.client, true);
117
+ return selection;
118
+ }
119
+ function useWebSocketTopic(topics, topic) {
120
+ const key = topic == null ? null : JSON.stringify(typeof topic === "string" ? [topic] : topic);
121
+ useEffect(() => {
122
+ if (!topics || key === null) return;
123
+ const releases = JSON.parse(key).map((t) => topics.acquire(t));
124
+ return () => releases.forEach((release) => release());
125
+ }, [topics, key]);
126
+ }
96
127
  export {
97
128
  useWebSocket,
98
129
  useWebSocketEvent,
99
- useWebSocketStatus
130
+ useWebSocketState,
131
+ useWebSocketStatus,
132
+ useWebSocketTopic
100
133
  };
101
134
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/react.ts"],"sourcesContent":["export * from './core';\nexport { useWebSocket, useWebSocketEvent, useWebSocketStatus } from './react';\nexport type { UseWebSocketOptions, UseWebSocketResult, WebSocketHandlers } from './react';\n","import { useEffect, useInsertionEffect, useRef, useSyncExternalStore } from 'react';\n// Import the client through the `core` entry: the build keeps it external, so both entries\n// share one copy of it (and of `MessageError`).\nimport { createWebSocket } from './core';\nimport type {\n CloseInfo,\n EventMap,\n Snapshot,\n Status,\n WebSocketClient,\n WebSocketOptions\n} from './types';\n\n/**\n * Per-component event handlers. They always see the component's latest props and\n * state, and changing them never reconnects.\n */\nexport interface WebSocketHandlers<In> {\n /** The socket opened (initially or after a reconnect). */\n onOpen?: (event: Event) => void;\n /** A message arrived and passed `parse`/`json` and `schema`. */\n onMessage?: (message: In, event: MessageEvent) => void;\n /** A socket closed. Called whether or not it will be retried. */\n onClose?: (close: CloseInfo) => void;\n /** A socket error `Event`, a `MessageError`, or an `Error` from the constructor or `url` function. */\n onError?: (error: Event | Error) => void;\n /**\n * `false` releases this component's hold on the connection and stops its handlers.\n * The connection closes once nothing else holds it.\n * @default true\n */\n enabled?: boolean;\n}\n\n/** Options for `useWebSocket(url, options)`: connection options plus handlers. */\nexport interface UseWebSocketOptions<In, Out>\n extends WebSocketOptions<In, Out>, WebSocketHandlers<In> {}\n\n/** What `useWebSocket` returns: the current {@link Snapshot} plus stable actions. */\nexport interface UseWebSocketResult<In, Out> extends Snapshot<In> {\n /** Send now, or queue until open. Returns `true` if sent immediately. Stable identity. */\n send: (message: Out) => boolean;\n /** Close and stop reconnecting (for every component sharing the connection). Stable identity. */\n close: (code?: number, reason?: string) => void;\n /** Drop the socket and connect again right away. Stable identity. */\n reconnect: () => void;\n /** The underlying client, or `null` when the URL is `null`/`undefined`. */\n client: WebSocketClient<In, Out> | null;\n}\n\nconst IDLE: Snapshot<never> = Object.freeze({ status: 'idle', lastMessage: undefined, attempt: 0 });\nconst idleSnapshot = () => IDLE;\nconst idleStatus = (): Status => 'idle';\nconst noopSubscribe = () => () => {};\nconst noopSend = () => false;\nconst noop = () => {};\n\n// Same key as `ON_TEARDOWN` in ./client, which this entry must not import directly.\nconst ON_TEARDOWN = Symbol.for('react-websocket.onTeardown');\n\n// Hooks given the same URL (and protocols) share one connection.\nconst registry = new Map<string, WebSocketClient<any, any>>();\n\nfunction sharedClient<In, Out>(url: string, options: WebSocketOptions<In, Out>) {\n // Don't let server renders accumulate clients that can never be torn down.\n if (typeof window === 'undefined') return createWebSocket(url, options);\n const key = `${url}\\u0000${JSON.stringify(options.protocols ?? null)}`;\n let client = registry.get(key) as WebSocketClient<In, Out> | undefined;\n if (!client) {\n const created: WebSocketClient<In, Out> = createWebSocket(url, {\n ...options,\n [ON_TEARDOWN]: () => {\n if (registry.get(key) === created) registry.delete(key);\n }\n } as WebSocketOptions<In, Out>);\n registry.set(key, created);\n client = created;\n }\n return client;\n}\n\n/** Always-current value for use inside effects and event listeners (a `useEffectEvent` stand-in). */\nfunction useLatest<T>(value: T) {\n const ref = useRef(value);\n useInsertionEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n\nfunction useHold(client: WebSocketClient<any, any> | null, enabled: boolean) {\n useEffect(() => {\n if (client && enabled) return client.acquire();\n }, [client, enabled]);\n}\n\n/**\n * Connect to a WebSocket and re-render with its status and latest message.\n *\n * - With a URL, every component using the same URL (and `protocols`) shares one\n * connection. Its options come from whichever component created it first.\n * - With a client from `createWebSocket()`, options are the client's; only handlers\n * and `enabled` apply here.\n * - With `null` or `undefined`, nothing connects and the status stays `idle`.\n *\n * The connection opens on mount and closes one tick after the last component using it\n * unmounts, so StrictMode and `<Activity>` don't open duplicate sockets.\n *\n * Re-renders on status changes and on every message. For high-frequency streams use\n * `useWebSocketEvent` and `useWebSocketStatus` instead.\n *\n * @example\n * ```tsx\n * const { status, lastMessage, send } = useWebSocket<Price, Order>('wss://api.example.com/prices', {\n * json: true,\n * onMessage: price => console.log(price)\n * });\n * ```\n */\nexport function useWebSocket<In = unknown, Out = unknown>(\n url: string | null | undefined,\n options?: UseWebSocketOptions<In, Out>\n): UseWebSocketResult<In, Out>;\nexport function useWebSocket<In, Out>(\n client: WebSocketClient<In, Out> | null | undefined,\n options?: WebSocketHandlers<In>\n): UseWebSocketResult<In, Out>;\nexport function useWebSocket<In, Out>(\n target: string | WebSocketClient<In, Out> | null | undefined,\n options: UseWebSocketOptions<In, Out> = {}\n): UseWebSocketResult<In, Out> {\n const client =\n target == null ? null : typeof target === 'string' ? sharedClient(target, options) : target;\n const enabled = options.enabled ?? true;\n\n const snapshot = useSyncExternalStore<Snapshot<In>>(\n client ? client.subscribe : noopSubscribe,\n client ? client.getSnapshot : idleSnapshot,\n idleSnapshot\n );\n\n const handlers = useLatest(options);\n useEffect(() => {\n if (!client || !enabled) return;\n const offs = [\n client.on('open', event => handlers.current.onOpen?.(event)),\n client.on('message', (message, event) => handlers.current.onMessage?.(message, event)),\n client.on('close', info => handlers.current.onClose?.(info)),\n client.on('error', error => handlers.current.onError?.(error))\n ];\n return () => offs.forEach(off => off());\n }, [client, enabled, handlers]);\n useHold(client, enabled);\n\n return {\n ...snapshot,\n send: client ? client.send : noopSend,\n close: client ? client.close : noop,\n reconnect: client ? client.reconnect : noop,\n client\n };\n}\n\n/**\n * Listen to a client's events without re-rendering the component. The listener always\n * sees the latest props and state. Keeps the connection open while mounted.\n *\n * @example\n * ```tsx\n * useWebSocketEvent(chat, 'message', message => setMessages(list => [...list, message]));\n * ```\n */\nexport function useWebSocketEvent<In, K extends keyof EventMap<In>>(\n client: WebSocketClient<In, any> | null | undefined,\n type: K,\n listener: EventMap<In>[K]\n): void {\n const latest = useLatest(listener);\n useEffect(() => {\n if (!client) return;\n const off = client.on(type, ((...args: unknown[]) =>\n (latest.current as (...a: unknown[]) => void)(...args)) as EventMap<In>[K]);\n const release = client.acquire();\n return () => {\n off();\n release();\n };\n }, [client, type, latest]);\n}\n\n/**\n * The connection status of a client. Re-renders only when the status changes, not on\n * messages. Keeps the connection open while mounted.\n *\n * @example\n * ```tsx\n * const status = useWebSocketStatus(chat); // 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'\n * ```\n */\nexport function useWebSocketStatus(client: WebSocketClient<any, any> | null | undefined): Status {\n const status = useSyncExternalStore(\n client ? client.subscribe : noopSubscribe,\n client ? () => client.getSnapshot().status : idleStatus,\n idleStatus\n );\n useHold(client ?? null, true);\n return status;\n}\n"],"mappings":";;;AAAA,cAAc;;;ACAd,SAAS,WAAW,oBAAoB,QAAQ,4BAA4B;AAG5E,SAAS,uBAAuB;AA+ChC,IAAM,OAAwB,OAAO,OAAO,EAAE,QAAQ,QAAQ,aAAa,QAAW,SAAS,EAAE,CAAC;AAClG,IAAM,eAAe,MAAM;AAC3B,IAAM,aAAa,MAAc;AACjC,IAAM,gBAAgB,MAAM,MAAM;AAAC;AACnC,IAAM,WAAW,MAAM;AACvB,IAAM,OAAO,MAAM;AAAC;AAGpB,IAAM,cAAc,uBAAO,IAAI,4BAA4B;AAG3D,IAAM,WAAW,oBAAI,IAAuC;AAE5D,SAAS,aAAsB,KAAa,SAAoC;AAE9E,MAAI,OAAO,WAAW,YAAa,QAAO,gBAAgB,KAAK,OAAO;AACtE,QAAM,MAAM,GAAG,GAAG,KAAS,KAAK,UAAU,QAAQ,aAAa,IAAI,CAAC;AACpE,MAAI,SAAS,SAAS,IAAI,GAAG;AAC7B,MAAI,CAAC,QAAQ;AACX,UAAM,UAAoC,gBAAgB,KAAK;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AS,QAAQ,CAAC;AAC9B,UAAQ,QAAQ,OAAO;AAEvB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,SAAS,OAAO,OAAO;AAAA,IAC7B,OAAO,SAAS,OAAO,QAAQ;AAAA,IAC/B,WAAW,SAAS,OAAO,YAAY;AAAA,IACvC;AAAA,EACF;AACF;AAWO,SAAS,kBACd,QACA,MACA,UACM;AACN,QAAM,SAAS,UAAU,QAAQ;AACjC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,MAAM,OAAO,GAAG,OAAO,IAAI,SAC9B,OAAO,QAAsC,GAAG,IAAI,EAAqB;AAC5E,UAAM,UAAU,OAAO,QAAQ;AAC/B,WAAO,MAAM;AACX,UAAI;AACJ,cAAQ;AAAA,IACV;AAAA,EACF,GAAG,CAAC,QAAQ,MAAM,MAAM,CAAC;AAC3B;AAWO,SAAS,mBAAmB,QAA8D;AAC/F,QAAM,SAAS;AAAA,IACb,SAAS,OAAO,YAAY;AAAA,IAC5B,SAAS,MAAM,OAAO,YAAY,EAAE,SAAS;AAAA,IAC7C;AAAA,EACF;AACA,UAAQ,UAAU,MAAM,IAAI;AAC5B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/react.ts"],"sourcesContent":["export * from './core';\nexport {\n useWebSocket,\n useWebSocketEvent,\n useWebSocketState,\n useWebSocketStatus,\n useWebSocketTopic\n} from './react';\nexport type { UseWebSocketOptions, UseWebSocketResult, WebSocketHandlers } from './react';\n","import { useEffect, useInsertionEffect, useMemo, useRef, useSyncExternalStore } from 'react';\n// Import the client through the `core` entry: the build keeps it external, so both entries\n// share one copy of it (and of `MessageError`).\nimport { createWebSocket } from './core';\nimport type { WebSocketState } from './state';\nimport type { WebSocketTopics } from './topics';\nimport type {\n CloseInfo,\n EventMap,\n Snapshot,\n Status,\n WebSocketClient,\n WebSocketOptions\n} from './types';\n\n/**\n * Per-component event handlers. They always see the component's latest props and\n * state, and changing them never reconnects.\n */\nexport interface WebSocketHandlers<In> {\n /** The socket opened (initially or after a reconnect). */\n onOpen?: (event: Event) => void;\n /** A message arrived and passed `parse`/`json` and `schema`. */\n onMessage?: (message: In, event: MessageEvent) => void;\n /** A socket closed. Called whether or not it will be retried. */\n onClose?: (close: CloseInfo) => void;\n /** A socket error `Event`, a `MessageError`, or an `Error` from the constructor or `url` function. */\n onError?: (error: Event | Error) => void;\n /**\n * `false` releases this component's hold on the connection and stops its handlers.\n * The connection closes once nothing else holds it.\n * @default true\n */\n enabled?: boolean;\n}\n\n/** Options for `useWebSocket(url, options)`: connection options plus handlers. */\nexport interface UseWebSocketOptions<In, Out>\n extends WebSocketOptions<In, Out>, WebSocketHandlers<In> {}\n\n/** What `useWebSocket` returns: the current {@link Snapshot} plus stable actions. */\nexport interface UseWebSocketResult<In, Out> extends Snapshot<In> {\n /** Send now, or queue until open. Returns `true` if sent immediately. Stable identity. */\n send: (message: Out) => boolean;\n /** Close and stop reconnecting (for every component sharing the connection). Stable identity. */\n close: (code?: number, reason?: string) => void;\n /** Drop the socket and connect again right away. Stable identity. */\n reconnect: () => void;\n /** The underlying client, or `null` when the URL is `null`/`undefined`. */\n client: WebSocketClient<In, Out> | null;\n}\n\nconst IDLE: Snapshot<never> = Object.freeze({ status: 'idle', lastMessage: undefined, attempt: 0 });\nconst idleSnapshot = () => IDLE;\nconst idleStatus = (): Status => 'idle';\nconst noopSubscribe = () => () => {};\nconst noopSend = () => false;\nconst noop = () => {};\n\n// Same key as `ON_TEARDOWN` in ./client, which this entry must not import directly.\nconst ON_TEARDOWN = Symbol.for('react-websocket.onTeardown');\n\n// Hooks given the same URL (and protocols) share one connection.\nconst registry = new Map<string, WebSocketClient<any, any>>();\n\nfunction sharedClient<In, Out>(url: string, options: WebSocketOptions<In, Out>) {\n // Don't let server renders accumulate clients that can never be torn down.\n if (typeof window === 'undefined') return createWebSocket(url, options);\n const key = `${url}\\u0000${JSON.stringify(options.protocols ?? null)}`;\n let client = registry.get(key) as WebSocketClient<In, Out> | undefined;\n if (!client) {\n const created: WebSocketClient<In, Out> = createWebSocket(url, {\n ...options,\n [ON_TEARDOWN]: () => {\n if (registry.get(key) === created) registry.delete(key);\n }\n } as WebSocketOptions<In, Out>);\n registry.set(key, created);\n client = created;\n }\n return client;\n}\n\n/** Always-current value for use inside effects and event listeners (a `useEffectEvent` stand-in). */\nfunction useLatest<T>(value: T) {\n const ref = useRef(value);\n useInsertionEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n\nfunction useHold(client: WebSocketClient<any, any> | null, enabled: boolean) {\n useEffect(() => {\n if (client && enabled) return client.acquire();\n }, [client, enabled]);\n}\n\n/**\n * Connect to a WebSocket and re-render with its status and latest message.\n *\n * - With a URL, every component using the same URL (and `protocols`) shares one\n * connection. Its options come from whichever component created it first.\n * - With a client from `createWebSocket()`, options are the client's; only handlers\n * and `enabled` apply here.\n * - With `null` or `undefined`, nothing connects and the status stays `idle`.\n *\n * The connection opens on mount and closes one tick after the last component using it\n * unmounts, so StrictMode and `<Activity>` don't open duplicate sockets.\n *\n * Re-renders on status changes and on every message. For high-frequency streams use\n * `useWebSocketEvent` and `useWebSocketStatus` instead.\n *\n * @example\n * ```tsx\n * const { status, lastMessage, send } = useWebSocket<Price, Order>('wss://api.example.com/prices', {\n * json: true,\n * onMessage: price => console.log(price)\n * });\n * ```\n */\nexport function useWebSocket<In = unknown, Out = unknown>(\n url: string | null | undefined,\n options?: UseWebSocketOptions<In, Out>\n): UseWebSocketResult<In, Out>;\nexport function useWebSocket<In, Out>(\n client: WebSocketClient<In, Out> | null | undefined,\n options?: WebSocketHandlers<In>\n): UseWebSocketResult<In, Out>;\nexport function useWebSocket<In, Out>(\n target: string | WebSocketClient<In, Out> | null | undefined,\n options: UseWebSocketOptions<In, Out> = {}\n): UseWebSocketResult<In, Out> {\n const client =\n target == null ? null : typeof target === 'string' ? sharedClient(target, options) : target;\n const enabled = options.enabled ?? true;\n\n const snapshot = useSyncExternalStore<Snapshot<In>>(\n client ? client.subscribe : noopSubscribe,\n client ? client.getSnapshot : idleSnapshot,\n idleSnapshot\n );\n\n const handlers = useLatest(options);\n useEffect(() => {\n if (!client || !enabled) return;\n const offs = [\n client.on('open', event => handlers.current.onOpen?.(event)),\n client.on('message', (message, event) => handlers.current.onMessage?.(message, event)),\n client.on('close', info => handlers.current.onClose?.(info)),\n client.on('error', error => handlers.current.onError?.(error))\n ];\n return () => offs.forEach(off => off());\n }, [client, enabled, handlers]);\n useHold(client, enabled);\n\n return {\n ...snapshot,\n send: client ? client.send : noopSend,\n close: client ? client.close : noop,\n reconnect: client ? client.reconnect : noop,\n client\n };\n}\n\n/**\n * Listen to a client's events without re-rendering the component. The listener always\n * sees the latest props and state. Keeps the connection open while mounted.\n *\n * @example\n * ```tsx\n * useWebSocketEvent(chat, 'message', message => setMessages(list => [...list, message]));\n * ```\n */\nexport function useWebSocketEvent<In, K extends keyof EventMap<In>>(\n client: WebSocketClient<In, any> | null | undefined,\n type: K,\n listener: EventMap<In>[K]\n): void {\n const latest = useLatest(listener);\n useEffect(() => {\n if (!client) return;\n const off = client.on(type, ((...args: unknown[]) =>\n (latest.current as (...a: unknown[]) => void)(...args)) as EventMap<In>[K]);\n const release = client.acquire();\n return () => {\n off();\n release();\n };\n }, [client, type, latest]);\n}\n\n/**\n * The connection status of a client. Re-renders only when the status changes, not on\n * messages. Keeps the connection open while mounted.\n *\n * @example\n * ```tsx\n * const status = useWebSocketStatus(chat); // 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'\n * ```\n */\nexport function useWebSocketStatus(client: WebSocketClient<any, any> | null | undefined): Status {\n const status = useSyncExternalStore(\n client ? client.subscribe : noopSubscribe,\n client ? () => client.getSnapshot().status : idleStatus,\n idleStatus\n );\n useHold(client ?? null, true);\n return status;\n}\n\nconst identity = <T>(value: T) => value;\n\n/**\n * Read state built from messages by `createWebSocketState`. Re-renders only when the\n * selected value changes (by `isEqual`, default `Object.is`), however often messages\n * arrive. Keeps the connection open while mounted.\n *\n * On the server, and during hydration, it reads from `initialState`.\n *\n * @example\n * ```tsx\n * const acme = useWebSocketState(priceState, state => state.ACME);\n * ```\n */\nexport function useWebSocketState<S>(store: WebSocketState<S>): S;\nexport function useWebSocketState<S, T>(\n store: WebSocketState<S>,\n selector: (state: S) => T,\n isEqual?: (a: T, b: T) => boolean\n): T;\nexport function useWebSocketState<S, T>(\n store: WebSocketState<S>,\n selector: (state: S) => T = identity as (state: S) => T,\n isEqual: (a: T, b: T) => boolean = Object.is\n): T {\n const [getSelection, getServerSelection] = useMemo(() => {\n // Return the previous selection while the state is unchanged or the result is equal,\n // so inline selectors that build objects don't re-render (or loop) on every message.\n const memoized = (read: () => S) => {\n let memo: { state: S; selection: T } | undefined;\n return () => {\n const state = read();\n if (memo && Object.is(memo.state, state)) return memo.selection;\n const selection = selector(state);\n if (memo && isEqual(memo.selection, selection)) {\n memo = { state, selection: memo.selection };\n return memo.selection;\n }\n memo = { state, selection };\n return selection;\n };\n };\n return [memoized(store.getState), memoized(() => store.initialState)] as const;\n }, [store, selector, isEqual]);\n\n const selection = useSyncExternalStore(store.subscribe, getSelection, getServerSelection);\n useHold(store.client, true);\n return selection;\n}\n\n/**\n * Subscribe to one topic (or several) while mounted, through a `createWebSocketTopics`\n * manager. Components holding the same topic share one subscription, and it is sent again\n * after every reconnect. Keeps the connection open while mounted. `null` holds nothing.\n *\n * @example\n * ```tsx\n * useWebSocketTopic(topics, `prices:${symbol}`);\n * useWebSocketTopic(topics, watchlist.map(symbol => `prices:${symbol}`));\n * ```\n */\nexport function useWebSocketTopic(\n topics: WebSocketTopics | null | undefined,\n topic: string | readonly string[] | null | undefined\n): void {\n // A stable key, so a new array with the same topics doesn't resubscribe.\n const key = topic == null ? null : JSON.stringify(typeof topic === 'string' ? [topic] : topic);\n useEffect(() => {\n if (!topics || key === null) return;\n const releases = (JSON.parse(key) as string[]).map(t => topics.acquire(t));\n return () => releases.forEach(release => release());\n }, [topics, key]);\n}\n"],"mappings":";;;AAAA,cAA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CAAC;AAClB;","names":["selection"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-websocket",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Hooks-first WebSocket client for React: shared connections, auto-reconnect, typed messages, Suspense-ready",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -82,6 +82,7 @@
82
82
  "devDependencies": {
83
83
  "@arethetypeswrong/cli": "^0.18.5",
84
84
  "@eslint/js": "^10.0.1",
85
+ "@fontsource-variable/geist-mono": "^5.3.0",
85
86
  "@size-limit/preset-small-lib": "^14.2.0",
86
87
  "@testing-library/react": "^16.3.3",
87
88
  "@types/react": "^19.3.0",
@@ -122,6 +123,15 @@
122
123
  "react"
123
124
  ],
124
125
  "limit": "2.6 kB"
126
+ },
127
+ {
128
+ "name": "react-websocket (topics + state hooks)",
129
+ "path": "dist/index.js",
130
+ "import": "{ useWebSocketTopic, useWebSocketState, createWebSocketTopics, createWebSocketState }",
131
+ "ignore": [
132
+ "react"
133
+ ],
134
+ "limit": "1 kB"
125
135
  }
126
136
  ],
127
137
  "overrides": {