react-websocket 3.5.0 → 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.
package/dist/index.d.ts CHANGED
@@ -31,7 +31,10 @@ interface Snapshot<In> {
31
31
  readonly status: Status;
32
32
  /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */
33
33
  readonly lastMessage: In | undefined;
34
- /** Consecutive failed attempts since the last successful open. `0` while open. */
34
+ /**
35
+ * Consecutive failed attempts since the last stable connection. A connection that closes
36
+ * within `reconnect.minUptime` of opening counts as failed. `0` while open.
37
+ */
35
38
  readonly attempt: number;
36
39
  }
37
40
  /** Details of a closed connection, from the browser's `CloseEvent`. */
@@ -53,6 +56,14 @@ interface ReconnectOptions {
53
56
  * @default Infinity
54
57
  */
55
58
  maxAttempts?: number;
59
+ /**
60
+ * How long a connection must stay open, in ms, before the backoff resets. One that closes
61
+ * sooner counts as a failed attempt, so a server that accepts and then closes right away
62
+ * (e.g. rejecting the credentials sent on open) is retried with a growing delay, and
63
+ * `maxAttempts` still applies. `0` resets on every open.
64
+ * @default 5000
65
+ */
66
+ minUptime?: number;
56
67
  /**
57
68
  * Delay before the first retry, in ms.
58
69
  * @default 1000
@@ -70,19 +81,26 @@ interface ReconnectOptions {
70
81
  factor?: number;
71
82
  /**
72
83
  * Randomly shave up to this fraction (0–1) off each delay, so that many clients
73
- * dropped at once don't all reconnect at the same moment.
74
- * @default 0.5
84
+ * dropped at once don't all reconnect at the same moment. The default `1` picks each
85
+ * delay at random between 0 and the backoff ("full jitter").
86
+ * @default 1
75
87
  */
76
88
  jitter?: number;
77
89
  /**
78
90
  * Called on every unexpected close. Return `false` to stop reconnecting.
79
91
  *
92
+ * The default, `retryableClose`, retries everything except `1002` (protocol error), `1003`
93
+ * (unsupported data) and `1008` (policy violation). Your own function replaces it; call
94
+ * `retryableClose` from it to keep that rule, or return `true` to retry every close.
95
+ *
80
96
  * @example
81
97
  * ```ts
82
- * // Don't retry when the server rejects our credentials.
83
- * shouldReconnect: close => close.code !== 4001
98
+ * import { retryableClose } from 'react-websocket';
99
+ *
100
+ * // Also stop when our server rejects the credentials.
101
+ * shouldReconnect: close => close.code !== 4001 && retryableClose(close)
84
102
  * ```
85
- * @default () => true
103
+ * @default retryableClose
86
104
  */
87
105
  shouldReconnect?: (close: CloseInfo) => boolean;
88
106
  }
@@ -157,7 +175,8 @@ interface QueueOptions {
157
175
  /**
158
176
  * Maximum number of messages held while not connected. When full, the oldest
159
177
  * message is dropped, skipping `priority` messages unless nothing else is queued.
160
- * @default Infinity
178
+ * `Infinity` keeps every message.
179
+ * @default 100
161
180
  */
162
181
  limit?: number;
163
182
  }
@@ -233,8 +252,8 @@ interface WebSocketOptions<In = unknown, Out = unknown> {
233
252
  heartbeat?: HeartbeatOptions;
234
253
  /**
235
254
  * Buffer `send()` calls made while not connected and send them, in order, on open
236
- * (right after `open` listeners run).
237
- * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.
255
+ * (right after `open` listeners run). It holds up to 100 messages, dropping the oldest;
256
+ * `{ limit }` changes that. `false` drops messages instead of queueing them.
238
257
  * The queue is cleared by `close()` or when the client gives up.
239
258
  * @default true
240
259
  */
@@ -402,6 +421,56 @@ interface WebSocketLatency {
402
421
  dispose(): void;
403
422
  }
404
423
  //#endregion
424
+ //#region src/requests.d.ts
425
+ /** Per-call options for {@link WebSocketRequests.request} and {@link WebSocketRequests.stream}. */
426
+ interface RequestOptions extends SendOptions {
427
+ /**
428
+ * Time to wait for a reply (for a stream, for each reply), in ms. Overrides the manager's
429
+ * `timeout`.
430
+ */
431
+ timeout?: number;
432
+ /** Abort the request. It rejects (a stream throws) with `signal.reason`. A late reply is ignored. */
433
+ signal?: AbortSignal;
434
+ }
435
+ /** Request/response over one client. Create with {@link createWebSocketRequests}. */
436
+ interface WebSocketRequests<Req, In> {
437
+ /** The client requests are sent on. */
438
+ readonly client: WebSocketClient<any, any>;
439
+ /**
440
+ * Send a request and resolve with its reply. Holds the connection until it settles.
441
+ *
442
+ * Rejects with a `TimeoutError` `DOMException` after `timeout`, with `signal.reason` when
443
+ * aborted, and with an `Error` when the connection it was sent on closes (the reply can
444
+ * no longer arrive) or the client stops. A request made while disconnected is queued like
445
+ * any other message and waits for the connection; it rejects if it is dropped from the
446
+ * queue (replaced by a newer request with the same `key`, or evicted by `queue.limit`).
447
+ */
448
+ request(message: Req, options?: RequestOptions): Promise<In>;
449
+ /**
450
+ * Send a request and iterate over its replies, up to and including the one `done` matches.
451
+ * Holds the connection until the stream ends. Needs the `done` option.
452
+ *
453
+ * `timeout` is the time to wait for each reply. Replies that arrive before the loop reads
454
+ * them are buffered. The stream is one-shot: iterate it once.
455
+ *
456
+ * Fails where `request()` rejects, with the same errors, after yielding the replies already
457
+ * received. Aborting `signal` throws `signal.reason` right away and discards them. Leaving
458
+ * the loop early, aborting and timing out send `cancel`.
459
+ *
460
+ * @example
461
+ * ```ts
462
+ * for await (const reply of rpc.stream({ type: 'ask', prompt }, { signal })) {
463
+ * text += reply.delta;
464
+ * }
465
+ * ```
466
+ */
467
+ stream(message: Req, options?: RequestOptions): AsyncIterableIterator<In>;
468
+ /** Number of requests and streams waiting for a reply. */
469
+ pending(): number;
470
+ /** Reject every pending request and stop listening. Only needed for managers created dynamically. */
471
+ dispose(): void;
472
+ }
473
+ //#endregion
405
474
  //#region src/responder.d.ts
406
475
  /** A request from the server that hasn't been answered yet. */
407
476
  interface IncomingRequest<P = unknown, R = unknown> {
@@ -544,7 +613,8 @@ interface UseWebSocketResult<In, Out> extends Snapshot<In> {
544
613
  * Connect to a WebSocket and re-render with its status and latest message.
545
614
  *
546
615
  * - With a URL, every component using the same URL (and `protocols`) shares one
547
- * connection. Its options come from whichever component created it first.
616
+ * connection. Its options come from whichever component created it first; in
617
+ * development, a component passing different ones gets a console warning.
548
618
  * - With a client from `createWebSocket()`, options are the client's; only handlers
549
619
  * and `enabled` apply here.
550
620
  * - With `null` or `undefined`, nothing connects and the status stays `idle`.
@@ -646,6 +716,61 @@ export declare function useWebSocketLatency(latency: WebSocketLatency): Latency;
646
716
  * ```
647
717
  */
648
718
  export declare function useAgentApproval<P, R>(responder: WebSocketResponder<P, R> | null | undefined, method: string | null | undefined): readonly IncomingRequest<P, R>[];
719
+ /** Options for `useWebSocketStream` that fold replies into one value, e.g. tokens into text. */
720
+ interface UseWebSocketStreamOptions<In, T> {
721
+ /** The value before the first reply. `start()` resets to it. */
722
+ initial: T;
723
+ /** Fold a reply into the value. Return a new value instead of changing the old one. */
724
+ reduce: (value: T, reply: In) => T;
725
+ /**
726
+ * `'frame'`: re-render at most once per animation frame instead of once per reply. Browsers
727
+ * pause frames in background tabs; the value catches up when the tab is visible again.
728
+ */
729
+ batch?: 'frame';
730
+ }
731
+ /** What `useWebSocketStream` returns: the stream's progress plus stable actions. */
732
+ interface UseWebSocketStreamResult<Req, T> {
733
+ /** The replies so far, folded with `reduce`, or as an array without it. */
734
+ readonly value: T;
735
+ /**
736
+ * `idle` until `start()`. `done` after the last reply, `error` when the stream failed (see
737
+ * `error`), `aborted` after `abort()`. The value stays as it was when the stream ended.
738
+ */
739
+ readonly status: 'idle' | 'streaming' | 'done' | 'error' | 'aborted';
740
+ /** Why the stream failed, while `status` is `error`. */
741
+ readonly error: unknown;
742
+ /** Reset the value and stream the replies to `message`, aborting the stream before. Stable identity. */
743
+ start: (message: Req, options?: Omit<RequestOptions, 'signal'>) => void;
744
+ /** Stop the stream and send the manager's `cancel`. Stable identity. */
745
+ abort: () => void;
746
+ }
747
+ /**
748
+ * Stream the replies to a request into a value, e.g. a model's tokens into its answer.
749
+ * `start(message)` sends it with `rpc.stream()` and folds each reply in with `reduce`, or
750
+ * collects the replies without it. Starting again aborts the stream before; so do `abort()`,
751
+ * unmounting and a new `rpc`, and each sends the manager's `cancel`. Re-renders on every
752
+ * reply, or once per frame with `batch: 'frame'`. Keeps the connection open while mounted.
753
+ *
754
+ * @example
755
+ * ```tsx
756
+ * const answer = useWebSocketStream(ask, {
757
+ * initial: '',
758
+ * reduce: (text, reply) => text + reply.delta,
759
+ * batch: 'frame'
760
+ * });
761
+ * return (
762
+ * <>
763
+ * <button onClick={() => answer.start({ prompt })}>Ask</button>
764
+ * <button onClick={answer.abort} disabled={answer.status !== 'streaming'}>Stop</button>
765
+ * <p>{answer.value}</p>
766
+ * </>
767
+ * );
768
+ * ```
769
+ */
770
+ export declare function useWebSocketStream<Req, In, T>(rpc: WebSocketRequests<Req, In> | null | undefined, options: UseWebSocketStreamOptions<NoInfer<In>, T>): UseWebSocketStreamResult<Req, T>;
771
+ export declare function useWebSocketStream<Req, In>(rpc: WebSocketRequests<Req, In> | null | undefined, options?: {
772
+ batch?: 'frame';
773
+ }): UseWebSocketStreamResult<Req, readonly In[]>;
649
774
  //#endregion
650
- export type { UseWebSocketOptions, UseWebSocketResult, WebSocketHandlers };
775
+ export type { UseWebSocketOptions, UseWebSocketResult, UseWebSocketStreamOptions, UseWebSocketStreamResult, WebSocketHandlers };
651
776
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { createWebSocket } from "./core.js";
3
- import { useEffect, useInsertionEffect, useMemo, useRef, useSyncExternalStore } from "react";
3
+ import { useEffect, useId, useInsertionEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  export * from "./core.js";
5
5
  //#region src/react.ts
6
6
  const IDLE = Object.freeze({
@@ -22,7 +22,38 @@ const noopSend = () => false;
22
22
  const noop = () => {};
23
23
  const ON_TEARDOWN = Symbol.for("react-websocket.onTeardown");
24
24
  const registry = /* @__PURE__ */ new Map();
25
- function sharedClient(url, options) {
25
+ const origins = /* @__PURE__ */ new WeakMap();
26
+ const warned = /* @__PURE__ */ new Set();
27
+ const CONNECTION_OPTIONS = {
28
+ protocols: void 0,
29
+ binaryType: "blob",
30
+ json: false,
31
+ parse: void 0,
32
+ serialize: void 0,
33
+ schema: void 0,
34
+ reconnect: true,
35
+ heartbeat: void 0,
36
+ queue: true,
37
+ logger: void 0,
38
+ WebSocket: void 0
39
+ };
40
+ const IGNORED_OPTIONS = /* @__PURE__ */ new Set(["protocols", "logger"]);
41
+ const sameValue = (a, b) => Object.is(a, b) || typeof a === "function" && typeof b === "function" && String(a) === String(b);
42
+ const isPlainObject = (value) => typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
43
+ function sameOption(a, b) {
44
+ if (sameValue(a, b)) return true;
45
+ if (!isPlainObject(a) || !isPlainObject(b)) return false;
46
+ return [...Object.keys(a), ...Object.keys(b)].every((key) => sameValue(a[key], b[key]));
47
+ }
48
+ function warnOnConflict(url, key, client, options, id) {
49
+ const origin = origins.get(client);
50
+ if (!origin || origin.id === id || warned.has(`${key}\u0000${id}`)) return;
51
+ const differing = Object.keys(CONNECTION_OPTIONS).filter((name) => !IGNORED_OPTIONS.has(name) && !sameOption(origin.options[name] ?? CONNECTION_OPTIONS[name], options[name] ?? CONNECTION_OPTIONS[name]));
52
+ if (!differing.length) return;
53
+ warned.add(`${key}\u0000${id}`);
54
+ console.warn(`react-websocket: useWebSocket("${url}") was given different ${differing.join(", ")} than the component that opened this shared connection. They are ignored: every component using the URL gets the first one's options. Pass the same options, or define the connection once with createWebSocket().`);
55
+ }
56
+ function sharedClient(url, options, id) {
26
57
  if (typeof window === "undefined") return createWebSocket(url, options);
27
58
  const key = `${url}\u0000${JSON.stringify(options.protocols ?? null)}`;
28
59
  let client = registry.get(key);
@@ -35,7 +66,11 @@ function sharedClient(url, options) {
35
66
  });
36
67
  registry.set(key, created);
37
68
  client = created;
38
- }
69
+ if (process.env.NODE_ENV !== "production") origins.set(created, {
70
+ options,
71
+ id
72
+ });
73
+ } else if (process.env.NODE_ENV !== "production") warnOnConflict(url, key, client, options, id);
39
74
  return client;
40
75
  }
41
76
  /** Always-current value for use inside effects and event listeners (a `useEffectEvent` stand-in). */
@@ -52,7 +87,8 @@ function useHold(client, enabled) {
52
87
  }, [client, enabled]);
53
88
  }
54
89
  function useWebSocket(target, options = {}) {
55
- const client = target == null ? null : typeof target === "string" ? sharedClient(target, options) : target;
90
+ const id = useId();
91
+ const client = target == null ? null : typeof target === "string" ? sharedClient(target, options, id) : target;
56
92
  const enabled = options.enabled ?? true;
57
93
  const snapshot = useSyncExternalStore(client ? client.subscribe : noopSubscribe, client ? client.getSnapshot : idleSnapshot, idleSnapshot);
58
94
  const handlers = useLatest(options);
@@ -219,7 +255,70 @@ function useAgentApproval(responder, method) {
219
255
  return mine.length ? mine : NO_REQUESTS;
220
256
  }, [waiting, method]);
221
257
  }
258
+ const append = (list, reply) => [...list, reply];
259
+ function nextFrame(callback) {
260
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(callback);
261
+ else setTimeout(callback, 16);
262
+ }
263
+ function useWebSocketStream(rpc, options = {}) {
264
+ const [state, setState] = useState(() => ({
265
+ value: options.reduce ? options.initial : NO_REQUESTS,
266
+ status: "idle",
267
+ error: void 0
268
+ }));
269
+ const latest = useLatest({
270
+ rpc,
271
+ options
272
+ });
273
+ const running = useRef(null);
274
+ const actions = useMemo(() => ({
275
+ abort: () => running.current?.abort(),
276
+ start(message, requestOptions) {
277
+ running.current?.abort();
278
+ const controller = running.current = new AbortController();
279
+ const { reduce, initial, batch } = latest.current.options;
280
+ const fold = reduce ?? append;
281
+ let value = reduce ? initial : NO_REQUESTS;
282
+ let frame = false;
283
+ const show = (status, error) => {
284
+ frame = false;
285
+ if (running.current === controller) setState({
286
+ value,
287
+ status,
288
+ error
289
+ });
290
+ };
291
+ show("streaming");
292
+ (async () => {
293
+ try {
294
+ const replies = latest.current.rpc.stream(message, {
295
+ ...requestOptions,
296
+ signal: controller.signal
297
+ });
298
+ for await (const reply of replies) {
299
+ value = fold(value, reply);
300
+ if (batch !== "frame") show("streaming");
301
+ else if (!frame) {
302
+ frame = true;
303
+ nextFrame(() => frame && show("streaming"));
304
+ }
305
+ }
306
+ show("done");
307
+ } catch (error) {
308
+ if (controller.signal.aborted) show("aborted");
309
+ else show("error", error);
310
+ }
311
+ })();
312
+ }
313
+ }), [latest]);
314
+ useEffect(() => actions.abort, [actions, rpc]);
315
+ useHold(rpc?.client ?? null, true);
316
+ return {
317
+ ...state,
318
+ ...actions
319
+ };
320
+ }
222
321
  //#endregion
223
- export { useAgentApproval, useWebSocket, useWebSocketEvent, useWebSocketLatency, useWebSocketState, useWebSocketStatus, useWebSocketTopic };
322
+ export { useAgentApproval, useWebSocket, useWebSocketEvent, useWebSocketLatency, useWebSocketState, useWebSocketStatus, useWebSocketStream, useWebSocketTopic };
224
323
 
225
324
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["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 { Latency, WebSocketLatency } from './latency';\n// Types only: a value import from anything but `./core` would bundle a second copy into this entry.\nimport type { IncomingRequest, WebSocketResponder } from './responder';\nimport type { WebSocketState } from './state';\nimport type { WebSocketTopics } from './topics';\nimport type {\n CloseInfo,\n EventMap,\n SendOptions,\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 /**\n * Send now, or queue until open (see {@link SendOptions} for volatile and keyed sends).\n * Returns `true` if sent immediately. Stable identity.\n */\n send: (message: Out, options?: SendOptions) => 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 NO_LATENCY: Latency = Object.freeze({ rtt: undefined, offset: undefined });\nconst noLatency = () => NO_LATENCY;\n// Not frozen: a call would keep it in bundles that never use the hook.\nconst NO_REQUESTS: readonly never[] = [];\nconst noRequests = () => NO_REQUESTS;\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\n/**\n * Read round-trip time and server clock offset from a `createWebSocketLatency` instance.\n * Re-renders when a measurement changes, about once per ping interval. Keeps the connection\n * open while mounted. On the server, and during hydration, both values are `undefined`.\n *\n * @example\n * ```tsx\n * const { rtt } = useWebSocketLatency(latency);\n * return <span>{rtt === undefined ? '–' : `${Math.round(rtt)} ms`}</span>;\n * ```\n */\nexport function useWebSocketLatency(latency: WebSocketLatency): Latency {\n const snapshot = useSyncExternalStore(latency.subscribe, latency.getSnapshot, noLatency);\n useHold(latency.client, true);\n return snapshot;\n}\n\n/**\n * Requests for `method` that a person answers, e.g. an agent asking to run a tool. While mounted,\n * it registers `method` on the responder without a handler, so new requests wait here instead of\n * getting a `NotFoundError` reply. Call `respond` or `reject` on one to answer it. Re-renders\n * when the list changes. Keeps the connection open while mounted. `null` holds nothing.\n *\n * Requests stay listed after unmount until they are answered, time out, are cancelled or lose\n * their connection, so a remounted dialog shows them again. On the server the list is empty.\n *\n * @example\n * ```tsx\n * const [request] = useAgentApproval(tools, 'approve');\n * if (!request) return null;\n * return (\n * <dialog open>\n * {request.params.summary}\n * <button onClick={() => request.respond({ approved: true })}>Approve</button>\n * <button onClick={() => request.respond({ approved: false })}>Deny</button>\n * </dialog>\n * );\n * ```\n */\nexport function useAgentApproval<P, R>(\n responder: WebSocketResponder<P, R> | null | undefined,\n method: string | null | undefined\n): readonly IncomingRequest<P, R>[] {\n const waiting = useSyncExternalStore(\n responder ? responder.subscribe : noopSubscribe,\n responder ? responder.getSnapshot : noRequests,\n noRequests\n );\n useEffect(() => {\n if (responder && method != null) return responder.onRequest(method);\n }, [responder, method]);\n useHold(responder?.client ?? null, method != null);\n return useMemo(() => {\n const mine = waiting.filter(request => request.method === method);\n return mine.length ? mine : NO_REQUESTS;\n }, [waiting, method]);\n}\n"],"mappings":";;;;;AA2DA,MAAM,OAAwB,OAAO,OAAO;CAAE,QAAQ;CAAQ,aAAa,KAAA;CAAW,SAAS;AAAE,CAAC;AAClG,MAAM,qBAAqB;AAC3B,MAAM,mBAA2B;AACjC,MAAM,aAAsB,OAAO,OAAO;CAAE,KAAK,KAAA;CAAW,QAAQ,KAAA;AAAU,CAAC;AAC/E,MAAM,kBAAkB;AAExB,MAAM,cAAgC,CAAC;AACvC,MAAM,mBAAmB;AACzB,MAAM,4BAA4B,CAA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E,OAAO,KAAK,SAAS,OAAO;CAC9B,GAAG,CAAC,SAAS,MAAM,CAAC;AACtB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["import {\n useEffect,\n useId,\n useInsertionEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore\n} 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 { Latency, WebSocketLatency } from './latency';\n// Types only: a value import from anything but `./core` would bundle a second copy into this entry.\nimport type { RequestOptions, WebSocketRequests } from './requests';\nimport type { IncomingRequest, WebSocketResponder } from './responder';\nimport type { WebSocketState } from './state';\nimport type { WebSocketTopics } from './topics';\nimport type {\n CloseInfo,\n EventMap,\n SendOptions,\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 /**\n * Send now, or queue until open (see {@link SendOptions} for volatile and keyed sends).\n * Returns `true` if sent immediately. Stable identity.\n */\n send: (message: Out, options?: SendOptions) => 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 NO_LATENCY: Latency = Object.freeze({ rtt: undefined, offset: undefined });\nconst noLatency = () => NO_LATENCY;\n// Not frozen: a call would keep it in bundles that never use the hook.\nconst NO_REQUESTS: readonly never[] = [];\nconst noRequests = () => NO_REQUESTS;\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\n// Development only: the options (and `useId` of the component) each URL client was created with,\n// to warn when another component passes different ones for the same URL.\nconst origins = new WeakMap<\n WebSocketClient<any, any>,\n { options: WebSocketOptions<any, any>; id: string }\n>();\nconst warned = new Set<string>();\n\n// The options that shape a shared connection, with what leaving one out means.\nconst CONNECTION_OPTIONS: { [K in keyof WebSocketOptions]-?: unknown } = {\n protocols: undefined, // part of the registry key\n binaryType: 'blob',\n json: false,\n parse: undefined,\n serialize: undefined,\n schema: undefined,\n reconnect: true,\n heartbeat: undefined,\n queue: true,\n logger: undefined, // debugging only\n WebSocket: undefined\n};\nconst IGNORED_OPTIONS = new Set(['protocols', 'logger']);\n\n// Inline functions and objects are new on every render: compare them by source and by field.\nconst sameValue = (a: unknown, b: unknown) =>\n Object.is(a, b) ||\n (typeof a === 'function' && typeof b === 'function' && String(a) === String(b));\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;\n\nfunction sameOption(a: unknown, b: unknown) {\n if (sameValue(a, b)) return true;\n if (!isPlainObject(a) || !isPlainObject(b)) return false;\n return [...Object.keys(a), ...Object.keys(b)].every(key => sameValue(a[key], b[key]));\n}\n\nfunction warnOnConflict(\n url: string,\n key: string,\n client: WebSocketClient<any, any>,\n options: WebSocketOptions<any, any>,\n id: string\n) {\n const origin = origins.get(client);\n if (!origin || origin.id === id || warned.has(`${key}\\u0000${id}`)) return;\n const differing = (Object.keys(CONNECTION_OPTIONS) as (keyof WebSocketOptions)[]).filter(\n name =>\n !IGNORED_OPTIONS.has(name) &&\n !sameOption(\n origin.options[name] ?? CONNECTION_OPTIONS[name],\n options[name] ?? CONNECTION_OPTIONS[name]\n )\n );\n if (!differing.length) return;\n warned.add(`${key}\\u0000${id}`);\n console.warn(\n `react-websocket: useWebSocket(\"${url}\") was given different ${differing.join(', ')} than ` +\n `the component that opened this shared connection. They are ignored: every component ` +\n `using the URL gets the first one's options. Pass the same options, or define the ` +\n `connection once with createWebSocket().`\n );\n}\n\nfunction sharedClient<In, Out>(url: string, options: WebSocketOptions<In, Out>, id: string) {\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 if (process.env.NODE_ENV !== 'production') origins.set(created, { options, id });\n } else if (process.env.NODE_ENV !== 'production') {\n warnOnConflict(url, key, client, options, id);\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; in\n * development, a component passing different ones gets a console warning.\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 id = useId();\n const client =\n target == null ? null : typeof target === 'string' ? sharedClient(target, options, id) : 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\n/**\n * Read round-trip time and server clock offset from a `createWebSocketLatency` instance.\n * Re-renders when a measurement changes, about once per ping interval. Keeps the connection\n * open while mounted. On the server, and during hydration, both values are `undefined`.\n *\n * @example\n * ```tsx\n * const { rtt } = useWebSocketLatency(latency);\n * return <span>{rtt === undefined ? '–' : `${Math.round(rtt)} ms`}</span>;\n * ```\n */\nexport function useWebSocketLatency(latency: WebSocketLatency): Latency {\n const snapshot = useSyncExternalStore(latency.subscribe, latency.getSnapshot, noLatency);\n useHold(latency.client, true);\n return snapshot;\n}\n\n/**\n * Requests for `method` that a person answers, e.g. an agent asking to run a tool. While mounted,\n * it registers `method` on the responder without a handler, so new requests wait here instead of\n * getting a `NotFoundError` reply. Call `respond` or `reject` on one to answer it. Re-renders\n * when the list changes. Keeps the connection open while mounted. `null` holds nothing.\n *\n * Requests stay listed after unmount until they are answered, time out, are cancelled or lose\n * their connection, so a remounted dialog shows them again. On the server the list is empty.\n *\n * @example\n * ```tsx\n * const [request] = useAgentApproval(tools, 'approve');\n * if (!request) return null;\n * return (\n * <dialog open>\n * {request.params.summary}\n * <button onClick={() => request.respond({ approved: true })}>Approve</button>\n * <button onClick={() => request.respond({ approved: false })}>Deny</button>\n * </dialog>\n * );\n * ```\n */\nexport function useAgentApproval<P, R>(\n responder: WebSocketResponder<P, R> | null | undefined,\n method: string | null | undefined\n): readonly IncomingRequest<P, R>[] {\n const waiting = useSyncExternalStore(\n responder ? responder.subscribe : noopSubscribe,\n responder ? responder.getSnapshot : noRequests,\n noRequests\n );\n useEffect(() => {\n if (responder && method != null) return responder.onRequest(method);\n }, [responder, method]);\n useHold(responder?.client ?? null, method != null);\n return useMemo(() => {\n const mine = waiting.filter(request => request.method === method);\n return mine.length ? mine : NO_REQUESTS;\n }, [waiting, method]);\n}\n\n/** Options for `useWebSocketStream` that fold replies into one value, e.g. tokens into text. */\nexport interface UseWebSocketStreamOptions<In, T> {\n /** The value before the first reply. `start()` resets to it. */\n initial: T;\n /** Fold a reply into the value. Return a new value instead of changing the old one. */\n reduce: (value: T, reply: In) => T;\n /**\n * `'frame'`: re-render at most once per animation frame instead of once per reply. Browsers\n * pause frames in background tabs; the value catches up when the tab is visible again.\n */\n batch?: 'frame';\n}\n\n/** What `useWebSocketStream` returns: the stream's progress plus stable actions. */\nexport interface UseWebSocketStreamResult<Req, T> {\n /** The replies so far, folded with `reduce`, or as an array without it. */\n readonly value: T;\n /**\n * `idle` until `start()`. `done` after the last reply, `error` when the stream failed (see\n * `error`), `aborted` after `abort()`. The value stays as it was when the stream ended.\n */\n readonly status: 'idle' | 'streaming' | 'done' | 'error' | 'aborted';\n /** Why the stream failed, while `status` is `error`. */\n readonly error: unknown;\n /** Reset the value and stream the replies to `message`, aborting the stream before. Stable identity. */\n start: (message: Req, options?: Omit<RequestOptions, 'signal'>) => void;\n /** Stop the stream and send the manager's `cancel`. Stable identity. */\n abort: () => void;\n}\n\nconst append = <T>(list: readonly T[], reply: T): readonly T[] => [...list, reply];\n\n// Node and some workers have no animation frames: wait about one instead.\nfunction nextFrame(callback: () => void) {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(callback);\n else setTimeout(callback, 16);\n}\n\n/**\n * Stream the replies to a request into a value, e.g. a model's tokens into its answer.\n * `start(message)` sends it with `rpc.stream()` and folds each reply in with `reduce`, or\n * collects the replies without it. Starting again aborts the stream before; so do `abort()`,\n * unmounting and a new `rpc`, and each sends the manager's `cancel`. Re-renders on every\n * reply, or once per frame with `batch: 'frame'`. Keeps the connection open while mounted.\n *\n * @example\n * ```tsx\n * const answer = useWebSocketStream(ask, {\n * initial: '',\n * reduce: (text, reply) => text + reply.delta,\n * batch: 'frame'\n * });\n * return (\n * <>\n * <button onClick={() => answer.start({ prompt })}>Ask</button>\n * <button onClick={answer.abort} disabled={answer.status !== 'streaming'}>Stop</button>\n * <p>{answer.value}</p>\n * </>\n * );\n * ```\n */\nexport function useWebSocketStream<Req, In, T>(\n rpc: WebSocketRequests<Req, In> | null | undefined,\n options: UseWebSocketStreamOptions<NoInfer<In>, T>\n): UseWebSocketStreamResult<Req, T>;\nexport function useWebSocketStream<Req, In>(\n rpc: WebSocketRequests<Req, In> | null | undefined,\n options?: { batch?: 'frame' }\n): UseWebSocketStreamResult<Req, readonly In[]>;\nexport function useWebSocketStream<Req, In>(\n rpc: WebSocketRequests<Req, In> | null | undefined,\n options: Partial<UseWebSocketStreamOptions<In, any>> = {}\n): UseWebSocketStreamResult<Req, unknown> {\n type Status = UseWebSocketStreamResult<Req, unknown>['status'];\n const [state, setState] = useState<{ value: unknown; status: Status; error: unknown }>(() => ({\n value: options.reduce ? options.initial : NO_REQUESTS,\n status: 'idle',\n error: undefined\n }));\n const latest = useLatest({ rpc, options });\n const running = useRef<AbortController | null>(null);\n\n const actions = useMemo(\n () => ({\n abort: () => running.current?.abort(),\n start(message: Req, requestOptions?: Omit<RequestOptions, 'signal'>) {\n running.current?.abort();\n const controller = (running.current = new AbortController());\n const { reduce, initial, batch } = latest.current.options;\n const fold = reduce ?? append;\n let value: unknown = reduce ? initial : NO_REQUESTS;\n let frame = false;\n // A stream that was started over no longer shows; ending also skips a pending frame.\n const show = (status: Status, error?: unknown) => {\n frame = false;\n if (running.current === controller) setState({ value, status, error });\n };\n show('streaming');\n void (async () => {\n try {\n const replies = latest.current.rpc!.stream(message, {\n ...requestOptions,\n signal: controller.signal\n });\n for await (const reply of replies) {\n value = fold(value, reply);\n if (batch !== 'frame') show('streaming');\n else if (!frame) {\n frame = true;\n nextFrame(() => frame && show('streaming'));\n }\n }\n show('done');\n } catch (error) {\n if (controller.signal.aborted) show('aborted');\n else show('error', error);\n }\n })();\n }\n }),\n [latest]\n );\n // Unmounting, or replies from another manager: stop this one's stream.\n useEffect(() => actions.abort, [actions, rpc]);\n useHold(rpc?.client ?? null, true);\n\n return { ...state, ...actions };\n}\n"],"mappings":";;;;;AAoEA,MAAM,OAAwB,OAAO,OAAO;CAAE,QAAQ;CAAQ,aAAa,KAAA;CAAW,SAAS;AAAE,CAAC;AAClG,MAAM,qBAAqB;AAC3B,MAAM,mBAA2B;AACjC,MAAM,aAAsB,OAAO,OAAO;CAAE,KAAK,KAAA;CAAW,QAAQ,KAAA;AAAU,CAAC;AAC/E,MAAM,kBAAkB;AAExB,MAAM,cAAgC,CAAC;AACvC,MAAM,mBAAmB;AACzB,MAAM,4BAA4B,CAAC;AACnC,MAAM,iBAAiB;AACvB,MAAM,aAAa,CAAC;AAGpB,MAAM,cAAc,OAAO,IAAI,4BAA4B;AAG3D,MA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,OAAO,KAAK;MACzB,IAAI,UAAU,SAAS,KAAK,WAAW;WAClC,IAAI,CAAC,OAAO;OACf,QAAQ;OACR,gBAAgB,SAAS,KAAK,WAAW,CAAC;MAC5C;KACF;KACA,KAAK,MAAM;IACb,SAAS,OAAO;KACd,IAAI,WAAW,OAAO,SAAS,KAAK,SAAS;UACxC,KAAK,SAAS,KAAK;IAC1B;GACF,EAAA,CAAG;EACL;CACF,IACA,CAAC,MAAM,CACT;CAEA,gBAAgB,QAAQ,OAAO,CAAC,SAAS,GAAG,CAAC;CAC7C,QAAQ,KAAK,UAAU,MAAM,IAAI;CAEjC,OAAO;EAAE,GAAG;EAAO,GAAG;CAAQ;AAChC"}
@@ -29,7 +29,10 @@ interface Snapshot<In> {
29
29
  readonly status: Status;
30
30
  /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */
31
31
  readonly lastMessage: In | undefined;
32
- /** Consecutive failed attempts since the last successful open. `0` while open. */
32
+ /**
33
+ * Consecutive failed attempts since the last stable connection. A connection that closes
34
+ * within `reconnect.minUptime` of opening counts as failed. `0` while open.
35
+ */
33
36
  readonly attempt: number;
34
37
  }
35
38
  /** Details of a closed connection, from the browser's `CloseEvent`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-websocket",
3
- "version": "3.5.0",
3
+ "version": "4.0.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",
@@ -134,7 +134,7 @@
134
134
  "ignore": [
135
135
  "react"
136
136
  ],
137
- "limit": "3.2 kB",
137
+ "limit": "3.3 kB",
138
138
  "gzip": true
139
139
  },
140
140
  {
@@ -164,7 +164,17 @@
164
164
  "ignore": [
165
165
  "react"
166
166
  ],
167
- "limit": "1.5 kB",
167
+ "limit": "1.8 kB",
168
+ "gzip": true
169
+ },
170
+ {
171
+ "name": "react-websocket (requests + stream hook)",
172
+ "path": "dist/index.js",
173
+ "import": "{ createWebSocketRequests, useWebSocketStream }",
174
+ "ignore": [
175
+ "react"
176
+ ],
177
+ "limit": "1.7 kB",
168
178
  "gzip": true
169
179
  },
170
180
  {